auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Bindings createBindings(Entity entity, int depth) { Bindings bindings = new SimpleBindings(); JSObject global = (JSObject) magmaBindings.get("nashorn.global"); JSObject magmaScript = (JSObject) global.getMember(KEY_MAGMA_SCRIPT); JSObject dollarFunction = (JSObject) magmaScript.getMember(KEY_DOLLAR); JSObject bindFunction = (JSObject) dollarFunction.getMember(BIND); Object boundDollar = bindFunction.call(dollarFunction, toScriptEngineValueMap(entity, depth)); bindings.put(KEY_DOLLAR, boundDollar); bindings.put(KEY_NEW_VALUE, magmaScript.getMember(KEY_NEW_VALUE)); bindings.put(KEY_IS_NULL, magmaScript.getMember(KEY_IS_NULL)); return bindings; }

Target:
private Bindings createBindings(Entity entity, int depth) { Bindings bindings = new SimpleBindings(); JSObject global = (JSObject) magmaBindings.get("nashorn.global"); JSObject magmaScript = (JSObject) global.getMember(KEY_MAGMA_SCRIPT); JSObject dollarFunction = (JSObject) magmaScript.getMember(KEY_DOLLAR); JSObject bindFunction = (JSObject) dollarFunction.getMember(BIND); Object boundDollar = bindFunction.call(dollarFunction, toScriptEngineValueMap(entity, depth)); bindings.put(KEY_DOLLAR, boundDollar); bindings.put(KEY_NEW_VALUE, magmaScript.getMember(KEY_NEW_VALUE)); bindings.put(KEY_IS_NULL, magmaScript.getMember(KEY_IS_NULL)); return bindings; }
Source:
public static boolean isVolatile(IType type) { if (type instanceof ICPPReferenceType) { ICPPReferenceType refType = (ICPPReferenceType) type; return isVolatile(refType.getType()); } else if (type instanceof CPPQualifierType) { CPPQualifierType qualifierType = (CPPQualifierType) type; return qualifierType.isVolatile(); } return false; }

Target:
public static boolean isVolatile(IType type) { if (type instanceof ICPPReferenceType) { ICPPReferenceType refType = (ICPPReferenceType) type; return isVolatile(refType.getType()); } return ExpressionTypes.isVolatile(type); }
Source:
public void doAct(StaplerRequest req, StaplerResponse rsp) throws IOException { if(req.hasParameter("dismiss")) { disable(true); rsp.sendRedirect(req.getContextPath()+"/manage"); } else { rsp.sendRedirect(req.getContextPath()+"/pluginManager"); } }

Target:
public void doAct(StaplerRequest req, StaplerResponse rsp) throws IOException { if(req.hasParameter("correct")) { rsp.sendRedirect(req.getContextPath()+"/pluginManager"); } }
Source:
public synchronized void aggregate() { if (selector.getObject() instanceof Number) { histogram.add(((Number) selector.getObject()).doubleValue()); } else { throw new IAE("Expected a number, received " + selector.getObject() + " of type " + selector.getObject()); } }

Target:
public void aggregate() { if (selector.getObject() instanceof Number) { synchronized (this) { histogram.add(((Number) selector.getObject()).doubleValue()); } } else { TDigestSketchUtils.throwExceptionForWrongType(selector); } }
Source:
public static String getDefaultBackingIndexName(String dataStreamName, long generation) { return String.format(Locale.ROOT, ".ds-%s-%06d", dataStreamName, generation); }

Target:
public static String getDefaultBackingIndexName(String dataStreamName, long generation) { return String.format(Locale.ROOT, BACKING_INDEX_PREFIX + "%s-%06d", dataStreamName, generation); }
Source:
private StreamPartitionCountMonitor getPartitionCountMonitor(Config config) { Map<String, SystemAdmin> systemAdmins = new HashMap<>(); JavaSystemConfig sysConfig = new JavaSystemConfig(config); sysConfig.getSystemFactories().entrySet().forEach(entry -> { systemAdmins.put(entry.getKey(), entry.getValue().getAdmin(entry.getKey(), config)); }); StreamMetadataCache streamMetadata = new StreamMetadataCache(Util.javaMapAsScalaMap(systemAdmins), 0, SystemClock.instance()); Set<SystemStream> inputStreamsToMonitor = new TaskConfigJava(config).getAllInputStreams(); try { checkArgument(!inputStreamsToMonitor.isEmpty(), "Input streams can not be empty for a job."); } catch (Exception e) { throw new SamzaException("Input streams to a job can not be empty."); } return new StreamPartitionCountMonitor( inputStreamsToMonitor, streamMetadata, this.metrics, new JobConfig(config).getMonitorPartitionChangeFrequency(), streamsChanged -> { if (this.hasDurableStores) { log.error("Input topic partition count changed in a job with durable state. Failing the job."); this.state.status.set(SamzaApplicationState.SamzaAppStatus.FAILED); } coordinatorException = new PartitionChangeException("Input topic partition count changes detected."); }); }

Target:
private StreamPartitionCountMonitor getPartitionCountMonitor(Config config) { Map<String, SystemAdmin> systemAdmins = new JavaSystemConfig(config).getSystemAdmins(); StreamMetadataCache streamMetadata = new StreamMetadataCache(Util.javaMapAsScalaMap(systemAdmins), 0, SystemClock.instance()); Set<SystemStream> inputStreamsToMonitor = new TaskConfigJava(config).getAllInputStreams(); if (inputStreamsToMonitor.isEmpty()) { throw new SamzaException("Input streams to a job can not be empty."); } return new StreamPartitionCountMonitor( inputStreamsToMonitor, streamMetadata, metrics, new JobConfig(config).getMonitorPartitionChangeFrequency(), streamsChanged -> { if (hasDurableStores) { log.error("Input topic partition count changed in a job with durable state. Failing the job."); state.status = SamzaApplicationState.SamzaAppStatus.FAILED; } coordinatorException = new PartitionChangeException("Input topic partition count changes detected."); }); }
Source:
public void close() throws IOException { orcDataSource.close(); if (writeChecksumBuilder.isPresent()) { WriteChecksum actualChecksum = writeChecksumBuilder.get().build(); validateWrite(validation -> validation.getChecksum().getTotalRowCount() == actualChecksum.getTotalRowCount(), "Invalid row count"); List<Long> columnHashes = actualChecksum.getColumnHashes(); for (int i = 0; i < columnHashes.size(); i++) { int columnIndex = i; validateWrite(validation -> validation.getChecksum().getColumnHashes().get(columnIndex).equals(columnHashes.get(columnIndex)), "Invalid checksum for column %s", columnIndex); } validateWrite(validation -> validation.getChecksum().getStripeHash() == actualChecksum.getStripeHash(), "Invalid stripes checksum"); } if (fileStatisticsValidation.isPresent()) { List<ColumnStatistics> columnStatistics = fileStatisticsValidation.get().build(); writeValidation.get().validateFileStatistics(orcDataSource.getId(), columnStatistics); } for (StreamReader column : streamReaders) { if (column != null) { column.close(); } } }

Target:
public void close() throws IOException { try (Closer closer = Closer.create()) { closer.register(orcDataSource); for (StreamReader column : streamReaders) { if (column != null) { closer.register(() -> column.close()); } } } if (writeChecksumBuilder.isPresent()) { WriteChecksum actualChecksum = writeChecksumBuilder.get().build(); validateWrite(validation -> validation.getChecksum().getTotalRowCount() == actualChecksum.getTotalRowCount(), "Invalid row count"); List<Long> columnHashes = actualChecksum.getColumnHashes(); for (int i = 0; i < columnHashes.size(); i++) { int columnIndex = i; validateWrite(validation -> validation.getChecksum().getColumnHashes().get(columnIndex).equals(columnHashes.get(columnIndex)), "Invalid checksum for column %s", columnIndex); } validateWrite(validation -> validation.getChecksum().getStripeHash() == actualChecksum.getStripeHash(), "Invalid stripes checksum"); } if (fileStatisticsValidation.isPresent()) { List<ColumnStatistics> columnStatistics = fileStatisticsValidation.get().build(); writeValidation.get().validateFileStatistics(orcDataSource.getId(), columnStatistics); } }
Source:
public int getNumberOfPersistedEntries() { long size = CompletionStages.join(persistenceManager.size()); if (size > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } return (int) size; }

Target:
public int getNumberOfPersistedEntries() { long size = CompletionStages.join(persistenceManager.size()); return (int) Math.min(size, Integer.MAX_VALUE); }
Source:
public DockerContainerWatchdog() { super("Docker Container Watchdog Asynchronouse Periodic Work"); this.clock = Clock.systemUTC(); }

Target:
public DockerContainerWatchdog() { super(String.format("%s Asynchronous Periodic Work", DockerContainerWatchdog.class.getSimpleName())); clock = Clock.systemUTC(); }
Source:
public void onTextChanged(CharSequence s, int start, int before, int count) { mEmailInput.setError(null); mLoginGoogleFragment = null; }

Target:
public void onTextChanged(CharSequence s, int start, int before, int count) { mEmailInput.setError(null); isSocialLogin = false; }
Source:
public void testExplicitPropertyMappings() { Map<String, String> properties = new ImmutableMap.Builder<String, String>() .put("exchange.max-buffer-size", "1GB") .put("exchange.concurrent-request-multiplier", "13") .put("exchange.min-error-duration", "13s") .put("exchange.max-error-duration", "33s") .put("exchange.max-response-size", "1MB") .put("exchange.client-threads", "2") .put("exchange.page-buffer-client.max-callback-threads", "16") .put("exchange.acknowledge-pages", "false") .put("exchange.response-size-exponential-moving-average-decaying-alpha", "0.42") .put("exchange.async-page-transport-enabled", "true") .build(); ExchangeClientConfig expected = new ExchangeClientConfig() .setMaxBufferSize(new DataSize(1, Unit.GIGABYTE)) .setConcurrentRequestMultiplier(13) .setMinErrorDuration(new Duration(13, TimeUnit.SECONDS)) .setMaxErrorDuration(new Duration(33, TimeUnit.SECONDS)) .setMaxResponseSize(new DataSize(1, Unit.MEGABYTE)) .setClientThreads(2) .setPageBufferClientMaxCallbackThreads(16) .setAcknowledgePages(false) .setResponseSizeExponentialMovingAverageDecayingAlpha(0.42) .setAsyncPageTransportEnabled(true); assertFullMapping(properties, expected); }

Target:
public void testExplicitPropertyMappings() { Map<String, String> properties = new ImmutableMap.Builder<String, String>() .put("exchange.max-buffer-size", "1GB") .put("exchange.concurrent-request-multiplier", "13") .put("exchange.min-error-duration", "13s") .put("exchange.max-error-duration", "33s") .put("exchange.async-page-transport-timeout", "30s") .put("exchange.max-response-size", "1MB") .put("exchange.client-threads", "2") .put("exchange.page-buffer-client.max-callback-threads", "16") .put("exchange.acknowledge-pages", "false") .put("exchange.response-size-exponential-moving-average-decaying-alpha", "0.42") .put("exchange.async-page-transport-enabled", "true") .build(); ExchangeClientConfig expected = new ExchangeClientConfig() .setMaxBufferSize(new DataSize(1, Unit.GIGABYTE)) .setConcurrentRequestMultiplier(13) .setMinErrorDuration(new Duration(33, TimeUnit.SECONDS)) .setMaxErrorDuration(new Duration(33, TimeUnit.SECONDS)) .setAsyncPageTransportTimeout(new Duration(30, TimeUnit.SECONDS)) .setMaxResponseSize(new DataSize(1, Unit.MEGABYTE)) .setClientThreads(2) .setPageBufferClientMaxCallbackThreads(16) .setAcknowledgePages(false) .setResponseSizeExponentialMovingAverageDecayingAlpha(0.42) .setAsyncPageTransportEnabled(true); assertFullMapping(properties, expected); }
Source:
public void execute(ActivityExecution execution) throws Exception { PvmActivity activity = execution.getActivity(); List<PvmTransition> outgoingTransitions = execution.getActivity().getOutgoingTransitions(); execution.inactivate(); lockConcurrentRoot(execution); List<ActivityExecution> joinedExecutions = execution.findInactiveConcurrentExecutions(activity); List<ActivityExecution> finalExecutions = new ArrayList<ActivityExecution>(); Map<String, List<ActivityExecution>> mappedExecutions = mapExecutionsToTransitions(joinedExecutions, finalExecutions); List<PvmTransition> incomingTransitions = execution.getActivity().getIncomingTransitions(); for (PvmTransition incomingTransition : incomingTransitions) { List<ActivityExecution> sequenceExecutions = mappedExecutions.get(incomingTransition.getId()); if (sequenceExecutions == null || sequenceExecutions.isEmpty()){ break; } else { finalExecutions.add(sequenceExecutions.get(0)); } } int nbrOfExecutionsToJoin = incomingTransitions.size(); int nbrOfExecutionsJoined = finalExecutions.size(); if (nbrOfExecutionsJoined==nbrOfExecutionsToJoin) { log.fine("parallel gateway '"+activity.getId()+"' activates: "+nbrOfExecutionsJoined+" of "+nbrOfExecutionsToJoin+" joined"); execution.takeAll(outgoingTransitions, finalExecutions); } else if (log.isLoggable(Level.FINE)){ log.fine("parallel gateway '"+activity.getId()+"' does not activate: "+nbrOfExecutionsJoined+" of "+nbrOfExecutionsToJoin+" joined"); } }

Target:
public void execute(ActivityExecution execution) throws Exception { PvmActivity activity = execution.getActivity(); List<PvmTransition> outgoingTransitions = execution.getActivity().getOutgoingTransitions(); execution.inactivate(); lockConcurrentRoot(execution); List<ActivityExecution> joinedExecutions = execution.findInactiveConcurrentExecutions(activity); List<ActivityExecution> finalExecutions = new ArrayList<ActivityExecution>(); Map<String, List<ActivityExecution>> mappedExecutions = mapExecutionsToTransitions(joinedExecutions, finalExecutions); List<PvmTransition> incomingTransitions = execution.getActivity().getIncomingTransitions(); int nbrOfExecutionsToJoin = incomingTransitions.size(); for (PvmTransition incomingTransition : incomingTransitions) { if(finalExecutions.size() == nbrOfExecutionsToJoin){ break; } List<ActivityExecution> sequenceExecutions = mappedExecutions.get(incomingTransition.getId()); if (sequenceExecutions != null && !sequenceExecutions.isEmpty()){ finalExecutions.add(sequenceExecutions.get(0)); } } int nbrOfExecutionsJoined = finalExecutions.size(); if (nbrOfExecutionsJoined==nbrOfExecutionsToJoin) { log.fine("parallel gateway '"+activity.getId()+"' activates: "+nbrOfExecutionsJoined+" of "+nbrOfExecutionsToJoin+" joined"); execution.takeAll(outgoingTransitions, finalExecutions); } else if (log.isLoggable(Level.FINE)){ log.fine("parallel gateway '"+activity.getId()+"' does not activate: "+nbrOfExecutionsJoined+" of "+nbrOfExecutionsToJoin+" joined"); } }
Source:
public ConnectedFuzzyContext withThreshold(float threshold) { return this; }

Target:
public ConnectedFuzzyContext withThreshold(float threshold) { termContext.setThreshold( threshold ); return this; }
Source:
public void navigatePrefix(final int offset) { if (getSearchText() == lastSearch_ && lastResults_ != null) { navigateSearchPrefix(offset); } else { server_.searchHistoryArchiveByPrefix( getSearchText(), 20, true, new HistoryCallback(getSearchText(), PopupMode.PopupNone) { @Override public void onResponseReceived(RpcObjectList<HistoryEntry> entries) { super.onResponseReceived(entries); navigateSearchPrefix(offset); } }); } }

Target:
public void navigatePrefix(final int offset) { if (StringUtil.equals(getSearchText(), lastSearch_) && lastResults_ != null) { navigateSearchPrefix(offset); } else { server_.searchHistoryArchiveByPrefix( getSearchText(), 20, true, new HistoryCallback(getSearchText(), PopupMode.PopupNone) { @Override public void onResponseReceived(RpcObjectList<HistoryEntry> entries) { super.onResponseReceived(entries); navigateSearchPrefix(offset); } }); } }
Source:
private void populateUsernameSuggestions(List<String> suggestions) { String usernameOrSelected = getUsernameOrSelected(); List<String> suggestionList = new ArrayList<>(); suggestionList.add(usernameOrSelected); for (String suggestion : suggestions) { if (!TextUtils.equals(suggestion, usernameOrSelected)) { suggestionList.add(suggestion); } } mUsernamesAdapter = new UsernameChangerRecyclerViewAdapter(getActivity(), suggestionList); mUsernamesAdapter.setOnUsernameSelectedListener(UsernameChangerFullScreenDialogFragment.this); mUsernamesAdapter.setSelectedItem(0); mUsernameSelectedIndex = 0; mUsernameSuggestions.setAdapter(mUsernamesAdapter); }

Target:
private void populateUsernameSuggestions(List<String> suggestions) { String usernameOrSelected = getUsernameOrSelected(); List<String> suggestionList = new ArrayList<>(); suggestionList.add(usernameOrSelected); for (String suggestion : suggestions) { if (!TextUtils.equals(suggestion, usernameOrSelected)) { suggestionList.add(suggestion); } } mUsernameSelectedIndex = 0; setUsernameSuggestions(suggestionList); }
Source:
public boolean isPassthrough() { if (isThresholdConfigured()) { InstanceCollectionPartitioner partitioner = getPartitioner(this, SimpleLog.NO_LOG); return !partitioner.usesReferences(); } else if (isPartitionByFeatureTypeConfigured()) { return false; } else { return true; } }

Target:
public boolean isPassthrough() { if (isPartitionByFeatureTypeConfigured()) { return false; } else if (isThresholdConfigured()) { InstanceCollectionPartitioner partitioner = getPartitioner(this, SimpleLog.NO_LOG); return !partitioner.usesReferences(); } else { return true; } }
Source:
private ZkBaseDataAccessor(Builder builder) throws IOException, InvalidRoutingDataException { switch (builder.realmMode) { case MULTI_REALM: _zkClient = new FederatedZkClient(builder.realmAwareZkConnectionConfig, builder.realmAwareZkClientConfig); break; case SINGLE_REALM: _zkClient = SharedZkClientFactory.getInstance() .buildZkClient(builder.realmAwareZkConnectionConfig.createZkConnectionConfig(), builder.realmAwareZkClientConfig.createHelixZkClientConfig()); break; default: throw new HelixException("Invalid RealmMode given: " + builder.realmMode); } _usesExternalZkClient = false; }

Target:
private ZkBaseDataAccessor(Builder builder) { switch (builder.realmMode) { case MULTI_REALM: try { if (builder.zkClientType == ZkClientType.DEDICATED) { _zkClient = DedicatedZkClientFactory.getInstance() .buildZkClient(builder.realmAwareZkConnectionConfig, builder.realmAwareZkClientConfig); } else if (builder.zkClientType == ZkClientType.SHARED) { _zkClient = SharedZkClientFactory.getInstance() .buildZkClient(builder.realmAwareZkConnectionConfig, builder.realmAwareZkClientConfig); } else { _zkClient = new FederatedZkClient(builder.realmAwareZkConnectionConfig, builder.realmAwareZkClientConfig); } } catch (IOException | InvalidRoutingDataException | IllegalStateException e) { throw new HelixException("Not able to connect on multi-realm mode.", e); } break; case SINGLE_REALM: if (builder.zkClientType == ZkClientType.DEDICATED) { _zkClient = DedicatedZkClientFactory.getInstance() .buildZkClient(new HelixZkClient.ZkConnectionConfig(builder.zkAddress), builder.realmAwareZkClientConfig.createHelixZkClientConfig()); } else { _zkClient = SharedZkClientFactory.getInstance() .buildZkClient(new HelixZkClient.ZkConnectionConfig(builder.zkAddress), builder.realmAwareZkClientConfig.createHelixZkClientConfig()); _zkClient .waitUntilConnected(HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS); } break; default: throw new HelixException("Invalid RealmMode given: " + builder.realmMode); } _usesExternalZkClient = false; }
Source:
public MutableClock(Instant instant, ZoneId zone, TemporalAmount changeAmount) { assert instant != null : "instant may not be null"; assert zone != null : "zone may not be null"; assert changeAmount != null : "changeAmount may not be null"; this.instant = instant; this.zone = zone; this.changeAmount = changeAmount; }

Target:
public MutableClock(Instant instant, ZoneId zone, TemporalAmount changeAmount) { this.instant = Objects.requireNonNull(instant,"instant may not be null"); this.zone = Objects.requireNonNull(zone, "zone may not be null"); this.changeAmount = Objects.requireNonNull(changeAmount, "changeAmount may not be null"); }
Source:
public Response importRealm(final RealmRepresentation rep) { RealmManager realmManager = new RealmManager(session); AdminPermissions.realms(session, auth).requireCreateRealm(); logger.debugv("importRealm: {0}", rep.getRealm()); try { RealmModel realm = realmManager.getRealm(rep.getId()); if (realm == null) { realm = realmManager.getRealmByName(rep.getRealm()); } if (realm == null) { realm = realmManager.importRealm(rep); grantPermissionsToRealmCreator(realm); } URI location = AdminRoot.realmsUrl(session.getContext().getUri()).path(realm.getName()).build(); logger.debugv("imported realm success, sending back: {0}", location.toString()); return Response.created(location).build(); } catch (ModelDuplicateException e) { logger.error("Conflict detected", e); return ErrorResponse.exists("Conflict detected. See logs for details"); } catch (PasswordPolicyNotMetException e) { logger.error("Password policy not met for user " + e.getUsername(), e); if (session.getTransactionManager().isActive()) session.getTransactionManager().setRollbackOnly(); return ErrorResponse.error("Password policy not met. See logs for details", Response.Status.BAD_REQUEST); } }

Target:
public Response importRealm(final RealmRepresentation rep) { RealmManager realmManager = new RealmManager(session); AdminPermissions.realms(session, auth).requireCreateRealm(); logger.debugv("importRealm: {0}", rep.getRealm()); try { RealmModel realm = realmManager.getRealm(rep.getId()); if (realm == null) { realm = realmManager.getRealmByName(rep.getRealm()); } if (realm == null) { realm = realmManager.importRealm(rep); grantPermissionsToRealmCreator(realm); } else { logger.debugv("Attempt to import realm that already exists: {0}", realm.getName()); } URI location = AdminRoot.realmsUrl(session.getContext().getUri()).path(realm.getName()).build(); logger.debugv("imported realm success, sending back: {0}", location.toString()); return Response.created(location).build(); } catch (ModelDuplicateException e) { logger.error("Conflict detected", e); return ErrorResponse.exists("Conflict detected. See logs for details"); } catch (PasswordPolicyNotMetException e) { logger.error("Password policy not met for user " + e.getUsername(), e); if (session.getTransactionManager().isActive()) session.getTransactionManager().setRollbackOnly(); return ErrorResponse.error("Password policy not met. See logs for details", Response.Status.BAD_REQUEST); } }
Source:
public void addListener(AsyncCallback<Void> cb) { if (finalAdded) { if (failed) { cb.onFailure(failedThrowable); } else if (remaining.isEmpty()) { cb.onSuccess(null); } else { listeners.add(cb); } } else { listeners.add(cb); } }

Target:
public void addListener(AsyncCallback<Void> cb) { if (!failed && finalAdded && remaining.isEmpty()) { cb.onSuccess(null); } else { handleAdd(cb).onSuccess(null); } }
Source:
public void requestHandleOnCloseTest() throws IOException { doRequestHandleTest(HttpMethod.POST, "close", true); doRequestHandleTest(HttpMethod.GET, "close", true); doRequestHandleTest(HttpMethod.DELETE, "close", true); }

Target:
public void requestHandleOnCloseTest() throws IOException { doRequestHandleTest(HttpMethod.POST, EchoMethodHandler.CLOSE_URI, true); doRequestHandleTest(HttpMethod.GET, EchoMethodHandler.CLOSE_URI, true); doRequestHandleTest(HttpMethod.DELETE, EchoMethodHandler.CLOSE_URI, true); }
Source:
public void onSaveClick() { editView.setError(null); if (call != null) { call.cancel(); } call = new DescriptionEditClient().request(pageTitle, editView.getDescription(), new DescriptionEditClient.Callback() { @Override public void success(@NonNull Call<DescriptionEdit> call) { editView.setSaveState(false); if (getActivity() != null) { DeviceUtil.hideSoftKeyboard(getActivity()); getActivity().finish(); } } @Override public void abusefilter(@NonNull Call<DescriptionEdit> call, boolean disallowed) { if (disallowed) { } else { } } @Override public void failure(@NonNull Call<DescriptionEdit> call, @NonNull Throwable caught) { editView.setSaveState(false); editView.setError(caught.getMessage()); } }); }

Target:
public void onSaveClick() { editView.setError(null); editView.setSaveState(true); if (call != null) { call.cancel(); } call = new DescriptionEditClient().request(pageTitle, editView.getDescription(), new DescriptionEditClient.Callback() { @Override public void success(@NonNull Call<DescriptionEdit> call) { if (getActivity() != null) { DeviceUtil.hideSoftKeyboard(getActivity()); getActivity().finish(); } } @Override public void abusefilter(@NonNull Call<DescriptionEdit> call, boolean disallowed) { if (disallowed) { } else { } } @Override public void failure(@NonNull Call<DescriptionEdit> call, @NonNull Throwable caught) { editView.setSaveState(false); editView.setError(caught.getMessage()); } }); }
Source:
public void testConnectATMode() throws Exception { PowerMockito.doReturn(XBeeMode.AT).when(xbeeDevice, "determineConnectionMode"); try { xbeeDevice.connect(); } catch (XBeeException e) { fail("This exception shouldn't be thrown now."); } catch (InvalidOperatingModeException e) { } assertEquals(xbeeDevice.getOperatingMode(), XBeeMode.AT); }

Target:
public void testConnectATMode() throws Exception { PowerMockito.doReturn(OperatingMode.AT).when(xbeeDevice, "determineConnectionMode"); try { xbeeDevice.open(); } catch (XBeeException e) { fail("This exception shouldn't be thrown now."); } catch (InvalidOperatingModeException e) { } assertFalse(xbeeDevice.isOpen()); assertFalse(dataReader.isRunning()); assertEquals(xbeeDevice.getOperatingMode(), OperatingMode.AT); }
Source:
public Quantity(String amount) { AbstractMap.SimpleEntry<String, String> amountFormatPair = splitAmountAndFormat(amount); this.amount = amountFormatPair.getKey(); this.format = amountFormatPair.getValue(); }

Target:
public Quantity(String amount) { Quantity parsedQuantity = parse(amount); this.amount = parsedQuantity.getAmount(); this.format = parsedQuantity.getFormat(); }
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + _curve.hashCode(); result = prime * result + _fixedCurve.hashCode(); return result; }

Target:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + _curve.hashCode(); result = prime * result + _fixedCurve.hashCode(); result = prime * result + _name.hashCode(); return result; }
Source:
public void setInitializationData(IConfigurationElement config, String propertyName, Object data) { Hashtable<String, String> parameters = (Hashtable<String, String>) data; String profilingType = parameters .get(ProviderProfileConstants.INIT_DATA_TYPE_KEY); String configId = parameters .get(ProviderProfileConstants.INIT_DATA_CONFIG_ID_KEY); if (profilingType == null) { profilingType = ""; } if (configId == null) { configId = ""; } setLaunchConfigID(configId); setProfilingType(profilingType); }

Target:
public void setInitializationData(IConfigurationElement config, String propertyName, Object data) { Map<String, String> parameters = (Map<String, String>) data; String profilingType = parameters .get(ProviderProfileConstants.INIT_DATA_TYPE_KEY); String configId = parameters .get(ProviderProfileConstants.INIT_DATA_CONFIG_ID_KEY); if (profilingType == null) { profilingType = ""; } if (configId == null) { configId = ""; } setLaunchConfigID(configId); setProfilingType(profilingType); }
Source:
private TemplateStoreInitializer getTemplateStoreInitializer() { if (fJavaPluginInitializer == null) { fJavaPluginInitializer = new TemplateStoreInitializer(); fJavaPluginInitializer.activate(); } return fJavaPluginInitializer; }

Target:
private synchronized TemplateStoreInitializer getTemplateStoreInitializer() { if (fJavaPluginInitializer == null) { fJavaPluginInitializer = new TemplateStoreInitializer(); fJavaPluginInitializer.activate(); } return fJavaPluginInitializer; }
Source:
public void shouldReadAllLines() throws Exception { ExecutionContext executionContext = MetaDataInstanceFactory.createStepExecution().getExecutionContext(); final String inputFilePath = "/small20.vcf.gz"; String inputFile = VcfReaderTest.class.getResource(inputFilePath).getFile(); String fileId = "5"; String studyId = "7"; String studyName = "study name"; VariantSource source = new VariantSource(inputFile, fileId, studyId, studyName, VariantStudy.StudyType.COLLECTION, VariantSource.Aggregation.NONE); VcfReader vcfReader = new VcfReader(source, inputFile); vcfReader.setSaveState(false); vcfReader.open(executionContext); List<Variant> variants; int count = 0; while ((variants = vcfReader.read()) != null) { count++; } long actualCount = JobTestUtils.getLines(new GZIPInputStream(new FileInputStream(inputFile))); assertEquals(actualCount, count); }

Target:
public void shouldReadAllLines() throws Exception { ExecutionContext executionContext = MetaDataInstanceFactory.createStepExecution().getExecutionContext(); final String inputFilePath = "/small20.vcf.gz"; String input = VcfReaderTest.class.getResource(inputFilePath).getFile(); String fileId = "5"; String studyId = "7"; String studyName = "study name"; VcfHeaderReader headerReader = new VcfHeaderReader(new File(input), fileId, studyId, studyName, VariantStudy.StudyType.COLLECTION, VariantSource.Aggregation.NONE); VariantSource source = headerReader.read(); VcfReader vcfReader = new VcfReader(source, input); vcfReader.setSaveState(false); vcfReader.open(executionContext); consumeReader(input, vcfReader); }
Source:
void createWidget (int index) { super.createWidget (index); items = new TreeItem [4]; columns = new TreeColumn [4]; columnCount = 0; if (OS.GTK_VERSION < OS.VERSION(3, 21, 0)) { setFontDescription(defaultFont().handle); } }

Target:
void createWidget (int index) { super.createWidget (index); items = new TreeItem [4]; columns = new TreeColumn [4]; columnCount = 0; if (OS.GTK_VERSION < OS.VERSION(3, 22, 0)) { setFontDescription(defaultFont().handle); } }
Source:
private void executeBuildNoBusyCheck(final String type, final String subType) { workbenchContext_.setBuildInProgress(true); source_.withSaveFilesBeforeCommand(new Command() { @Override public void execute() { server_.startBuild(type, subType, new SimpleRequestCallback<Boolean>() { @Override public void onResponseReceived(Boolean response) { } @Override public void onError(ServerError error) { super.onError(error); workbenchContext_.setBuildInProgress(false); } }); } }, new Command() { public void execute() { } }, "Build"); }

Target:
private void executeBuildNoBusyCheck(final String type, final String subType) { workbenchContext_.setBuildInProgress(true); source_.withSaveFilesBeforeCommand(() -> { server_.startBuild(type, subType, new SimpleRequestCallback<Boolean>() { @Override public void onResponseReceived(Boolean response) { } @Override public void onError(ServerError error) { super.onError(error); workbenchContext_.setBuildInProgress(false); } }); }, () -> {}, "Build"); }
Source:
private Result<TimeseriesResultValue> getNullTimeseriesResultValue(TimeseriesQuery query) { List<AggregatorFactory> aggregatorSpecs = query.getAggregatorSpecs(); Aggregator[] aggregators = new Aggregator[aggregatorSpecs.size()]; String[] aggregatorNames = new String[aggregatorSpecs.size()]; for (int i = 0; i < aggregatorSpecs.size(); i++) { aggregators[i] = aggregatorSpecs.get(i) .factorize(RowBasedColumnSelectorFactory.create(() -> new MapBasedRow( null, null ), null)); aggregatorNames[i] = aggregatorSpecs.get(i).getName(); } TimeseriesResultBuilder bob = new TimeseriesResultBuilder(DateTimes.EPOCH); for (int i = 0; i < aggregatorSpecs.size(); i++) { bob.addMetric(aggregatorNames[i], aggregators[i]); aggregators[i].close(); } return bob.build(); }

Target:
private Result<TimeseriesResultValue> getNullTimeseriesResultValue(TimeseriesQuery query) { List<AggregatorFactory> aggregatorSpecs = query.getAggregatorSpecs(); Aggregator[] aggregators = new Aggregator[aggregatorSpecs.size()]; String[] aggregatorNames = new String[aggregatorSpecs.size()]; for (int i = 0; i < aggregatorSpecs.size(); i++) { aggregators[i] = aggregatorSpecs.get(i) .factorize(RowBasedColumnSelectorFactory.create(() -> new MapBasedRow( null, null ), null)); aggregatorNames[i] = aggregatorSpecs.get(i).getName(); } final DateTime start = query.getIntervals().isEmpty() ? DateTimes.EPOCH : query.getIntervals().get(0).getStart(); TimeseriesResultBuilder bob = new TimeseriesResultBuilder(start); for (int i = 0; i < aggregatorSpecs.size(); i++) { bob.addMetric(aggregatorNames[i], aggregators[i]); aggregators[i].close(); } return bob.build(); }
Source:
protected abstract void processIncoming() throws IOException, ClientConnectionException; private void processHeartbeat() { int incoming = this.policy.getIncomingHeartbeat() / 2; if (!this.isInInit() && getHeartbeatTime() > incoming && this.half) { log.info("There was no massege from " + getHostname() + " for " + incoming + " milliseconds"); this.half = false; } if (!this.isInInit() && this.policy.isIncomingHeartbeat() && this.isIncomingHeartbeatExeeded()) { log.info("Heartbeat exceeded for " + getHostname() + " last message was " + getHeartbeatTime() + " milliseconds ago."); this.disconnect("Heartbeat exceeded"); } }

Target:
protected abstract void processIncoming() throws IOException, ClientConnectionException; private void processHeartbeat() { int incoming = this.policy.getIncomingHeartbeat() / 2; if (!this.isInInit() && getHeartbeatTime() > incoming && this.half) { log.info("No heartbeat message arrived from host '{}' for ms.", getHostname(), incoming); this.half = false; } if (!this.isInInit() && this.policy.isIncomingHeartbeat() && this.isIncomingHeartbeatExeeded()) { log.error("Heartbeat exceeded for host '{}', last response arrived ms ago.", getHostname(), getHeartbeatTime()); this.disconnect("Heartbeat exceeded"); } }
Source:
public void executionStarted(final TestDescriptor testDescriptor) { String displayName = testDescriptor.getDisplayName(); if (testDescriptor.isTest()) { incrementTests(); } else if (displayName.equals("A") || displayName.equals("B")) { incrementClasses(); } }

Target:
public void executionStarted(final TestDescriptor testDescriptor) { if (testDescriptor.isTest()) { incrementTests(); } else if (!testDescriptor.isRoot()) { incrementClasses(); } }
Source:
public Boolean openDatabase() { DBMSConnectionProperties connectionProperties = new DBMSConnectionProperties(); connectionProperties.setType(selectedDBMSType.getValue()); connectionProperties.setHost(host.getValue()); connectionProperties.setPort(Integer.parseInt(port.getValue())); connectionProperties.setDatabase(database.getValue()); connectionProperties.setUser(user.getValue()); connectionProperties.setPassword(password.getValue()); connectionProperties.setUseSSL(useSSL.getValue()); connectionProperties.setKeyStore(keystore.getValue()); connectionProperties.setServerTimezone(serverTimezone.getValue()); setupKeyStore(); Boolean connected = openSharedDatabase(connectionProperties); return connected; }

Target:
public boolean openDatabase() { DBMSConnectionProperties connectionProperties = new DBMSConnectionProperties(); connectionProperties.setType(selectedDBMSType.getValue()); connectionProperties.setHost(host.getValue()); connectionProperties.setPort(Integer.parseInt(port.getValue())); connectionProperties.setDatabase(database.getValue()); connectionProperties.setUser(user.getValue()); connectionProperties.setPassword(password.getValue()); connectionProperties.setUseSSL(useSSL.getValue()); connectionProperties.setKeyStore(keystore.getValue()); connectionProperties.setServerTimezone(serverTimezone.getValue()); setupKeyStore(); boolean connected = openSharedDatabase(connectionProperties); return connected; }
Source:
public TemplateDataset(NetcdfDatasetIF dataset, Set<String> requestedVariables, Map<String, ValueTemplate> attributeModifications, CalendarDateRange timeRange, Range verticalSubset, LatLonRect bbox) { this.globalAttributes = getGlobalAttributes(dataset, attributeModifications, timeRange, verticalSubset, bbox); List<NetcdfVariable> templateVariables = new ArrayList<>(); Map<String, Dimension> templateDimensions = new LinkedHashMap<>(); String timeDimension = dataset.getTimeAxis().getDimensionName(); for (NetcdfVariable variable: dataset.getVariables()) { if (requestedVariables != null && !requestedVariables.contains(variable.getShortName())) { continue; } TemplateVariable templateVariable = new TemplateVariable(variable, timeDimension); templateVariables.add(templateVariable); for (Dimension templateDimension: templateVariable.getDimensions()) { templateDimensions.put(templateDimension.getShortName(), templateDimension); } } List<Dimension> orderedTemplateDimensions = new ArrayList<>(); for (Dimension dimension: dataset.getDimensions()) { Dimension templateDimension = templateDimensions.get(dimension.getShortName()); if (templateDimension != null) { orderedTemplateDimensions.add(templateDimension); } } this.dimensions = new ArrayList<>(orderedTemplateDimensions); this.variables = new ArrayList<>(templateVariables); }

Target:
public TemplateDataset(NetcdfDatasetIF dataset, Set<String> requestedVariables, Map<String, ValueTemplate> attributeModifications, CalendarDateRange timeRange, Range verticalSubset, LatLonRect bbox) { this.globalAttributes = getGlobalAttributes(dataset, attributeModifications, timeRange); List<NetcdfVariable> templateVariables = new ArrayList<>(); Map<String, Dimension> templateDimensions = new LinkedHashMap<>(); String timeDimension = dataset.getTimeAxis().getDimensionName(); for (NetcdfVariable variable: dataset.getVariables()) { if (requestedVariables != null && !requestedVariables.contains(variable.getShortName())) { continue; } TemplateVariable templateVariable = new TemplateVariable(variable, timeDimension); templateVariables.add(templateVariable); for (Dimension templateDimension: templateVariable.getDimensions()) { templateDimensions.put(templateDimension.getShortName(), templateDimension); } } List<Dimension> orderedTemplateDimensions = new ArrayList<>(); for (Dimension dimension: dataset.getDimensions()) { Dimension templateDimension = templateDimensions.get(dimension.getShortName()); if (templateDimension != null) { orderedTemplateDimensions.add(templateDimension); } } this.dimensions = new ArrayList<>(orderedTemplateDimensions); this.variables = new ArrayList<>(templateVariables); }
Source:
public boolean existsVMReplica(ClaudiaData claudiaData, String tier, VM vm, String region) { try { String token = claudiaData.getUser().getToken(); String vdc = claudiaData.getVdc(); boolean exists = openStackUtil.existsServerForDelete(vm.getVmid(), region, token, vdc); if (!exists) { return false; } } catch (Exception e) { String errorMessage = "Error checking info from server " + vm.getVmid(); log.error(errorMessage); return false; } return true; }

Target:
public boolean existsVMReplica(ClaudiaData claudiaData, String tier, VM vm, String region) { String token = claudiaData.getUser().getToken(); String vdc = claudiaData.getVdc(); boolean exists = openStackUtil.existsServerForDelete(vm.getVmid(), region, token, vdc); if (!exists) { return false; } return true; }
Source:
protected void executeCommand() { if (getDiskImage() != null) { try { Guid taskId = persistAsyncTaskPlaceHolder(getParameters().getParentCommand()); VDSReturnValue vdsReturnValue = performImageVdsmOperation(); getReturnValue().getInternalVdsmTaskIdList().add( createTask(taskId, vdsReturnValue.getCreationInfo(), getParameters().getParentCommand(), VdcObjectType.Storage, getStorageDomainId())); } catch (VdcBLLException e) { if (e.getErrorCode() == VdcBllErrors.ImageDoesNotExistInDomainError) { log.warnFormat("The image group with id {0} wasn't actually deleted from the storage domain {1} " + "because it didn't exist in it", getDiskImage().getId(), getStorageDomainId()); } else if (isImageRemovedFromStorage()) { log.infoFormat("The image group with id {0} was deleted from storage"); } else { throw e; } } if (getParameters().getParentCommand() != VdcActionType.RemoveVmFromImportExport && getParameters().getParentCommand() != VdcActionType.RemoveVmTemplateFromImportExport) { performImageDbOperations(); } } else { log.warn("DiskImage is null, nothing to remove"); } setSucceeded(true); }

Target:
protected void executeCommand() { if (getDiskImage() != null) { try { Guid taskId = persistAsyncTaskPlaceHolder(getParameters().getParentCommand()); VDSReturnValue vdsReturnValue = performImageVdsmOperation(); getReturnValue().getInternalVdsmTaskIdList().add( createTask(taskId, vdsReturnValue.getCreationInfo(), getParameters().getParentCommand(), VdcObjectType.Storage, getStorageDomainId())); } catch (VdcBLLException e) { if (e.getErrorCode() == VdcBllErrors.ImageDoesNotExistInDomainError) { log.warnFormat("The image group with id {0} wasn't actually deleted from the storage domain {1} " + "because it didn't exist in it", getDiskImage().getId(), getStorageDomainId()); } else if (e.getErrorCode() == VdcBllErrors.ImageDeleteError && isImageRemovedFromStorage()) { log.infoFormat("The image group with id {0} was deleted from storage"); } else { throw e; } } if (getParameters().getParentCommand() != VdcActionType.RemoveVmFromImportExport && getParameters().getParentCommand() != VdcActionType.RemoveVmTemplateFromImportExport) { performImageDbOperations(); } } else { log.warn("DiskImage is null, nothing to remove"); } setSucceeded(true); }
Source:
default CompletionStage<Void> prepareWithModifications(Transaction transaction, BatchModification batchModification) { throw new UnsupportedOperationException("Store characteristic included " + Characteristic.TRANSACTIONAL + ", but it does not implement rollback"); }

Target:
default CompletionStage<Void> prepareWithModifications(Transaction transaction, BatchModification batchModification) { throw new UnsupportedOperationException("Store characteristic included " + Characteristic.TRANSACTIONAL + ", but it does not implement prepareWithModifications"); }
Source:
public void getOrderGroupsByEncounter_shouldGetOrderGroupsFromAnEncounter() { Encounter existingEncounter = Context.getEncounterService().getEncounter(4); List<OrderGroup> ordergroups1 = Context.getOrderService().getOrderGroupsByEncounter(existingEncounter); assertEquals(1, ordergroups1.size()); }

Target:
public void getOrderGroupsByEncounter_shouldGetOrderGroupsFromAnEncounter() { Encounter existingEncounter = Context.getEncounterService().getEncounter(4); List<OrderGroup> ordergroups = Context.getOrderService().getOrderGroupsByEncounter(existingEncounter); assertEquals(1, ordergroups.size()); }
Source:
public void performAction(SolrUpdateRequest updateRequest) throws IndexingException { Assert.notEmpty(updateRequest.getParams()); Map<String, String> params = updateRequest.getParams(); String staleTimestamp = params.get(STALE_TIMESTAMP); if (StringUtils.isEmpty(staleTimestamp)) { throw new IllegalArgumentException("Cannot cleanup stale children, no staleTimestamp provided"); } try { solrUpdateDriver.commit(); StringBuilder query = new StringBuilder(); if (getContentRootPid().equals(updateRequest.getPid())) { query.append("*:*"); } else { BriefObjectMetadata ancestorPathBean = getRootAncestorPath(updateRequest); query.append(solrSettings.getFieldName(SearchFieldKeys.ANCESTOR_PATH.name())).append(':') .append(SolrSettings.sanitize(ancestorPathBean.getPath().getSearchValue())); } query.append(" AND ").append(solrSettings.getFieldName(SearchFieldKeys.TIMESTAMP.name())) .append(":{* TO ").append(staleTimestamp).append("}"); solrUpdateDriver.deleteByQuery(query.toString()); } catch (Exception e) { throw new IndexingException("Error encountered in deleteStaleChildren for " + updateRequest.getTargetID(), e); } }

Target:
public void performAction(SolrUpdateRequest updateRequest) throws IndexingException { Assert.notEmpty(updateRequest.getParams()); Map<String, String> params = updateRequest.getParams(); String staleTimestamp = params.get(STALE_TIMESTAMP); Assert.hasText(staleTimestamp, "Cannot cleanup stale children, no staleTimestamp provided"); try { solrUpdateDriver.commit(); StringBuilder query = new StringBuilder(); if (getContentRootPid().equals(updateRequest.getPid())) { query.append("*:*"); } else { BriefObjectMetadata ancestorPathBean = getRootAncestorPath(updateRequest); query.append(solrSettings.getFieldName(SearchFieldKeys.ANCESTOR_PATH.name())).append(':') .append(SolrSettings.sanitize(ancestorPathBean.getPath().getSearchValue())); } query.append(" AND ").append(solrSettings.getFieldName(SearchFieldKeys.TIMESTAMP.name())) .append(":{* TO ").append(staleTimestamp).append("}"); solrUpdateDriver.deleteByQuery(query.toString()); } catch (Exception e) { throw new IndexingException("Error encountered in deleteStaleChildren for " + updateRequest.getTargetID(), e); } }
Source:
protected void initialize() { addWindowListener(new WindowAdapter() { @Override public void windowActivated(WindowEvent e) { getMessageSender().cleanup(); } @Override public void windowClosing(WindowEvent e) { getMessageSender().cleanup(); saveConfig(); } }); setContentPane(getWindowPanel()); }

Target:
protected void initialize() { addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { getMessageSender().cleanup(); saveConfig(); } }); setContentPane(getWindowPanel()); }
Source:
public void load(File directory) throws ConfigurationException { if (!directory.exists()) { throw new ConfigurationException(new FileNotFoundException( "The directory \"" + directory.getAbsolutePath() + "\" containing the configuration files doesn't " + "exist.")); } File[] files = directory.listFiles(); if (files != null) { sort(files); for (File file : files) { if (file.getName().endsWith(".properties")) { loadFile(file); } } } }

Target:
private void load(File directory) throws ConfigurationException { if (!directory.exists()) { throw new ConfigurationException(new FileNotFoundException( "The directory \"" + directory.getAbsolutePath() + "\" containing the configuration files doesn't " + "exist.")); } File[] files = directory.listFiles(); if (files != null) { sort(files); for (File file : files) { if (file.getName().endsWith(".properties")) { loadFile(file); } } } }
Source:
private void saveState(Bundle outState) { outState.putBoolean("pausedZeroEnabledState", isZeroEnabled); outState.putString("pausedZeroConfig", GsonMarshaller.marshal(currentZeroConfig)); outState.putBoolean("isSearching", isSearching()); outState.putString(LANGUAGE_CODE_BUNDLE_KEY, app.getAppOrSystemLanguageCode()); }

Target:
private void saveState(Bundle outState) { outState.putBoolean("isSearching", isSearching()); outState.putString(LANGUAGE_CODE_BUNDLE_KEY, app.getAppOrSystemLanguageCode()); }
Source:
public boolean equals(Object obj) { if (!(obj instanceof GlusterHookEntity)) { return false; } GlusterHookEntity hook = (GlusterHookEntity) obj; if (!(getId().equals(hook.getId()) && clusterId.equals(hook.getClusterId()) && glusterCommand.equals(hook.getGlusterCommand()) && stage == hook.getStage() && name.equals(hook.getName()) && contentType == hook.getContentType() && conflictStatus == hook.getConflictStatus() && checksum.equals(hook.getChecksum()) && status == hook.getStatus())) { return false; } return true; }

Target:
public boolean equals(Object obj) { if (!(obj instanceof GlusterHookEntity)) { return false; } GlusterHookEntity hook = (GlusterHookEntity) obj; if (!(ObjectUtils.objectsEqual(getId(),hook.getId()) && ObjectUtils.objectsEqual(clusterId,hook.getClusterId()) && ObjectUtils.objectsEqual(glusterCommand,hook.getGlusterCommand()) && stage == hook.getStage() && ObjectUtils.objectsEqual(name,hook.getName()) && contentType == hook.getContentType() && ObjectUtils.objectsEqual(conflictStatus,hook.getConflictStatus()) && ObjectUtils.objectsEqual(checksum,hook.getChecksum()) && status == hook.getStatus())) { return false; } return true; }