auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected IStatus run(final IProgressMonitor monitor) { monitor.beginTask("", IProgressMonitor.UNKNOWN); while (!monitor.isCanceled()) { try { long prevNbEvents = fTrace.getNbEvents(); Thread.sleep(250); long nbEvents = fTrace.getNbEvents(); setName(Messages.TmfCheckpointIndexer_Indexing + ' ' + fTrace.getName() + " (" + String.format("%,d", nbEvents) + ")"); long rate = (nbEvents - prevNbEvents) * 4; monitor.setTaskName(String.format("%,d", rate) + " " + Messages.TmfCheckpointIndexer_EventsPerSecond); } catch (final InterruptedException e) { return Status.OK_STATUS; } } monitor.done(); return fException != null ? new Status(IStatus.ERROR, "", fException.getMessage(), fException) : Status.OK_STATUS; }

Target:
protected IStatus run(final IProgressMonitor monitor) { monitor.beginTask("", IProgressMonitor.UNKNOWN); while (!monitor.isCanceled()) { try { long prevNbEvents = fTrace.getNbEvents(); Thread.sleep(250); long nbEvents = fTrace.getNbEvents(); setName(Messages.TmfCheckpointIndexer_Indexing + ' ' + fTrace.getName() + " (" + String.format("%,d", nbEvents) + ")"); long rate = (nbEvents - prevNbEvents) * 4; monitor.setTaskName(String.format("%,d", rate) + " " + Messages.TmfCheckpointIndexer_EventsPerSecond); } catch (final InterruptedException e) { return Status.OK_STATUS; } } monitor.done(); return fException != null ? new Status(IStatus.ERROR, Activator.PLUGIN_ID, fException.getMessage(), fException) : Status.OK_STATUS; }
Source:
public BibtexExtractorViewModel(BibDatabaseContext bibdatabaseContext, DialogService dialogService, JabRefPreferences jabRefPreferences, FileUpdateMonitor fileUpdateMonitor, TaskExecutor taskExecutor, UndoManager undoManager, StateManager stateManager) { this.dialogService = dialogService; currentCitationfetcher = new GrobidCitationFetcher(jabRefPreferences.getImportFormatPreferences()); this.taskExecutor = taskExecutor; this.bibEntryFormat = bibdatabaseContext.getMode(); this.importHandler = new ImportHandler( dialogService, bibdatabaseContext, ExternalFileTypes.getInstance(), jabRefPreferences, fileUpdateMonitor, undoManager, stateManager); }

Target:
public BibtexExtractorViewModel(BibDatabaseContext bibdatabaseContext, DialogService dialogService, JabRefPreferences jabRefPreferences, FileUpdateMonitor fileUpdateMonitor, TaskExecutor taskExecutor, UndoManager undoManager, StateManager stateManager) { this.dialogService = dialogService; currentCitationfetcher = new GrobidCitationFetcher(jabRefPreferences.getImportFormatPreferences()); this.taskExecutor = taskExecutor; this.importHandler = new ImportHandler( dialogService, bibdatabaseContext, ExternalFileTypes.getInstance(), jabRefPreferences, fileUpdateMonitor, undoManager, stateManager); }
Source:
private void updateStackStatus(Stack stack, SyncResult result, List<ProviderSyncResult> providerSyncResults, int alreadyDeletedCount) { DetailedStackStatus status = getStackStatus(providerSyncResults, result, alreadyDeletedCount); if (status != stack.getStackStatus().getDetailedStackStatus()) { if (autoSyncConfig.isUpdateStatus()) { if (!flowLogService.isOtherFlowRunning(stack.getId())) { stackUpdater.updateStackStatus(stack, status, result.getMessage()); } else { LOGGER.debug(":::Auto sync::: do not update stack status because flow is running on freeipa stack {}", stack.getName()); } } else { LOGGER.info(":::Auto sync::: The stack status would be had to update from to {}", stack.getStackStatus().getDetailedStackStatus(), status); } } }

Target:
private void updateStackStatus(Stack stack, SyncResult result, List<ProviderSyncResult> providerSyncResults, int alreadyDeletedCount) { DetailedStackStatus status = getStackStatus(providerSyncResults, result, alreadyDeletedCount); if (status != stack.getStackStatus().getDetailedStackStatus()) { if (autoSyncConfig.isUpdateStatus()) { if (flowLogService.isOtherFlowRunning(stack.getId())) { throw new InterruptSyncingException(":::Auto sync::: interrupt syncing in updateStackStatus, flow is running on freeipa stack " + stack.getName()); } else { stackUpdater.updateStackStatus(stack, status, result.getMessage()); } } else { LOGGER.info(":::Auto sync::: The stack status would be had to update from to {}", stack.getStackStatus().getDetailedStackStatus(), status); } } }
Source:
public static void saveRequest(final Context ctx, final AuthenticationRequest request, final String url) { final String methodName = ":saveRequest"; Logger.v(TAG + methodName, "ApplicationReceiver starts to save the request in shared preference."); SharedPreferences prefs = ctx.getSharedPreferences(INSTALL_REQUEST_TRACK_FILE, Activity.MODE_PRIVATE); if (prefs != null) { HashMap<String, String> parameters = StringExtensions.getUrlParameters(url); if (parameters != null && parameters.containsKey(INSTALL_UPN_KEY)) { Logger.v(TAG + methodName, "Coming redirect contains the UNP, setting it on the request for both loginhint and broker account name."); request.setLoginHint(parameters.get(INSTALL_UPN_KEY)); request.setBrokerAccountName(parameters.get(INSTALL_UPN_KEY)); } Editor prefsEditor = prefs.edit(); Gson gson = new Gson(); String jsonRequest = gson.toJson(request); prefsEditor.putString(INSTALL_REQUEST_KEY, jsonRequest); prefsEditor.apply(); } else { Logger.v(TAG + methodName, "SharePreference is null, nothing saved."); } }

Target:
public static void saveRequest(final Context ctx, final AuthenticationRequest request, final String url) { final String methodName = "saveRequest"; Logger.v(TAG + methodName, "ApplicationReceiver starts to save the request in shared preference."); SharedPreferences prefs = ctx.getSharedPreferences(INSTALL_REQUEST_TRACK_FILE, Activity.MODE_PRIVATE); if (prefs != null) { HashMap<String, String> parameters = StringExtensions.getUrlParameters(url); if (parameters != null && parameters.containsKey(INSTALL_UPN_KEY)) { Logger.v(TAG + methodName, "Coming redirect contains the UPN, setting it on the request for both loginhint and broker account name."); request.setLoginHint(parameters.get(INSTALL_UPN_KEY)); request.setBrokerAccountName(parameters.get(INSTALL_UPN_KEY)); } Editor prefsEditor = prefs.edit(); Gson gson = new Gson(); String jsonRequest = gson.toJson(request); prefsEditor.putString(INSTALL_REQUEST_KEY, jsonRequest); final Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); prefsEditor.putLong(INSTALL_REQUEST_TIMESTAMP_KEY, calendar.getTimeInMillis()); prefsEditor.apply(); } else { Logger.v(TAG + methodName, "SharePreference is null, nothing saved."); } }
Source:
private <T extends Described> T updateDescribed(T existing, T fetched) { SetView<String> mergedAliasUrls = Sets.union(existing.getAliasUrls(), fetched.getAliasUrls()); if (!mergedAliasUrls.equals(existing.getAliasUrls())) { existing.setAliasUrls(mergedAliasUrls); copyLastUpdated(fetched, existing); } SetView<Alias> mergedAliases = Sets.union(existing.getAliases(), fetched.getAliases()); if (!mergedAliases.equals(existing.getAliasUrls())) { existing.setAliases(mergedAliases); copyLastUpdated(fetched, existing); } return updateDescriptions(existing, fetched); }

Target:
private <T extends Described> T updateDescribed(T existing, T fetched) { SetView<String> mergedAliasUrls = Sets.union(existing.getAliasUrls(), fetched.getAliasUrls()); if (!mergedAliasUrls.equals(existing.getAliasUrls())) { existing.setAliasUrls(mergedAliasUrls); copyLastUpdated(fetched, existing); } if (fetched.getAliases() != null && !existing.getAliases().equals(fetched.getAliases())) { existing.setAliases(fetched.getAliases()); copyLastUpdated(fetched, existing); } return updateDescriptions(existing, fetched); }
Source:
private void fetchJetpackSettings() { WordPress.getRestClientUtils().getJetpackSettings( mSite.getSiteId(), new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { AppLog.d(AppLog.T.API, "Received response to Jetpack Settings REST request."); mRemoteSettings.localTableId = mSite.getId(); deserializeJetpackRestResponse(mSite, response); mSettings.copyFrom(mRemoteSettings); notifyUpdatedOnUiThread(null); } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { AppLog.w(AppLog.T.API, "Error response to Jetpack Settings REST request: " + error); notifyUpdatedOnUiThread(error); } }); }

Target:
private void fetchJetpackSettings() { WordPress.getRestClientUtils().getJetpackSettings( mSite.getSiteId(), new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { AppLog.v(AppLog.T.API, "Received response to Jetpack Settings REST request."); mRemoteSettings.localTableId = mSite.getId(); deserializeJetpackRestResponse(mSite, response); mSettings.copyFrom(mRemoteSettings); notifyUpdatedOnUiThread(null); } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { AppLog.e(AppLog.T.API, "Error response to Jetpack Settings REST request: " + error); notifyUpdatedOnUiThread(error); } }); }
Source:
public void nextTuple() { int emitCount = 0; for (Map.Entry<String, TestRecordsInformation> entry : testRecordsInformationPerOutputStream.entrySet()) { String outputStream = entry.getKey(); TestRecordsInformation info = entry.getValue(); Optional<Map<String, Object>> recordOptional = info.nextRecord(); if (recordOptional.isPresent()) { Map<String, Object> record = recordOptional.get(); StreamlineEventImpl streamlineEvent = new StreamlineEventImpl(record, testRunSource.getId()); LOG.debug("Emitting event to stream {}", streamlineEvent, outputStream); collector.emit(outputStream, new Values(streamlineEvent), streamlineEvent.getId()); emitCount++; } } if (emitCount == 0) { LOG.info("All iterations are completed or in sleep phase, sleeping..."); try { Thread.sleep(1000); } catch (InterruptedException e) { } } }

Target:
public void nextTuple() { int emitCount = 0; boolean allOutputStreamsCompleted = true; for (Map.Entry<String, TestRecordsInformation> entry : testRecordsInformationPerOutputStream.entrySet()) { String outputStream = entry.getKey(); TestRecordsInformation info = entry.getValue(); if (info.isCompleted()) { continue; } allOutputStreamsCompleted = false; Optional<Map<String, Object>> recordOptional = info.nextRecord(); if (recordOptional.isPresent()) { Map<String, Object> record = recordOptional.get(); StreamlineEventImpl streamlineEvent = new StreamlineEventImpl(record, testRunSource.getId()); LOG.debug("Emitting event to stream {}", streamlineEvent, outputStream); collector.emit(outputStream, new Values(streamlineEvent), streamlineEvent.getId()); emitCount++; } } if (allOutputStreamsCompleted) { LOG.info("All iterations are completed, sleeping..."); Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS); } else if (emitCount == 0) { LOG.info("All output streams are finished last iteration and now in sleep phase, sleeping..."); Uninterruptibles.sleepUninterruptibly(testRunSource.getSleepMsPerIteration(), TimeUnit.MILLISECONDS); } }
Source:
public List<URIStatus> listStatus(AlluxioURI path, ListStatusPOptions options) throws IOException { List<URIStatus> statuses = Arrays.stream(fileSystem.listStatus(toPath(path))).map(this::toUriStatus).collect(Collectors.toList()); return statuses; }

Target:
public List<URIStatus> listStatus(AlluxioURI path, ListStatusPOptions options) throws IOException { return Arrays.stream(fileSystem.listStatus(toPath(path))).map(this::toUriStatus).collect(Collectors.toList()); }
Source:
public Response toolsIndexGet(SecurityContext securityContext) { List<Entry> published = getPublished(); if (!config.getEsConfiguration().getHostname().isEmpty() && !published.isEmpty()) { try (RestClient restClient = RestClient .builder(new HttpHost(config.getEsConfiguration().getHostname(), config.getEsConfiguration().getPort(), "http")) .build()) { try { restClient.performRequest("DELETE", "/entry"); } catch (Exception e) { LOG.info("Could not delete previous elastic search index, not an issue if this is cold start", e); } URL url = Resources.getResource("queries/mapping.json"); String text = Resources.toString(url, StandardCharsets.UTF_8); HttpEntity mappingEntity = new NStringEntity(text, ContentType.APPLICATION_JSON); restClient.performRequest("PUT", "/entry", Collections.emptyMap(), mappingEntity); ElasticManager elasticManager = new ElasticManager(); elasticManager.bulkUpsert(published); } catch (IOException e) { LOG.error("Could not create elastic search index", e); throw new CustomWebApplicationException(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR); } return Response.ok().entity(published.size()).build(); } return Response.ok().entity(0).build(); }

Target:
public Response toolsIndexGet(SecurityContext securityContext) { List<Entry> published = getPublished(); if (!config.getEsConfiguration().getHostname().isEmpty() && !published.isEmpty()) { try (RestClient restClient = RestClient .builder(new HttpHost(config.getEsConfiguration().getHostname(), config.getEsConfiguration().getPort(), "http")) .build()) { try { restClient.performRequest("DELETE", "/entry"); } catch (Exception e) { LOG.warn("Could not delete previous elastic search index, not an issue if this is cold start", e); } URL url = Resources.getResource("queries/mapping.json"); String text = Resources.toString(url, StandardCharsets.UTF_8); HttpEntity mappingEntity = new NStringEntity(text, ContentType.APPLICATION_JSON); restClient.performRequest("PUT", "/entry", Collections.emptyMap(), mappingEntity); ElasticManager elasticManager = new ElasticManager(); elasticManager.bulkUpsert(published); } catch (IOException e) { LOG.error("Could not create elastic search index", e); throw new CustomWebApplicationException(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR); } return Response.ok().entity(published.size()).build(); } return Response.ok().entity(0).build(); }
Source:
protected BooleanWritable toWritable(Integer value) throws IOException { writable.set(value.intValue() == 1 ? true : false); return writable; }

Target:
protected BooleanWritable toWritable(Integer value) throws IOException { int valueInt = value.intValue(); if (valueInt == 1 ) { writable.set(true); } else if (valueInt == 0) { writable.set(false); } else { throw new IllegalArgumentException("Only 1 and 0 could be convert to BooleanWritable!"); } return writable; }
Source:
public IAnswerData getAnswer() { if (mBinaryName != null) { return new StringData(mBinaryName); } else if (oversizedMediaSize > 0) { return new InvalidData("", new IntegerData(oversizedMediaSize)); } return null; }

Target:
public IAnswerData getAnswer() { if (oversizedMediaSize > 0) { return new InvalidData("", new IntegerData(oversizedMediaSize)); } else if (mBinaryName != null) { return new StringData(mBinaryName); } return null; }
Source:
public void removeConsumer(final Consumer consumer) { synchronized (this) { consumersChanged = true; for (ConsumerHolder holder : consumerList) { if (holder.consumer == consumer) { if (holder.iter != null) { holder.iter.close(); } consumerList.remove(holder); break; } } if (consumerList.isEmpty()) { supportsDirectDeliver = true; } if (pos > 0 && pos >= consumerList.size()) { pos = consumerList.size() - 1; } if (consumerSet.remove(consumer)) { consumersCount.decrementAndGet(); } LinkedList<SimpleString> groupsToRemove = null; for (SimpleString groupID : groups.keySet()) { if (consumer == groups.get(groupID)) { if (groupsToRemove == null) { groupsToRemove = new LinkedList<>(); } groupsToRemove.add(groupID); } } if (groupsToRemove != null) { for (SimpleString groupID : groupsToRemove) { groups.remove(groupID); } } if (refCountForConsumers != null) { refCountForConsumers.decrement(); } noConsumers.decrementAndGet(); } }

Target:
public void removeConsumer(final Consumer consumer) { synchronized (this) { consumersChanged = true; for (ConsumerHolder holder : consumerList) { if (holder.consumer == consumer) { if (holder.iter != null) { holder.iter.close(); } consumerList.remove(holder); break; } } this.supportsDirectDeliver = checkConsumerDirectDeliver(); if (pos > 0 && pos >= consumerList.size()) { pos = consumerList.size() - 1; } if (consumerSet.remove(consumer)) { consumersCount.decrementAndGet(); } LinkedList<SimpleString> groupsToRemove = null; for (SimpleString groupID : groups.keySet()) { if (consumer == groups.get(groupID)) { if (groupsToRemove == null) { groupsToRemove = new LinkedList<>(); } groupsToRemove.add(groupID); } } if (groupsToRemove != null) { for (SimpleString groupID : groupsToRemove) { groups.remove(groupID); } } if (refCountForConsumers != null) { refCountForConsumers.decrement(); } noConsumers.decrementAndGet(); } }
Source:
public Runnable commit() { return new Runnable() { @Override public void run() { } }; }

Target:
public Runnable commit() { return Runnables.getNoopRunnable(); }
Source:
public void preload() { if (!enabled) return; AdvancedCacheLoader<Object, Object> preloadCl = null; for (CacheLoader l : loaders) { if (configMap.get(l).preload()) { if (!(l instanceof AdvancedCacheLoader)) { throw new PersistenceException("Cannot preload from cache loader '" + l.getClass().getName() + "' as it doesn't implement '" + AdvancedCacheLoader.class.getName() + "'"); } preloadCl = (AdvancedCacheLoader) l; if (preloadCl instanceof AdvancedAsyncCacheLoader) preloadCl = (AdvancedCacheLoader) ((AdvancedAsyncCacheLoader) preloadCl).undelegate(); break; } } if (preloadCl == null) return; long start = timeService.time(); final long maxEntries = getMaxEntries(); final AtomicInteger loadedEntries = new AtomicInteger(0); final AdvancedCache<Object, Object> flaggedCache = getCacheForStateInsertion(); Long insertAmount = Flowable.fromPublisher(preloadCl.publishEntries(null, true, true)) .take(maxEntries).doOnNext(me -> { Metadata metadata = me.getMetadata() != null ? ((InternalMetadataImpl) me.getMetadata()).actual() : null; preloadKey(flaggedCache, me.getKey(), me.getValue(), metadata); }).count().blockingGet(); this.preloaded = insertAmount < maxEntries; log.debugf("Preloaded %d keys in %s", loadedEntries.get(), Util.prettyPrintTime(timeService.timeDuration(start, MILLISECONDS))); }

Target:
public void preload() { if (!enabled) return; AdvancedCacheLoader<Object, Object> preloadCl = null; storesMutex.readLock().lock(); try { for (CacheLoader l : loaders) { if (configMap.get(l).preload()) { if (!(l instanceof AdvancedCacheLoader)) { throw new PersistenceException("Cannot preload from cache loader '" + l.getClass().getName() + "' as it doesn't implement '" + AdvancedCacheLoader.class.getName() + "'"); } preloadCl = (AdvancedCacheLoader) l; if (preloadCl instanceof AdvancedAsyncCacheLoader) preloadCl = (AdvancedCacheLoader) ((AdvancedAsyncCacheLoader) preloadCl).undelegate(); break; } } } finally { storesMutex.readLock().unlock(); } if (preloadCl == null) return; long start = timeService.time(); final long maxEntries = getMaxEntries(); final AtomicInteger loadedEntries = new AtomicInteger(0); final AdvancedCache<Object, Object> flaggedCache = getCacheForStateInsertion(); Long insertAmount = Flowable.fromPublisher(preloadCl.publishEntries(null, true, true)) .take(maxEntries) .doOnNext(me -> { Metadata metadata = me.getMetadata() != null ? ((InternalMetadataImpl) me.getMetadata()).actual() : null; preloadKey(flaggedCache, me.getKey(), me.getValue(), metadata); }).count().blockingGet(); this.preloaded = insertAmount < maxEntries; log.debugf("Preloaded %d keys in %s", loadedEntries.get(), Util.prettyPrintTime(timeService.timeDuration(start, MILLISECONDS))); }
Source:
default void setUnmapped(final boolean unmapped) { addFlag(SAMFlag.READ_UNMAPPED, unmapped); }

Target:
default void setUnmapped(final boolean unmapped) { setFlag(SAMFlag.READ_UNMAPPED, unmapped); }
Source:
public static void setup() { CqlSession session = sessionRule.session(); session.execute( SimpleStatement.builder( "CREATE KEYSPACE IF NOT EXISTS " + DEFAULT_KEYSPACE + " " + "WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}") .setExecutionProfile(sessionRule.slowProfile()) .build()); session.execute( SimpleStatement.builder( "CREATE TABLE " + DEFAULT_KEYSPACE + ".product_simple_default_ks(id uuid PRIMARY KEY, description text)") .setExecutionProfile(sessionRule.slowProfile()) .build()); session.execute( SimpleStatement.builder( "CREATE TABLE product_simple_without_ks(id uuid PRIMARY KEY, description text)") .setExecutionProfile(sessionRule.slowProfile()) .build()); session.execute( SimpleStatement.builder( "CREATE TABLE product_simple_default_ks(id uuid PRIMARY KEY, description text)") .setExecutionProfile(sessionRule.slowProfile()) .build()); mapper = new DefaultKeyspaceIT_InventoryMapperBuilder(session).build(); }

Target:
public static void setup() { CqlSession session = sessionRule.session(); session.execute( SimpleStatement.builder( String.format( "CREATE KEYSPACE IF NOT EXISTS %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", DEFAULT_KEYSPACE)) .setExecutionProfile(sessionRule.slowProfile()) .build()); session.execute( SimpleStatement.builder( String.format( "CREATE TABLE %s.product_simple_default_ks(id uuid PRIMARY KEY, description text)", DEFAULT_KEYSPACE)) .setExecutionProfile(sessionRule.slowProfile()) .build()); session.execute( SimpleStatement.builder( "CREATE TABLE product_simple_without_ks(id uuid PRIMARY KEY, description text)") .setExecutionProfile(sessionRule.slowProfile()) .build()); session.execute( SimpleStatement.builder( "CREATE TABLE product_simple_default_ks(id uuid PRIMARY KEY, description text)") .setExecutionProfile(sessionRule.slowProfile()) .build()); mapper = new DefaultKeyspaceIT_InventoryMapperBuilder(session).build(); }
Source:
private static void generateGetEstimatedSize(ClassDefinition definition, List<FieldDefinition> stateFields) { MethodDefinition method = definition.declareMethod(a(PUBLIC), "getEstimatedSize", type(long.class)); Variable estimatedSize = method.getScope().declareVariable(long.class, "estimatedSize"); method.getBody().append(estimatedSize.set(constantLong(0L))); for (FieldDefinition stateField : stateFields) { BytecodeExpression state = method.getThis().getField(stateField); method.getBody() .append(estimatedSize.set( createArithmeticBytecodeExpression( IADD, estimatedSize, state.invoke("getEstimatedSize", long.class)))); } method.getBody().append(estimatedSize.ret()); }

Target:
private static void generateGetEstimatedSize(ClassDefinition definition, List<FieldDefinition> stateFields) { MethodDefinition method = definition.declareMethod(a(PUBLIC), "getEstimatedSize", type(long.class)); Variable estimatedSize = method.getScope().declareVariable(long.class, "estimatedSize"); method.getBody().append(estimatedSize.set(constantLong(0L))); for (FieldDefinition stateField : stateFields) { method.getBody() .append(estimatedSize.set( BytecodeExpressions.add( estimatedSize, method.getThis().getField(stateField).invoke("getEstimatedSize", long.class)))); } method.getBody().append(estimatedSize.ret()); }
Source:
public void validateCountryMinLength_shouldFailValue() { String invalidMaxLengthEmail = randomAlphanumeric(1); CreatePaymentRequest createPaymentRequest = createPaymentRequestBuilderWithAgreementId().country(invalidMaxLengthEmail).build(); expectedException.expect(PaymentValidationException.class); expectedException.expect(aValidationExceptionContaining("P0102", "Invalid attribute value: country. Must be exactly 2 characters length")); paymentRequestValidator.validate(createPaymentRequest); }

Target:
public void validateCountryMinLength_shouldFailValue() { String invalidMaxLengthEmail = randomAlphanumeric(1); CreatePaymentRequest createPaymentRequest = createPaymentRequestBuilderWithAgreementId().country(invalidMaxLengthEmail).build(); expectedException.expect(aValidationExceptionContaining("P0102", "Invalid attribute value: country. Must be exactly 2 characters length")); paymentRequestValidator.validate(createPaymentRequest); }
Source:
private boolean isPermittedIpAddr(HttpRequestHeader requestHeader) { if (getOptionsParamApi().isPermittedAddress(requestHeader.getSenderAddress().getHostAddress())) { if (! requestHeader.getHostName().equalsIgnoreCase("zap") && ! requestHeader.getHostName().equalsIgnoreCase("localhost") && !getOptionsParamApi().isPermittedAddress(requestHeader.getHostName())) { logger.warn("Request to API URL " + requestHeader.getURI().toString() + " with host header " + requestHeader.getHostName() + " not permitted"); return false; } return true; } logger.warn("Request to API URL " + requestHeader.getURI().toString() + " from " + requestHeader.getSenderAddress().getHostAddress() + " not permitted"); return false; }

Target:
private boolean isPermittedIpAddr(HttpRequestHeader requestHeader) { if (getOptionsParamApi().isPermittedAddress(requestHeader.getSenderAddress().getHostAddress())) { if (getOptionsParamApi().isPermittedAddress(requestHeader.getHostName())) { logger.warn("Request to API URL " + requestHeader.getURI().toString() + " with host header " + requestHeader.getHostName() + " not permitted"); return false; } return true; } logger.warn("Request to API URL " + requestHeader.getURI().toString() + " from " + requestHeader.getSenderAddress().getHostAddress() + " not permitted"); return false; }
Source:
public IntentToParticipate build() { if (OperatingSystem.SYNONYMS.containsKey(osName)) { osName = OperatingSystem.SYNONYMS.get(osName); } return new IntentToParticipate(study, phone, subpopGuid, scope, osName, consentSignature); }

Target:
public IntentToParticipate build() { if (OperatingSystem.SYNONYMS.containsKey(osName)) { osName = OperatingSystem.SYNONYMS.get(osName); } return new IntentToParticipate(studyId, phone, subpopGuid, scope, osName, consentSignature); }
Source:
public void addSegments(Iterable<DataSegment> segments, final DataSegmentChangeCallback callback) { try(final BackgroundSegmentAnnouncer backgroundSegmentAnnouncer = new BackgroundSegmentAnnouncer(announcer, exec, config.getAnnounceIntervalMillis())) { backgroundSegmentAnnouncer.startAnnouncing(); final List<ListenableFuture<Boolean>> segmentLoading = Lists.newArrayList(); for (final DataSegment segment : segments) { segmentLoading.add( getLoadingExecutor().submit( new Callable<Boolean>() { @Override public Boolean call() throws SegmentLoadingException { try { log.info("Loading segment %s", segment.getIdentifier()); final boolean loaded = loadSegment(segment, callback); if (loaded) { try { backgroundSegmentAnnouncer.announceSegment(segment); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new SegmentLoadingException(e, "Loading Interrupted"); } } return loaded; } catch(SegmentLoadingException e) { log.error(e, "[%s] failed to load", segment.getIdentifier()); throw e; } } } ) ); } int failed = 0; for(ListenableFuture future : segmentLoading) { try { future.get(); } catch(InterruptedException e) { Thread.currentThread().interrupt(); throw new SegmentLoadingException(e, "Loading Interrupted"); } catch(ExecutionException e) { failed++; } } if(failed > 0) { throw new SegmentLoadingException("%,d errors seen while loading segments", failed); } backgroundSegmentAnnouncer.finishAnnouncing(); } catch (SegmentLoadingException e) { log.makeAlert(e, "Failed to load segments") .addData("segments", segments) .emit(); } finally { callback.execute(); } }

Target:
public void addSegments(Iterable<DataSegment> segments, final DataSegmentChangeCallback callback) { try(final BackgroundSegmentAnnouncer backgroundSegmentAnnouncer = new BackgroundSegmentAnnouncer(announcer, exec, config.getAnnounceIntervalMillis())) { backgroundSegmentAnnouncer.startAnnouncing(); final List<ListenableFuture> segmentLoading = Lists.newArrayList(); for (final DataSegment segment : segments) { segmentLoading.add( getLoadingExecutor().submit( new Callable<Void>() { @Override public Void call() throws SegmentLoadingException { try { log.info("Loading segment %s", segment.getIdentifier()); final boolean loaded = loadSegment(segment, callback); if (loaded) { try { backgroundSegmentAnnouncer.announceSegment(segment); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new SegmentLoadingException(e, "Loading Interrupted"); } } return null; } catch(SegmentLoadingException e) { log.error(e, "[%s] failed to load", segment.getIdentifier()); throw e; } } } ) ); } int failed = 0; for(ListenableFuture future : segmentLoading) { try { future.get(); } catch(InterruptedException e) { Thread.currentThread().interrupt(); throw new SegmentLoadingException(e, "Loading Interrupted"); } catch(ExecutionException e) { failed++; } } if(failed > 0) { throw new SegmentLoadingException("%,d errors seen while loading segments", failed); } backgroundSegmentAnnouncer.finishAnnouncing(); } catch (SegmentLoadingException e) { log.makeAlert(e, "Failed to load segments") .addData("segments", segments) .emit(); } finally { callback.execute(); } }
Source:
private void handleRefreshCapabilities(BrokerCommandCallback callback, AtomicBoolean processHardwareCapsNeeded, VDS vds, VDS oldVDS, VDSReturnValue caps) { if (caps.getSucceeded()) { Set<Version> hostVersions = null; Version clusterCompatibility = vds.getClusterCompatibilityVersion(); if ( (hostVersions = vds.getSupportedClusterVersionsSet()) != null && hostVersions.contains(clusterCompatibility)) { resourceManager.runVdsCommand(VDSCommandType.GetHardwareInfoAsync, new VdsIdAndVdsVDSCommandParametersBase(vds).withCallback( new VdsManagerGetHardwareInfoCallback(callback, processHardwareCapsNeeded, vds, oldVDS, vdsManager))); } else { vdsManager.postProcessRefreshCapabilities(callback, processHardwareCapsNeeded, vds, oldVDS); } } else if (caps.getExceptionObject() != null) { if (callback != null) { callback.onFailure(caps.getExceptionObject()); } throw caps.getExceptionObject(); } else { log.error("refreshCapabilities:GetCapabilitiesVDSCommand failed with no exception!"); if (callback != null) { callback.onFailure(caps.getExceptionObject()); } throw new RuntimeException(caps.getExceptionString()); } }

Target:
private void handleRefreshCapabilities(BrokerCommandCallback callback, AtomicBoolean processHardwareCapsNeeded, VDS vds, VDS oldVDS, VDSReturnValue caps) { if (caps.getSucceeded()) { Set<Version> hostVersions = vds.getSupportedClusterVersionsSet(); Version clusterCompatibility = vds.getClusterCompatibilityVersion(); if (hostVersions != null && hostVersions.contains(clusterCompatibility)) { resourceManager.runVdsCommand(VDSCommandType.GetHardwareInfoAsync, new VdsIdAndVdsVDSCommandParametersBase(vds).withCallback( Injector.injectMembers(new VdsManagerGetHardwareInfoCallback(callback, processHardwareCapsNeeded, vds, oldVDS, vdsManager)))); } else { vdsManager.postProcessRefreshCapabilities(callback, processHardwareCapsNeeded, vds, oldVDS); } } else if (caps.getExceptionObject() != null) { if (callback != null) { callback.onFailure(caps.getExceptionObject()); } throw caps.getExceptionObject(); } else { log.error("refreshCapabilities:GetCapabilitiesVDSCommand failed with no exception!"); if (callback != null) { callback.onFailure(caps.getExceptionObject()); } throw new RuntimeException(caps.getExceptionString()); } }
Source:
public void hideWindow() { if (window != null) { Platform.runLater(window::hide); } }

Target:
public void hideWindow() { Platform.runLater(window::hide); }
Source:
private void sendMessageToLocalTopicListener(TopicListener topicListener, String topic, String path) { String message = null; try { ZNRecord zNRecord = helixStore.get(path, null, AccessOption.PERSISTENT); if (zNRecord != null) { message = zNRecord.getSimpleField(MESSAGE_KEY); long startTimeMs = System.currentTimeMillis(); topicListener.onMessageReceive(topic, message); logger.trace("Message has been sent to TopicListener={} on topic={} with message={} using {}ms", topicListener, topic, message, System.currentTimeMillis() - startTimeMs); } else { logger.debug("TopicListener={} on topic={} should receive a message, but the corresponding ZNRecord is null", topicListener, topic); } } catch (Exception e) { logger.warn("Failed to send message to TopicListener={} for topic={} with message={}", topicListener, topic, message, e); } }

Target:
private void sendMessageToLocalTopicListener(TopicListener topicListener, String topic, String path) { String message = null; try { ZNRecord zNRecord = helixStore.get(path, null, AccessOption.PERSISTENT); if (zNRecord != null) { message = zNRecord.getSimpleField(MESSAGE_KEY); long startTimeMs = System.currentTimeMillis(); topicListener.onMessage(topic, message); logger.trace("Message has been sent to TopicListener={} on topic={} with message={} using {}ms", topicListener, topic, message, System.currentTimeMillis() - startTimeMs); } else { logger.debug("TopicListener={} on topic={} should receive a message, but the corresponding ZNRecord is null", topicListener, topic); } } catch (Exception e) { logger.error("Failed to send message to TopicListener={} for topic={} with message={}", topicListener, topic, message, e); } }
Source:
public Iterator<Rowboat> iterator() { final IntBuffer[] converterArray = FluentIterable .from(convertedDims) .transform( new Function<String, IntBuffer>() { @Override public IntBuffer apply(String input) { return converters.get(input); } } ).toArray(IntBuffer.class); return Iterators.transform( index.iterator(), new Function<Rowboat, Rowboat>() { int rowCount = 0; @Override public Rowboat apply(@Nullable Rowboat input) { int[][] dims = input.getDims(); int[][] newDims = new int[convertedDims.size()][]; for (int i = 0; i < convertedDims.size(); ++i) { IntBuffer converter = converterArray[i]; String dimName = convertedDims.get(i); if (converter == null) { continue; } if (dims[i] == null) { if (dimCardinalities.get(dimName) > 0) { newDims[i] = EMPTY_STR_DIM; } continue; } if (i >= dims.length) { continue; } newDims[i] = new int[dims[i].length]; for (int j = 0; j < dims[i].length; ++j) { if (!converter.hasRemaining()) { log.error("Converter mismatch! wtfbbq!"); } newDims[i][j] = converter.get(dims[i][j]); } } final Rowboat retVal = new Rowboat( input.getTimestamp(), newDims, input.getMetrics(), input.getRowNum() ); retVal.addRow(indexNumber, input.getRowNum()); return retVal; } } ); }

Target:
public Iterator<Rowboat> iterator() { final IntBuffer[] converterArray = FluentIterable .from(convertedDims) .transform( new Function<String, IntBuffer>() { @Override public IntBuffer apply(String input) { return converters.get(input); } } ).toArray(IntBuffer.class); return Iterators.transform( index.iterator(), new Function<Rowboat, Rowboat>() { @Override public Rowboat apply(@Nullable Rowboat input) { int[][] dims = input.getDims(); int[][] newDims = new int[convertedDims.size()][]; for (int i = 0; i < convertedDims.size(); ++i) { IntBuffer converter = converterArray[i]; String dimName = convertedDims.get(i); if (converter == null) { continue; } if (i >= dims.length) { continue; } if (dims[i] == null) { if (dimCardinalities.get(dimName) > 0) { newDims[i] = EMPTY_STR_DIM; } continue; } newDims[i] = new int[dims[i].length]; for (int j = 0; j < dims[i].length; ++j) { if (!converter.hasRemaining()) { log.error("Converter mismatch! wtfbbq!"); } newDims[i][j] = converter.get(dims[i][j]); } } final Rowboat retVal = new Rowboat( input.getTimestamp(), newDims, input.getMetrics(), input.getRowNum() ); retVal.addRow(indexNumber, input.getRowNum()); return retVal; } } ); }
Source:
public List<Chromosome> setup(StoppingCondition sc, int budget, String cut){ Properties.CRITERION = new Criterion[1]; Properties.CRITERION[0] = Criterion.BRANCH; Properties.ALGORITHM = Algorithm.CELLULARGA; Properties.POPULATION = 50; Properties.STOPPING_CONDITION = sc; Properties.SEARCH_BUDGET = budget; Properties.MINIMIZE = false; Randomness.setSeed(10); EvoSuite evosuite = new EvoSuite(); String targetClass = cut; Properties.TARGET_CLASS = targetClass; String[] command = new String[] {"-generateSuite", "-class", targetClass}; Object result = evosuite.parseCommandLine(command); Assert.assertNotNull(result); GeneticAlgorithm<?> ga = getGAFromResult(result); List<Chromosome> population = new ArrayList<Chromosome>(ga.getBestIndividuals()); return population; }

Target:
public List<Chromosome> setup(StoppingCondition sc, int budget, String cut){ Properties.CRITERION = new Criterion[1]; Properties.CRITERION[0] = Criterion.BRANCH; Properties.ALGORITHM = Algorithm.CELLULARGA; Properties.POPULATION = 50; Properties.STOPPING_CONDITION = sc; Properties.SEARCH_BUDGET = budget; Properties.MINIMIZE = false; EvoSuite evosuite = new EvoSuite(); String targetClass = cut; Properties.TARGET_CLASS = targetClass; String[] command = new String[] {"-generateSuite", "-class", targetClass}; Object result = evosuite.parseCommandLine(command); Assert.assertNotNull(result); GeneticAlgorithm<?> ga = getGAFromResult(result); List<Chromosome> population = new ArrayList<Chromosome>(ga.getBestIndividuals()); return population; }
Source:
public static IStatus removeXmlFile(File toDelete) { if(!xmlFileIsActive(toDelete)) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "The XML file is not an active XML Analysis"); } File activeXMLFolder = new File(XmlUtils.getXmlFilesPath().toString()); File[] activeXMLs = activeXMLFolder.listFiles(); for(int i = 0; i < activeXMLs.length; i++) { if(activeXMLs[i].getName().equals(toDelete.getName())) { activeXMLs[i].delete(); break; } } return Status.OK_STATUS; }

Target:
public static IStatus removeXmlFile(File toDelete) { if (!xmlValidate(toDelete).isOK()) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "The XML file is not an active XML Analysis"); } File activeXMLFolder = new File(XmlUtils.getXmlFilesPath().toString()); File[] activeXMLs = activeXMLFolder.listFiles(); for (int i = 0; i < activeXMLs.length; i++) { if (activeXMLs[i].getName().equals(toDelete.getName())) { activeXMLs[i].delete(); break; } } return Status.OK_STATUS; }
Source:
public void functionalFit(FitParams fitParams) throws Exception { try { ComputationGraph model = fitParams.getFunctionalModel(); DataSetIterator trainIterator; DataSetIterator testIterator; trainIterator = new HDF5MiniBatchDataSetIterator( fitParams.getTrainXPath(), fitParams.getTrainYPath() ); if(fitParams.isDoValidation()) { testIterator = new HDF5MiniBatchDataSetIterator( fitParams.getValidationXPath(), fitParams.getValidationYPath() ); } else { testIterator = null; } for (int i = 0; i < fitParams.getNbEpoch(); i++) { log.info("Fitting epoch: " + i); model.fit(trainIterator); double score = model.score(); log.info("Score is "+score); if(fitParams.isDoValidation()) { log.info("Evaluating epoch: " + i); model.evaluate(testIterator); } } log.info("model.fit() operation complete."); } catch (Throwable e) { log.error("Error while performing model.fit()", e); throw e; } }

Target:
public void functionalFit(FitParams fitParams) throws Exception { try { ComputationGraph model = fitParams.getFunctionalModel(); DataSetIterator trainIterator; DataSetIterator testIterator; trainIterator = new HDF5MiniBatchDataSetIterator( fitParams.getTrainXPath(), fitParams.getTrainYPath() ); if(fitParams.isDoValidation()) { testIterator = new HDF5MiniBatchDataSetIterator( fitParams.getValidationXPath(), fitParams.getValidationYPath() ); } else { testIterator = null; } for (int i = 0; i < fitParams.getNbEpoch(); i++) { log.info("Fitting epoch: " + i); model.fit(trainIterator); double score = model.score(); log.info("Score is "+score); if(fitParams.isDoValidation()) { log.info("Evaluating epoch: " + i); Evaluation eval = model.evaluate(testIterator); log.info("Accuracy: "+eval.accuracy()); log.info("Precision: "+eval.precision()); } } log.info("model.fit() operation complete."); } catch (Throwable e) { log.error("Error while performing model.fit()", e); throw e; } }
Source:
public void activate() { super.activate(); View view = getView(); if (view == null) { return; } getDiagramEventBroker().addNotificationListener(view, this); }

Target:
public void activate() { super.activate(); View view = getView(); if (view == null) { return; } subscribe(view); }
Source:
public void testApplication() throws IOException, Exception { try { cleanup(); createTopics(); Configuration conf = getConfig(); LocalMode lma = LocalMode.newInstance(); lma.prepareDAG(new Application(), conf); ValidationToFile validationToFile = (ValidationToFile)lma.getDAG().getOperatorMeta("validationToFile").getOperator(); LocalMode.Controller lc = lma.getController(); lc.runAsync(); while(!validationToFile.validationDone) { System.out.println("Sleeping ...."); Thread.sleep(500); } lc.shutdown(); Thread.sleep(1000); checkOutput(); } catch (ConstraintViolationException e) { Assert.fail("constraint violations: " + e.getConstraintViolations()); } }

Target:
public void testApplication() throws IOException, Exception { try { createTopics(); Configuration conf = getConfig(); LocalMode lma = LocalMode.newInstance(); lma.prepareDAG(new Application(), conf); ValidationToFile validationToFile = (ValidationToFile)lma.getDAG().getOperatorMeta("validationToFile").getOperator(); LocalMode.Controller lc = lma.getController(); lc.runAsync(); int count = 1; int maxSleepRounds = 300; while (!validationToFile.validationDone) { logger.info("Sleeping ...."); Thread.sleep(500); if(count > maxSleepRounds){ fail("validationDone flag did not get set to true in ValidationToFile operator"); } count++; } lc.shutdown(); Thread.sleep(1000); checkOutput(); } catch (ConstraintViolationException e) { fail("constraint violations: " + e.getConstraintViolations()); } }
Source:
protected Object encodeCommand(Command command) { switch (command.getType()) { case Command.TYPE_CUSTOM: return encodeContent(command.getString(Command.KEY_DATA)); case Command.TYPE_ENGINE_STOP: return encodeContent("RELAY,1#"); case Command.TYPE_ENGINE_RESUME: return encodeContent("RELAY,0#"); case Command.TYPE_REBOOT_DEVICE: return encodeContent("RESET#"); case Command.TYPE_GET_VERSION: return encodeContent("VERSION#"); case Command.TYPE_GET_DEVICE_STATUS: return encodeContent("STATUS#"); case Command.TYPE_SOS_NUMBER: String num = command.getString(Command.KEY_DATA); if (!num.isEmpty()) { return encodeContent("SOS,A," + num + "#"); } else { return encodeContent("SOS,D#"); } default: Log.warning(new UnsupportedOperationException(command.getType())); break; } return null; }

Target:
protected Object encodeCommand(Command command) { switch (command.getType()) { case Command.TYPE_CUSTOM: return encodeContent(command.getString(Command.KEY_DATA)); case Command.TYPE_ENGINE_STOP: return encodeContent("RELAY,1#"); case Command.TYPE_ENGINE_RESUME: return encodeContent("RELAY,0#"); case Command.TYPE_REBOOT_DEVICE: return encodeContent("RESET#"); default: Log.warning(new UnsupportedOperationException(command.getType())); break; } return null; }
Source:
private String computeSourceForEnumerator(IASTTranslationUnit ast, IEnumerator binding) throws CoreException { Long numValue = binding.getValue().numericalValue(); if ( numValue != null) { return String.valueOf(numValue); } else { IName[] defs = ast.getDefinitions(binding); for (IName def : defs) { String source= computeSourceForName(def, binding); if (source != null) { return source; } } } return null; }

Target:
private String computeSourceForEnumerator(IASTTranslationUnit ast, IEnumerator binding) throws CoreException { Long numValue = binding.getValue().numericalValue(); if ( numValue != null) { return numValue.toString(); } else { IName[] defs = ast.getDefinitions(binding); for (IName def : defs) { String source= computeSourceForName(def, binding); if (source != null) { return source; } } } return null; }
Source:
public <T> List<T> getBackendCollection(Class<T> clz, VdcQueryType query, VdcQueryParametersBase queryParams) { try { VdcQueryReturnValue result = runQuery(query, queryParams); if (!result.getSucceeded()) { backendFailure(result.getExceptionString()); } List<T> results = asCollection(clz, result.getReturnValue()); if (results!=null && getMaxResults()!=NO_LIMIT && getMaxResults()<results.size()) { results = results.subList(0, getMaxResults()); } return results; } catch (Exception e) { return handleError(e, false); } }

Target:
protected <T> List<T> getBackendCollection(Class<T> clz, VdcQueryType query, VdcQueryParametersBase queryParams) { try { VdcQueryReturnValue result = runQuery(query, queryParams); if (!result.getSucceeded()) { backendFailure(result.getExceptionString()); } List<T> results = asCollection(clz, result.getReturnValue()); if (results!=null && getMaxResults()!=NO_LIMIT && getMaxResults()<results.size()) { results = results.subList(0, getMaxResults()); } return results; } catch (Exception e) { return handleError(e, false); } }
Source:
protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode resolvedValue, ModelNode currentValue, org.jboss.as.controller.AbstractWriteAttributeHandler.HandbackHolder<ModelNode> handbackHolder) throws OperationFailedException { if (!context.isBooting()) { MonitorService agent = getMonitorService(context); if (agent.isImmutable()) { throw new OperationFailedException("The agent is configured to be immutable - no changes are allowed"); } } ModelNode headers = operation.has(OPERATION_HEADERS) ? operation.get(OPERATION_HEADERS) : null; boolean restartAllowedOptionSet = (headers != null) && headers.hasDefined(ALLOW_RESOURCE_SERVICE_RESTART); boolean restartAllowed = !restartAllowedOptionSet || headers.get(ALLOW_RESOURCE_SERVICE_RESTART).asBoolean(); Object tempOwner = null; PathAddress address = null; if (!restartAllowed) { address = getParentAddress(context.getCurrentAddress()); tempOwner = new Object(); context.markResourceRestarted(address, tempOwner); } super.applyUpdateToRuntime(context, operation, attributeName, resolvedValue, currentValue, handbackHolder); if (!restartAllowed) { context.revertResourceRestarted(address, tempOwner); } return false; }

Target:
protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode resolvedValue, ModelNode currentValue, org.jboss.as.controller.AbstractWriteAttributeHandler.HandbackHolder<ModelNode> handbackHolder) throws OperationFailedException { if (!context.isBooting()) { MonitorService agent = getMonitorService(context); if (agent.isImmutable()) { throw new OperationFailedException("The agent is configured to be immutable - no changes are allowed"); } } ModelNode headers = operation.has(OPERATION_HEADERS) ? operation.get(OPERATION_HEADERS) : null; boolean restartAllowedOptionSet = (headers != null) && headers.hasDefined(ALLOW_RESOURCE_SERVICE_RESTART); boolean restartAllowed = !restartAllowedOptionSet || headers.get(ALLOW_RESOURCE_SERVICE_RESTART).asBoolean(); Object tempOwner = null; PathAddress address = null; try { if (!restartAllowed) { address = getParentAddress(WildflyCompatibilityUtils.getCurrentAddress(context, operation)); tempOwner = new Object(); context.markResourceRestarted(address, tempOwner); } super.applyUpdateToRuntime(context, operation, attributeName, resolvedValue, currentValue, handbackHolder); } finally { if (!restartAllowed && null != address && null != tempOwner) { context.revertResourceRestarted(address, tempOwner); } } return false; }
Source:
public void addNewModelElements(EObject eObject, EReference eReference) { final EObject newMEInstance = getNewModelElementInstance(eObject, eReference); if (newMEInstance == null) { return; } if (eReference.isContainer()) { MessageDialog.openError(Display.getDefault().getActiveShell(), "Error", "Operation not permitted for container references!"); return; } if (!eReference.isContainment()) { attachment.addElementToModel(eObject, eReference, newMEInstance); } addReference.addElementToReference(eObject, eReference, newMEInstance); openInNewContext(newMEInstance); }

Target:
public void addNewModelElements(EObject eObject, EReference eReference) { final EObject newMEInstance = getNewModelElementInstance(eObject, eReference); if (newMEInstance == null) { return; } if (eReference.isContainer()) { MessageDialog.openError(Display.getDefault().getActiveShell(), "Error", "Operation not permitted for container references!"); return; } if (!eReference.isContainment()) { attachment.addElementToModel(eObject, eReference, newMEInstance); } addReference.addElementsToReference(eObject, eReference, singleton(newMEInstance)); openInNewContext(newMEInstance); }