auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testKeyRangeCompareUpperRange() throws Exception { List<KeyRange> rowKeyRanges1 = CreateKeyRangeListWithFixedLowerRange( Arrays.asList(Integer.MAX_VALUE, Integer.MAX_VALUE, 10000, 1001, 1000, 1000, 1000, 1000), Arrays.asList(false, false, true, true, true, true, false, true)); List<KeyRange> rowKeyRanges2 = CreateKeyRangeListWithFixedLowerRange( Arrays.asList(Integer.MAX_VALUE, 10000, Integer.MAX_VALUE, 1000, 1001, 1000, 1000, 1000), Arrays.asList(false, false, false, true, true, true, false, false)); List<Integer> expectedResults = Arrays.asList(0, 1, -1, 1, -1, 0, 0, 1); assertEquals(rowKeyRanges1.size(), rowKeyRanges2.size()); assertEquals(rowKeyRanges1.size(), expectedResults.size()); for (int i = 0; i < expectedResults.size(); i++) { int compareResult = KeyRange.compareUpperRange(rowKeyRanges1.get(i), rowKeyRanges2.get(i)); assertEquals(expectedResults.get(i).intValue(), compareResult); } }

Target:
public void testKeyRangeCompareUpperRange() throws Exception { List<KeyRange> rowKeyRanges1 = createKeyRangeListWithFixedLowerRange( Arrays.asList(Integer.MAX_VALUE, Integer.MAX_VALUE, 10000, 1001, 1000, 1000, 1000, 1000, 1000), Arrays.asList(false, false, true, true, true, true, false, true, false)); List<KeyRange> rowKeyRanges2 = createKeyRangeListWithFixedLowerRange( Arrays.asList(Integer.MAX_VALUE, 10000, Integer.MAX_VALUE, 1000, 1001, 1000, 1000, 1000, 1000), Arrays.asList(false, false, false, true, true, true, false, false, true)); List<Integer> expectedResults = Arrays.asList(0, 1, -1, 1, -1, 0, 0, 1, -1); assertEquals(rowKeyRanges1.size(), rowKeyRanges2.size()); assertEquals(rowKeyRanges1.size(), expectedResults.size()); for (int i = 0; i < expectedResults.size(); i++) { int compareResult = KeyRange.compareUpperRange(rowKeyRanges1.get(i), rowKeyRanges2.get(i)); assertEquals(expectedResults.get(i).intValue(), compareResult); } }
Source:
private Locale deJavaLocale(String value) { if (value.length() == 0) { return new Locale(""); } int extStart = value.indexOf("_#"); if (extStart != -1) value = value.substring(0, extStart); int pos1 = value.indexOf('_'); if (pos1 == -1) { return null; } String lang = value.substring(0, pos1++), country, var; int pos2 = value.indexOf('_', pos1); if (pos2 == -1) { country = value.substring(pos1); var = ""; } else { country = value.substring(pos1, pos2); var = value.substring(pos2 + 1); } return new Locale(lang, country, var); }

Target:
private Locale deJavaLocale(String value) { if (value.isEmpty()) { return new Locale(""); } int extStart = value.indexOf("_#"); if (extStart != -1) value = value.substring(0, extStart); String language = value, country = "", variant = ""; int pos1 = value.indexOf('_'); if (pos1 != -1) { language = value.substring(0, pos1++); int pos2 = value.indexOf('_', pos1); if (pos2 == -1) { country = value.substring(pos1); } else { country = value.substring(pos1, pos2); variant = value.substring(pos2 + 1); } } return new Locale(language, country, variant); }
Source:
protected static void checkHostStatusOnMaster(String host) throws Exception { final URI mgmtURI = getMasterMgmtUri(); final String operation = getHostStateRunningOperationJson(host); final long time = System.currentTimeMillis() + TIMEOUT; do { Thread.sleep(1000); if (isHostStateRunning(mgmtURI, operation)) { return; } } while (System.currentTimeMillis() < time); Assert.fail("Cannot validate host '" + host + "' is running"); }

Target:
protected static void checkHostStatusOnMaster(String host) throws Exception { final URI mgmtURI = getMasterMgmtUri(); final String operation = createHostStateRunningOperationJson(host); final long time = System.currentTimeMillis() + TIMEOUT; do { if (isHostStateRunning(mgmtURI, operation)) { return; } Thread.sleep(100); } while (System.currentTimeMillis() < time); Assert.fail("Cannot validate host '" + host + "' is running"); }
Source:
private void notifyUserThatAcctCreatedAndReturnToProfile() { new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(R.string.done_registering) .setMessage(R.string.done_registering_msg) .setPositiveButton( R.string.OK, (dialog1, which) -> { startActivity(new Intent(App.getAppInstance(), InstanceSwitcherActivity.class)); }) .show(); }

Target:
private void notifyUserThatAcctCreatedAndReturnToProfile() { new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(R.string.done_registering) .setMessage(R.string.done_registering_msg) .setPositiveButton( R.string.OK, (dialog1, which) -> { startActivity(new Intent(App.getAppInstance(), App.hasInstanceCode() ? TabLayout.class : InstanceSwitcherActivity.class)); }) .show(); }
Source:
public String getTypeName() { return SchemaOrgConstants.TYPE_TIMESPAN; }

Target:
public String getTypeName() { return SchemaOrgConstants.TYPE_THING;}
Source:
public KeychainModule(ReactApplicationContext reactContext) { super(reactContext); prefsStorage = new PrefsStorage(reactContext); mReactContext = reactContext; addCipherStorageToMap(new CipherStorageFacebookConceal(reactContext)); addCipherStorageToMap(new CipherStorageKeystoreAESCBC()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { addCipherStorageToMap(new CipherStorageKeystoreRSAECB(reactContext)); } }

Target:
public KeychainModule(ReactApplicationContext reactContext) { super(reactContext); prefsStorage = new PrefsStorage(reactContext); addCipherStorageToMap(new CipherStorageFacebookConceal(reactContext)); addCipherStorageToMap(new CipherStorageKeystoreAESCBC()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { addCipherStorageToMap(new CipherStorageKeystoreRSAECB()); } }
Source:
private void givenSequentialRecords(long deltaSeconds, int deltaNanos) { final Duration delta = Duration.newBuilder().setSeconds(deltaSeconds).setNanos(deltaNanos).build(); time1 = getCurrentTime().toBuilder().setNanos(POSITIVE_DELTA * 10).build(); record1 = Given.EventStorage.projectCreated(time1); time2 = add(time1, delta); record2 = Given.EventStorage.taskAdded(time2); time3 = add(time2, delta); record3 = Given.EventStorage.projectStarted(time3); writeAll(record1, record2, record3); }

Target:
private void givenSequentialRecords(long deltaSeconds, int deltaNanos) { final Duration delta = Duration.newBuilder().setSeconds(deltaSeconds).setNanos(deltaNanos).build(); time1 = getCurrentTime().toBuilder().setNanos(POSITIVE_DELTA * 10).build(); record1 = Given.EventStorageRecord.projectCreated(time1); time2 = add(time1, delta); record2 = Given.EventStorageRecord.taskAdded(time2); time3 = add(time2, delta); record3 = Given.EventStorageRecord.projectStarted(time3); writeAll(record1, record2, record3); }
Source:
public boolean isRunning() { WinRmToolResponse runningCheck = executeCommand(VanillaWindowsProcess.CHECK_RUNNING_COMMAND, VanillaWindowsProcess.CHECK_RUNNING_POWERSHELL_COMMAND, false); if(runningCheck.getStatusCode() != 0) { LOG.info(this + " isRunning check failed: exit code " + runningCheck.getStatusCode() + "; " + runningCheck.getStdErr()); } return runningCheck.getStatusCode() == 0; }

Target:
public boolean isRunning() { WinRmToolResponse runningCheck = executeCommand(VanillaWindowsProcess.CHECK_RUNNING_COMMAND, VanillaWindowsProcess.CHECK_RUNNING_POWERSHELL_COMMAND, false); if(runningCheck.getStatusCode() != 0) { LOG.info(getEntity() + " isRunning check failed: exit code " + runningCheck.getStatusCode() + "; " + runningCheck.getStdErr()); } return runningCheck.getStatusCode() == 0; }
Source:
public int write(Iterable<StructuredRecord> structuredRecords, DataWriter dataWriter) throws Exception { int numRecordsWritten = 0; String solrFieldName; List<SolrInputDocument> documentList = new ArrayList<SolrInputDocument>(); SolrInputDocument document; for (StructuredRecord structuredRecord : structuredRecords) { config.validateKeyField(structuredRecord.getSchema()); config.validateInputFieldsDataType(structuredRecord.getSchema()); if (structuredRecord.get(uniqueKey) == null) { continue; } document = new SolrInputDocument(); for (Schema.Field field : structuredRecord.getSchema().getFields()) { solrFieldName = field.getName(); if (outputFieldMap.containsKey(solrFieldName)) { document.addField(outputFieldMap.get(solrFieldName), structuredRecord.get(solrFieldName)); } else { document.addField(solrFieldName, structuredRecord.get(solrFieldName)); } } documentList.add(document); numRecordsWritten++; } solrClient.add(documentList); solrClient.commit(); return numRecordsWritten; }

Target:
public int write(Iterable<StructuredRecord> structuredRecords, DataWriter dataWriter) throws Exception { int numRecordsWritten = 0; List<SolrInputDocument> documentList = new ArrayList<SolrInputDocument>(); for (StructuredRecord structuredRecord : structuredRecords) { config.validateKeyField(structuredRecord.getSchema()); config.validateInputFieldsDataType(structuredRecord.getSchema()); if (structuredRecord.get(keyField) == null) { metrics.count("invalid", 1); continue; } SolrInputDocument document = new SolrInputDocument(); for (Schema.Field field : structuredRecord.getSchema().getFields()) { String solrFieldName = field.getName(); if (outputFieldMap.containsKey(solrFieldName)) { document.addField(outputFieldMap.get(solrFieldName), structuredRecord.get(solrFieldName)); } else { document.addField(solrFieldName, structuredRecord.get(solrFieldName)); } } documentList.add(document); numRecordsWritten++; } solrClient.add(documentList); solrClient.commit(); return numRecordsWritten; }
Source:
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); discussionCommentsAdapter = new DiscussionCommentsAdapter(getActivity(), this, discussionComment); discussionCommentsListView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false)); final int overlap = getResources().getDimensionPixelSize(R.dimen.edx_hairline); discussionCommentsListView.addItemDecoration(new RecyclerView.ItemDecoration() { @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { outRect.set(0, -overlap, 0, 0); } }); discussionCommentsListView.setAdapter(discussionCommentsAdapter); if (isTopicClosed) { createNewCommentTextView.setText(context.getString(R.string.discussion_add_comment_disabled_title)); TextViewCompat.setCompoundDrawablesRelative(createNewCommentTextView, new IconDrawable(getActivity(), Iconify.IconValue.fa_lock) .sizeRes(R.dimen.icon_view_standard_width_height) .colorRes(R.color.edx_grayscale_neutral_white_t), null, null, null ); createNewCommentLayout.setEnabled(false); } else { createNewCommentTextView.setText(context.getString(R.string.discussion_post_create_new_comment)); TextViewCompat.setCompoundDrawablesRelative(createNewCommentTextView, new IconDrawable(getActivity(), Iconify.IconValue.fa_plus_circle) .sizeRes(R.dimen.icon_view_standard_width_height) .colorRes(R.color.edx_grayscale_neutral_white_t), null, null, null ); createNewCommentLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { router.showCourseDiscussionAddComment(context, discussionComment); } }); } }

Target:
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); discussionCommentsAdapter = new DiscussionCommentsAdapter(getActivity(), this, discussionComment); discussionCommentsListView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false)); final int overlap = getResources().getDimensionPixelSize(R.dimen.edx_hairline); discussionCommentsListView.addItemDecoration(new RecyclerView.ItemDecoration() { @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { outRect.set(0, -overlap, 0, 0); } }); discussionCommentsListView.setAdapter(discussionCommentsAdapter); DiscussionUtils.setStateOnTopicClosed(isTopicClosed, createNewCommentTextView, R.string.discussion_post_create_new_comment, R.string.discussion_add_comment_disabled_title, createNewCommentLayout, new View.OnClickListener() { @Override public void onClick(View v) { router.showCourseDiscussionAddComment(context, discussionComment); } }); }
Source:
protected PagerAdapter createAdapter() { return new WelcomePagerAdapter(R.layout.welcome_pager_item, new int[]{R.drawable.waving_android, R.drawable.welcome_app_icon, R.drawable.thumb_up}, new String[]{"So a while a go the GitHub app was discontinued and some of us wanted something new...", "We move the app under a new name and are now PocketHub", "Click done and we'll get you logged in!"}, new String[]{"Welcome", "Long story short", "Let's get started"}); }

Target:
protected PagerAdapter createAdapter() { return new WelcomePagerAdapter(R.layout.welcome_pager_item, new int[]{R.drawable.waving_android, R.drawable.welcome_app_icon, R.drawable.thumb_up}, getResources().getStringArray(R.array.welcome_texts), getResources().getStringArray(R.array.welcome_titles)); }
Source:
DigitalTwinsAsyncClient(HttpPipeline pipeline, DigitalTwinsServiceVersion serviceVersion, String host) { final SimpleModule stringModule = new SimpleModule("String Serializer"); stringModule.addSerializer(new StdSerializer<String>(String.class, false){ @Override public void serialize(String value, JsonGenerator gen, SerializerProvider provider) throws IOException { if (isJSONValid(value)) { gen.writeRawValue(value); } else { gen.writeString(value); } } }); JacksonAdapter jacksonAdapter = new JacksonAdapter(); jacksonAdapter.serializer().registerModule(stringModule); this.protocolLayer = new AzureDigitalTwinsAPIBuilder() .host(host) .pipeline(pipeline) .serializerAdapter(jacksonAdapter) .buildClient(); this.serviceVersion = serviceVersion; }

Target:
DigitalTwinsAsyncClient(HttpPipeline pipeline, DigitalTwinsServiceVersion serviceVersion, String host) { final SimpleModule stringModule = new SimpleModule("String Serializer"); stringModule.addSerializer(new DigitalTwinsStringSerializer(String.class, false, mapper)); JacksonAdapter jacksonAdapter = new JacksonAdapter(); jacksonAdapter.serializer().registerModule(stringModule); this.protocolLayer = new AzureDigitalTwinsAPIImplBuilder() .host(host) .pipeline(pipeline) .serializerAdapter(jacksonAdapter) .buildClient(); this.serviceVersion = serviceVersion; }
Source:
public Optional<BufferOrEvent> pollNext() throws IOException, InterruptedException { Optional<BufferOrEvent> next = inputGate.pollNext(); if (!next.isPresent()) { return handleEmptyBuffer(); } BufferOrEvent bufferOrEvent = next.get(); checkState(!barrierHandler.isBlocked(bufferOrEvent.getChannelInfo())); if (bufferOrEvent.isEvent()) { handleEvent(bufferOrEvent); } else { barrierHandler.processBuffer(bufferOrEvent.getBuffer(), bufferOrEvent.getChannelInfo()); } return next; }

Target:
public Optional<BufferOrEvent> pollNext() throws IOException, InterruptedException { Optional<BufferOrEvent> next = inputGate.pollNext(); if (!next.isPresent()) { return handleEmptyBuffer(); } BufferOrEvent bufferOrEvent = next.get(); checkState(!barrierHandler.isBlocked(bufferOrEvent.getChannelInfo())); if (bufferOrEvent.isEvent()) { handleEvent(bufferOrEvent); } return next; }
Source:
public void initialize(InputSplit inputSplit, TaskAttemptContext context) throws IOException, InterruptedException { Preconditions.checkNotNull(inputSplit, "InputSplit is null"); Preconditions.checkNotNull(context, "TaskAttemptContext is null"); Configuration conf = context.getConfiguration(); this.fileSplit = (FileSplit) inputSplit; Path path = this.fileSplit.getPath(); this.reader = new SequenceFile.Reader(FileSystem.get(conf), path, conf); this.vbytes = this.reader.createValueBytes(); this.more = true; }

Target:
public void initialize(InputSplit inputSplit, TaskAttemptContext context) throws IOException, InterruptedException { Preconditions.checkNotNull(inputSplit, "InputSplit is null"); Preconditions.checkNotNull(context, "TaskAttemptContext is null"); Configuration conf = context.getConfiguration(); FileSplit fileSplit = (FileSplit) inputSplit; Path path = fileSplit.getPath(); reader = new SequenceFile.Reader(FileSystem.get(conf), path, conf); vbytes = this.reader.createValueBytes(); start = fileSplit.getStart(); if (start > reader.getPosition()) { reader.sync(start); } start = reader.getPosition(); end = fileSplit.getStart() + fileSplit.getLength(); more = start < end; }
Source:
public double getClassNumber(int elem) { return (double) (2.5f * Math.pow(elem, 0.25)); }

Target:
public double getClassNumber(int elem) { return 2.5f * Math.pow(elem, 0.25); }
Source:
public Integer getMaxPagePartitioningBufferCount() { return maxPagePartitioningBufferCount; }

Target:
public int getMaxPagePartitioningBufferCount() { return maxPagePartitioningBufferCount; }
Source:
private void replicate(String binaryPath, String originalFileChecksum, String[] replicationLocations, String binaryMimeType, String binaryUri) throws InterruptedException { String remoteFile = null; String localBinary = null; try { for (String location : replicationLocations) { String fullPath = createRemoteSubDirectory(location, originalFileChecksum); if (Files.exists(Paths.get(binaryPath))) { localBinary = binaryPath; } else { localBinary = dbFilePath(binaryUri, originalFileChecksum); } remoteFile = fullPath + "/" + originalFileChecksum; String[] cmd = new String[]{"rsync", "--update", "--whole-file", "--times", "--verbose", localBinary, remoteFile}; Process runCmd = Runtime.getRuntime().exec(cmd); int exitCode = runCmd.waitFor(); if (exitCode != 0) { BufferedReader errInput = new BufferedReader(new InputStreamReader( runCmd.getErrorStream())); String message = errInput.readLine(); throw new ReplicationException(String.format("Error replicating %s to %s with error code %d and message %s", binaryPath, remoteFile, exitCode, message)); } verifyChecksums(originalFileChecksum, remoteFile); } } catch (IOException e) { throw new ReplicationException(String.format("Unable to replicate %s", binaryPath), e); } }

Target:
private void replicate(String binaryPath, String originalFileChecksum, String[] replicationLocations, String binaryMimeType, String binaryUri) throws InterruptedException { String destinationFullPath = null; String localBinary = null; File fcrepoBinary = null; if (Files.exists(Paths.get(binaryPath))) { localBinary = binaryPath; } else { try { fcrepoBinary = fcrepoBinaryDownload(binaryUri, originalFileChecksum); } catch (IOException e) { throw new ReplicationException(String.format("Unable to replicate %s", binaryPath), e); } localBinary = fcrepoBinary.getAbsolutePath(); } try { for (String location : replicationLocations) { String destinationDirectory = createRemoteSubDirectory(location, originalFileChecksum); destinationFullPath = destinationDirectory + "/" + originalFileChecksum; String[] cmd = new String[]{"rsync", "--update", "--whole-file", "--times", "--verbose", localBinary, destinationFullPath}; Process runCmd = Runtime.getRuntime().exec(cmd); int exitCode = runCmd.waitFor(); if (exitCode != 0) { BufferedReader errInput = new BufferedReader(new InputStreamReader( runCmd.getErrorStream())); String message = errInput.readLine(); String errorMsg = String.format("Error replicating %s to %s with error code %d and message %s", binaryPath, destinationFullPath, exitCode, message); throw new ReplicationException(errorMsg); } verifyChecksums(originalFileChecksum, destinationFullPath); if (fcrepoBinary != null) { fcrepoBinary.delete(); } } } catch (IOException e) { throw new ReplicationException(String.format("Unable to replicate %s", binaryPath), e); } }
Source:
protected BufferBuilder getBufferBuilder() throws IOException, InterruptedException { BufferBuilder builder; if (!targetPartition.isApproximatelyAvailable()) { long start = System.currentTimeMillis(); builder = targetPartition.getBufferBuilder(); idleTimeMsPerSecond.markEvent(System.currentTimeMillis() - start); } else { builder = targetPartition.getBufferBuilder(); } return builder; }

Target:
public BufferBuilder getBufferBuilder() throws IOException, InterruptedException { BufferBuilder builder = targetPartition.tryGetBufferBuilder(); if (builder == null) { long start = System.currentTimeMillis(); builder = targetPartition.getBufferBuilder(); idleTimeMsPerSecond.markEvent(System.currentTimeMillis() - start); } return builder; }
Source:
public Optional<ElderData> createFrom(DataHolder dataHolder) { if (dataHolder.supports(Keys.ELDER_GUARDIAN)) { return Optional.<ElderData>of(new SpongeElderData(dataHolder.get(Keys.ELDER_GUARDIAN).get())); } return Optional.absent(); }

Target:
public Optional<ElderData> createFrom(DataHolder dataHolder) { if (dataHolder instanceof EntityGuardian) { return Optional.of(new SpongeElderData(((EntityGuardian) dataHolder).isElder())); } return Optional.empty(); }
Source:
private Boolean processOutput(CallContext callContext){ logger.trace("output endpoint={} count={} state={}", getEndpointPath(), getCallCount(), callContext.getEndpointState()); InputStream[] output = getOutputStream(); processOutputBatch(output, getOutputListener()); switch(getPhase()) { case INTERRUPTING: setPhase(WorkPhase.INTERRUPTED); logger.info("output interrupted endpoint={} count={} work={}", getEndpointPath(), getCallCount(), getWorkUnit()); return false; case RUNNING: if (output == null || output.length == 0) { setPhase(WorkPhase.COMPLETED); logger.info("output completed endpoint={} count={} work={}", getEndpointPath(), getCallCount(), callContext.getWorkUnit()); return false; } return true; case INTERRUPTED: case COMPLETED: throw new IllegalStateException( "cannot process more output as current phase is " + getPhase().name()); default: throw new MarkLogicInternalException( "unexpected state for "+getEndpointPath()+" during loop: "+getPhase().name() ); } }

Target:
private boolean processOutput(CallContext callContext){ logger.trace("output endpoint={} count={} state={}", getEndpointPath(), getCallCount(), callContext.getEndpointState()); InputStream[] output = getOutputStream(); processOutputBatch(output, getOutputListener()); switch(getPhase()) { case INTERRUPTING: setPhase(WorkPhase.INTERRUPTED); logger.info("output interrupted endpoint={} count={} work={}", getEndpointPath(), getCallCount(), getWorkUnit()); return false; case RUNNING: if (output == null || output.length == 0) { setPhase(WorkPhase.COMPLETED); logger.info("output completed endpoint={} count={} work={}", getEndpointPath(), getCallCount(), callContext.getWorkUnit()); return false; } return true; case INTERRUPTED: case COMPLETED: throw new IllegalStateException( "cannot process more output as current phase is " + getPhase().name()); default: throw new MarkLogicInternalException( "unexpected state for "+getEndpointPath()+" during loop: "+getPhase().name() ); } }
Source:
public static List<CharSequence> truncateCommonSubdir(@NonNull final List<CharSequence> directories) { if (directories.size() < 2) { return directories; } final String firstDir = directories.get(0).toString(); String commonEnding = null; int offset = 0; LOOP: while (true) { final String newEnding = firstDir.substring(firstDir.lastIndexOf('/', firstDir.length() - offset)); for (int i = 1; i < directories.size(); i++) { if (!directories.get(i).toString().endsWith(newEnding)) { break LOOP; } } commonEnding = newEnding; offset = commonEnding.length() + 1; } final List<CharSequence> truncatedDirs = new ArrayList<>(directories.size()); for (final CharSequence title : directories) { CharSequence truncated = title; if (commonEnding != null) { truncated = title.subSequence(0, title.length() - commonEnding.length() + 1) + "\u2026"; } truncatedDirs.add(truncated); } return truncatedDirs; }

Target:
public static List<CharSequence> truncateCommonSubdir(@NonNull final List<CharSequence> directories) { if (directories.size() < 2) { return directories; } String commonEnding = directories.get(0).toString(); for (int i = 1; i < directories.size(); i++) { final String directory = directories.get(i).toString(); while (!directory.endsWith(commonEnding)) { final int offset = commonEnding.indexOf('/', 1); if (offset == -1) { return directories; } commonEnding = commonEnding.substring(offset); } } final List<CharSequence> truncatedDirs = new ArrayList<>(directories.size()); for (final CharSequence title : directories) { truncatedDirs.add(title.subSequence(0, title.length() - commonEnding.length() + 1) + "\u2026"); } return truncatedDirs; }
Source:
public boolean performFinishingActions() { String projectLocation = myState.get(PROJECT_LOCATION_KEY); if (projectLocation != null) { File projectRoot = new File(projectLocation); File moduleRoot = new File(projectRoot, myState.get(myModuleNameKey)); try { Template.checkedCreateDirectoryIfMissing(moduleRoot); } catch (IOException e) { LOG.error(e); return false; } Template template = Template.createFromPath(myTemplateFile); Map<String, Object> templateState = FormFactorUtils.scrubFormFactorPrefixes(myFormFactor, myState.flatten()); template.render(projectRoot, moduleRoot, templateState, myWizard.getProject()); TemplateEntry templateEntry = myState.get(KEY_SELECTED_TEMPLATE); if (templateEntry == null) { return true; } Template activityTemplate = templateEntry.getTemplate(); for (Parameter parameter : templateEntry.getMetadata().getParameters()) { templateState.put(parameter.id, myState.get(myParameterStep.getParameterKey(parameter))); } activityTemplate.render(projectRoot, moduleRoot, templateState, myWizard.getProject()); List<File> filesToOpen = myState.get(WizardConstants.FILES_TO_OPEN_KEY); if (filesToOpen != null) { filesToOpen.addAll(activityTemplate.getFilesToOpen()); } return true; } else { return false; } }

Target:
public boolean performFinishingActions() { String projectLocation = myState.get(PROJECT_LOCATION_KEY); if (projectLocation != null) { File projectRoot = new File(projectLocation); File moduleRoot = new File(projectRoot, myState.get(myModuleNameKey)); try { Template.checkedCreateDirectoryIfMissing(moduleRoot); } catch (IOException e) { LOG.error(e); return false; } Template template = Template.createFromPath(myTemplateFile); Map<String, Object> templateState = FormFactorUtils.scrubFormFactorPrefixes(myFormFactor, myState.flatten()); template.render(projectRoot, moduleRoot, templateState, myWizard.getProject()); TemplateEntry templateEntry = myState.get(KEY_SELECTED_TEMPLATE); if (templateEntry == null) { return true; } Template activityTemplate = templateEntry.getTemplate(); for (Parameter parameter : templateEntry.getMetadata().getParameters()) { templateState.put(parameter.id, myState.get(myParameterStep.getParameterKey(parameter))); } activityTemplate.render(projectRoot, moduleRoot, templateState, myWizard.getProject()); List<File> filesToOpen = myState.get(FILES_TO_OPEN_KEY); assert filesToOpen != null; filesToOpen.addAll(activityTemplate.getFilesToOpen()); return true; } else { return false; } }
Source:
public void testUnrecoverableErrorCount() throws Exception{ ServerMetrics.resetAll(); PrepRequestProcessor processor =new PrepRequestProcessor(new ZooKeeperServer(), new MyRequestProcessor()); processor.start(); processor.processRequest(createRquest(1L, 1)); Thread.sleep(200); processor.shutdown(); Map<String, Object> values = ServerMetrics.getAllValues(); Assert.assertEquals(1L, values.get("unrecoverable_error_count")); }

Target:
public void testUnrecoverableErrorCount() { ServerMetrics.resetAll(); ZooKeeperServer zks = new ZooKeeperServer(); ZooKeeperCriticalThread thread = new ZooKeeperCriticalThread("test", zks.getZooKeeperServerListener()); thread.handleException("test", new Exception()); Map<String, Object> values = ServerMetrics.getAllValues(); Assert.assertEquals(1L, values.get("unrecoverable_error_count")); }
Source:
public static Cardinality fromId(String id) { return cardinalityMap.get(id); }

Target:
public static Cardinality fromId(String id) { return Stream.of(values()) .filter(x -> x.getId().equals(id)) .findFirst().get(); }
Source:
public String convertMemberName(Member member) { if (member instanceof Field) { Field f = (Field) member; if (f.isAnnotationPresent(JsonIgnore.class)) { return null; } if (f.isAnnotationPresent(JsonProperty.class)) { String propertyName = f.getDeclaredAnnotation(JsonProperty.class).value(); return CoreUtils.isNullOrEmpty(propertyName) ? f.getName() : propertyName; } } if (member instanceof Method) { Method m = (Method) member; if (m.isAnnotationPresent(JsonIgnore.class)) { return null; } if (m.isAnnotationPresent(JsonProperty.class)) { String propertyName = m.getDeclaredAnnotation(JsonProperty.class).value(); return CoreUtils.isNullOrEmpty(propertyName) ? m.getName() : propertyName; } } return member.getName(); }

Target:
public String convertMemberName(Member member) { if (Modifier.isTransient(member.getModifiers())) { return null; } if (member instanceof Field) { Field f = (Field) member; if (f.isAnnotationPresent(JsonIgnore.class)) { return null; } if (f.isAnnotationPresent(JsonProperty.class)) { String propertyName = f.getDeclaredAnnotation(JsonProperty.class).value(); return CoreUtils.isNullOrEmpty(propertyName) ? f.getName() : propertyName; } return member.getName(); } if (member instanceof Method) { Method m = (Method) member; if (m.isAnnotationPresent(JsonIgnore.class)) { return null; } if (m.isAnnotationPresent(JsonProperty.class)) { String propertyName = m.getDeclaredAnnotation(JsonProperty.class).value(); return CoreUtils.isNullOrEmpty(propertyName) ? m.getName() : propertyName; } return member.getName(); } return null; }
Source:
public void testFindDistinctChromosomesByStudyId() { List<String> chromosomeList = variantEntityRepository.findDistinctChromosomes(); Set<String> expectedChromosomeSet = new HashSet<>(); expectedChromosomeSet.add("11"); expectedChromosomeSet.add("9"); expectedChromosomeSet.add("2"); assertEquals(expectedChromosomeSet, new HashSet<>(chromosomeList)); }

Target:
public void testFindDistinctChromosomesByStudyId() { Set<String> chromosomeSet = variantEntityRepository.findDistinctChromosomes(); Set<String> expectedChromosomes = new HashSet<>(); expectedChromosomes.add("11"); expectedChromosomes.add("9"); expectedChromosomes.add("2"); assertEquals(expectedChromosomes, chromosomeSet); }
Source:
protected Optional<PlanNodeStatsEstimate> doCalculate(TableScanNode node, StatsProvider sourceStats, Lookup lookup, Session session, TypeProvider types) { Constraint<ColumnHandle> constraint = new Constraint<>(node.getCurrentConstraint()); TableStatistics tableStatistics = metadata.getTableStatistics(session, node.getTable(), constraint); Map<VariableReferenceExpression, VariableStatsEstimate> outputVariableStats = new HashMap<>(); for (Map.Entry<VariableReferenceExpression, ColumnHandle> entry : node.getAssignments().entrySet()) { ColumnHandle columnHandle = entry.getValue().withRequiredSubfields(ImmutableList.of()); Optional<ColumnStatistics> columnStatistics = Optional.ofNullable(tableStatistics.getColumnStatistics().get(columnHandle)); outputVariableStats.put(entry.getKey(), columnStatistics.map(statistics -> toSymbolStatistics(tableStatistics, statistics)).orElse(VariableStatsEstimate.unknown())); } return Optional.of(PlanNodeStatsEstimate.builder() .setOutputRowCount(tableStatistics.getRowCount().getValue()) .addVariableStatistics(outputVariableStats) .build()); }

Target:
protected Optional<PlanNodeStatsEstimate> doCalculate(TableScanNode node, StatsProvider sourceStats, Lookup lookup, Session session, TypeProvider types) { Constraint<ColumnHandle> constraint = new Constraint<>(node.getCurrentConstraint()); TableStatistics tableStatistics = metadata.getTableStatistics(session, node.getTable(), ImmutableList.copyOf(node.getAssignments().values()), constraint); Map<VariableReferenceExpression, VariableStatsEstimate> outputVariableStats = new HashMap<>(); for (Map.Entry<VariableReferenceExpression, ColumnHandle> entry : node.getAssignments().entrySet()) { Optional<ColumnStatistics> columnStatistics = Optional.ofNullable(tableStatistics.getColumnStatistics().get(entry.getValue())); outputVariableStats.put(entry.getKey(), columnStatistics.map(statistics -> toSymbolStatistics(tableStatistics, statistics)).orElse(VariableStatsEstimate.unknown())); } return Optional.of(PlanNodeStatsEstimate.builder() .setOutputRowCount(tableStatistics.getRowCount().getValue()) .addVariableStatistics(outputVariableStats) .build()); }
Source:
public Function<Result<TimeseriesResultValue>, Result<TimeseriesResultValue>> makeMetricManipulatorFn( final TimeseriesQuery query, final MetricManipulationFn fn ) { return new Function<Result<TimeseriesResultValue>, Result<TimeseriesResultValue>>() { @Override public Result<TimeseriesResultValue> apply(Result<TimeseriesResultValue> result) { final Map<String, Object> values = Maps.newHashMap(); final TimeseriesResultValue holder = result.getValue(); for (AggregatorFactory agg : query.getAggregatorSpecs()) { values.put(agg.getName(), fn.manipulate(agg, holder.getMetric(agg.getName()))); } for (PostAggregator postAgg : query.getPostAggregatorSpecs()) { Object computedPostAggValue = holder.getMetric(postAgg.getName()); if (computedPostAggValue != null) { values.put(postAgg.getName(), computedPostAggValue); } else { values.put(postAgg.getName(), postAgg.compute(values)); } } return new Result<TimeseriesResultValue>( result.getTimestamp(), new TimeseriesResultValue(values) ); } }; }

Target:
public Function<Result<TimeseriesResultValue>, Result<TimeseriesResultValue>> makeMetricManipulatorFn( final TimeseriesQuery query, final MetricManipulationFn fn ) { return new Function<Result<TimeseriesResultValue>, Result<TimeseriesResultValue>>() { @Override public Result<TimeseriesResultValue> apply(Result<TimeseriesResultValue> result) { final Map<String, Object> values = Maps.newHashMap(); final TimeseriesResultValue holder = result.getValue(); for (AggregatorFactory agg : query.getAggregatorSpecs()) { values.put(agg.getName(), fn.manipulate(agg, holder.getMetric(agg.getName()))); } for (PostAggregator postAgg : query.getPostAggregatorSpecs()) { values.put(postAgg.getName(), postAgg.compute(values)); } return new Result<TimeseriesResultValue>( result.getTimestamp(), new TimeseriesResultValue(values) ); } }; }
Source:
public void testEventLookup() { Set<ITmfEventType> eventTypes = fixture.getEventTypeSet(); Set<String> eventNames = TmfEventTypeCollectionHelper.getEventNames(eventTypes); assertTrue(eventNames.contains("sched_switch")); assertFalse(eventNames.contains("Sched_switch")); String[] events = { "sched_switch", "sched_wakeup", "timer_init" }; assertTrue(eventNames.containsAll(Arrays.asList(events))); Set<String> copy = new HashSet<>(eventNames); copy.retainAll(Arrays.asList(events)); assertTrue(!copy.isEmpty()); String[] names = { "inexistent", "sched_switch", "SomeThing" }; copy = new HashSet<>(eventNames); copy.retainAll(Arrays.asList(names)); assertTrue(!copy.isEmpty()); assertFalse(eventNames.containsAll(Arrays.asList(names))); }

Target:
public void testEventLookup() { Set<ITmfEventType> eventTypes = fixture.getEventTypes(); Set<String> eventNames = TmfEventTypeCollectionHelper.getEventNames(eventTypes); assertTrue(eventNames.contains("sched_switch")); assertFalse(eventNames.contains("Sched_switch")); String[] events = { "sched_switch", "sched_wakeup", "timer_init" }; assertTrue(eventNames.containsAll(Arrays.asList(events))); Set<String> copy = new HashSet<>(eventNames); copy.retainAll(Arrays.asList(events)); assertTrue(!copy.isEmpty()); String[] names = { "inexistent", "sched_switch", "SomeThing" }; copy = new HashSet<>(eventNames); copy.retainAll(Arrays.asList(names)); assertTrue(!copy.isEmpty()); assertFalse(eventNames.containsAll(Arrays.asList(names))); }
Source:
public DottedVersion dottedVersion(String version) throws EvalException { try { return DottedVersion.fromString(version); } catch (IllegalArgumentException e) { throw new EvalException(null, e.getMessage()); } }

Target:
public DottedVersion dottedVersion(String version) throws EvalException { try { return DottedVersion.fromString(version); } catch (DottedVersion.InvalidDottedVersionException e) { throw new EvalException(null, e.getMessage()); } }
Source:
private GitUser getCommitCommitter(RevCommit commit) { PersonIdent committerIdentity = commit.getCommitterIdent(); GitUser oCommitter = createDto(GitUser.class).withName(committerIdentity.getName()) .withEmail(committerIdentity.getEmailAddress()); return oCommitter; }

Target:
private GitUser getCommitCommitter(RevCommit commit) { PersonIdent committerIdentity = commit.getCommitterIdent(); GitUser committer = createDto(GitUser.class).withName(committerIdentity.getName()) .withEmail(committerIdentity.getEmailAddress()); return committer; }
Source:
public String getCACertsDir(CAType caType) { return Paths.get(getCAParentPath(caType), "certs").toString(); }

Target:
public Path getCACertsDir(CAType caType) { return Paths.get(getCAParentPath(caType), "certs"); }
Source:
public ClientCertificateCredential build() { List<String> missing = new ArrayList<>(); if (clientId == null) { missing.add("clientId"); } if (tenantId == null) { missing.add("tenantId"); } if (clientCertificate == null) { missing.add("clientCertificate"); } if (missing.size() > 0) { throw new IllegalArgumentException("Must provide non-null values for " + String.join(", ", missing) + " properties in " + this.getClass().getSimpleName()); } return new ClientCertificateCredential(tenantId, clientId, clientCertificate, clientCertificatePassword, identityClientOptions); }

Target:
public ClientCertificateCredential build() { ValidationUtil.validate(getClass().getSimpleName(), new HashMap<String, Object>() {{ put("clientId", clientId); put("tenantId", tenantId); put("clientCertificate", clientCertificate); }}); return new ClientCertificateCredential(tenantId, clientId, clientCertificate, clientCertificatePassword, identityClientOptions); }
Source:
public AgentLauncher find(String agentName, String machineType) { return launchers.stream().filter(l -> agentName.equals(l.getAgentName()) && machineType.equals(l.getMachineType())) .findAny() .orElse(defaultLauncher); }

Target:
public AgentLauncher find(String agentName, String machineType) { return launchers.stream() .filter(l -> l.getAgentName().equals(agentName)) .filter(l -> l.getMachineType().equals(machineType)) .findAny() .orElse(defaultLauncher); }
Source:
public ParenthesisedExpressionTree PARENTHESIZED_EXPRESSION() { return b.<ParenthesisedExpressionTree>nonterminal(Kind.PARENTHESISED_EXPRESSION).is( f.parenthesizedExpression( b.token(LPARENTHESIS), b.firstOf( EXPRESSION()), b.token(RPARENTHESIS))); }

Target:
public ParenthesisedExpressionTree PARENTHESIZED_EXPRESSION() { return b.<ParenthesisedExpressionTree>nonterminal(Kind.PARENTHESISED_EXPRESSION).is( f.parenthesizedExpression( b.token(LPARENTHESIS), EXPRESSION(), b.token(RPARENTHESIS))); }
Source:
public void addBrokerConnection(MqttBrokerConnection connection) { synchronized (brokerConnections) { brokerConnections.put(connection.getName(), connection); for (MqttBrokersObserver o : brokersObservers) { o.brokerAdded(connection); } } }

Target:
public boolean addBrokerConnection(MqttBrokerConnection connection) { synchronized (brokerConnections) { final String brokerID = connection.getName().toLowerCase(); if (brokerConnections.containsKey(brokerID)) { return false; } brokerConnections.put(brokerID, connection); for (MqttBrokersObserver o : brokersObservers) { o.brokerAdded(connection); } } return true; }
Source:
public void testIfColonPresentAtTheStartAndEndInUriCreds() { locator.setUri("http://:foobar:@localhost:9999"); locator.setPassword("secret"); assertEquals("http://localhost:9999", locator.getRawUri()); assertEquals(":foobar", locator.getUsername()); assertEquals("secret", locator.getPassword()); }

Target:
public void testIfColonPresentAtTheStartAndEndInUriCreds() { locator.setUri("http://:foobar:@localhost:9999"); assertEquals("http://localhost:9999", locator.getRawUri()); assertEquals("", locator.getUsername()); assertEquals("foobar:", locator.getPassword()); }
Source:
private BoundedContext createContext() { Class<? extends AbstractCommandBusTestSuite> cls = getClass(); String name = cls.getSimpleName(); return (multitenant ? BoundedContext.multitenant(name) : BoundedContext.singleTenant(name)) .build(); }

Target:
private BoundedContext createContext() { Class<? extends AbstractCommandBusTestSuite> cls = getClass(); String name = cls.getSimpleName(); BoundedContextBuilder builder = multitenant ? BoundedContext.multitenant(name) : BoundedContext.singleTenant(name); return builder.build(); }
Source:
protected JwtClaims buildJwtClaims(final SingleLogoutRequest request) { val oidc = configurationContext.getCasProperties().getAuthn().getOidc(); val claims = new JwtClaims(); claims.setIssuer(oidc.getIssuer()); claims.setSubject(request.getTicketGrantingTicket().getAuthentication().getPrincipal().getId()); claims.setAudience(((OidcRegisteredService) request.getRegisteredService()).getClientId()); claims.setIssuedAtToNow(); claims.setJwtId(UUID.randomUUID().toString()); val events = new HashMap<String, Object>(); events.put("<LINK_0>", new HashMap()); claims.setClaim("events", events); claims.setClaim(OidcConstants.CLAIM_SESSIOND_ID, DigestUtils.sha(request.getTicketGrantingTicket().getId())); return claims; }

Target:
protected JwtClaims buildJwtClaims(final SingleLogoutRequest request) { val oidc = configurationContext.getCasProperties().getAuthn().getOidc(); val claims = new JwtClaims(); claims.setIssuer(oidc.getIssuer()); claims.setSubject(request.getTicketGrantingTicket().getAuthentication().getPrincipal().getId()); claims.setAudience(((OidcRegisteredService) request.getRegisteredService()).getClientId()); claims.setIssuedAtToNow(); claims.setJwtId(UUID.randomUUID().toString()); val events = new HashMap<String, Object>(); events.put("<LINK_0>", new HashMap<>()); claims.setClaim("events", events); claims.setClaim(OidcConstants.CLAIM_SESSIOND_ID, DigestUtils.sha(request.getTicketGrantingTicket().getId())); return claims; }
Source:
public String getETag() { return DigestUtils.sha1Hex(toString()); }

Target:
public String getETag() { return _eTag; }
Source:
void setClippingInPixels(int x, int y, int width, int height) { if (width < 0) { x = x + width; width = -width; } if (height < 0) { y = y + height; height = -height; } Rectangle requested = new Rectangle(x, y, width, height); Rectangle intersect = clipping.intersection(requested); GdkRectangle rect = new GdkRectangle(); rect.x = intersect.x; rect.y = intersect.y; rect.width = intersect.width; rect.height = intersect.height; long clipRgn = GDK.gdk_region_new(); GDK.gdk_region_union_with_rect(clipRgn, rect); setClipping(clipRgn); GDK.gdk_region_destroy(clipRgn); }

Target:
void setClippingInPixels(int x, int y, int width, int height) { if (width < 0) { x = x + width; width = -width; } if (height < 0) { y = y + height; height = -height; } GdkRectangle rect = new GdkRectangle(); rect.x = x; rect.y = y; rect.width = width; rect.height = height; long clipRgn = GDK.gdk_region_new(); GDK.gdk_region_union_with_rect(clipRgn, rect); setClipping(clipRgn); GDK.gdk_region_destroy(clipRgn); }
Source:
public void reloadServer() throws Exception { try (ManagementClient managementClient = getManagementClient()) { block(managementClient); long timeout = SHUTDOWN_WAITING_TIME + System.currentTimeMillis(); try { ModelNode result = managementClient.getControllerClient().execute( Operations.createOperation(RELOAD, new ModelNode().setEmptyList())); Assert.assertEquals("success", result.get(OUTCOME).asString()); } catch (IOException e) { final Throwable cause = e.getCause(); if (!(cause instanceof ExecutionException) && !(cause instanceof CancellationException)) { throw new RuntimeException(e); } } while (System.currentTimeMillis() < timeout) { Thread.sleep(FREQUENCY); try { managementClient.isServerInRunningState(); } catch (RuntimeException ex) { break; } } Assert.assertFalse(System.currentTimeMillis() < timeout); timeout = RESTART_WAITING_TIME + System.currentTimeMillis(); while (System.currentTimeMillis() < timeout) { Thread.sleep(FREQUENCY); try { managementClient.isServerInRunningState(); } catch (RuntimeException ex) { break; } } } }

Target:
public void reloadServer() throws Exception { try (ManagementClient managementClient = getManagementClient()) { block(managementClient); long timeout = SHUTDOWN_WAITING_TIME + System.currentTimeMillis(); ServerReload.executeReload(managementClient.getControllerClient(), false); while (System.currentTimeMillis() < timeout) { Thread.sleep(FREQUENCY); try { managementClient.isServerInRunningState(); } catch (RuntimeException ex) { break; } } Assert.assertFalse(System.currentTimeMillis() < timeout); timeout = RESTART_WAITING_TIME + System.currentTimeMillis(); while (System.currentTimeMillis() < timeout) { Thread.sleep(FREQUENCY); try { managementClient.isServerInRunningState(); } catch (RuntimeException ex) { break; } } } }
Source:
public Base(final Request req) throws IOException { super(req); this.body = Base.body(req); this.buffer = Base.buffer(req); this.map = this.requests(req); }

Target:
public Base(final Request req) throws IOException { super(req); this.stream = new RqLengthAware(req).body(); this.buffer = ByteBuffer.allocate( Math.min(8192, this.stream.available()) ); this.map = this.requests(req); }
Source:
default Properties asProperties() { ImmutableMap.Builder<String, String> mb = ImmutableMap.builder(); try { if (getVoltDBRoot() == null) { throw new SettingsException("Missing VoltDB root " + "information in path.properties file."); } File voltDBRoot = getVoltDBRoot(); if (voltDBRoot.isAbsolute()) { mb.put(VOLTDBROOT_PATH_KEY, voltDBRoot.getCanonicalPath()); for (Map.Entry<String, File> e: getManagedArtifactPaths().entrySet()) { mb.put(e.getKey(), e.getValue().getCanonicalPath()); } } else { mb.put(VOLTDBROOT_PATH_KEY, voltDBRoot.getPath()); for (Map.Entry<String, File> e: getManagedArtifactPaths().entrySet()) { mb.put(e.getKey(), e.getValue().getName()); } } mb.put(LOCAL_SITES_COUNT_KEY, Integer.toString(getLocalSitesCount())); } catch (IOException e) { throw new SettingsException("failed to canonicalize" + this); } Properties props = new Properties(); props.putAll(mb.build()); return props; }

Target:
default Properties asProperties() { ImmutableMap.Builder<String, String> mb = ImmutableMap.builder(); try { if (getVoltDBRoot() == null) { throw new SettingsException("Missing VoltDB root " + "information in path.properties file."); } File voltdbroot = getVoltDBRoot().getCanonicalFile(); mb.put(VOLTDBROOT_PATH_KEY, voltdbroot.getCanonicalPath()); for (Map.Entry<String, File> e: getManagedArtifactPaths().entrySet()) { File path = e.getValue(); if (path.isAbsolute()) { mb.put(e.getKey(), path.getCanonicalPath()); } else { mb.put(e.getKey(), voltdbroot.toPath().relativize(path.getCanonicalFile().toPath()).toString()); } } mb.put(LOCAL_SITES_COUNT_KEY, Integer.toString(getLocalSitesCount())); } catch (IOException e) { throw new SettingsException("failed to canonicalize" + this); } Properties props = new Properties(); props.putAll(mb.build()); return props; }
Source:
@Nonnull private static <T> Set<T> union(@Nonnull Set<T> a, @Nonnull Set<T> b) { Set<T> set = new LinkedHashSet<>(); if (a.stream().allMatch(x -> x == None.INSTANCE) && a.equals(b)) { return set; } set.addAll(a.stream().filter(x -> x != None.INSTANCE).collect(Collectors.toCollection(LinkedHashSet::new))); set.addAll(b.stream().filter(x -> x != None.INSTANCE).collect(Collectors.toCollection(LinkedHashSet::new))); Optional<T> star = set.stream().filter(x -> x instanceof HostSource && ((HostSource) x).isWildcard()).findAny(); if (star.isPresent()) { set.removeIf(y -> y instanceof HostSource); set.add(star.get()); } return set; }

Target:
@Nonnull private static <T> Set<T> union(@Nonnull Set<T> a, @Nonnull Set<T> b) { Set<T> set = new LinkedHashSet<>(); set.addAll(a); set.addAll(b); set.remove(None.INSTANCE); Optional<T> star = set.stream().filter(x -> x instanceof HostSource && ((HostSource) x).isWildcard()).findAny(); if (star.isPresent()) { set.removeIf(y -> y instanceof HostSource); set.add(star.get()); } return set; }