auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void scheduleOnDemandRebalance(long delay) { if (_helixManager == null) { logger.warn("Failed to schedule a future pipeline run for cluster {}. Helix manager is null!", _clusterName); return; } long current = System.currentTimeMillis(); long rebalanceTime = current + delay; if (delay > 0) { RebalanceTask preTask = _nextRebalanceTask.get(); if (preTask != null && preTask.getNextRebalanceTime() > current && preTask.getNextRebalanceTime() < rebalanceTime) { return; } } RebalanceTask newTask = new RebalanceTask(_helixManager, ClusterEventType.OnDemandRebalance, rebalanceTime); _onDemandRebalanceTimer.schedule(newTask, delay); logger.info("Scheduled instant pipeline run for cluster {}." , _helixManager.getClusterName()); RebalanceTask preTask = _nextRebalanceTask.getAndSet(newTask); if (preTask != null) { preTask.cancel(); } }

Target:
public void scheduleOnDemandRebalance(long delay) { if (_helixManager == null) { logger.error("Failed to schedule a future pipeline run for cluster {}. Helix manager is null!", _clusterName); return; } long currentTime = System.currentTimeMillis(); long rebalanceTime = currentTime + delay; if (delay > 0) { RebalanceTask preTask = _nextRebalanceTask.get(); if (preTask != null && preTask.getNextRebalanceTime() > currentTime && preTask.getNextRebalanceTime() < rebalanceTime) { return; } } RebalanceTask newTask = new RebalanceTask(_helixManager, ClusterEventType.OnDemandRebalance, rebalanceTime); _onDemandRebalanceTimer.schedule(newTask, delay); logger.info("Scheduled instant pipeline run for cluster {}." , _helixManager.getClusterName()); RebalanceTask preTask = _nextRebalanceTask.getAndSet(newTask); if (preTask != null) { preTask.cancel(); } }
Source:
private void send(String data) { if (socket == null) { try { log.info(String.format("Connecting to ATSD at %s:%s", serverName, port)); socket = recreateSocket(); writer = recreateWriter(socket); } catch (IOException e) { throw new AtsdClientException( String.format("Error while connecting to ATSD at %s:%s", serverName, port), e); } } try { writer.write(data); writer.flush(); return; } catch (Exception e) { log.warn(String.format( "Error while sending commands to ATSD at %s:%s. Trying to reconnect", serverName, port), e); } try { socket = recreateSocket(); writer = recreateWriter(socket); writer.write(data); writer.flush(); } catch (Exception e) { throw new AtsdClientException( String.format("Error while sending command to ATSD at %s:%s", serverName, port), e); } }

Target:
private void send(String data) { if (socket == null) { try { log.info("Connecting to ATSD at {}:{}", serverName, port); socket = recreateSocket(); writer = recreateWriter(socket); } catch (IOException e) { throw new AtsdClientException( String.format("Error while connecting to ATSD at %s:%s", serverName, port), e); } } try { writeData(data); return; } catch (Exception e) { log.warn("Error while sending commands to ATSD at {}:{}. Trying to reconnect", serverName, port, e); } try { socket = recreateSocket(); writer = recreateWriter(socket); writeData(data); } catch (Exception e) { throw new AtsdClientException( String.format("Error while sending command to ATSD at %s:%s", serverName, port), e); } }
Source:
public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.actionSettings: Intent i = new Intent(this, SettingsActivity.class); startActivity(i); return true; case R.id.actionSearchLocal: return true; case R.id.actionLogout: this.showLogoutDialog(); return true; case R.id.syncbutton: boolean syncState = OpenMRS.getInstance().getSyncState(); if (syncState) { OpenMRS.getInstance().setSyncState(false); setSyncButtonState(false); showNoInternetConnectionSnackbar(); ToastUtil.showShortToast(getApplicationContext(), ToastUtil.ToastType.NOTICE, R.string.disconn_server); } else if (NetworkUtils.hasNetwork()) { OpenMRS.getInstance().setSyncState(true); setSyncButtonState(true); Intent intent = new Intent("org.openmrs.mobile.intent.action.SYNC_PATIENTS"); getApplicationContext().sendBroadcast(intent); ToastUtil.showShortToast(getApplicationContext(), ToastUtil.ToastType.NOTICE, R.string.reconn_server); if (PatientDetailsFragment.snackbar != null) { PatientDetailsFragment.snackbar.dismiss(); showInternetConnectionSnackbar(); } if (snackbar != null) { snackbar.dismiss(); showInternetConnectionSnackbar(); } } else { showNoInternetConnectionSnackbar(); } return true; case R.id.actionLocation: if (!locationList.isEmpty()) { locationList.clear(); } Observable<List<Location>> observableList = new LocationDAO().getLocations(); observableList.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(getLocationList()); return true; default: return super.onOptionsItemSelected(item); } }

Target:
public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.actionSettings: Intent i = new Intent(this, SettingsActivity.class); startActivity(i); return true; case R.id.actionSearchLocal: return true; case R.id.actionLogout: this.showLogoutDialog(); return true; case R.id.syncbutton: boolean syncState = OpenMRS.getInstance().getSyncState(); if (syncState) { OpenMRS.getInstance().setSyncState(false); setSyncButtonState(false); showNoInternetConnectionSnackbar(); ToastUtil.showShortToast(getApplicationContext(), ToastUtil.ToastType.NOTICE, R.string.disconn_server); } else if (NetworkUtils.hasNetwork()) { OpenMRS.getInstance().setSyncState(true); setSyncButtonState(true); Intent intent = new Intent("org.openmrs.mobile.intent.action.SYNC_PATIENTS"); getApplicationContext().sendBroadcast(intent); ToastUtil.showShortToast(getApplicationContext(), ToastUtil.ToastType.NOTICE, R.string.reconn_server); if (PatientDetailsFragment.snackbar != null) { PatientDetailsFragment.snackbar.dismiss(); } if (snackbar != null) { snackbar.dismiss(); showConnectedToInternetSnackbar(); } } else { showNoInternetConnectionSnackbar(); } return true; case R.id.actionLocation: if (!locationList.isEmpty()) { locationList.clear(); } Observable<List<Location>> observableList = new LocationDAO().getLocations(); observableList.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(getLocationList()); return true; default: return super.onOptionsItemSelected(item); } }
Source:
protected Matcher getRegexMatcher(String regex, String stringToMatch) { Matcher result = regexMatchers.get(regex); if (result == null) { result = Pattern.compile(regex).matcher(stringToMatch); regexMatchers.put(regex, result); } else { result.reset(stringToMatch); } return result; }

Target:
protected Matcher getRegexMatcher(String regex, String stringToMatch) { final Map<String, Matcher> cache = getRegexCache(); Matcher result = cache.get(regex); if (result == null) { result = Pattern.compile(regex).matcher(stringToMatch); cache.put(regex, result); } else { result.reset(stringToMatch); } return result; }
Source:
private ReportPayload createReportPayload(CosmosAsyncClient cosmosAsyncClient, CosmosDiagnostics cosmosDiagnostics, int statusCode, Integer objectSize, String containerId, String databaseId, OperationType operationType, ResourceType resourceType, ConsistencyLevel consistencyLevel, String metricsName, String unitName) { ReportPayload reportPayload = new ReportPayload(metricsName, unitName); reportPayload.setRegionsContacted(BridgeInternal.getRegionContacted(cosmosDiagnostics).toString()); reportPayload.setConsistency(consistencyLevel == null ? BridgeInternal.getContextClient(cosmosAsyncClient).getConsistencyLevel() : consistencyLevel); if (objectSize != null) { reportPayload.setGreaterThan1Kb(objectSize > 1024); } reportPayload.setDatabasesName(databaseId); reportPayload.setContainerName(containerId); reportPayload.setOperation(operationType); reportPayload.setResource(resourceType); reportPayload.setStatusCode(statusCode); return reportPayload; }

Target:
private ReportPayload createReportPayload(CosmosAsyncClient cosmosAsyncClient, CosmosDiagnostics cosmosDiagnostics, int statusCode, Integer objectSize, String containerId, String databaseId, OperationType operationType, ResourceType resourceType, ConsistencyLevel consistencyLevel, String metricsName, String unitName) { ReportPayload reportPayload = new ReportPayload(metricsName, unitName); reportPayload.setRegionsContacted(BridgeInternal.getRegionsContacted(cosmosDiagnostics).toString()); reportPayload.setConsistency(consistencyLevel == null ? BridgeInternal.getContextClient(cosmosAsyncClient).getConsistencyLevel() : consistencyLevel); if (objectSize != null) { reportPayload.setGreaterThan1Kb(objectSize > ClientTelemetry.ONE_KB_TO_BYTES); } reportPayload.setDatabaseName(databaseId); reportPayload.setContainerName(containerId); reportPayload.setOperation(operationType); reportPayload.setResource(resourceType); reportPayload.setStatusCode(statusCode); return reportPayload; }
Source:
public UpdateTransaction newUpdateTransaction(PartitionUpdate update, WriteContext ctx, int nowInSec) { if (!hasIndexes()) return UpdateTransaction.NO_OP; ArrayList<Index.Indexer> idxrs = new ArrayList<>(); for (Index i : indexes.values()) { Index.Indexer idxr = i.indexerFor(update.partitionKey(), update.columns(), nowInSec, ctx, IndexTransaction.Type.UPDATE); if (idxr != null && isIndexWritable(i)) { idxrs.add(idxr); } } if (idxrs.size() == 0) return UpdateTransaction.NO_OP; else return new WriteTimeTransaction(idxrs.toArray(new Index.Indexer[idxrs.size()])); }

Target:
public UpdateTransaction newUpdateTransaction(PartitionUpdate update, WriteContext ctx, int nowInSec) { if (!hasIndexes()) return UpdateTransaction.NO_OP; ArrayList<Index.Indexer> idxrs = new ArrayList<>(); for (Index i : writableIndexes.values()) { Index.Indexer idxr = i.indexerFor(update.partitionKey(), update.columns(), nowInSec, ctx, IndexTransaction.Type.UPDATE); if (idxr != null) idxrs.add(idxr); } if (idxrs.size() == 0) return UpdateTransaction.NO_OP; else return new WriteTimeTransaction(idxrs.toArray(new Index.Indexer[idxrs.size()])); }
Source:
public void updateFailedLoginCount(UserDTO userToUpdate) throws UserRetrievalException { userDAO.updateFailedLoginCount(userToUpdate.getSubjectName(), userToUpdate.getFailedLoginCount()); String maxLoginsStr = env.getProperty("authMaximumLoginAttempts"); int maxLogins = Integer.parseInt(maxLoginsStr); if (userToUpdate.getFailedLoginCount() == maxLogins) { userToUpdate.setAccountLocked(true); try { userDAO.updateAccountLockedStatus(userToUpdate.getSubjectName(), userToUpdate.isAccountLocked()); sendAccountLockedEmail(userToUpdate); } catch (Exception ex) { LOGGER.error("Unable to set account " + userToUpdate.getSubjectName() + " as locked.", ex); } } }

Target:
public void updateFailedLoginCount(UserDTO userToUpdate) throws UserRetrievalException { userDAO.updateFailedLoginCount(userToUpdate.getSubjectName(), userToUpdate.getFailedLoginCount()); String maxLoginsStr = env.getProperty("authMaximumLoginAttempts"); int maxLogins = Integer.parseInt(maxLoginsStr); if (userToUpdate.getFailedLoginCount() >= maxLogins) { userToUpdate.setAccountLocked(true); try { userDAO.updateAccountLockedStatus(userToUpdate.getSubjectName(), userToUpdate.isAccountLocked()); if (userToUpdate.getFailedLoginCount() == maxLogins) { sendAccountLockedEmail(userToUpdate); } } catch (Exception ex) { LOGGER.error("Unable to set account " + userToUpdate.getSubjectName() + " as locked.", ex); } } }
Source:
public SingleConsole getAvailableConsole(ConsoleProperties baseConsoleProperties) { ConsoleEntry consoleEntry = null; try { consoleEntry = consoleQueue.poll(getMaxWaitingMilliSecond(), TimeUnit.MILLISECONDS); if (consoleEntry == null) { throw processException("no console entry available"); } synchronized (this) { consoleEntry.releaseSocket(); ConsoleCommunicationSetting consoleCommunicationSetting = ConsoleCommunicationSetting.asDefault(); if (config.getInactiveClientTimeOut() > 0) { consoleCommunicationSetting.setInactiveClientTimeOut(config.getInactiveClientTimeOut()); } SingleConsole singleConsole = new SingleConsole(config.getCurrentIP(), consoleEntry.getPort(), consoleCommunicationSetting, baseConsoleProperties, config.getCsvSeparator()); getConsoleInUse().add(singleConsole); return singleConsole; } } catch (Exception e) { if (consoleEntry != null) { consoleQueue.add(consoleEntry); } throw processException("no console entry available"); } }

Target:
public SingleConsole getAvailableConsole(ConsoleProperties baseConsoleProperties) { ConsoleEntry consoleEntry = null; try { consoleEntry = consoleQueue.poll(getMaxWaitingMilliSecond(), TimeUnit.MILLISECONDS); if (consoleEntry == null) { throw processException("no console entry available"); } synchronized (this) { consoleEntry.releaseSocket(); ConsoleCommunicationSetting consoleCommunicationSetting = ConsoleCommunicationSetting.asDefault(); if (config.getInactiveClientTimeOut() > 0) { consoleCommunicationSetting.setInactiveClientTimeOut(config.getInactiveClientTimeOut()); } SingleConsole singleConsole = new SingleConsole(config.getCurrentIP(), consoleEntry.getPort(), consoleCommunicationSetting, baseConsoleProperties); getConsoleInUse().add(singleConsole); singleConsole.setCsvSeparator(config.getCsvSeparator()); return singleConsole; } } catch (Exception e) { if (consoleEntry != null) { consoleQueue.add(consoleEntry); } throw processException("no console entry available"); } }
Source:
public Optional<SchemaIncompatibility> validate(final List<String> jsonPath, final Schema schema) { if (schema instanceof ObjectSchema) { final ObjectSchema objectSchema = (ObjectSchema) schema; if (!objectSchema.getPatternProperties().isEmpty()) { return Optional.of(new ForbiddenAttributeIncompatibility(jsonPathString(jsonPath), this.ATTRIBUTE)); } } return Optional.empty(); }

Target:
public Optional<SchemaIncompatibility> validate(final List<String> jsonPath, final Schema schema) { if (schema instanceof ObjectSchema) { final ObjectSchema objectSchema = (ObjectSchema) schema; if (!objectSchema.getPatternProperties().isEmpty()) { return Optional.of(new ForbiddenAttributeIncompatibility(jsonPathString(jsonPath), PatternPropertiesConstraint.ATTRIBUTE)); } } return Optional.empty(); }
Source:
private CollectionSet getCollectionSet(MonitoredService service, Map<String, Number> entries, String rrdBaseName) { String ifLabel = ""; Map<String, String> ifInfo = new HashMap<>(); if (m_ifLabelDao != null) { ifLabel = m_ifLabelDao.getIfLabel(service.getNodeId(), InetAddressUtils.addr(service.getIpAddr())); if (ifLabel != null) { ifInfo.putAll(m_ifLabelDao.getInterfaceInfoFromIfLabel(service.getNodeId(), ifLabel)); } } LatencyCollectionResource latencyResource = new LatencyCollectionResource(service.getSvcName(), service.getIpAddr(), service.getNodeLocation(), ifLabel, ifInfo); for (final Entry<String, Number> entry : entries.entrySet()) { final String ds = entry.getKey(); final Number value = entry.getValue() != null ? entry.getValue() : Double.NaN; LatencyCollectionAttributeType latencyType = new LatencyCollectionAttributeType(rrdBaseName, ds); latencyResource.addAttribute(new LatencyCollectionAttribute(latencyResource, latencyType, ds, value.doubleValue())); } SingleResourceCollectionSet collectionSet = new SingleResourceCollectionSet(latencyResource, new Date()); collectionSet.setStatus(CollectionStatus.SUCCEEDED); return collectionSet; }

Target:
private CollectionSet getCollectionSet(MonitoredService service, Map<String, Number> entries, String rrdBaseName) { LatencyCollectionResource latencyResource = new LatencyCollectionResource(service.getSvcName(), service.getIpAddr(), service.getNodeLocation()); for (final Entry<String, Number> entry : entries.entrySet()) { final String ds = entry.getKey(); final Number value = entry.getValue() != null ? entry.getValue() : Double.NaN; LatencyCollectionAttributeType latencyType = new LatencyCollectionAttributeType(rrdBaseName, ds); latencyResource.addAttribute(new LatencyCollectionAttribute(latencyResource, latencyType, ds, value.doubleValue())); } SingleResourceCollectionSet collectionSet = new SingleResourceCollectionSet(latencyResource, new Date()); collectionSet.setStatus(CollectionStatus.SUCCEEDED); return collectionSet; }
Source:
private void setupDirectories(PanStampBindingSettings cfg) { File xmlDir = new File(cfg.xmlDir); if (xmlDir.exists() && xmlDir.isDirectory() && xmlDir.canRead()) { File devFile = new File(xmlDir, "devices.xml"); if (devFile.exists() && devFile.canRead() && devFile.isFile()) { network.setDeviceLibrary(new CompoundDeviceLibrary( new FileLibrary(xmlDir), new ClassLoaderLibrary())); logger.info("Configured XML directory to {}", cfg.xmlDir); } else { logger.error( "Devices file in XML directory can not be read", cfg.xmlDir); } } else { logger.error("XML directory can not be read", cfg.xmlDir); } }

Target:
private void setupDirectories(PanStampBindingSettings cfg) { File xmlDir = new File(cfg.xmlDir); if (xmlDir.exists() && xmlDir.isDirectory() && xmlDir.canRead()) { File devFile = new File(xmlDir, "devices.xml"); if (devFile.exists() && devFile.canRead() && devFile.isFile()) { network.setDeviceLibrary(new CompoundDeviceLibrary(new FileLibrary(xmlDir), new ClassLoaderLibrary())); logger.info("Configured XML directory to {}", cfg.xmlDir); } else { logger.error("devices.xml in XML directory can not be read", cfg.xmlDir); } } else { logger.error("XML directory can not be read", cfg.xmlDir); } }
Source:
public static DsRdata parse(final String value) { final Matcher matcher = RDATA_PATTERN.matcher(value); if (!matcher.matches()) { throw new AttributeParseException("Invalid syntax", value); } final int keytag = Integer.parseInt(matcher.group(1)); final int algorithm = Integer.parseInt(matcher.group(2)); final int digestType = Integer.parseInt(matcher.group(3)); final String digestAsHex = StringUtils.deleteWhitespace(matcher.group(4)); if (keytag < 0 || keytag > 65535) { throw new AttributeParseException("Invalid keytag: " + keytag, value); } if (algorithm < 0 || algorithm > 255) { throw new AttributeParseException("Invalid algorithm: " + algorithm, value); } if (digestType < 0 || digestType > 255) { throw new AttributeParseException("Invalid digest type: " + digestType, value); } try { if (!DsRdataDigestType.validateLength(digestType, digestAsHex)) { throw new AttributeParseException("Digest format is invalid for digest type " + digestType + ": ", digestAsHex); } } catch (AttributeParseException e) { throw e; } catch (IllegalArgumentException e) { return new DsRdata(keytag, algorithm, digestType, digestAsHex); } return new DsRdata(keytag, algorithm, digestType, digestAsHex); }

Target:
public static DsRdata parse(final String value) { final Matcher matcher = RDATA_PATTERN.matcher(value); if (!matcher.matches()) { throw new AttributeParseException("Invalid syntax", value); } final int keytag = Integer.parseInt(matcher.group(1)); final int algorithm = Integer.parseInt(matcher.group(2)); final int digestType = Integer.parseInt(matcher.group(3)); final String digestAsHex = StringUtils.deleteWhitespace(matcher.group(4)); if (keytag < 0 || keytag > 65535) { throw new AttributeParseException("Invalid keytag: " + keytag, value); } if (algorithm < 0 || algorithm > 255) { throw new AttributeParseException("Invalid algorithm: " + algorithm, value); } if (digestType < 0 || digestType > 255) { throw new AttributeParseException("Invalid digest type: " + digestType, value); } if(!DsRdataDigestType.validateLengthForKnownTypes(digestType, digestAsHex)) { throw new AttributeParseException("Digest format is invalid for digest type " + digestType + ": ", digestAsHex); } return new DsRdata(keytag, algorithm, digestType, digestAsHex); }
Source:
public static final byte[] hexStringToByteArray(String s) throws DecoderException { return new Hex().decode(s.getBytes()); }

Target:
public static final byte[] hexStringToByteArray(String s) throws DecoderException { return Hex.decodeHex(s.toCharArray()); }
Source:
public synchronized void runInBackground() { Preconditions.checkState(daemon == null); daemon = new Thread(this); daemon.setDaemon(true); daemon.setName("BackgroundSweeper"); daemon.start(); Runtime.getRuntime().addShutdownHook(new Thread(() -> { log.info("Shutting down persistent lock manager"); try { persistentLockManager.shutdown(); log.info("Shutdown complete!"); } catch (Exception e) { log.error("Exception while shutting down", e); } })); }

Target:
public synchronized void runInBackground() { Preconditions.checkState(daemon == null); daemon = new Thread(this); daemon.setDaemon(true); daemon.setName("BackgroundSweeper"); daemon.start(); Runtime.getRuntime().addShutdownHook(new Thread(() -> { log.info("Shutting down persistent lock manager"); try { persistentLockManager.shutdown(); log.info("Shutdown complete!"); } catch (Exception e) { log.warn("An exception occurred while shutting down. This means that we had the backup lock out when" + "the shutdown was triggered, but failed to release it. If this is the case, sweep or backup" + "may fail to take out the lock in future. If this happens consistently, " + "consult the following documentation on how to release the dead lock: " + "<LINK_0>", e); } })); }
Source:
public void testTooManyFetchFailureWhileSuccessFinishing() throws Exception { MockEventHandler eventHandler = new MockEventHandler(); TaskAttemptImpl taImpl = createTaskAttemptImpl(eventHandler); TaskId reducetaskId = MRBuilderUtils.newTaskId(taImpl.getID().getTaskId() .getJobId(), 1, TaskType.REDUCE); TaskAttemptId reduceTAId = MRBuilderUtils.newTaskAttemptId(reducetaskId, 0); taImpl.handle(new TaskAttemptEvent(taImpl.getID(), TaskAttemptEventType.TA_DONE)); assertEquals("Task attempt's internal state is not " + "SUCCESS_FINISHING_CONTAINER", taImpl.getInternalState(), TaskAttemptStateInternal.SUCCESS_FINISHING_CONTAINER); taImpl.handle(new TaskAttemptTooManyFetchFailureEvent(taImpl.getID(), reduceTAId, "Host")); assertEquals("Task attempt is not in FAILED state", taImpl.getState(), TaskAttemptState.FAILED); assertFalse("InternalError occurred", eventHandler.internalError); }

Target:
public void testTooManyFetchFailureWhileSuccessFinishing() throws Exception { MockEventHandler eventHandler = new MockEventHandler(); TaskAttemptImpl taImpl = createTaskAttemptImpl(eventHandler); TaskId reducetaskId = MRBuilderUtils.newTaskId(taImpl.getID().getTaskId() .getJobId(), 1, TaskType.REDUCE); TaskAttemptId reduceTAId = MRBuilderUtils.newTaskAttemptId(reducetaskId, 0); taImpl.handle(new TaskAttemptEvent(taImpl.getID(), TaskAttemptEventType.TA_DONE)); assertEquals("Task attempt's internal state is not " + "SUCCESS_FINISHING_CONTAINER", TaskAttemptStateInternal.SUCCESS_FINISHING_CONTAINER, taImpl.getInternalState()); taImpl.handle(new TaskAttemptTooManyFetchFailureEvent(taImpl.getID(), reduceTAId, "Host")); assertEquals("Task attempt is not in FAILED state", TaskAttemptState.FAILED, taImpl.getState()); assertFalse("InternalError occurred", eventHandler.internalError); }
Source:
public void close() { if (context != null) { MDC.clear(); if (backup != null) { MDC.setContextMap(backup); backup = null; } } }

Target:
public void close() throws IllegalStateException { if (backup == null) { throw new IllegalStateException(getClass().getSimpleName() + " must not be reused and can not be closed more than once"); } MDC.setContextMap(backup); backup = null; }
Source:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } SwitchStatementTree switchStatementTree = (SwitchStatementTree) tree; Optional<CaseLabelTree> defaultLabel = getDefaultLabel(switchStatementTree); if (defaultLabel.isPresent() && !defaultIsLastCase(switchStatementTree)) { reportIssue(defaultLabel.get(), "Move this default to the end of the switch."); } }

Target:
public void visitNode(Tree tree) { SwitchStatementTree switchStatementTree = (SwitchStatementTree) tree; getDefaultLabelAtWrongPosition(switchStatementTree).ifPresent(defaultLabel -> reportIssue(defaultLabel, "Move this default to the end of the switch.")); }
Source:
public void testGetProcessBuilder() throws IOException { String[] command = {"printenv"}; Map<String, String> env = new HashMap<>(); String key = "heron-shell-utils-test-env-key"; String value = "heron-shell-utils-test-env-value"; env.put(key, value); ProcessBuilder pb = ShellUtils.getProcessBuilder(false, command, new File("."), env); Process p = pb.start(); try { p.waitFor(2, TimeUnit.SECONDS); } catch (InterruptedException e) { LOG.log(Level.SEVERE, "Wait interrupted", e); } Assert.assertTrue(p.getInputStream().available() > 0); String output = ShellUtils.inputstreamToString(p.getInputStream()); String entry = String.format("%s=%s", key, value); Assert.assertTrue(output.contains(entry)); }

Target:
public void testGetProcessBuilder() throws IOException, InterruptedException { String[] command = {"printenv"}; Map<String, String> env = new HashMap<>(); String key = "heron-shell-utils-test-env-key"; String value = "heron-shell-utils-test-env-value"; env.put(key, value); ProcessBuilder pb = ShellUtils.getProcessBuilder(false, command, new File("."), env); Process p = pb.start(); p.waitFor(2, TimeUnit.SECONDS); Assert.assertTrue(p.getInputStream().available() > 0); String output = ShellUtils.inputstreamToString(p.getInputStream()); String entry = String.format("%s=%s", key, value); Assert.assertTrue(output.contains(entry)); }
Source:
protected void before(ActionInvocation invocation) throws Exception { invocation.addPreResultListener(this); Map<String, Object> session = ActionContext.getContext().getSession(); if (session == null && autoCreateSession) { session = new SessionMap<>(ServletActionContext.getRequest()); ActionContext.getContext().withSession(session); } if ( session != null) { lock(session, invocation); } String key = getKey(invocation); Map<String, Object> app = ActionContext.getContext().getApplication(); final ValueStack stack = ActionContext.getContext().getValueStack(); LOG.debug("scope interceptor before"); if (application != null) for (String string : application) { Object attribute = app.get(key + string); if (attribute != null) { LOG.debug("Application scoped variable set = {}", string, String.valueOf(attribute)); stack.setValue(string, nullConvert(attribute)); } } if (ActionContext.getContext().getParameters().get(sessionReset).isDefined()) { return; } if (reset) { return; } if (session == null) { LOG.debug("No HttpSession created... Cannot set session scoped variables"); return; } if (this.session != null && (!"start".equals(type))) { for (String string : this.session) { Object attribute = session.get(key + string); if (attribute != null) { LOG.debug("Session scoped variable set = {}", string, String.valueOf(attribute)); stack.setValue(string, nullConvert(attribute)); } } } }

Target:
protected void before(ActionInvocation invocation) throws Exception { invocation.addPreResultListener(this); Map<String, Object> session = ActionContext.getContext().getSession(); if (session == null && autoCreateSession) { session = new SessionMap<>(ServletActionContext.getRequest()); ActionContext.getContext().withSession(session); } if ( session != null) { lock(session, invocation); } String key = getKey(invocation); Map<String, Object> application = ActionContext.getContext().getApplication(); final ValueStack stack = ActionContext.getContext().getValueStack(); LOG.debug("scope interceptor before"); if (this.application != null) for (String string : this.application) { Object attribute = application.get(key + string); if (attribute != null) { LOG.debug("Application scoped variable set = {}", string, String.valueOf(attribute)); stack.setValue(string, nullConvert(attribute)); } } if (ActionContext.getContext().getParameters().get(sessionReset).isDefined()) { return; } if (reset) { return; } if (session == null) { LOG.debug("No HttpSession created... Cannot set session scoped variables"); return; } if (this.session != null && (!"start".equals(type))) { for (String string : this.session) { Object attribute = session.get(key + string); if (attribute != null) { LOG.debug("Session scoped variable set = {}", string, String.valueOf(attribute)); stack.setValue(string, nullConvert(attribute)); } } } }
Source:
private void guardedRun() throws Exception { while (true) { try { for (final byte[] messageBody : stream.messageIterable()) { if (messageBody == null) { log.info("Received null message"); } if (shouldStop.getCount() == 0 || messageBody == null) { break; } log.info("Received incoming message. Size=" + messageBody.length); consumeOneWithRetry(messageBody); parkPaused(); if (shouldStop.getCount() == 0) { break; } } break; } catch (ConsumerTimeoutException cte) { log.info("ConsumerTimeoutException while waiting for data from Kafka. Will retry."); if (shouldStop.getCount() == 0) { break; } parkPaused(); if (shouldStop.getCount() == 0) { break; } continue; } } }

Target:
private void guardedRun() throws Exception { while (true) { try { for (final byte[] messageBody : stream.messageIterable()) { if (shouldStop.getCount() == 0 || messageBody == null) { break; } consumeOneWithRetry(messageBody); parkPaused(); if (shouldStop.getCount() == 0) { break; } } break; } catch (ConsumerTimeoutException cte) { log.info("ConsumerTimeoutException while waiting for data from Kafka. Will retry."); if (shouldStop.getCount() == 0) { break; } parkPaused(); if (shouldStop.getCount() == 0) { break; } continue; } } }
Source:
private void setRadix(int radix) { if (radix > Character.MAX_RADIX) { throw new IllegalArgumentException("radix == " + radix); } if (this.radix != radix) { integerPattern = null; this.radix = radix; } }

Target:
private void setRadix(int radix) { if (radix > Character.MAX_RADIX) { throw new IllegalArgumentException("radix == " + radix); } END Android-added: Complain loudly if a bogus radix is being set. if (this.radix != radix) { integerPattern = null; this.radix = radix; } }
Source:
public Layout build() { this.pageFirstButton = new ToolStripButton("<< Latest Jobs"); this.pageFirstButton.disable(); this.pageFirstButton.addStyleName("navPreviousPaginationButton"); this.pageFirstButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { paginationController.firstPage(); } }); this.pagePreviousButton = new ToolStripButton("< Later Jobs"); this.pagePreviousButton.disable(); this.pagePreviousButton.addStyleName("navPreviousPaginationButton"); this.pagePreviousButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { paginationController.previousPage(); } }); this.pageNextButton = new ToolStripButton("Older Jobs >"); this.pageNextButton.disable(); this.pageNextButton.addStyleName("navNextPaginationButton"); this.pageNextButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { paginationController.nextPage(); } }); this.pageLastButton = new ToolStripButton("Oldest Jobs >>"); this.pageLastButton.disable(); this.pageLastButton.addStyleName("navNextPaginationButton"); this.pageLastButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { paginationController.lastPage(); } }); return buildLayout(); }

Target:
public Layout build() { this.pageFirstButton = new ToolStripButton("<< Newest Jobs"); this.pageFirstButton.disable(); this.pageFirstButton.addStyleName("navPreviousPaginationButton"); this.pageFirstButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { paginationController.firstPage(); } }); this.pagePreviousButton = new ToolStripButton("< Newer Jobs"); this.pagePreviousButton.disable(); this.pagePreviousButton.addStyleName("navPreviousPaginationButton"); this.pagePreviousButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { paginationController.previousPage(); } }); this.pageNextButton = new ToolStripButton("Older Jobs >"); this.pageNextButton.disable(); this.pageNextButton.addStyleName("navNextPaginationButton"); this.pageNextButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { paginationController.nextPage(); } }); this.pageLastButton = new ToolStripButton("Oldest Jobs >>"); this.pageLastButton.disable(); this.pageLastButton.addStyleName("navNextPaginationButton"); this.pageLastButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { paginationController.lastPage(); } }); return buildLayout(); }
Source:
public static String getRuntimeCount(long l) { if (l / 1000 / 1000 > 0) { return l /1000 / 1000 + "ms"; } else if (l / 1000 > 0) { return l / 1000 + "us"; }else { return l + "ns"; } }

Target:
public String getRuntimeCount(long l) { if (l / 1000 / 1000 > 0) { return l /1000 / 1000 + "ms"; } else if (l / 1000 > 0) { return l / 1000 + "us"; }else { return l + "ns"; } }
Source:
public Writer setCharacterStream(long pos) throws SQLException { try { if (isDebugEnabled()) { debugCodeCall("setCharacterStream(" + pos + ");"); } checkClosed(); if (pos != 1) { throw DbException.getInvalidValueException("pos", pos); } if (value.getPrecision() != 0) { throw DbException.getInvalidValueException("length", value.getPrecision()); } final PipedInputStream in = new PipedInputStream(); final Task task = new Task() { @Override public void call() { value = conn.createClob(IOUtils.getReader(in), -1); } }; PipedOutputStream out = new PipedOutputStream(in) { @Override public void close() throws IOException { super.close(); try { task.get(); } catch (Exception e) { throw DbException.convertToIOException(e); } } }; task.execute(); return IOUtils.getBufferedWriter(out); } catch (Exception e) { throw logAndConvert(e); } }

Target:
public Writer setCharacterStream(long pos) throws SQLException { try { if (isDebugEnabled()) { debugCodeCall("setCharacterStream(" + pos + ");"); } checkClosed(); if (pos != 1) { throw DbException.getInvalidValueException("pos", pos); } if (value.getPrecision() != 0) { throw DbException.getInvalidValueException("length", value.getPrecision()); } final JdbcConnection c = conn; final PipedInputStream in = new PipedInputStream(); final Task task = new Task() { @Override public void call() { value = c.createClob(IOUtils.getReader(in), -1); } }; PipedOutputStream out = new PipedOutputStream(in) { @Override public void close() throws IOException { super.close(); try { task.get(); } catch (Exception e) { throw DbException.convertToIOException(e); } } }; task.execute(); return IOUtils.getBufferedWriter(out); } catch (Exception e) { throw logAndConvert(e); } }
Source:
public void removeType(@Nonnull JDefinedClassOrInterface type, boolean permanent) { if (!this.declaredTypes.contains(type)) { throw new RuntimeException("type does not exist"); } if (permanent) { removeItemWithName(type); } declaredTypes.remove(type); }

Target:
public void removeType(@Nonnull JDefinedClassOrInterface type, boolean permanent) { if (!this.declaredTypes.contains(type)) { throw new AssertionError("type does not exist"); } if (permanent) { removeItemWithName(type); } declaredTypes.remove(type); }
Source:
private History mergeOldAndNewHistory(File cacheFile, History histNew, Repository repo) throws HistoryException { History histOld; History history = null; try { histOld = readCache(cacheFile); List<HistoryEntry> listOld = histOld.getHistoryEntries(); if (!listOld.isEmpty()) { RuntimeEnvironment env = RuntimeEnvironment.getInstance(); List<HistoryEntry> listNew = histNew.getHistoryEntries(); ListIterator li = listNew.listIterator(listNew.size()); while (li.hasPrevious()) { listOld.add(0, (HistoryEntry) li.previous()); } history = new History(listOld); if (env.isTagsEnabled() && repo.hasFileBasedTags()) { for (HistoryEntry ent : history.getHistoryEntries()) { ent.setTags(null); } repo.assignTagsInHistory(history); } } } catch (IOException ex) { LOGGER.log(Level.SEVERE, "Cannot open history cache file " + cacheFile.getPath()); } return history; }

Target:
private History mergeOldAndNewHistory(File cacheFile, History histNew, Repository repo) throws HistoryException { History histOld; History history = null; try { histOld = readCache(cacheFile); List<HistoryEntry> listOld = histOld.getHistoryEntries(); if (!listOld.isEmpty()) { RuntimeEnvironment env = RuntimeEnvironment.getInstance(); List<HistoryEntry> listNew = histNew.getHistoryEntries(); ListIterator li = listNew.listIterator(listNew.size()); while (li.hasPrevious()) { listOld.add(0, (HistoryEntry) li.previous()); } history = new History(listOld); if (env.isTagsEnabled() && repo.hasFileBasedTags()) { for (HistoryEntry ent : history.getHistoryEntries()) { ent.setTags(null); } repo.assignTagsInHistory(history); } } } catch (IOException ex) { LOGGER.log(Level.SEVERE, String.format("Cannot open history cache file %s", cacheFile.getPath()), ex); } return history; }
Source:
public void noUpstreamCancelOnCasualChainClose() { AtomicBoolean parentUpstreamCancelled = new AtomicBoolean(false); Flowable.range(1, 10) .doOnCancel(new Action() { @Override public void run() throws Throwable { parentUpstreamCancelled.set(true); } }) .publish(new Function<Flowable<Integer>, Publisher<Integer>>() { @Override public Publisher<Integer> apply(Flowable<Integer> v) throws Exception { return v; } }) .test() .awaitDone(1, TimeUnit.SECONDS); assertFalse("Unnecessary upstream .cancel() call in FlowablePublishMulticast", parentUpstreamCancelled.get()); }

Target:
public void noUpstreamCancelOnCasualChainClose() { AtomicBoolean parentUpstreamCancelled = new AtomicBoolean(false); Flowable.range(1, 10) .doOnCancel(() -> parentUpstreamCancelled.set(true)) .publish(Functions.identity()) .test() .awaitDone(1, TimeUnit.SECONDS); assertFalse("Unnecessary upstream .cancel() call in FlowablePublishMulticast", parentUpstreamCancelled.get()); }
Source:
public void testOpportunistic() throws Exception { Configuration conf = new YarnConfiguration(); conf.setBoolean(YarnConfiguration.NM_PMEM_CHECK_ENABLED, false); conf.setBoolean(YarnConfiguration.NM_VMEM_CHECK_ENABLED, false); String id = "container_01_01"; ContainerId mockContainerId = mock(ContainerId.class); when(mockContainerId.toString()).thenReturn(id); cGroupsMemoryResourceHandler.bootstrap(conf); ContainerTokenIdentifier tokenId = mock(ContainerTokenIdentifier.class); when(tokenId.getExecutionType()).thenReturn(ExecutionType.OPPORTUNISTIC); Container container = mock(Container.class); when(container.getContainerId()).thenReturn(mockContainerId); when(container.getContainerTokenIdentifier()).thenReturn(tokenId); when(container.getResource()).thenReturn(Resource.newInstance(1024, 2)); cGroupsMemoryResourceHandler.preStart(container); verify(mockCGroupsHandler, times(1)) .updateCGroupParam(CGroupsHandler.CGroupController.MEMORY, id, CGroupsHandler.CGROUP_PARAM_MEMORY_SOFT_LIMIT_BYTES, "0M"); verify(mockCGroupsHandler, times(1)) .updateCGroupParam(CGroupsHandler.CGroupController.MEMORY, id, CGroupsHandler.CGROUP_PARAM_MEMORY_SWAPPINESS, "100"); verify(mockCGroupsHandler, times(1)) .updateCGroupParam(CGroupsHandler.CGroupController.MEMORY, id, CGroupsHandler.CGROUP_PARAM_MEMORY_HARD_LIMIT_BYTES, "1024M"); }

Target:
public void testOpportunistic() throws Exception { Configuration conf = new YarnConfiguration(); conf.setBoolean(YarnConfiguration.NM_PMEM_CHECK_ENABLED, false); conf.setBoolean(YarnConfiguration.NM_VMEM_CHECK_ENABLED, false); cGroupsMemoryResourceHandler.bootstrap(conf); ContainerTokenIdentifier tokenId = mock(ContainerTokenIdentifier.class); when(tokenId.getExecutionType()).thenReturn(ExecutionType.OPPORTUNISTIC); Container container = mock(Container.class); String id = "container_01_01"; ContainerId mockContainerId = mock(ContainerId.class); when(mockContainerId.toString()).thenReturn(id); when(container.getContainerId()).thenReturn(mockContainerId); when(container.getContainerTokenIdentifier()).thenReturn(tokenId); when(container.getResource()).thenReturn(Resource.newInstance(1024, 2)); cGroupsMemoryResourceHandler.preStart(container); verify(mockCGroupsHandler, times(1)) .updateCGroupParam(CGroupsHandler.CGroupController.MEMORY, id, CGroupsHandler.CGROUP_PARAM_MEMORY_SOFT_LIMIT_BYTES, "0M"); verify(mockCGroupsHandler, times(1)) .updateCGroupParam(CGroupsHandler.CGroupController.MEMORY, id, CGroupsHandler.CGROUP_PARAM_MEMORY_SWAPPINESS, "100"); verify(mockCGroupsHandler, times(1)) .updateCGroupParam(CGroupsHandler.CGroupController.MEMORY, id, CGroupsHandler.CGROUP_PARAM_MEMORY_HARD_LIMIT_BYTES, "1024M"); }
Source:
public SQLSessionContext createSQLSessionContext() throws StandardException { return new SQLSessionContextImpl(getDataDictionary().getDatabaseDescriptor(dbName, getTransactionCompile()), getInitialDefaultSchemaDescriptor(), getSessionUserId(), defaultRoles, groupuserlist); }

Target:
public SQLSessionContext createSQLSessionContext() { return new SQLSessionContextImpl(databaseDescriptor, getInitialDefaultSchemaDescriptor(), getSessionUserId(), defaultRoles, groupuserlist); }
Source:
public String moveEntity(@CommandParam("The world in which the entity is formed") String worldName, @CommandParam("Id of the entity to be moved") int id) { for (Map.Entry<WorldInfo, EngineEntityPool> entry : entityManager.getWorldPoolsMap().entrySet()) { if (entry.getKey().getTitle().equalsIgnoreCase(worldName)) { if (entityManager.moveToPool(id, entry.getValue())) { return "Entity " + id + " moved to " + entry.getKey().getTitle() + "world"; } else { return id + "could not be moved"; } } } return worldName + " does not exist"; }

Target:
public String moveEntity(@CommandParam("The world in which the entity is formed") String worldName, @CommandParam("Id of the entity to be moved") int id) { for (Map.Entry<WorldInfo, EngineEntityPool> entry : entityManager.getWorldPoolsMap().entrySet()) { if (entry.getKey().getTitle().equalsIgnoreCase(worldName)) { if (entityManager.moveToPool(id, entry.getValue())) { return "Entity " + id + " moved to " + entry.getKey().getTitle() + "world"; } else { return "Entity" + id + "could not be moved"; } } } return worldName + " does not exist"; }
Source:
public boolean isFinished() { try { return gzipStream.available() == 0; } catch (IOException e) { throw new CitrusRuntimeException("Failed to check gzip intput stream availability", e); } }

Target:
public boolean isFinished() { try { return gzipStream.available() == 0; } catch (IOException e) { throw new CitrusRuntimeException("Failed to check gzip input stream availability", e); } }
Source:
public LinkPreviewFunnel(WikipediaApp app) { super(app, SCHEMA_NAME, REV_ID, app.isProdRelease() ? Funnel.SAMPLE_LOG_100 : Funnel.SAMPLE_LOG_ALL); version = PROD_LINK_PREVIEW_VERSION; }

Target:
public LinkPreviewFunnel(WikipediaApp app) { super(app, SCHEMA_NAME, REV_ID, app.isProdRelease() ? Funnel.SAMPLE_LOG_100 : Funnel.SAMPLE_LOG_ALL); }
Source:
private static boolean isQualityGateNameAvailable(Context context, String qualityGateName) throws SQLException { return context.prepareSelect( "SELECT COUNT(*) FROM quality_gates WHERE name = '" + qualityGateName + "'") .get( row -> row.getInt(1) == 0); }

Target:
private static boolean isQualityGateNameAvailable(Context context, String qualityGateName) throws SQLException { return context.prepareSelect( "SELECT COUNT(id) FROM quality_gates WHERE name = '" + qualityGateName + "'") .get( row -> row.getInt(1) == 0); }
Source:
Stream<ExecutionPath> addEdge(ExplodedGraph.Edge edge) { ImmutableList.Builder<JavaFileScannerContext.Location> flowBuilder = ImmutableList.builder(); flowBuilder.addAll(flow); List<JavaFileScannerContext.Location> laFlow = learnedAssociation(edge) .map(la -> flowFromLearnedAssociation(la, edge.parent)) .orElse(ImmutableList.of()); flowBuilder.addAll(laFlow); PSet<Symbol> newTrackSymbols = newTrackedSymbols(edge); SameConstraints newSameConstaints = new SameConstraints(sameConstraints, newTrackSymbols, domains); Set<LearnedConstraint> learnedConstraints = learnedConstraints(edge); List<JavaFileScannerContext.Location> lcFlow = flowFromLearnedConstraints(edge, filterRedundantObjectDomain(learnedConstraints)); flowBuilder.addAll(lcFlow); boolean endOfPath = visitedAllParents(edge) || shouldTerminate(learnedConstraints); if (endOfPath) { flowBuilder.addAll(flowForNullableMethodParameters(edge.parent)); } List<JavaFileScannerContext.Location> currentFlow = flowBuilder.build(); Set<List<JavaFileScannerContext.Location>> yieldsFlows = flowFromYields(edge); return yieldsFlows.stream() .map(yieldFlow -> ImmutableList.<JavaFileScannerContext.Location>builder().addAll(currentFlow).addAll(yieldFlow).build()) .map(f -> new ExecutionPath(edge, visited.add(edge), newTrackSymbols, newSameConstaints, f, endOfPath)); }

Target:
Stream<ExecutionPath> addEdge(ExplodedGraph.Edge edge) { ImmutableList.Builder<JavaFileScannerContext.Location> flowBuilder = ImmutableList.builder(); flowBuilder.addAll(flow); List<JavaFileScannerContext.Location> laFlow = learnedAssociation(edge) .map(la -> flowFromLearnedAssociation(la, edge.parent)) .orElse(ImmutableList.of()); flowBuilder.addAll(laFlow); PSet<Symbol> newTrackSymbols = newTrackedSymbols(edge); SameConstraints newSameConstraints = newTrackSymbols == trackedSymbols ? sameConstraints : new SameConstraints(sameConstraints, newTrackSymbols); Set<LearnedConstraint> learnedConstraints = learnedConstraints(edge); List<JavaFileScannerContext.Location> lcFlow = flowFromLearnedConstraints(edge, filterRedundantObjectDomain(learnedConstraints)); flowBuilder.addAll(lcFlow); boolean endOfPath = visitedAllParents(edge) || shouldTerminate(learnedConstraints); if (endOfPath) { flowBuilder.addAll(flowForNullableMethodParameters(edge.parent)); } List<JavaFileScannerContext.Location> currentFlow = flowBuilder.build(); Set<List<JavaFileScannerContext.Location>> yieldsFlows = flowFromYields(edge); return yieldsFlows.stream() .map(yieldFlow -> ImmutableList.<JavaFileScannerContext.Location>builder().addAll(currentFlow).addAll(yieldFlow).build()) .map(f -> new ExecutionPath(edge, visited.add(edge), newTrackSymbols, newSameConstraints, f, endOfPath)); }