auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testIterationApp() throws Exception { LocalMode lma = LocalMode.newInstance(); Configuration conf = new Configuration(false); Application app = new Application(); String outputFileName = "target/output.txt"; new File(outputFileName).delete(); app.setExtraOutputFileName(outputFileName); lma.prepareDAG(app, conf); LocalMode.Controller lc = lma.getController(); lc.runAsync(); while (true) { try { Thread.sleep(500); } catch (InterruptedException ex) { break; } File file = new File(outputFileName); if (file.length() > 50) { break; } } lc.shutdown(); try (BufferedReader br = new BufferedReader(new FileReader(outputFileName))) { Assert.assertEquals("1", br.readLine()); Assert.assertEquals("1", br.readLine()); Assert.assertEquals("2", br.readLine()); Assert.assertEquals("3", br.readLine()); Assert.assertEquals("5", br.readLine()); Assert.assertEquals("8", br.readLine()); Assert.assertEquals("13", br.readLine()); Assert.assertEquals("21", br.readLine()); Assert.assertEquals("34", br.readLine()); Assert.assertEquals("55", br.readLine()); Assert.assertEquals("89", br.readLine()); Assert.assertEquals("144", br.readLine()); Assert.assertEquals("233", br.readLine()); Assert.assertEquals("377", br.readLine()); Assert.assertEquals("610", br.readLine()); Assert.assertEquals("987", br.readLine()); } }

Target:
public void testIterationApp() throws Exception { LocalMode lma = LocalMode.newInstance(); Configuration conf = new Configuration(false); Application app = new Application(); String outputFileName = "target/output.txt"; long timeout = 10 * 1000; new File(outputFileName).delete(); app.setExtraOutputFileName(outputFileName); lma.prepareDAG(app, conf); LocalMode.Controller lc = lma.getController(); lc.runAsync(); long startTime = System.currentTimeMillis(); do { try { Thread.sleep(500); } catch (InterruptedException ex) { break; } File file = new File(outputFileName); if (file.length() > 50) { break; } } while (System.currentTimeMillis() - startTime < timeout); lc.shutdown(); try (BufferedReader br = new BufferedReader(new FileReader(outputFileName))) { Assert.assertEquals("1", br.readLine()); Assert.assertEquals("1", br.readLine()); Assert.assertEquals("2", br.readLine()); Assert.assertEquals("3", br.readLine()); Assert.assertEquals("5", br.readLine()); Assert.assertEquals("8", br.readLine()); Assert.assertEquals("13", br.readLine()); Assert.assertEquals("21", br.readLine()); Assert.assertEquals("34", br.readLine()); Assert.assertEquals("55", br.readLine()); Assert.assertEquals("89", br.readLine()); Assert.assertEquals("144", br.readLine()); Assert.assertEquals("233", br.readLine()); Assert.assertEquals("377", br.readLine()); Assert.assertEquals("610", br.readLine()); Assert.assertEquals("987", br.readLine()); } }
Source:
public void setNotificationPreferenceStatus(String userId, String eventType, String applicationId, String notificationFormat, boolean notificationStatus, Date startDate) throws NotificationException { NotificationFormat format = NotificationFormat.valueOf(notificationFormat.toUpperCase()); NotificationPreference preference = new NotificationPreference(eventType, applicationId, notificationStatus, format, startDate); try { this.modelBridge.saveNotificationPreference(this.documentReferenceResolver.resolve(userId), preference); } catch (NotificationException e) { throw new NotificationException(String.format( "Unable to save the notification preferences [%s] in [%s] for the user [%s]", eventType, applicationId, userId)); } }

Target:
public void setNotificationPreferenceStatus(String userId, String eventType, String applicationId, String notificationFormat, boolean notificationStatus, Date startDate) throws NotificationException { NotificationPreference preference = new NotificationPreference(eventType, applicationId, notificationStatus, notificationFormat, startDate); DocumentReference userReference = this.documentReferenceResolver.resolve(userId); try { this.authorizationManager.checkAccess(Right.EDIT, userReference); this.modelBridge.saveNotificationPreference(userReference, preference); } catch (Exception e) { throw new NotificationException(String.format( "Unable to save the notification preferences [%s] in [%s] for the user [%s]", eventType, applicationId, userId)); } }
Source:
public PersistedData serializeCollection(Collection<T> value, SerializationContext context) { List<PersistedData> rawList = Lists.newArrayList(); rawList.addAll(value.stream().map(item -> serialize(item, context)).collect(Collectors.toList())); return context.create(rawList); }

Target:
public PersistedData serializeCollection(Collection<T> value, SerializationContext context) { List<PersistedData> rawList = Lists.newArrayList(); for (T item : value) { rawList.add(serialize(item, context)); } return context.create(rawList); }
Source:
private static Optional<TypeSignature> getColumnTypeRewrite(TypeSignature type) { if (type.equals(DATE.getTypeSignature())) { return Optional.of(TIMESTAMP.getTypeSignature()); } return Optional.empty(); }

Target:
private static Optional<TypeSignature> getColumnTypeRewrite(TypeSignature type) { if (type.equals(DATE.getTypeSignature())) { return Optional.of(TIMESTAMP.getTypeSignature()); } if (type.equals(UNKNOWN.getTypeSignature())) { return Optional.of(BIGINT.getTypeSignature()); } return Optional.empty(); }
Source:
private CacheEntry getFromContainerForWrite(Object key, int segment, boolean isOwner) { if (isOwner) { final InternalCacheEntry ice = innerGetFromContainer(key, segment, false, isPrimaryOwner(isOwner, segment)); if (trace) log.tracef("Retrieved from container %s", ice); if (ice == null) { return NullCacheEntry.getInstance(); } return ice; } else if (isL1Enabled) { final InternalCacheEntry ice = innerGetFromContainer(key, segment, false, isPrimaryOwner(isOwner, segment)); if (trace) log.tracef("Retrieved from container %s", ice); if (ice == null || !ice.isL1Entry()) return null; return ice; } return null; }

Target:
private CacheEntry getFromContainerForWrite(Object key, int segment, boolean isOwner) { if (isOwner) { final InternalCacheEntry ice = innerGetFromContainerForWrite(key, segment, false, isPrimaryOwner(segment)); if (trace) log.tracef("Retrieved from container %s", ice); if (ice == null) { return NullCacheEntry.getInstance(); } return ice; } else if (isL1Enabled) { final InternalCacheEntry ice = innerGetFromContainerForWrite(key, segment, false, false); if (trace) log.tracef("Retrieved from container %s", ice); if (ice == null || !ice.isL1Entry()) return null; return ice; } return null; }
Source:
public HostStatusTracker refreshHosts() { if (stop.get() || Thread.currentThread().isInterrupted()) { return null; } List<Host> allHosts = hostSupplier.getHosts(); if (allHosts == null || allHosts.isEmpty()) { throw new NoAvailableHostsException("No available hosts when starting HostsUpdater"); } List<Host> hostsUp = new ArrayList<>(); List<Host> hostsDown = new ArrayList<>(); for (Host host : allHosts) { if (host.isUp()) { hostsUp.add(host); } else { hostsDown.add(host); } } if (!hostTracker.get().checkIfChanged(new HashSet<>(hostsUp), new HashSet<>(hostsDown))) { return hostTracker.get(); } Collections.sort(allHosts); Set<Host> hostSet = new HashSet<>(allHosts); List<HostToken> hostTokens; if (tokenMapSupplier != null) { Logger.info("Getting Hosts from TMS"); hostTokens = tokenMapSupplier.getTokens(hostSet); if (hostTokens.isEmpty()) { throw new DynoException("No hosts in the TokenMapSupplier"); } } else { throw new DynoException("TokenMapSupplier not provided"); } Map<Host, Host> allHostSetFromTMS = new HashMap<>(); for (HostToken ht : hostTokens) { allHostSetFromTMS.put(ht.getHost(), ht.getHost()); } hostsUp.clear(); hostsDown.clear(); for (Host host : allHosts) { if (host.isUp()) { hostsUp.add(allHostSetFromTMS.get(host)); } else { hostsDown.add(allHostSetFromTMS.get(host)); } } HostStatusTracker newTracker = hostTracker.get().computeNewHostStatus(hostsUp, hostsDown); hostTracker.set(newTracker); return hostTracker.get(); }

Target:
public HostStatusTracker refreshHosts() { if (stop.get() || Thread.currentThread().isInterrupted()) { return null; } List<Host> allHosts = hostSupplier.getHosts(); if (allHosts == null || allHosts.isEmpty()) { throw new NoAvailableHostsException("No available hosts when starting HostsUpdater"); } List<Host> hostsUp = new ArrayList<>(); List<Host> hostsDown = new ArrayList<>(); for (Host host : allHosts) { if (host.isUp()) { hostsUp.add(host); } else { hostsDown.add(host); } } if (!hostTracker.get().checkIfChanged(new HashSet<>(hostsUp), new HashSet<>(hostsDown))) { return hostTracker.get(); } Collections.sort(allHosts); Set<Host> hostSet = new HashSet<>(allHosts); List<HostToken> hostTokens; if (tokenMapSupplier != null) { Logger.info("Getting Hosts from TokenMapSupplier"); hostTokens = tokenMapSupplier.getTokens(hostSet); if (hostTokens.isEmpty()) { throw new DynoException("No hosts in the TokenMapSupplier"); } } else { throw new DynoException("TokenMapSupplier not provided"); } Map<Host, Host> allHostSetFromTokenMapSupplier = new HashMap<>(); for (HostToken ht : hostTokens) { allHostSetFromTokenMapSupplier.put(ht.getHost(), ht.getHost()); } hostsUp.clear(); hostsDown.clear(); for (Host host : allHosts) { if (host.isUp()) { hostsUp.add(allHostSetFromTokenMapSupplier.get(host)); } else { hostsDown.add(allHostSetFromTokenMapSupplier.get(host)); } } HostStatusTracker newTracker = hostTracker.get().computeNewHostStatus(hostsUp, hostsDown); hostTracker.set(newTracker); return hostTracker.get(); }
Source:
public void colorSettingsChanged(StateItem[] stateItems) { if (stateItems != null) { fEventColorMap = new Color[stateItems.length]; for (int i = 0; i < stateItems.length; i++) { fEventColorMap[i] = fResourceManager.createColor(stateItems[i].getStateColor()); } } else { fEventColorMap = new Color[] { }; } }

Target:
public void colorSettingsChanged(StateItem[] stateItems) { for (Color color : fEventColorMap) { fResourceManager.destroyColor(color.getRGB()); } if (stateItems != null) { fEventColorMap = new Color[stateItems.length]; for (int i = 0; i < stateItems.length; i++) { fEventColorMap[i] = fResourceManager.createColor(stateItems[i].getStateColor()); } } else { fEventColorMap = new Color[] { }; } redraw(); }
Source:
private void closeStatements() throws SQLException { List<SQLCloseable> statements = this.statements; this.statements = Lists.newArrayList(); try { mutationState.clear(); } finally { try { SQLCloseables.closeAll(statements); } finally { statements.clear(); } } }

Target:
private void closeStatements() throws SQLException { List<SQLCloseable> statements = this.statements; this.statements = Lists.newArrayList(); try { mutationState.rollback(this); } finally { try { SQLCloseables.closeAll(statements); } finally { statements.clear(); } } }
Source:
private List<String> extractPortValues(String prefix, Properties properties) { List<String> ports = listWithPrefix(prefix, PORTS, properties); if (ports == null) { return null; } Iterable<String[]> parsedPorts = EnvUtil.splitOnLastColon(ports); return Lists.newArrayList(Iterables.transform(parsedPorts, EXTRACT_SECOND)); }

Target:
private List<String> extractPortValues(String prefix, Properties properties) { List<String> ret = new ArrayList<>(); List<String> ports = listWithPrefix(prefix, PORTS, properties); if (ports == null) { return null; } List<String[]> parsedPorts = EnvUtil.splitOnLastColon(ports); for (String[] port : parsedPorts) { ret.add(port[1]); } return ret; }
Source:
public Commit ensureExists(RepositoryEntity repositoryEntity, String commitId) { return retrieve(repositoryEntity, commitId).orElseGet(() -> { final Commit commit = new Commit(); final DiffModel diffModel = retrieveDiffModel(repositoryEntity, commitId); commit.setCommitId(commitId); commit.setRepository(repositoryEntity); commit.setComments(Lists.newArrayList()); commit.setPushTime(new Date()); commit.setLinesAdded(diffModel.getLinesAdded()); commit.setLinesRemoved(diffModel.getLinesRemoved()); enhanceCommitSafely(repositoryEntity, commitId, commit); return persist(commit); }); }

Target:
public Commit ensureExists(RepositoryEntity repositoryEntity, String commitId) { return retrieve(repositoryEntity, commitId).orElseGet(() -> { final Commit commit = new Commit(); commit.setCommitId(commitId); commit.setRepository(repositoryEntity); commit.setComments(Lists.newArrayList()); commit.setPushTime(new Date()); enhanceCommitSafely(commit); return persist(commit); }); }
Source:
protected void showLocaleChangeMenu(final CommCareActivityUIController uiController) { final PaneledChoiceDialog dialog = new PaneledChoiceDialog(this, Localization.get("home.menu.locale.select")); AdapterView.OnItemClickListener listClickListener = (parent, view, position, id) -> { String[] localeCodes = ChangeLocaleUtil.getLocaleCodes(); if (position >= localeCodes.length) { Localization.setLocale("default"); } else { String selectedLocale = localeCodes[position]; LocalePreferences.saveCurrentLocale(selectedLocale); Localization.setLocale(selectedLocale); } if (uiController != null) { uiController.setupUI(); } rebuildOptionsMenu(); dismissAlertDialog(); recreate(); }; dialog.setChoiceItems(buildLocaleChoices(), listClickListener); showAlertDialog(dialog); }

Target:
protected void showLocaleChangeMenu(final CommCareActivityUIController uiController) { final PaneledChoiceDialog dialog = new PaneledChoiceDialog(this, Localization.get("home.menu.locale.select")); AdapterView.OnItemClickListener listClickListener = (parent, view, position, id) -> { String[] localeCodes = ChangeLocaleUtil.getLocaleCodes(); if (position >= localeCodes.length) { Localization.setLocale("default"); } else { String selectedLocale = localeCodes[position]; Localization.setLocale(selectedLocale); MainConfigurablePreferences.setCurrentLocale(selectedLocale); } if (uiController != null) { uiController.setupUI(); } rebuildOptionsMenu(); dismissAlertDialog(); }; dialog.setChoiceItems(buildLocaleChoices(), listClickListener); showAlertDialog(dialog); }
Source:
private void writeEmailsIntoTextFile(HashSet<String> studentEmailSet, HashSet<String> instructorEmailSet) { try { File newFile = new File(filePathForSaving + this.getCurrentDateForDisplay() + ".txt"); try (FileOutputStream fos = new FileOutputStream(newFile); OutputStreamWriter osw = new OutputStreamWriter(fos); Writer w = new BufferedWriter(osw)) { int studentEmailCount = 0; if (!studentEmailSet.isEmpty()) { for (String email : studentEmailSet) { if (!shouldIncludeTestData && email.endsWith(".tmt")) { continue; } w.write(email + ","); studentEmailCount++; } } int instructorEmailCount = 0; if (!instructorEmailSet.isEmpty()) { for (String email : instructorEmailSet) { if (!shouldIncludeTestData && email.endsWith(".tmt")) { continue; } w.write(email + ","); instructorEmailCount++; } } System.out.print("Student email num: " + studentEmailCount + "\n"); System.out.print("Instructor email num: " + instructorEmailCount + "\n"); } } catch (IOException e) { System.err.println("Problem writing to the file statsTest.txt"); } }

Target:
private void writeEmailsIntoTextFile(HashSet<String> studentEmailSet, HashSet<String> instructorEmailSet) { try { File newFile = new File(filePathForSaving + this.getCurrentDateForDisplay() + ".txt"); try (Writer w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newFile)))) { int studentEmailCount = 0; for (String email : studentEmailSet) { if (!shouldIncludeTestData && email.endsWith(".tmt")) { continue; } w.write(email + ","); studentEmailCount++; } int instructorEmailCount = 0; for (String email : instructorEmailSet) { if (!shouldIncludeTestData && email.endsWith(".tmt")) { continue; } w.write(email + ","); instructorEmailCount++; } System.out.print("Student email num: " + studentEmailCount + "\n"); System.out.print("Instructor email num: " + instructorEmailCount + "\n"); } } catch (IOException e) { System.err.println("Problem writing to the file statsTest.txt"); } }
Source:
protected void packColumns() { if (fPackDone) { return; } fTable.setRedraw(false); try { TableColumn tableColumns[] = fTable.getColumns(); for (int i = 0; i < tableColumns.length; i++) { final TableColumn column = tableColumns[i]; packSingleColumn(i, column); column.setData(WIDTH, column.getWidth()); } } finally { fTable.setRedraw(true); } fPackDone = true; }

Target:
protected void packColumns() { if (fPackDone) { return; } fTable.setRedraw(false); try { TableColumn tableColumns[] = fTable.getColumns(); for (int i = 0; i < tableColumns.length; i++) { final TableColumn column = tableColumns[i]; packSingleColumn(i, column); column.setData(Key.WIDTH, column.getWidth()); } } finally { fTable.setRedraw(true); } fPackDone = true; }
Source:
public void removeCache(String name, EnumSet<CacheContainerAdmin.AdminFlag> flags) { String cacheMode = findCacheMode(name, false); if (cacheMode == null) { throw new CacheConfigurationException("No such cache"); } final ModelNode cacheRemoveOp = new ModelNode(); cacheRemoveOp.get(OP).set(REMOVE_OPERATION); cacheRemoveOp.get(OP_ADDR).set(rootPath.append(cacheMode, name).toModelNode()); try { ModelNode resp = modelControllerClient.execute(cacheRemoveOp); if (!SUCCESS.equals(resp.get(OUTCOME).asString())) { throw new CacheConfigurationException("Could not remove cache"); } } catch (IOException e) { throw new CacheConfigurationException("Could not remove cache", e); } }

Target:
public void removeCache(String name, EnumSet<CacheContainerAdmin.AdminFlag> flags) { String cacheMode = findCacheMode(name, false); if (cacheMode == null) { throw InfinispanMessages.MESSAGES.nonExistingCache(name); } final ModelNode cacheRemoveOp = new ModelNode(); cacheRemoveOp.get(OP).set(REMOVE_OPERATION); cacheRemoveOp.get(OP_ADDR).set(rootPath.append(cacheMode, name).toModelNode()); try { ModelNode resp = modelControllerClient.execute(cacheRemoveOp); if (!SUCCESS.equals(resp.get(OUTCOME).asString())) { throw InfinispanMessages.MESSAGES.cannotRemoveCache(null, name); } } catch (IOException e) { throw InfinispanMessages.MESSAGES.cannotRemoveCache(e, name); } }
Source:
public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { checkPermission(CONFIGURE); String proposedName = Util.fixEmptyAndTrim(req.getSubmittedForm().getString("name")); Jenkins.checkGoodName(proposedName); Node node = getNode(); if (node == null) { throw new ServletException("No such node " + nodeName); } if ((!proposedName.equals(nodeName)) && Jenkins.getActiveInstance().getNode(proposedName) != null) { throw new FormException(Messages.ComputerSet_SlaveAlreadyExists(proposedName), "name"); } String nExecutors = req.getSubmittedForm().getString("numExecutors"); if (!nExecutors.matches("^(\\d*[1-9]\\d*)$")) { throw new FormException(Messages.Slave_InvalidConfig_Executors(nodeName), "numExecutors"); } Node result = node.reconfigure(req, req.getSubmittedForm()); Jenkins.getInstance().getNodesObject().replaceNode(this.getNode(), result); rsp.sendRedirect2("../" + result.getNodeName() + '/'); }

Target:
public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { checkPermission(CONFIGURE); String proposedName = Util.fixEmptyAndTrim(req.getSubmittedForm().getString("name")); Jenkins.checkGoodName(proposedName); Node node = getNode(); if (node == null) { throw new ServletException("No such node " + nodeName); } if ((!proposedName.equals(nodeName)) && Jenkins.getActiveInstance().getNode(proposedName) != null) { throw new FormException(Messages.ComputerSet_SlaveAlreadyExists(proposedName), "name"); } String nExecutors = req.getSubmittedForm().getString("numExecutors"); if (Integer.parseInt(nExecutors)<=0) { throw new FormException(Messages.Slave_InvalidConfig_Executors(nodeName), "numExecutors"); } Node result = node.reconfigure(req, req.getSubmittedForm()); Jenkins.getInstance().getNodesObject().replaceNode(this.getNode(), result); rsp.sendRedirect2("../" + result.getNodeName() + '/'); }
Source:
private void logToIndexToolOutputTable(byte[] dataRowKey, byte[] indexRowKey, long dataRowTs, long indexRowTs, String errorMsg) { try (Table hTable = ServerUtil.ConnectionFactory.getConnection(ServerUtil.ConnectionType.INDEX_WRITER_CONNECTION, env).getTable(TableName.valueOf(IndexTool.OUTPUT_TABLE_NAME))) { byte[] rowKey = new byte[Long.BYTES]; Bytes.putLong(rowKey, 0, scan.getTimeRange().getMax()); Put put = new Put(rowKey); long scanMaxTs = scan.getTimeRange().getMax(); put.addColumn(IndexTool.OUTPUT_TABLE_COLUMN_FAMILY, IndexTool.DATA_TABLE_NAME_BYTES, scanMaxTs, region.getRegionInfo().getTable().getName()); put.addColumn(IndexTool.OUTPUT_TABLE_COLUMN_FAMILY, IndexTool.INDEX_TABLE_NAME_BYTES, scanMaxTs, indexMaintainer.getIndexTableName()); if (dataRowKey != null) { put.addColumn(IndexTool.OUTPUT_TABLE_COLUMN_FAMILY, IndexTool.DATA_TABLE_ROW_KEY_BYTES, scanMaxTs, dataRowKey); put.addColumn(IndexTool.OUTPUT_TABLE_COLUMN_FAMILY, IndexTool.DATA_TABLE_TS_BYTES, scanMaxTs, Bytes.toBytes(dataRowTs)); } if (indexRowKey != null) { put.addColumn(IndexTool.OUTPUT_TABLE_COLUMN_FAMILY, IndexTool.DATA_TABLE_ROW_KEY_BYTES, scanMaxTs, indexRowKey); put.addColumn(IndexTool.OUTPUT_TABLE_COLUMN_FAMILY, IndexTool.DATA_TABLE_TS_BYTES, scanMaxTs, Bytes.toBytes(indexRowTs)); } put.addColumn(IndexTool.OUTPUT_TABLE_COLUMN_FAMILY, IndexTool.ERROR_MESSAGE_BYTES, scanMaxTs, Bytes.toBytes(errorMsg)); hTable.put(put); } catch (IOException e) { exceptionMessage = "LogToIndexToolOutputTable failed " + e; } }

Target:
private void logToIndexToolOutputTable(byte[] dataRowKey, byte[] indexRowKey, long dataRowTs, long indexRowTs, String errorMsg) { logToIndexToolOutputTable(dataRowKey, indexRowKey, dataRowTs, indexRowTs, errorMsg, null, null); }
Source:
@Test public void connectWithIdnUrl() throws MalformedURLException { URL url = new URL("https://тест.рф"); Connection con = HttpConnection.connect(url, true); String expectedUrl = url.getProtocol() + "://" + IDN.toASCII(url.getHost()) + url.getPath(); assertEquals(expectedUrl, con.request().url().toExternalForm()); }

Target:
@Test public void connectWithIdnUrl() throws MalformedURLException { URL url = new URL("https://тест.рф"); Connection con = HttpConnection.connect(url); String expectedUrl = url.getProtocol() + "://" + IDN.toASCII(url.getHost()) + url.getPath(); assertEquals(expectedUrl, con.request().url().toExternalForm()); }
Source:
public void testDataStalenessCheck() throws NetworkException, InterruptedException { final int numberOfKeys = 3; for (int i = 0; i < numberOfKeys; i++) { parameterWorker.pull(i); } verify(mockSender, times(numberOfKeys)).sendPullMsg(anyString(), anyObject()); for (int i = 0; i < numberOfKeys; i++) { parameterWorker.pull(i); } verify(mockSender, times(numberOfKeys)).sendPullMsg(anyString(), anyObject()); final int oldWorkerClock = workerClock.getWorkerClock(); final int deltaWorkerClock = STALENESS_BOUND + 1; for (int i = 0; i < deltaWorkerClock; i++) { workerClock.clock(); } assertEquals(oldWorkerClock + deltaWorkerClock, workerClock.getWorkerClock()); final int oldGlobalMinimumClock = workerClock.getGlobalMinimumClock(); final int deltaGlobMinClock = 1; final byte[] initClockMsgData = codec.encode(ClockManager.getBroadcastMinClockMessage(oldGlobalMinimumClock + deltaGlobMinClock)); mockAggregationMaster.send(ClockManager.AGGREGATION_CLIENT_NAME, WORKER_ID, initClockMsgData); assertEquals(workerClock.getWorkerClock(), workerClock.getGlobalMinimumClock() + STALENESS_BOUND); for (int i = 0; i < numberOfKeys; i++) { parameterWorker.pull(i); } verify(mockSender, times(2 * numberOfKeys)).sendPullMsg(anyString(), anyObject()); }

Target:
public void testDataStalenessCheck() throws NetworkException, InterruptedException { final int numberOfKeys = 3; for (int i = 0; i < numberOfKeys; i++) { parameterWorker.pull(i); } verify(mockSender, times(numberOfKeys)).sendPullMsg(anyString(), anyObject()); for (int i = 0; i < numberOfKeys; i++) { parameterWorker.pull(i); } verify(mockSender, times(numberOfKeys)).sendPullMsg(anyString(), anyObject()); final int oldWorkerClock = workerClock.getWorkerClock(); final int deltaWorkerClock = STALENESS_BOUND + 1; for (int i = 0; i < deltaWorkerClock; i++) { workerClock.clock(); } assertEquals(oldWorkerClock + deltaWorkerClock, workerClock.getWorkerClock()); final int oldGlobalMinimumClock = workerClock.getGlobalMinimumClock(); final int deltaGlobalMinClock = 1; final byte[] initClockMsgData = codec.encode(ClockManager.getBroadcastMinClockMessage(oldGlobalMinimumClock + deltaGlobalMinClock)); mockAggregationMaster.send(ClockManager.AGGREGATION_CLIENT_NAME, WORKER_ID, initClockMsgData); assertEquals(workerClock.getWorkerClock(), workerClock.getGlobalMinimumClock() + STALENESS_BOUND); for (int i = 0; i < numberOfKeys; i++) { parameterWorker.pull(i); } verify(mockSender, times(2 * numberOfKeys)).sendPullMsg(anyString(), anyObject()); }
Source:
public Builder setClient(CDAClient client) { if (accessToken != null) { throw new IllegalStateException( "Do not set a client, when an access token is already set. Use either space id and " + "a token or a previously created client." ); } if (spaceId != null) { throw new IllegalStateException( "Do not set a client, when a space id is already set. Use either space id and " + "a token or a previously created client." ); } if (environment != null) { throw new IllegalStateException( "Do not set a client, when an environment is already set. User either environment " + "or a previously created client." ); } this.client = client; return this; }

Target:
public Builder setClient(CDAClient client) { if (accessToken != null) { throw new IllegalStateException(format(FIELD_ALREADY_EXISTS, "client", "access token")); } if (spaceId != null) { throw new IllegalStateException(format(FIELD_ALREADY_EXISTS, "client", "space id")); } if (environment != null) { throw new IllegalStateException(format(FIELD_ALREADY_EXISTS, "client", "environment")); } this.client = client; return this; }
Source:
public UpgradeConfirmationModel(final VDS host) { this.host = host; getLatch().setIsAvailable(true); getLatch().setEntity(true); getLatch().setIsChangeable(true); }

Target:
public UpgradeConfirmationModel(final VDS host) { this.host = host; setReboot(new EntityModel<>()); getReboot().setEntity(true); getReboot().setIsAvailable(true); getReboot().setIsChangeable(true); }
Source:
protected void activate(Map<String, Object> properties) { if (properties != null) { String value = (String) properties.get("autoIgnore"); autoIgnore = value == null || !value.toString().equals("false"); } }

Target:
protected void activate(Map<String, Object> properties) { if (properties != null) { Object value = properties.get("autoIgnore"); autoIgnore = value == null || !value.toString().equals("false"); } }
Source:
public <T extends Annotation> Set<T> getInterceptorBindingsByType(Class<T> annotationType) { Preconditions.checkArgumentNotNull(annotationType, "annotationType"); Set<T> result = new HashSet<>(); for (Annotation interceptorBinding : interceptorBindings) { if (interceptorBinding.annotationType().equals(annotationType)) { result.add((T) interceptorBinding); } } return result; }

Target:
public <T extends Annotation> Set<T> getInterceptorBindingsByType(Class<T> annotationType) { Preconditions.checkArgumentNotNull(annotationType, "annotationType"); return interceptorBindings.stream() .filter((annotation) -> annotation.annotationType().equals(annotationType)) .map(annotation -> (T) annotation) .collect(ImmutableSet.collector()); }
Source:
private <T extends HasMetadata> String resolvePlural(Class<T> apiTypeClass) { if (CustomResource.class.isAssignableFrom(apiTypeClass)) { return CustomResourceDefinitionContext.fromCustomResourceType(apiTypeClass).getPlural(); } return Pluralize.toPlural(HasMetadata.getKind(apiTypeClass)).toLowerCase(); }

Target:
private <T extends HasMetadata> String resolvePlural(Class<T> apiTypeClass) { if (CustomResource.class.isAssignableFrom(apiTypeClass)) { return CustomResource.getPlural((Class<? extends CustomResource>)apiTypeClass); } return Pluralize.toPlural(HasMetadata.getKind(apiTypeClass)).toLowerCase(); }
Source:
private void allocate0(long index) { if (index > Integer.MAX_VALUE) { throw new OutOfMemoryError(); } if (index > maxPages) { throw LimitOverflowException.instance().put("Maximum number of pages (").put(maxPages).put(") breached"); } if (index >= pages.size()) { pages.extendAndSet((int) index, Unsafe.malloc(pageSize)); LOG.info().$("new page [size=").$(pageSize).$(']').$(); } cachePageLo = index << bits; cachePageHi = cachePageLo + pageSize; }

Target:
private void allocate0(long index) { if (index > Integer.MAX_VALUE) { throw new OutOfMemoryError(); } if (index > maxPages) { throw LimitOverflowException.instance().put("Maximum number of pages (").put(maxPages).put(") breached in MemoryPages"); } if (index >= pages.size()) { pages.extendAndSet((int) index, Unsafe.malloc(pageSize)); LOG.info().$("new page [size=").$(pageSize).$(']').$(); } cachePageLo = index << bits; cachePageHi = cachePageLo + pageSize; }
Source:
protected JobLaunchingTasklet(MessageBus messageBus, JobDefinitionRepository jobDefinitionRepository, DomainRepository instanceRepository, String jobName, MessageChannel launchingChannel, PublishSubscribeChannel listeningChannel) { Assert.notNull(messageBus, "A message bus is required."); Assert.notNull(jobDefinitionRepository, "A JobDefinitionRepository is required"); Assert.notNull(instanceRepository, "A DomainRepository is required"); Assert.notNull(jobName, "A job name is required"); this.jobName = jobName; this.messageBus = messageBus; this.definitionRepository = jobDefinitionRepository; this.instanceRepository = instanceRepository; this.launchingChannel = launchingChannel; this.listeningChannel = listeningChannel; }

Target:
protected JobLaunchingTasklet(MessageBus messageBus, JobDefinitionRepository jobDefinitionRepository, DomainRepository instanceRepository, String jobName, MessageChannel launchingChannel, PublishSubscribeChannel listeningChannel) { Assert.notNull(messageBus, "A message bus is required"); Assert.notNull(jobDefinitionRepository, "A JobDefinitionRepository is required"); Assert.notNull(instanceRepository, "A DomainRepository is required"); Assert.notNull(jobName, "A job name is required"); this.jobName = jobName; this.messageBus = messageBus; this.definitionRepository = jobDefinitionRepository; this.instanceRepository = instanceRepository; this.launchingChannel = launchingChannel; this.listeningChannel = listeningChannel; }
Source:
public AdvancedXboxButton getXboxButton(XboxButton buttonName) { if (!allocatedButtons.containsKey(buttonName)) { allocatedButtons.put(buttonName, true); } else { assertionManager.assertTrue( !allocatedButtons.get(buttonName), "Button " + buttonName + " has already been allocated!"); } if (buttonName == XboxButton.LeftTrigger || buttonName == XboxButton.RightTrigger) { return new AdvancedXboxAxisButton(this, buttonName, 0.75); } return new AdvancedXboxButton(this, buttonName); }

Target:
public AdvancedXboxButton getXboxButton(XboxButton buttonName) { if (!allocatedButtons.containsKey(buttonName)) { AdvancedXboxButton candidate; if (buttonName == XboxButton.LeftTrigger || buttonName == XboxButton.RightTrigger) { candidate = new AdvancedXboxAxisButton(this, buttonName, 0.75); } else { candidate = new AdvancedXboxButton(this, buttonName); } allocatedButtons.put(buttonName, candidate); } else { assertionManager.assertTrue(false, "Button " + buttonName + " has already been allocated!"); } return allocatedButtons.get(buttonName); }
Source:
static String getCanonicalArchitecture(String arch, boolean softfloat) { arch = arch.toLowerCase().trim(); if ("powerpc".equals(arch)) { arch = "ppc"; } else if ("powerpc64".equals(arch)) { arch = "ppc64"; } else if ("i386".equals(arch) || "i686".equals(arch)) { arch = "x86"; } else if ("x86_64".equals(arch) || "amd64".equals(arch)) { arch = "x86-64"; } if ("ppc64".equals(arch) && "little".equals(System.getProperty("sun.cpu.endian"))) { arch = "ppc64le"; } if("arm".equals(arch) && softfloat) { arch = "armel"; } if ("mips64el".equals(arch)) { arch = "mips64el"; } return arch; }

Target:
static String getCanonicalArchitecture(String arch, boolean softfloat) { arch = arch.toLowerCase().trim(); if ("powerpc".equals(arch)) { arch = "ppc"; } else if ("powerpc64".equals(arch)) { arch = "ppc64"; } else if ("i386".equals(arch) || "i686".equals(arch)) { arch = "x86"; } else if ("x86_64".equals(arch) || "amd64".equals(arch)) { arch = "x86-64"; } if ("ppc64".equals(arch) && "little".equals(System.getProperty("sun.cpu.endian"))) { arch = "ppc64le"; } if("arm".equals(arch) && softfloat) { arch = "armel"; } return arch; }
Source:
private static synchronized ActivationService getActivationService() { if (activationService.get() == null) { setActivationService(); } return activationService.get(); }

Target:
private static synchronized ActivationService getActivationService() { if (activationService.get() == null) { activationService.set(PrivilegedServiceFactory.getInstance(ActivationService.class).getService()); } return activationService.get(); }
Source:
NamesStep(List<DataSource> existingDataSources, Metadata metadata, Resources resources, boolean xa) { super(resources.constants().attributes()); FormItem<String> nameItem = new NameItem(); nameItem.addValidationHandler(value -> { for (DataSource dataSource : existingDataSources) { if (dataSource.getName().equals(value)) { return ValidationResult.invalid(resources.messages().duplicateResource(Names.DATASOURCE)); } } return ValidationResult.OK; }); form = new ModelNodeForm.Builder<DataSource>(Ids.DATA_SOURCE_NAMES_FORM, metadata) .unboundFormItem(nameItem, 0) .include(JNDI_NAME) .onSave((form, changedValues) -> { wizard().getContext().dataSource = new DataSource(nameItem.getValue(), xa); wizard().getContext().dataSource.update(form.getModel()); }) .build(); form.getFormItem(JNDI_NAME).addValidationHandler(value -> value.toString().matches("java:(jboss)?/.*") ? ValidationResult.OK : ValidationResult.invalid("JNDI name has to start with java:/ or java:jboss/") ); registerAttachable(form); }

Target:
NamesStep(List<DataSource> existingDataSources, Metadata metadata, Resources resources, boolean xa) { super(resources.constants().attributes()); FormItem<String> nameItem = new NameItem(); nameItem.addValidationHandler(value -> { for (DataSource dataSource : existingDataSources) { if (dataSource.getName().equals(value)) { return ValidationResult.invalid(resources.messages().duplicateResource(Names.DATASOURCE)); } } return ValidationResult.OK; }); form = new ModelNodeForm.Builder<DataSource>(Ids.DATA_SOURCE_NAMES_FORM, metadata) .unboundFormItem(nameItem, 0) .include(JNDI_NAME) .onSave((form, changedValues) -> { wizard().getContext().dataSource = new DataSource(nameItem.getValue(), xa); wizard().getContext().dataSource.update(form.getModel()); }) .build(); form.getFormItem(JNDI_NAME).addValidationHandler(new PatternValidation.JNDINameValidation()); registerAttachable(form); }
Source:
public void testCheckAndMutate() throws InterruptedException, ExecutionException { AsyncTable<?> table = getTable.get(); int count = 10; CountDownLatch putLatch = new CountDownLatch(count + 1); table.put(new Put(row).addColumn(FAMILY, QUALIFIER, VALUE)).thenRun(() -> putLatch.countDown()); IntStream.range(0, count) .forEach(i -> table.put(new Put(row).addColumn(FAMILY, concat(QUALIFIER, i), VALUE)) .thenRun(() -> putLatch.countDown())); putLatch.await(); AtomicInteger successCount = new AtomicInteger(0); AtomicInteger successIndex = new AtomicInteger(-1); CountDownLatch mutateLatch = new CountDownLatch(count); IntStream.range(0, count).forEach(i -> { RowMutations mutation = new RowMutations(row); try { mutation.add((Mutation) new Delete(row).addColumn(FAMILY, QUALIFIER)); mutation .add((Mutation) new Put(row).addColumn(FAMILY, concat(QUALIFIER, i), concat(VALUE, i))); } catch (IOException e) { throw new UncheckedIOException(e); } table.checkAndMutate(new CheckAndMutate(row) .ifEquals(FAMILY, QUALIFIER, VALUE) .action(mutation)) .thenAccept(x -> { if (x) { successCount.incrementAndGet(); successIndex.set(i); } mutateLatch.countDown(); }); }); mutateLatch.await(); assertEquals(1, successCount.get()); Result result = table.get(new Get(row)).get(); IntStream.range(0, count).forEach(i -> { if (i == successIndex.get()) { assertArrayEquals(concat(VALUE, i), result.getValue(FAMILY, concat(QUALIFIER, i))); } else { assertArrayEquals(VALUE, result.getValue(FAMILY, concat(QUALIFIER, i))); } }); }

Target:
public void testCheckAndMutate() throws InterruptedException, ExecutionException { AsyncTable<?> table = getTable.get(); int count = 10; CountDownLatch putLatch = new CountDownLatch(count + 1); table.put(new Put(row).addColumn(FAMILY, QUALIFIER, VALUE)).thenRun(() -> putLatch.countDown()); IntStream.range(0, count) .forEach(i -> table.put(new Put(row).addColumn(FAMILY, concat(QUALIFIER, i), VALUE)) .thenRun(() -> putLatch.countDown())); putLatch.await(); AtomicInteger successCount = new AtomicInteger(0); AtomicInteger successIndex = new AtomicInteger(-1); CountDownLatch mutateLatch = new CountDownLatch(count); IntStream.range(0, count).forEach(i -> { RowMutations mutation = new RowMutations(row); try { mutation.add((Mutation) new Delete(row).addColumn(FAMILY, QUALIFIER)); mutation .add((Mutation) new Put(row).addColumn(FAMILY, concat(QUALIFIER, i), concat(VALUE, i))); } catch (IOException e) { throw new UncheckedIOException(e); } table.checkAndMutate(CheckAndMutate.newBuilder(row) .ifEquals(FAMILY, QUALIFIER, VALUE) .build(mutation)) .thenAccept(x -> { if (x) { successCount.incrementAndGet(); successIndex.set(i); } mutateLatch.countDown(); }); }); mutateLatch.await(); assertEquals(1, successCount.get()); Result result = table.get(new Get(row)).get(); IntStream.range(0, count).forEach(i -> { if (i == successIndex.get()) { assertArrayEquals(concat(VALUE, i), result.getValue(FAMILY, concat(QUALIFIER, i))); } else { assertArrayEquals(VALUE, result.getValue(FAMILY, concat(QUALIFIER, i))); } }); }
Source:
private Iterable<ThriftStructFieldInfo> getFieldInfos(ThriftStructCodec<?> c) { Class<? extends ThriftStructCodec> klass = c.getClass(); if (isUnion(klass)){ return getFieldInfosForUnion(klass); } else { try { Object r = klass.getMethod("fieldInfos").invoke(c); return JavaConversions$.MODULE$.asJavaIterable((scala.collection.Iterable<ThriftStructFieldInfo>)r); } catch (ReflectiveOperationException e) { throw new ScroogeSchemaConversionException("can not get field Info from: " + c.toString(), e); } } }

Target:
private Iterable<ThriftStructFieldInfo> getFieldInfos(ThriftStructCodec<?> c) { Class<? extends ThriftStructCodec> klass = c.getClass(); if (isUnion(klass)) { return getFieldInfosForUnion(klass); } else { try { Object r = klass.getMethod("fieldInfos").invoke(c); return JavaConversions$.MODULE$.asJavaIterable((scala.collection.Iterable<ThriftStructFieldInfo>) r); } catch (ClassCastException e) { throw new ScroogeSchemaConversionException("can not get field Info from: " + c.toString(), e); } catch (InvocationTargetException e) { throw new ScroogeSchemaConversionException("can not get field Info from: " + c.toString(), e); } catch (NoSuchMethodException e) { throw new ScroogeSchemaConversionException("can not get field Info from: " + c.toString(), e); } catch (IllegalAccessException e) { throw new ScroogeSchemaConversionException("can not get field Info from: " + c.toString(), e); } } }
Source:
public void handleStateChanged(Watcher.Event.KeeperState state) throws Exception { if (state == Watcher.Event.KeeperState.Expired) { LOG.warn("Got session expired event for processor=" + processorId); } }

Target:
public void handleStateChanged(Watcher.Event.KeeperState state) throws Exception { if (state == Watcher.Event.KeeperState.Expired) { LOG.warn("Got session expired event for processor=" + processorId); zkUtils.incGeneration(); if (coordinatorListener != null) { coordinatorListener.onJobModelExpired(); } zkUtils.unregister(); } }
Source:
public HttpResponse doChangePassword( @QueryParameter String password, @QueryParameter String newPassword1, @QueryParameter String newPassword2 ) throws Exception { if ( "".equals(password)) throw new UserError("Wrong current password"); if ( "".equals(newPassword1) || "".equals(newPassword2)) throw new UserError("New password is empty"); if (!newPassword1.equals(newPassword2)) throw new UserError("Password does not match the confirm password"); try { parent.connect(dn,password).close(); } catch (javax.naming.AuthenticationException e) { throw new UserError("Wrong current password"); } Attributes attrs = new BasicAttributes(); attrs.put("userPassword", PasswordUtil.hashPassword(newPassword1)); LdapContext context = parent.connect(); try { context.modifyAttributes(dn,DirContext.REPLACE_ATTRIBUTE,attrs); } finally { context.close(); } LOGGER.info("User "+userId+" changed the password"); return new HttpRedirect("done"); }

Target:
public HttpResponse doChangePassword( @QueryParameter String password, @QueryParameter String newPassword1, @QueryParameter String newPassword2 ) throws Exception { if (fixEmpty(password) == null) throw new UserError("Current password is empty"); if (fixEmpty(newPassword1) == null || fixEmpty(newPassword2) == null) throw new UserError("New password is empty"); if (!newPassword1.equals(newPassword2)) throw new UserError("Password does not match the confirm password"); try { parent.connect(dn,password).close(); } catch (javax.naming.AuthenticationException e) { throw new UserError("Wrong current password"); } Attributes attrs = new BasicAttributes(); attrs.put("userPassword", PasswordUtil.hashPassword(newPassword1)); LdapContext context = parent.connect(); try { context.modifyAttributes(dn,DirContext.REPLACE_ATTRIBUTE,attrs); } finally { context.close(); } LOGGER.info("User "+userId+" changed the password"); return new HttpRedirect("done"); }
Source:
public void checkout(@Nonnull Run<?, ?> build, @Nonnull Launcher launcher, @Nonnull FilePath workspace, @Nonnull TaskListener listener, @CheckForNull File changelogFile, @CheckForNull SCMRevisionState baseline) throws IOException, InterruptedException { final AccurevServer server = getServer(); boolean serverDisabled = server != null && server.isServerDisabled(); if (!serverDisabled) { boolean checkout = AccurevMode.findDelegate(this).checkout(build, launcher, workspace, listener, changelogFile); if (checkout) listener.getLogger().println("Checkout done"); else listener.getLogger().println("Checkout failed"); }else{ listener.getLogger().println("Checkout skipped due to server disabled"); throw new InterruptedException(); } }

Target:
public void checkout(@Nonnull Run<?, ?> build, @Nonnull Launcher launcher, @Nonnull FilePath workspace, @Nonnull TaskListener listener, @CheckForNull File changelogFile, @CheckForNull SCMRevisionState baseline) throws IOException, InterruptedException { boolean checkout = AccurevMode.findDelegate(this).checkout(build, launcher, workspace, listener, changelogFile); if (checkout) listener.getLogger().println("Checkout done"); else listener.getLogger().println("Checkout failed"); }
Source:
public Response toResponse(TMUnavailableException exception) { return Response.status(Response.Status.SERVICE_UNAVAILABLE).build(); }

Target:
public Response toResponse(TMUnavailableException exception) { return Response.status(HttpResponseCodes.SC_SERVICE_UNAVAILABLE).build(); }
Source:
protected Builder() { id("profitbricks-rest") .name("Digital Ocean v2 API") .identityName("Not used for OAuth") .credentialName("Must be oauth2 Bearer Token") .documentation(URI.create("<LINK_0>")) .defaultEndpoint("<LINK_1>") .defaultProperties(ProfitBricksApiMetadata.defaultProperties()) .view(typeToken(ComputeServiceContext.class)) .defaultModules(ImmutableSet.<Class<? extends Module>>builder() .add(OkHttpCommandExecutorServiceModule.class) .build()); }

Target:
protected Builder() { id("profitbricks-rest") .name("ProfitBricks REST API") .identityName("API Username") .credentialName("API Password") .documentation(URI.create("<LINK_0>")) .defaultEndpoint("<LINK_1>") .defaultProperties(ProfitBricksApiMetadata.defaultProperties()) .view(typeToken(ComputeServiceContext.class)) .defaultModules(ImmutableSet.<Class<? extends Module>>builder() .add(OkHttpCommandExecutorServiceModule.class) .add(ProfitBricksHttpApiModule.class) .build()); }
Source:
public boolean isPublic() { return hasModifier(PUBLIC) || (getDeclaringClass().isExtern() && !hasModifier(PRIVATE)); }

Target:
public boolean isPublic() { HaxeClassModel declaringClass = getDeclaringClass(); return hasModifier(PUBLIC) || ((declaringClass.isInterface() || declaringClass.isExtern()) && !hasModifier(PRIVATE)) || isOverriddenPublicMethod() || getDeclaringClass().hasMeta("@:publicFields"); }
Source:
public void shouldReturnDifferentCallHistoryForDifferentTables() throws Exception { final KnoxShellTable table1 = new KnoxShellTable(); final long id1 = KnoxShellTable.getUniqueTableId(); table1.id(id1); KnoxShellTableCallHistory.getInstance().saveCall(id1, new KnoxShellTableCall("class1", "method1", true, Collections.singletonMap("param1", String.class))); final KnoxShellTable table2 = new KnoxShellTable(); final long id2 = KnoxShellTable.getUniqueTableId(); table1.id(id2); KnoxShellTableCallHistory.getInstance().saveCall(id2, new KnoxShellTableCall("class2", "method2", false, Collections.singletonMap("param2", String.class))); assertNotEquals(table1.getCallHistoryList(), table2.getCallHistoryList()); }

Target:
public void shouldReturnDifferentCallHistoryForDifferentTables() throws Exception { final KnoxShellTable table1 = new KnoxShellTable(); KnoxShellTableCallHistory.getInstance().saveCall(table1.getId(), new KnoxShellTableCall("class1", "method1", true, Collections.singletonMap("param1", String.class))); final KnoxShellTable table2 = new KnoxShellTable(); KnoxShellTableCallHistory.getInstance().saveCall(table2.getId(), new KnoxShellTableCall("class2", "method2", false, Collections.singletonMap("param2", String.class))); assertNotEquals(table1.getCallHistoryList(), table2.getCallHistoryList()); }
Source:
protected Promise<? extends T> run(Context context) { _startedAt = System.currentTimeMillis(); Task<T> task = wrap(0); context.run(task); return task; }

Target:
private Promise<? extends T> run(Context context) { _startedAt = System.currentTimeMillis(); Task<T> task = wrap(0); context.run(task); return task; }