auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
void removeContent(PathAddress address, List<byte[]> hashes) { for (byte[] hash : hashes) { try { if (fileRepository != null) { if(contentRepository != null && contentRepository.hasContent(hash)) { contentRepository.removeContent(ModelContentReference.fromModelAddress(address, hash)); } else { fileRepository.deleteDeployment(ModelContentReference.fromModelAddress(address, hash)); } } } catch (Exception e) { DEPLOYMENT_LOGGER.debugf(e, "Exception occurred removing %s", Arrays.asList(hash)); } } }

Target:
void removeContent(PathAddress address, List<byte[]> hashes) { for (byte[] hash : hashes) { try { if (contentRepository.hasContent(hash)) { contentRepository.removeContent(ModelContentReference.fromModelAddress(address, hash)); } else { fileRepository.deleteDeployment(ModelContentReference.fromModelAddress(address, hash)); } } catch (Exception e) { DEPLOYMENT_LOGGER.debugf(e, "Exception occurred removing %s", Arrays.asList(hash)); } } }
Source:
public void setupServer() throws Exception { Logging.initialize(); server = new TestingPrestoServer( true, ImmutableMap.of("testing-warning-collector.add-warnings", "true", "testing-warning-collector.preloaded-warnings", String.valueOf(PRELOADED_WARNINGS)), null, null, new SqlParserOptions(), ImmutableList.of()); server.installPlugin(new BlackHolePlugin()); server.createCatalog("blackhole", "blackhole"); }

Target:
public void setupServer() throws Exception { server = new TestingPrestoServer( true, ImmutableMap.<String, String>builder() .put("testing-warning-collector.add-warnings", "true") .put("testing-warning-collector.preloaded-warnings", String.valueOf(PRELOADED_WARNINGS)) .build(), null, null, new SqlParserOptions(), ImmutableList.of()); server.installPlugin(new TpchPlugin()); server.createCatalog("tpch", "tpch"); server.installPlugin(new BlackHolePlugin()); server.createCatalog("blackhole", "blackhole"); waitForNodeRefresh(server); }
Source:
private void logExecutorState() { ExecutorStateEvent executorStateEvent = new ExecutorStateEvent(executorService, leaseCoordinator); DiagnosticEventHandler debugHandler = new DiagnosticEventHandler() { @Override public void visit(ExecutorStateEvent event) { log.debug(event.message()); } @Override public void visit(RejectedTaskEvent event) { } }; if (System.currentTimeMillis() >= nextExecutorLogTime) { executorStateEvent.accept(diagnosticEventHandler); nextExecutorLogTime = System.currentTimeMillis() + executorLogIntervalMillis; } else { executorStateEvent.accept(debugHandler); } }

Target:
private void logExecutorState() { ExecutorStateEvent executorStateEvent = diagnosticEventFactory.executorStateEvent(executorService, leaseCoordinator); executorStateEvent.accept(diagnosticEventHandler); }
Source:
public void handle(Request wsRequest, Response wsResponse) { userSession.checkIsSystemAdministrator(); String taskId = wsRequest.mandatoryParam(PARAM_TASK_ID); try (DbSession dbSession = dbClient.openSession(false)) { Optional<CeQueueDto> queueDto = dbClient.ceQueueDao().selectByUuid(dbSession, taskId); queueDto.ifPresent(dto -> { queue.cancel(dbSession, dto); }); } wsResponse.noContent(); }

Target:
public void handle(Request wsRequest, Response wsResponse) { String taskId = wsRequest.mandatoryParam(PARAM_TASK_ID); try (DbSession dbSession = dbClient.openSession(false)) { Optional<CeQueueDto> queueDto = dbClient.ceQueueDao().selectByUuid(dbSession, taskId); queueDto.ifPresent(dto -> { checkPermission(dbSession, dto); queue.cancel(dbSession, dto); }); } wsResponse.noContent(); }
Source:
private boolean runningTaskMustBeResetToPending(InternalTask task, RMProxy rmProxy) { boolean resetToPending; if (rmProxy != null) { NodeSet nodes = task.getExecuterInformation().getNodes(); boolean taskNodesKnownByRM = rmProxy.areNodesKnown(nodes); if (taskNodesKnownByRM) { TaskLauncher launcher = task.getExecuterInformation().getLauncher(); logger.debug("Checking whether task launcher has called its doTask method: " + launcher.getDoTaskInvoked()); if (launcher.getDoTaskInvoked()) { logger.info("Recover running task " + task.getId() + " (" + task.getName() + ") successfully with task launcher " + launcher); resetToPending = false; } else { logger.info(FAIL_TO_RECOVER_RUNNING_TASK_STRING + task.getId() + " (" + task.getName() + ") because its task launcher has not started to execute the task"); resetToPending = true; } } else { logger.info(FAIL_TO_RECOVER_RUNNING_TASK_STRING + task.getId() + " (" + task.getName() + ") because the task's node is not known by the resource manager"); resetToPending = true; } } else { logger.info(FAIL_TO_RECOVER_RUNNING_TASK_STRING + task.getId() + " (" + task.getName() + ") because the resource manager is not reachable"); resetToPending = true; } return resetToPending; }

Target:
private boolean runningTaskMustBeResetToPending(InternalTask task, RMProxy rmProxy) { boolean resetToPending; if (rmProxy != null) { NodeSet nodes = task.getExecuterInformation().getNodes(); boolean taskNodesKnownByRM = rmProxy.areNodesKnown(nodes); if (taskNodesKnownByRM) { TaskLauncher launcher = task.getExecuterInformation().getLauncher(); logger.debug("Checking whether task launcher has called its doTask method: " + launcher.isTaskStarted()); if (launcher.isTaskStarted()) { logger.info("Recover running task " + task.getId() + " (" + task.getName() + ") successfully with task launcher " + launcher); resetToPending = false; } else { logger.info(FAIL_TO_RECOVER_RUNNING_TASK_STRING + task.getId() + " (" + task.getName() + ") because its task launcher has not started to execute the task"); resetToPending = true; } } else { logger.info(FAIL_TO_RECOVER_RUNNING_TASK_STRING + task.getId() + " (" + task.getName() + ") because the task's node is not known by the resource manager"); resetToPending = true; } } else { logger.info(FAIL_TO_RECOVER_RUNNING_TASK_STRING + task.getId() + " (" + task.getName() + ") because the resource manager is not reachable"); resetToPending = true; } return resetToPending; }
Source:
public void testGetAllForNetwork() { List<VDSGroup> result = dao.getAllForNetwork(FixturesTool.NETWORK_ENGINE_2); assertEquals(existingVdsGroups, result); }

Target:
public void testGetAllForNetwork() { List<VDSGroup> result = dao.getAllForNetwork(FixturesTool.NETWORK_ENGINE_2); assertEqualsIgnoreOrder(existingVdsGroups, result); }
Source:
private static Properties loadBuildProperties() { Properties prop = new Properties(); try { prop.load(Update.class.getClassLoader().getResourceAsStream("git.properties")); } catch (IOException e) { log.warn("Failed to load properties file"); } return prop; }

Target:
private static Properties loadBuildProperties() { Properties prop = new Properties(); try(InputStream instream = Update.class.getClassLoader().getResourceAsStream("git.properties")) { prop.load(instream); } catch (IOException e) { log.warn("Failed to load properties file"); } return prop; }
Source:
private Runnable _confirmSignIn(final Map<String, String> signInChallengeResponse, final Callback<SignInResult> callback) { return new Runnable() { @Override public void run() { if (signInState == null) { callback.onError(new IllegalStateException("Cannot call confirmMFA(Map<String, String>, Callback) " + "without initiating sign-in. This call is used for CUSTOM_CHALLENGE sign-in state.")); return; } final CognitoIdentityProviderContinuation detectedContinuation; switch (signInState) { case SMS_MFA: case NEW_PASSWORD_REQUIRED: callback.onError(new IllegalStateException( "Please use confirmSignIn(String, Callback) " + "for SMS_MFA and NEW_PASSWORD_REQUIRED challenges")); case CUSTOM_CHALLENGE: for (final String key : signInChallengeResponse.keySet()) { signInChallengeContinuation.setChallengeResponse(key, signInChallengeResponse.get(key)); } detectedContinuation = signInChallengeContinuation; signInCallback = new InternalCallback<SignInResult>(callback); break; case DONE: detectedContinuation = null; Log.d(TAG, "confirmSignIn called after signIn has succeeded"); break; default: callback.onError(new IllegalStateException("confirmSignIn called on unsupported operation, " + "please file a feature request")); return; } if (detectedContinuation != null) { detectedContinuation.continueTask(); } } }; }

Target:
private Runnable _confirmSignIn(final Map<String, String> signInChallengeResponse, final Callback<SignInResult> callback) { return new Runnable() { @Override public void run() { if (signInState == null) { callback.onError(new IllegalStateException("Cannot call confirmSignIn(Map<String, String>, Callback) " + "without initiating sign-in. This call is used for CUSTOM_CHALLENGE sign-in state.")); return; } final CognitoIdentityProviderContinuation detectedContinuation; switch (signInState) { case SMS_MFA: case NEW_PASSWORD_REQUIRED: callback.onError(new IllegalStateException( "Please use confirmSignIn(String, Callback) " + "for SMS_MFA and NEW_PASSWORD_REQUIRED challenges")); case CUSTOM_CHALLENGE: for (final String key : signInChallengeResponse.keySet()) { signInChallengeContinuation.setChallengeResponse(key, signInChallengeResponse.get(key)); } detectedContinuation = signInChallengeContinuation; signInCallback = new InternalCallback<SignInResult>(callback); break; case DONE: detectedContinuation = null; callback.onError(new IllegalStateException("confirmSignIn called after signIn has succeeded")); break; default: callback.onError(new IllegalStateException("confirmSignIn called on unsupported operation, " + "please file a feature request")); return; } if (detectedContinuation != null) { detectedContinuation.continueTask(); } } }; }
Source:
private void setAllApprovals(ChangeData cd, Map<String, LabelInfo> labels) throws OrmException { Set<Account.Id> allUsers = Sets.newHashSet(); for (PatchSetApproval psa : cd.allApprovals(db)) { allUsers.add(psa.getAccountId()); } Multimap<Account.Id, PatchSetApproval> current = HashMultimap.create(); for (PatchSetApproval a : cd.currentApprovals(db)) { current.put(a.getAccountId(), a); } allUsers.addAll(current.keySet()); for (Account.Id accountId : allUsers) { IdentifiedUser user = userFactory.create(accountId); ChangeControl ctl = control(cd).forUser(user); Map<String, ApprovalInfo> byLabel = Maps.newHashMapWithExpectedSize(labels.size()); for (String name : labels.keySet()) { ApprovalInfo ai = new ApprovalInfo(accountId); accountLoader.put(ai); byLabel.put(name, ai); labels.get(name).addApproval(ai); } for (PatchSetApproval psa : current.get(accountId)) { LabelType lt = labelTypes.byId(psa.getCategoryId().get()); if (lt == null) { continue; } ApprovalInfo info = byLabel.get(lt.getName()); if (info == null) { continue; } PermissionRange range = ctl.getRange(lt.getName()); info.value = range != null ? range.squash(psa.getValue()) : 0; } } }

Target:
private void setAllApprovals(ChangeData cd, Map<String, LabelInfo> labels) throws OrmException { ChangeControl baseCtrl = control(cd); if (baseCtrl == null) { return; } Set<Account.Id> allUsers = Sets.newHashSet(); for (PatchSetApproval psa : cd.allApprovals(db)) { allUsers.add(psa.getAccountId()); } Multimap<Account.Id, PatchSetApproval> current = HashMultimap.create(); for (PatchSetApproval a : cd.currentApprovals(db)) { current.put(a.getAccountId(), a); } for (Account.Id accountId : allUsers) { IdentifiedUser user = userFactory.create(accountId); ChangeControl ctl = baseCtrl.forUser(user); Map<String, ApprovalInfo> byLabel = Maps.newHashMapWithExpectedSize(labels.size()); for (String name : labels.keySet()) { ApprovalInfo ai = approvalInfo(accountId, 0); byLabel.put(name, ai); labels.get(name).addApproval(ai); } for (PatchSetApproval psa : current.get(accountId)) { LabelType lt = labelTypes.byId(psa.getCategoryId().get()); if (lt == null) { continue; } ApprovalInfo info = byLabel.get(lt.getName()); if (info == null) { continue; } PermissionRange range = ctl.getRange(lt.getName()); info.value = range != null ? range.squash(psa.getValue()) : 0; } } }
Source:
public void propagateExceptionToGlobalExceptionHandler() { final Object LOCK = new Object(); Thread.UncaughtExceptionHandler handler = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable ex) { synchronized (LOCK) { propagatedExceptionToGlobalExceptionHandler = true; LOCK.notify(); } } }); propagatedExceptionToGlobalExceptionHandler = false; activity.backgroundThrowException(); waitOn(LOCK, 2000); Assert.assertTrue("Exception should have been caught in the DefaultUncaughtExceptionHandler during @Background call.", propagatedExceptionToGlobalExceptionHandler); Thread.setDefaultUncaughtExceptionHandler(handler); }

Target:
public void propagateExceptionToGlobalExceptionHandler() { final Object LOCK = new Object(); Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable ex) { synchronized (LOCK) { propagatedExceptionToGlobalExceptionHandler = true; LOCK.notify(); } } }); propagatedExceptionToGlobalExceptionHandler = false; activity.backgroundThrowException(); waitOn(LOCK, 2000); Assert.assertTrue("Exception should have been caught in the DefaultUncaughtExceptionHandler during @Background call.", propagatedExceptionToGlobalExceptionHandler); }
Source:
EmbeddedCacheManager smallCacheManager() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.eviction().maxEntries(4); EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(builder); System.out.println("Create small cache manager " + cm); return cm; }

Target:
EmbeddedCacheManager smallCacheManager() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.eviction().maxEntries(4); EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(builder); log.tracef("Create small cache manager %s", cm); return cm; }
Source:
public String getImplementationBeanName() { return configurationSource.getBeanNameGenerator().generateBeanName(definition) + getImplementationPostfix(); }

Target:
public String getImplementationBeanName() { return configurationSource.generateBeanName(definition) + configurationSource.getRepositoryImplementationPostfix().orElse("Impl"); }
Source:
public void shouldGetDiagnosisByUuid() { String uuid = "4e663d66-6b78-11e0-93c3-18a905e044dc"; int diagnosisId = 1; Diagnosis diagnosis = diagnosisDAO.getDiagnosisByUuid(uuid); assertEquals(diagnosisId, (int) diagnosis.getId()); }

Target:
public void shouldGetDiagnosisByUuid() { Diagnosis diagnosis = diagnosisDAO.getDiagnosisByUuid("4e663d66-6b78-11e0-93c3-18a905e044dc"); assertEquals(1, (int) diagnosis.getId()); }
Source:
public URI toURI() throws IOException, InterruptedException { return act(new SecureFileCallable<URI>() { private static final long serialVersionUID = 1L; public URI invoke(File f, VirtualChannel channel) { return f.toPath().toUri(); } }); }

Target:
public URI toURI() throws IOException, InterruptedException { return act(new SecureFileCallable<URI>() { private static final long serialVersionUID = 1L; public URI invoke(File f, VirtualChannel channel) { return f.toURI(); } }); }
Source:
private MessageProcessor getMessageProcessor(final String jmsType) throws JMSException { final MessageProcessor messageProcessor = this.messageProcessors.get(this.getMessageType(jmsType)); if (messageProcessor == null) { LOGGER.error("No message processor found for message type: {}", jmsType); throw new JMSException("Message processor not configured"); } return messageProcessor; }

Target:
private MessageProcessor getMessageProcessor(final String jmsType) throws JMSException { final MessageProcessor messageProcessor = this.messageProcessors.get(this.getMessageType(jmsType)); if (messageProcessor == null) { LOGGER.error("No message processor found in for message type: {}", this.messageProcessorMapName, jmsType); throw new JMSException("Message processor not configured"); } return messageProcessor; }
Source:
StepSprite(BoardView1 boardView1, final MoveStep step, boolean isLastStep) { super(boardView1); this.step = step; this.isLastStep = isLastStep; bounds = new Rectangle(bv.getHexLocation(step.getPosition()), bv.hex_size); image = null; baseScaleImage = null; }

Target:
public StepSprite(BoardView1 boardView1, final MoveStep step, boolean isLastStep) { super(boardView1); this.step = step; this.isLastStep = isLastStep; bounds = new Rectangle(bv.getHexLocation(step.getPosition()), bv.hex_size); image = null; baseScaleImage = null; }
Source:
public Object execute() throws Exception { transactionOperations.execute(status -> { try { final OnmsNode onmsNode = this.nodeDao.get(this.node); if (onmsNode == null) { System.out.printf("Cannot find node with ID/FS:FID=%s.\n", this.node); return null; } final Scope nodeScope = this.entityScopeProvider.getScopeForNode(onmsNode.getId()); final Scope interfaceScope = this.entityScopeProvider.getScopeForInterface(onmsNode.getId(), this.interfaceAddress); final Scope serviceScope = this.entityScopeProvider.getScopeForService(onmsNode.getId(), InetAddressUtils.getInetAddress(this.interfaceAddress), this.serviceName); System.out.printf("---\nMeta-Data for node (id=%d)\n", onmsNode.getId()); printScope(nodeScope); if (this.interfaceAddress != null) { System.out.printf("---\nMeta-Data for interface (ipAddress=%s):\n", this.interfaceAddress); printScope(interfaceScope); } if (this.serviceName != null) { System.out.printf("---\nMeta-Data for service (name=%s):\n", this.serviceName); printScope(serviceScope); } System.out.printf("---\n"); if (!Strings.isNullOrEmpty(this.expression)) { final String result = Interpolator.interpolate(this.expression, new FallbackScope(nodeScope, interfaceScope, serviceScope)); System.out.printf("Input: '%s'\nOutput: '%s'\n", this.expression, result); } return null; } catch (final Exception e) { e.printStackTrace(); } return null; }); return null; }

Target:
public Object execute() throws Exception { sessionUtils.withReadOnlyTransaction(() -> { try { final OnmsNode onmsNode = this.nodeDao.get(this.nodeRef); if (onmsNode == null) { System.out.printf("Cannot find node with ID/FS:FID=%s.\n", this.nodeRef); return null; } final Scope nodeScope = this.entityScopeProvider.getScopeForNode(onmsNode.getId()); final Scope interfaceScope = this.entityScopeProvider.getScopeForInterface(onmsNode.getId(), this.interfaceAddress); final Scope serviceScope = this.entityScopeProvider.getScopeForService(onmsNode.getId(), InetAddressUtils.getInetAddress(this.interfaceAddress), this.serviceName); System.out.printf("---\nMeta-Data for node (id=%d)\n", onmsNode.getId()); printScope(nodeScope); if (this.interfaceAddress != null) { System.out.printf("---\nMeta-Data for interface (ipAddress=%s):\n", this.interfaceAddress); printScope(interfaceScope); } if (this.serviceName != null) { System.out.printf("---\nMeta-Data for service (name=%s):\n", this.serviceName); printScope(serviceScope); } System.out.printf("---\n"); if (!Strings.isNullOrEmpty(this.expression)) { final String result = Interpolator.interpolate(this.expression, new FallbackScope(nodeScope, interfaceScope, serviceScope)); System.out.printf("Input: '%s'\nOutput: '%s'\n", this.expression, result); } return null; } catch (final Exception e) { e.printStackTrace(); } return null; }); return null; }
Source:
private QueryTemplate( String template, String name, Iterable<String> values, Charset charset, CollectionFormat collectionFormat) { super(template, false, true, true, charset); this.name = new Template(name, false, true, false, charset); this.collectionFormat = collectionFormat; this.values = StreamSupport.stream(values.spliterator(), false) .filter(Util::isNotBlank) .collect(Collectors.toList()); if (this.values.isEmpty()) { this.pure = true; } }

Target:
private QueryTemplate( String template, String name, Iterable<String> values, Charset charset, CollectionFormat collectionFormat) { super(template, ExpansionOptions.REQUIRED, EncodingOptions.REQUIRED, true, charset); this.name = new Template(name, ExpansionOptions.ALLOW_UNRESOLVED, EncodingOptions.REQUIRED, false, charset); this.collectionFormat = collectionFormat; this.values = StreamSupport.stream(values.spliterator(), false) .filter(Util::isNotBlank) .collect(Collectors.toList()); if (this.values.isEmpty()) { this.pure = true; } }
Source:
public void requestInterstitialAd(Context context, MediationInterstitialListener mediationInterstitialListener, Bundle serverParameters, MediationAdRequest mediationAdRequest, Bundle mediationExtras) { String[] placements = mediationExtras.getStringArray(VungleExtrasBuilder.EXTRA_ALL_PLACEMENTS); if (placements == null || placements.length == 0) { Log.e(TAG, "Placements should be specified!"); if (mediationInterstitialListener != null) mediationInterstitialListener.onAdFailedToLoad(VungleInterstitialAdapter.this, 0); return; } mMediationInterstitialListener = mediationInterstitialListener; String appId = serverParameters.getString("appid"); mVunglePub = VungleManager.getInstance(appId, placements, context); placementForPlay = mVunglePub.findPlacemnt(mediationExtras); adConfig = VungleExtrasBuilder.adConfigWithNetworkExtras(mediationExtras); mVunglePub.addListener(ID, vungleListener); if (mVunglePub.isInitialized()) { loadAd(); } else { vungleListener.setWaitingInit(true); mVunglePub.init(); } }

Target:
public void requestInterstitialAd(Context context, MediationInterstitialListener mediationInterstitialListener, Bundle serverParameters, MediationAdRequest mediationAdRequest, Bundle mediationExtras) { String[] placements; if (mediationExtras != null) { placements = mediationExtras.getStringArray(VungleExtrasBuilder.EXTRA_ALL_PLACEMENTS); if (placements == null || placements.length == 0) { Log.e(TAG, "Placements should be specified!"); if (mediationInterstitialListener != null) { mediationInterstitialListener.onAdFailedToLoad(VungleInterstitialAdapter.this, AdRequest.ERROR_CODE_INVALID_REQUEST); } return; } } else { Log.e(TAG, "mediationExtras is null."); if (mediationInterstitialListener != null) mediationInterstitialListener.onAdFailedToLoad(VungleInterstitialAdapter.this, AdRequest.ERROR_CODE_INVALID_REQUEST); return; } mMediationInterstitialListener = mediationInterstitialListener; String appId = serverParameters.getString("appid"); mVungleManager = VungleManager.getInstance(appId, placements); placementForPlay = mVungleManager.findPlacemnt(mediationExtras); adConfig = VungleExtrasBuilder.adConfigWithNetworkExtras(mediationExtras); adapterId = ID + String.valueOf(counter); counter++; mVungleManager.addListener(adapterId, vungleListener); if (mVungleManager.isInitialized()) { loadAd(); } else { vungleListener.setWaitingInit(true); mVungleManager.init(context); } }
Source:
public void beforeEachTest() throws Exception { firstResponse = secondResponse = null; blankActivityController = Robolectric.buildActivity(BlankActivity.class).create(); blankActivity = blankActivityController.get(); TestHelpers.beforeTestInitAndCleanup(); OneSignal.setAppContext(blankActivity); }

Target:
public void beforeEachTest() throws Exception { firstResponse = secondResponse = null; TestHelpers.beforeTestInitAndCleanup(); }
Source:
PatchSetSelectBox2(DiffTable table, final DisplaySide side, final Change.Id changeId, final PatchSet.Id revision, String path) { initWidget(uiBinder.createAndBindUi(this)); icon.setTitle(PatchUtil.C.addFileCommentToolTip()); icon.addStyleName(Gerrit.RESOURCES.css().link()); this.table = table; this.side = side; this.sideA = side == DisplaySide.A; this.changeId = changeId; this.path = path; setTitle(PatchUtil.C.addFileCommentByDoubleClick()); addDomHandler(new DoubleClickHandler() { @Override public void onDoubleClick(DoubleClickEvent event) { onIconClick(null); } }, DoubleClickEvent.getType()); RestApi call = ChangeApi.detail(changeId.get()); ChangeList.addOptions(call, EnumSet.of( ListChangesOption.ALL_REVISIONS, ListChangesOption.ALL_COMMITS)); call.get(new GerritCallback<ChangeInfo>() { @Override public void onSuccess(ChangeInfo info) { info.revisions().copyKeysIntoChildren("name"); JsArray<RevisionInfo> list = info.revisions().values(); RevisionInfo.sortRevisionInfoByNumber(list); int selected = 0; if (list.length() > 0 && sideA) { if (list.get(0).commit().parents().length() > 1) { revisionList.addItem(PatchUtil.C.patchBaseAutoMerge()); } else { revisionList.addItem(PatchUtil.C.patchBase()); } } for (int i = 0; i < list.length(); i++) { RevisionInfo r = list.get(i); revisionList.addItem( r._number() + ": " + r.name().substring(0, 6), "" + r._number()); if (revision != null && r._number() == revision.get()) { selected = i + 1; } } if (0 < selected) { idActive = new PatchSet.Id(changeId, selected); revisionList.setSelectedIndex(sideA ? selected : selected - 1); } else if (sideA && selected == 0) { idActive = null; revisionList.setSelectedIndex(0); } } }); }

Target:
PatchSetSelectBox2(DiffTable table, final DisplaySide side, final Change.Id changeId, final PatchSet.Id revision, String path) { initWidget(uiBinder.createAndBindUi(this)); icon.setTitle(PatchUtil.C.addFileCommentToolTip()); icon.addStyleName(Gerrit.RESOURCES.css().link()); this.table = table; this.side = side; this.sideA = side == DisplaySide.A; this.changeId = changeId; this.revision = revision; this.idActive = (sideA && revision == null) ? null : revision; this.path = path; setTitle(PatchUtil.C.addFileCommentByDoubleClick()); addDomHandler(new DoubleClickHandler() { @Override public void onDoubleClick(DoubleClickEvent event) { onIconClick(null); } }, DoubleClickEvent.getType()); }
Source:
public void testBatchRequestEncoding() throws Exception { InstanceInfo instance = InstanceInfoGenerator.takeOne(); List<ReplicationInstance> replicationInstances = new ArrayList<>(); replicationInstances.add(new ReplicationInstance( instance.getAppName(), instance.getId(), System.currentTimeMillis(), null, instance.getStatus().name(), instance, Action.Register )); final ReplicationList replicationList = new ReplicationList(replicationInstances); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(replicationList); ReplicationList decodedValue = decodingCodec.decode(encodedString, ReplicationList.class); assertThat(decodedValue.getReplicationList().size(), is(equalTo(1))); } }; List<CodecWrapper> jsonCodes = Arrays.asList( new CodecWrappers.JacksonJson(), new CodecWrappers.LegacyJacksonJson() ); verifyAllPairs(codingAction, Applications.class, jsonCodes); }

Target:
public void testBatchRequestEncoding() throws Exception { InstanceInfo instance = InstanceInfoGenerator.takeOne(); List<ReplicationInstance> replicationInstances = new ArrayList<>(); replicationInstances.add(new ReplicationInstance( instance.getAppName(), instance.getId(), System.currentTimeMillis(), null, instance.getStatus().name(), instance, Action.Register )); final ReplicationList replicationList = new ReplicationList(replicationInstances); Action2 codingAction = new Action2() { @Override public void call(EncoderWrapper encodingCodec, DecoderWrapper decodingCodec) throws IOException { String encodedString = encodingCodec.encode(replicationList); ReplicationList decodedValue = decodingCodec.decode(encodedString, ReplicationList.class); assertThat(decodedValue.getReplicationList().size(), is(equalTo(1))); } }; List<CodecWrapper> jsonCodes = Arrays.asList( new CodecWrappers.JacksonJson(), new CodecWrappers.LegacyJacksonJson() ); verifyAllPairs(codingAction, ReplicationList.class, jsonCodes); }
Source:
protected void readLedgerMetadata(final long ledgerId, final GenericCallback<LedgerMetadata> readCb, Watcher watcher) { zk.getData(getLedgerPath(ledgerId), watcher, new DataCallback() { @Override public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { if (rc == KeeperException.Code.NONODE.intValue()) { if (LOG.isDebugEnabled()) { LOG.debug("No such ledger: " + ledgerId, KeeperException.create(KeeperException.Code.get(rc), path)); } readCb.operationComplete(BKException.Code.NoSuchLedgerExistsException, null); return; } if (rc != KeeperException.Code.OK.intValue()) { LOG.error("Could not read metadata for ledger: " + ledgerId, KeeperException.create(KeeperException.Code.get(rc), path)); readCb.operationComplete(BKException.Code.ZKException, null); return; } LedgerMetadata metadata; try { metadata = LedgerMetadata.parseConfig(data, new ZkVersion(stat.getVersion()),stat.getCtime()); } catch (IOException e) { LOG.error("Could not parse ledger metadata for ledger: " + ledgerId, e); readCb.operationComplete(BKException.Code.ZKException, null); return; } readCb.operationComplete(BKException.Code.OK, metadata); } }, null); }

Target:
protected void readLedgerMetadata(final long ledgerId, final GenericCallback<LedgerMetadata> readCb, Watcher watcher) { zk.getData(getLedgerPath(ledgerId), watcher, new DataCallback() { @Override public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { if (rc == KeeperException.Code.NONODE.intValue()) { if (LOG.isDebugEnabled()) { LOG.debug("No such ledger: " + ledgerId, KeeperException.create(KeeperException.Code.get(rc), path)); } readCb.operationComplete(BKException.Code.NoSuchLedgerExistsException, null); return; } if (rc != KeeperException.Code.OK.intValue()) { LOG.error("Could not read metadata for ledger: " + ledgerId, KeeperException.create(KeeperException.Code.get(rc), path)); readCb.operationComplete(BKException.Code.ZKException, null); return; } if (stat == null) { LOG.error("Could not parse ledger metadata for ledger: " + ledgerId+". Stat object is null"); readCb.operationComplete(BKException.Code.ZKException, null); return; } LedgerMetadata metadata; try { metadata = LedgerMetadata.parseConfig(data, new ZkVersion(stat.getVersion()), Optional.of(stat.getCtime())); } catch (IOException e) { LOG.error("Could not parse ledger metadata for ledger: " + ledgerId, e); readCb.operationComplete(BKException.Code.ZKException, null); return; } readCb.operationComplete(BKException.Code.OK, metadata); } }, null); }
Source:
public static void toJSON(OutputWriter writer, PipelineSelectionResponse pipelineSelectionResponse) { writer.addChildList("selections", pipelineSelectionResponse.getSelectedPipelines().pipelineList()) .add("blacklist", pipelineSelectionResponse.getSelectedPipelines().isBlacklist()) .addChild("pipelines", pipelineGroupsWriter -> { pipelineSelectionResponse.getPipelineConfigs().forEach(pipelineConfigs -> { List<String> pipelineNames = pipelineConfigs .getPipelines().stream() .map(PipelineConfig::getName) .map(CaseInsensitiveString::toString) .collect(Collectors.toList()); if (!pipelineNames.isEmpty()) { pipelineGroupsWriter.addChildList(pipelineConfigs.getGroup(), pipelineNames); } }); }); }

Target:
public static void toJSON(OutputWriter writer, PipelineSelectionResponse pipelineSelectionResponse) { writer.addChildList("selections", pipelineSelectionResponse.getSelectedPipelines().pipelineList()) .add("blacklist", pipelineSelectionResponse.getSelectedPipelines().isBlacklist()) .addChild("pipelines", pipelineGroupsWriter -> { pipelineSelectionResponse.getPipelineConfigs().forEach(pipelineConfigs -> { List<String> pipelineNames = pipelineConfigs .getPipelines().stream() .map(pipelineConfig -> pipelineConfig.getName().toString()) .collect(Collectors.toList()); if (!pipelineNames.isEmpty()) { pipelineGroupsWriter.addChildList(pipelineConfigs.getGroup(), pipelineNames); } }); }); }
Source:
public void testAmendWithPropertyChange() { DiskImage disk = createDiskImage(); disk.setVolumeFormat(VolumeFormat.COW); disk.setQcowCompat(QcowCompat.QCOW2_V2); disk.setDiskAlias("Test"); disk.setDiskDescription("Test_Desc"); when(diskDao.get(diskImageGuid)).thenReturn(disk); disk.setQcowCompat(QcowCompat.QCOW2_V3); disk.setDiskAlias("New Disk Alias"); command.getParameters().setDiskInfo(disk); initializeCommand(); doNothing().when(command).amendDiskImage(); mockVdsCommandSetVolumeDescription(); command.executeVmCommand(); }

Target:
public void testAmendWithPropertyChange() { DiskImage oldDisk = createDiskImage(); oldDisk.setVolumeFormat(VolumeFormat.COW); oldDisk.setQcowCompat(QcowCompat.QCOW2_V2); oldDisk.setDiskAlias("Test"); oldDisk.setDiskDescription("Test_Desc"); when(diskDao.get(diskImageGuid)).thenReturn(oldDisk); DiskImage newDisk = DiskImage.copyOf(oldDisk); newDisk.setQcowCompat(QcowCompat.QCOW2_V3); newDisk.setDiskAlias("New Disk Alias"); command.getParameters().setDiskInfo(newDisk); initializeCommand(); doNothing().when(command).amendDiskImage(); mockVdsCommandSetVolumeDescription(); command.executeVmCommand(); verify(command, times(1)).amendDiskImage(); verify(command, times(1)).setVolumeDescription(any(DiskImage.class), any(StorageDomain.class)); }
Source:
public void saveOrder_shouldFailIfAnActiveDrugOrderForTheSameConceptAndDrugNonCodedAndCareSettingExists() throws Exception { executeDataSet("org/openmrs/api/include/OrderServiceTest-nonCodedDrugs.xml"); final Patient patient = patientService.getPatient(2); final Concept nonCodedConcept = conceptService.getConcept(5584); DrugOrder duplicateOrder = (DrugOrder) orderService.getOrder(584); assertTrue(duplicateOrder.isActive()); assertEquals(nonCodedConcept, duplicateOrder.getConcept()); DrugOrder drugOrder = new DrugOrder(); drugOrder.setPatient(patient); drugOrder.setCareSetting(orderService.getCareSetting(1)); drugOrder.setConcept(nonCodedConcept); drugOrder.setDrugNonCoded("non coded drug Crocine"); drugOrder.setEncounter(encounterService.getEncounter(6)); drugOrder.setOrderer(providerService.getProvider(1)); drugOrder.setCareSetting(duplicateOrder.getCareSetting()); drugOrder.setDrug(duplicateOrder.getDrug()); drugOrder.setDose(duplicateOrder.getDose()); drugOrder.setDoseUnits(duplicateOrder.getDoseUnits()); drugOrder.setRoute(duplicateOrder.getRoute()); drugOrder.setFrequency(duplicateOrder.getFrequency()); drugOrder.setQuantity(duplicateOrder.getQuantity()); drugOrder.setQuantityUnits(duplicateOrder.getQuantityUnits()); drugOrder.setNumRefills(duplicateOrder.getNumRefills()); expectedException.expect(APIException.class); expectedException.expectMessage("Cannot have more than one active order for the same orderable and care setting"); orderService.saveOrder(drugOrder, null); }

Target:
public void saveOrder_shouldFailIfAnActiveDrugOrderForTheSameConceptAndDrugNonCodedAndCareSettingExists() throws Exception { executeDataSet("org/openmrs/api/include/OrderServiceTest-nonCodedDrugs.xml"); final Concept nonCodedConcept = orderService.getNonCodedDrugConcept(); DrugOrder duplicateOrder = (DrugOrder) orderService.getOrder(584); assertTrue(duplicateOrder.isActive()); assertEquals(nonCodedConcept, duplicateOrder.getConcept()); DrugOrder drugOrder = duplicateOrder.copy(); drugOrder.setDrugNonCoded("non coded drug crocine"); expectedException.expect(APIException.class); expectedException.expectMessage("Cannot have more than one active order for the same orderable and care setting"); orderService.saveOrder(drugOrder, null); }
Source:
private void handleScheduledTask(final ProtocolResponseMessage message) { final ScheduledTask scheduledTask = this.scheduledTaskRepository .findByCorrelationUid(message.getCorrelationUid()); if (scheduledTask == null) { LOGGER.error("Scheduled task for device with correlation uid not found", message.getDeviceIdentification(), message.getCorrelationUid()); return; } if (message.getResult() == ResponseMessageResultType.OK && scheduledTask.getStatus() == ScheduledTaskStatusType.PENDING) { this.domainResponseMessageSender.send(message); } else { if (message.getRetryHeader() != null && message.getRetryHeader().shouldRetry()) { scheduledTask.retryOn(message.getRetryHeader().getScheduledRetryTime()); } else { this.domainResponseMessageSender.send(message); } } this.scheduledTaskRepository.delete(scheduledTask); }

Target:
private void handleScheduledTask(final ProtocolResponseMessage message) { final ScheduledTask scheduledTask = this.scheduledTaskRepository .findByCorrelationUid(message.getCorrelationUid()); if (scheduledTask == null) { LOGGER.error("Scheduled task for device with correlation uid not found", message.getDeviceIdentification(), message.getCorrelationUid()); return; } if (this.messageIsSuccessful(message, scheduledTask)) { this.domainResponseMessageSender.send(message); this.scheduledTaskRepository.delete(scheduledTask); } else { this.handleUnsuccessfulScheduledTask(message, scheduledTask); } }
Source:
private static Set<SequenceSegment> selectReference( final Graph<SequenceSegment> graph, final Sequence reference) { TreeSet<SequenceSegment> segments = new TreeSet<>(); for (SequenceSegment segment : graph.getAllVertices()) { if (segment.getSources().contains(reference)) { segments.add(segment); } } return segments; }

Target:
private static Set<SequenceSegment> selectReference( final Graph<SequenceSegment> graph, final Sequence reference) { Set<SequenceSegment> segments = new TreeSet<>(); for (SequenceSegment segment : graph.getAllVertices()) { if (segment.getSources().contains(reference)) { segments.add(segment); } } return segments; }
Source:
public void get(HttpServletRequest request, ModelMap model) { String currentProfile = Context.getAdministrationService().getGlobalProperty(GlobalProperties.CURRENT_PROFILE); model.addAttribute("currentProfile", currentProfile); model.addAttribute("authorized", authorized()); model = queryParamsToModelAttr(request, model); if(!profileDir.exists()){ model.addAttribute("success", false); model.addAttribute("message", "The Profile Manager directory does not exist. It must reside on " + "/usr/share/buendia/profiles or on a directory specified in openmrs-runtime.properties " + "file under profile_manager.profile_dir directive."); } else { model.addAttribute("profiles", listProfiles()); } }

Target:
public void get(HttpServletRequest request, ModelMap model) { String currentProfile = getCurrentProfile(); model.addAttribute("currentProfile", currentProfile); model.addAttribute("authorized", authorized()); model = queryParamsToModelAttr(request, model); if (!profileDir.exists()) { model.addAttribute("success", false); model.addAttribute("message", "The Profile Manager directory does not exist. It must reside on " + "/usr/share/buendia/profiles or on a directory specified in openmrs-runtime.properties " + "file under profile_manager.profile_dir directive."); } else { model.addAttribute("profiles", listProfiles()); } }
Source:
public Rectangle getBounds() { return syncExec(() -> this.widget.getBounds()); }

Target:
public Rectangle getBounds() { return super.getBounds(); }
Source:
public void GetText() { if (!havePermission) { final SpeechRecognizer me = this; form.runOnUiThread(new Runnable() { @Override public void run() { form.askPermission(Manifest.permission.RECORD_AUDIO, new PermissionResultHandler() { @Override public void HandlePermissionResponse(String permission, boolean granted) { if (granted) { me.havePermission = true; me.GetText(); } else { form.dispatchPermissionDeniedEvent(me, "Start", Manifest.permission.RECORD_AUDIO); } } }); } }); return; } BeforeGettingText(); recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); recognizerIntent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true); initialize(); speechRecognizerController.addListener(this); speechRecognizerController.start(); }

Target:
public void GetText() { if (!havePermission) { final SpeechRecognizer me = this; form.runOnUiThread(new Runnable() { @Override public void run() { form.askPermission(Manifest.permission.RECORD_AUDIO, new PermissionResultHandler() { @Override public void HandlePermissionResponse(String permission, boolean granted) { if (granted) { me.havePermission = true; me.GetText(); } else { form.dispatchPermissionDeniedEvent(me, "GetText", Manifest.permission.RECORD_AUDIO); } } }); } }); return; } BeforeGettingText(); speechRecognizerController.addListener(this); speechRecognizerController.start(); }
Source:
private void fireExpireEventLifetime(CallbackInfo ci) { try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { Sponge.getCauseStackManager().pushCause(this); ExpireEntityEvent event = SpongeEventFactory.createExpireEntityEvent(Sponge.getCauseStackManager().getCurrentCause(), this); SpongeImpl.postEvent(event); Sponge.getCauseStackManager().popCause(); } }

Target:
private void fireExpireEventLifetime(CallbackInfo ci) { try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { frame.pushCause(this); ExpireEntityEvent event = SpongeEventFactory.createExpireEntityEvent(Sponge.getCauseStackManager().getCurrentCause(), this); SpongeImpl.postEvent(event); } }
Source:
public DbUser mapRow(ResultSet rs, int rowNum) throws SQLException { DbUser entity = new DbUser(); entity.setDepartment(rs.getString("department")); entity.setDomain(rs.getString("domain")); entity.setEmail(rs.getString("email")); entity.setGroupNames(new HashSet<String>(Arrays.asList(StringUtils.split(rs.getString("groups"))))); entity.setFirstName(rs.getString("name")); entity.setNote(rs.getString("note")); entity.setNote(rs.getString("note")); entity.setRole(rs.getString("role")); entity.setActive(rs.getBoolean("active")); entity.setLastName(rs.getString("surname")); entity.setId(getGuidDefaultEmpty(rs, "user_id")); entity.setLoginName(rs.getString("username")); entity.setAdmin(rs.getBoolean("last_admin_check_status")); entity.setGroupIds(convertToGuidSet(rs.getString("group_ids"), ',')); entity.setExternalId(rs.getString("external_id")); entity.setNamespace(rs.getString("namespace")); return entity; }

Target:
public DbUser mapRow(ResultSet rs, int rowNum) throws SQLException { DbUser entity = new DbUser(); entity.setDepartment(rs.getString("department")); entity.setDomain(rs.getString("domain")); entity.setEmail(rs.getString("email")); entity.setGroupNames(new HashSet<String>(Arrays.asList(StringUtils.split(rs.getString("groups"), ",")))); entity.setFirstName(rs.getString("name")); entity.setNote(rs.getString("note")); entity.setNote(rs.getString("note")); entity.setRole(rs.getString("role")); entity.setActive(rs.getBoolean("active")); entity.setLastName(rs.getString("surname")); entity.setId(getGuidDefaultEmpty(rs, "user_id")); entity.setLoginName(rs.getString("username")); entity.setAdmin(rs.getBoolean("last_admin_check_status")); entity.setGroupIds(convertToGuidSet(rs.getString("group_ids"), ',')); entity.setExternalId(rs.getString("external_id")); entity.setNamespace(rs.getString("namespace")); return entity; }
Source:
public void initialise() { find("version", UILabel.class).setText(TerasologyVersion.getInstance().getHumanVersion()); WidgetUtil.trySubscribe(this, "singleplayer", button -> { UIScreenLayer screen = getManager().pushScreen("engine:selectGameScreen"); if (screen instanceof SelectGameScreen) { ((SelectGameScreen) screen).setLoadingAsServer(false); } }); WidgetUtil.trySubscribe(this, "multiplayer", button -> { UIScreenLayer screen = getManager().pushScreen("engine:selectGameScreen"); if (screen instanceof SelectGameScreen) { ((SelectGameScreen) screen).setLoadingAsServer(true); } }); WidgetUtil.trySubscribe(this, "join", button -> getManager().pushScreen("engine:joinGameScreen")); WidgetUtil.trySubscribe(this, "settings", button -> getManager().pushScreen("engine:settingsMenuScreen")); WidgetUtil.trySubscribe(this, "exit", button -> engine.shutdown()); }

Target:
public void initialise() { find("version", UILabel.class).setText(TerasologyVersion.getInstance().getHumanVersion()); WidgetUtil.trySubscribe(this, "singleplayer", button -> { getManager().pushScreen("engine:selectGameScreen", SelectGameScreen.class).setLoadingAsServer(false); }); WidgetUtil.trySubscribe(this, "multiplayer", button -> { getManager().pushScreen("engine:selectGameScreen", SelectGameScreen.class).setLoadingAsServer(true); }); WidgetUtil.trySubscribe(this, "join", button -> getManager().pushScreen("engine:joinGameScreen")); WidgetUtil.trySubscribe(this, "settings", button -> getManager().pushScreen("engine:settingsMenuScreen")); WidgetUtil.trySubscribe(this, "exit", button -> engine.shutdown()); }
Source:
void writeRegionEntries(List<WAL.Entry> entries) throws IOException { long startTime = System.nanoTime(); WAL.Entry currentWalEntry = null; try { int editsCount = 0; for (WAL.Entry logEntry : entries) { currentWalEntry = logEntry; filterCellByStore(logEntry); if (!logEntry.getEdit().isEmpty()) { writer.append(logEntry); updateRegionMaximumEditLogSeqNum(logEntry); editsCount++; } else { incrementSkippedEdits(1); } } incrementEdits(editsCount); incrementNanoTime(System.nanoTime() - startTime); } catch (IOException e) { e = e instanceof RemoteException ? ((RemoteException) e).unwrapRemoteException() : e; final String errorMsg = "Failed to write log entry " + currentWalEntry.toString() + " to log"; LOG.error(HBaseMarkers.FATAL, errorMsg, e); updateStatusWithMsg(errorMsg); throw e; } }

Target:
void writeRegionEntries(List<WAL.Entry> entries) throws IOException { long startTime = System.nanoTime(); int editsCount = 0; for (WAL.Entry logEntry : entries) { filterCellByStore(logEntry); if (!logEntry.getEdit().isEmpty()) { try { writer.append(logEntry); } catch (IOException e) { logAndThrowWriterAppendFailure(logEntry, e); } updateRegionMaximumEditLogSeqNum(logEntry); editsCount++; } else { incrementSkippedEdits(1); } } incrementEdits(editsCount); incrementNanoTime(System.nanoTime() - startTime); }
Source:
public void nextLine() { if (!columns.isEmpty()) { out.print(StringUtils.join(columns, columnSeparator)); out.println(); columns.clear(); } }

Target:
public void nextLine() { if (!columns.isEmpty()) { out.print(StringUtils.join(columns, columnSeparator)); out.print('\n'); columns.clear(); } }