auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testExplicitlySelected_ExplicitNoInternetExpected() throws Exception { WifiConfiguration config = makeLastSelectedWifiConfiguration(FRAMEWORK_NETWORK_ID, ClientModeImpl.LAST_SELECTED_NETWORK_EXPIRATION_AGE_MILLIS - 1); mConnectedNetwork.noInternetAccessExpected = true; connect(); expectRegisterNetworkAgent(); expectNetworkAgentMessage(NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED, 1 , 1 , null); }

Target:
public void testExplicitlySelected_ExplicitNoInternetExpected() throws Exception { WifiConfiguration config = makeLastSelectedWifiConfiguration(FRAMEWORK_NETWORK_ID, ClientModeImpl.LAST_SELECTED_NETWORK_EXPIRATION_AGE_MILLIS - 1); mConnectedNetwork.noInternetAccessExpected = true; connect(); expectRegisterNetworkAgent((agentConfig) -> { assertTrue(agentConfig.explicitlySelected); assertTrue(agentConfig.acceptUnvalidated); assertTrue(agentConfig.acceptPartialConnectivity); }); }
Source:
private void oldDrawMarker(IMarkerEvent marker, GC gc, Rectangle rect) { Color color = getColorScheme().getColor(marker.getColor()); gc.setBackground(color); gc.setAlpha(color.getAlpha()); gc.fillRectangle(rect); gc.setAlpha(BLACK.getAlpha()); String label = marker.getLabel(); if (fLabelsVisible && label != null && marker.getEntry() != null) { label = label.substring(0, Math.min(label.indexOf('\n') != -1 ? label.indexOf('\n') : label.length(), MAX_LABEL_LENGTH)); gc.setForeground(color); Utils.drawText(gc, label, rect.x - gc.textExtent(label).x, rect.y, true); } }

Target:
private void oldDrawMarker(IMarkerEvent marker, GC gc, Rectangle rect) { Color color = getColorScheme().getColor(marker.getColor()); gc.setBackground(color); gc.setAlpha(color.getAlpha()); gc.fillRectangle(rect); gc.setAlpha(OPAQUE); String label = marker.getLabel(); if (fLabelsVisible && label != null && marker.getEntry() != null) { label = label.substring(0, Math.min(label.indexOf('\n') != -1 ? label.indexOf('\n') : label.length(), MAX_LABEL_LENGTH)); gc.setForeground(color); Utils.drawText(gc, label, rect.x - gc.textExtent(label).x, rect.y, true); } }
Source:
public synchronized void done() { setSubmitted(); if (fDone) { throw new IllegalStateException("RequestMonitor: " + this + ", done() method called more than once"); } fDone = true; fCancelListeners = null; if (fParentRequestMonitor != null) { fParentRequestMonitor.removeCancelListener(fCanceledListener); } if (!isSuccess() && DEBUG_MONITORS) { IStatus status = getStatus(); try { throw new Exception(); } catch (Exception e) { DsfPlugin.getDefault().getLog().log(new Status(status.getSeverity(), DsfPlugin.PLUGIN_ID, status.getCode(), status.getMessage() + "\n\nMonitor Back Trace:\n" + fMonitorBacktrace.toString(), e)); } } try { fExecutor.execute(new DsfRunnable() { @Override public void run() { RequestMonitor.this.handleCompleted(); } @Override public String toString() { return "Completed: " + RequestMonitor.this.toString(); } }); } catch (RejectedExecutionException e) { handleRejectedExecutionException(); } }

Target:
public synchronized void done() { setSubmitted(); if (fDone) { throw new IllegalStateException("RequestMonitor: " + this + ", done() method called more than once"); } fDone = true; fCancelListeners = null; if (fParentRequestMonitor != null) { fParentRequestMonitor.removeCancelListener(fCanceledListener); } if (DEBUG_MONITORS && !isSuccess()) { IStatus status = getStatus(); try { throw new Exception(); } catch (Exception e) { DsfPlugin.getDefault().getLog().log(new Status(status.getSeverity(), DsfPlugin.PLUGIN_ID, status.getCode(), status.getMessage() + "\n\nMonitor Back Trace:\n" + fMonitorBacktrace.toString(), e)); } } try { fExecutor.execute(new DsfRunnable() { @Override public void run() { RequestMonitor.this.handleCompleted(); } @Override public String toString() { return "Completed: " + RequestMonitor.this.toString(); } }); } catch (RejectedExecutionException e) { handleRejectedExecutionException(); } }
Source:
public List<VirtualFile> getBestFileMatches() { if (myResources != null && myFile != null) { FolderConfiguration config = myConfiguration.getFullConfig(); VersionQualifier versionQualifier = config.getVersionQualifier(); config.setVersionQualifier(null); List<VirtualFile> matchingFiles = myResources.getMatchingFiles(myFile, getResourceType(), config); config.setVersionQualifier(versionQualifier); return matchingFiles; } return Collections.emptyList(); }

Target:
public List<VirtualFile> getBestFileMatches() { if (myResources != null && myFile != null) { FolderConfiguration config = myConfiguration.getFullConfig(); VersionQualifier versionQualifier = config.getVersionQualifier(); try { config.setVersionQualifier(null); return myResources.getMatchingFiles(myFile, getResourceType(), config); } finally { config.setVersionQualifier(versionQualifier); } } return Collections.emptyList(); }
Source:
public PushToApplicationAction(StateManager stateManager, PushToApplicationsManager pushToApplicationsManager, DialogService dialogService) { this.application = pushToApplicationsManager.getApplicationByName(Globals.prefs.get(JabRefPreferences.PUSH_TO_APPLICATION)); this.stateManager = stateManager; this.dialogService = dialogService; this.executable.bind(needsDatabase(stateManager).and(needsEntriesSelected(stateManager))); this.statusMessage.bind(BindingsHelper.ifThenElse(this.executable, "", Localization.lang("This operation requires one or more entries to be selected."))); }

Target:
public PushToApplicationAction(StateManager stateManager, PushToApplicationsManager pushToApplicationsManager, DialogService dialogService) { this.application = Globals.prefs.getActivePushToApplication(pushToApplicationsManager); this.stateManager = stateManager; this.dialogService = dialogService; this.executable.bind(needsDatabase(stateManager).and(needsEntriesSelected(stateManager))); this.statusMessage.bind(BindingsHelper.ifThenElse(this.executable, "", Localization.lang("This operation requires one or more entries to be selected."))); }
Source:
public void testAdsOnFilePageOasis() throws Exception { AdsBaseObject ads = buildAdsObjectForPage("File:Example.jpg"); ads.setPageType("file"); FILE_PAGE_EXPECTED_LINE_ITEMS.put(AdsContent.TOP_LB, PROJECT43_TEST_LINE_ITEM_ID); FILE_PAGE_EXPECTED_AD_UNITS.put(AdsContent.TOP_LB, FILE_PAGE_AD_UNIT); FILE_PAGE_EXPECTED_LINE_ITEMS.put(AdsContent.MEDREC, PROJECT43_TEST_LINE_ITEM_ID); FILE_PAGE_EXPECTED_AD_UNITS.put(AdsContent.MEDREC, FILE_PAGE_AD_UNIT); FILE_PAGE_EXPECTED_LINE_ITEMS.put(AdsContent.BOTTOM_LB, PROJECT43_TEST_LINE_ITEM_ID); FILE_PAGE_EXPECTED_AD_UNITS.put(AdsContent.BOTTOM_LB, FILE_PAGE_AD_UNIT); ads.verifyAds(FILE_PAGE_EXPECTED_LINE_ITEMS, FILE_PAGE_EXPECTED_AD_UNITS); }

Target:
public void testAdsOnFilePageOasis() throws Exception { AdsBaseObject ads = buildAdsObjectForPage("File:Example.jpg"); testFilePage(ads); }
Source:
public void log(EventType type, Object... values) { if(!enabled) { return; } try { Request request = Request.Post(forwardUrl + "/") .bodyString(mapper.writeValueAsString(new HttpEvent(new Date(), type, values)), ContentType.APPLICATION_JSON); async.execute(request, new FutureCallback<Content>() { public void failed(final Exception ex) { metrics.markProxyError(); } public void completed(final Content content) { } public void cancelled() { } }); } catch (Throwable t) { log.error("EventLog write failed: {}", t.getMessage()); metrics.markEventLogError(); } }

Target:
public void log(EventType type, Object... values) { if (!enabled) { return; } try { Request request = Request.Post(forwardUrl + "/") .bodyString(mapper.writeValueAsString(new HttpEvent(new Date(), type, values)), ContentType.APPLICATION_JSON); async.execute(request, new FutureCallback<Content>() { public void failed(final Exception ex) { metrics.markEventLogError(); } public void completed(final Content content) { } public void cancelled() { } }); } catch (Throwable t) { log.error("EventLog write failed: {}", t.getMessage()); metrics.markEventLogError(); } }
Source:
public void testAllocateSlot() throws Exception { CompletableFuture<SlotRequest> slotRequestFuture = new CompletableFuture<>(); resourceManagerGateway.setRequestSlotConsumer(slotRequestFuture::complete); try (SlotPoolImpl slotPool = createAndSetUpSlotPool()) { testMainThreadExecutor.execute(() -> slotPool.registerTaskManager(taskManagerLocation.getResourceID())); Scheduler scheduler = new SchedulerImpl(LocationPreferenceSlotSelectionStrategy.createDefault(), slotPool); scheduler.start(testMainThreadExecutor.getMainThreadExecutor()); SlotRequestId requestId = new SlotRequestId(); CompletableFuture<LogicalSlot> future = testMainThreadExecutor.execute(() -> scheduler.allocateSlot( requestId, new DummyScheduledUnit(), SlotProfile.noRequirements(), timeout)); assertFalse(future.isDone()); final SlotRequest slotRequest = slotRequestFuture.get(timeout.toMilliseconds(), TimeUnit.MILLISECONDS); final SlotOffer slotOffer = new SlotOffer( slotRequest.getAllocationId(), 0, DEFAULT_TESTING_PROFILE); assertTrue(testMainThreadExecutor.execute(() -> slotPool.offerSlot( taskManagerLocation, taskManagerGateway, slotOffer))); LogicalSlot slot = future.get(1, TimeUnit.SECONDS); assertTrue(future.isDone()); assertTrue(slot.isAlive()); assertEquals(taskManagerLocation, slot.getTaskManagerLocation()); } }

Target:
public void testAllocateSlot() throws Exception { CompletableFuture<SlotRequest> slotRequestFuture = new CompletableFuture<>(); resourceManagerGateway.setRequestSlotConsumer(slotRequestFuture::complete); try (SlotPoolImpl slotPool = createAndSetUpSlotPool()) { final Scheduler scheduler = createAndSetUpScheduler(slotPool); final CompletableFuture<LogicalSlot> allocatedSlotFuture = allocateSlot(scheduler); assertFalse(allocatedSlotFuture.isDone()); final SlotRequest slotRequest = slotRequestFuture.get(TIMEOUT.toMilliseconds(), TimeUnit.MILLISECONDS); testMainThreadExecutor.execute(() -> slotPool.registerTaskManager(taskManagerLocation.getResourceID())); final SlotOffer slotOffer = new SlotOffer( slotRequest.getAllocationId(), 0, ResourceProfile.ANY); testMainThreadExecutor.execute(() -> slotPool.offerSlot( taskManagerLocation, taskManagerGateway, slotOffer)); final LogicalSlot allocatedSlot = allocatedSlotFuture.get(1, TimeUnit.SECONDS); assertTrue(allocatedSlotFuture.isDone()); assertTrue(allocatedSlot.isAlive()); assertEquals(taskManagerLocation, allocatedSlot.getTaskManagerLocation()); } }
Source:
private ImmutableList<Dimension> createDimensions(Iterable<Map<String, Object>> dimensions) { if (dimensions == null) { return ImmutableList.of(); } return FluentIterable.from(dimensions).transform(MAP_ENTRY_TO_DIMENSION).toList(); }

Target:
private ImmutableList<Dimension> createDimensions(Iterable<Map<String, Object>> dimensions) { return FluentIterable.from(dimensions).transform(MAP_ENTRY_TO_DIMENSION).toList(); }
Source:
public Set<IInstallableUnit> readXML(InputStream is) throws IOException { Parser parser = new Parser(org.eclipse.tycho.p2.maven.repository.xmlio.MetadataIO.Parser.PARSER_MODE.REPO); parser.parse(is, new NullProgressMonitor()); Set<IInstallableUnit> units = new LinkedHashSet<IInstallableUnit>(); for (InstallableUnitDescription desc : parser.getUnits()) { units.add(MetadataFactory.createInstallableUnit(desc)); } return units; }

Target:
public Set<IInstallableUnit> readXML(InputStream is) throws IOException { Parser parser = new Parser(Parser.PARSER_MODE.REPO); parser.parse(is, new NullProgressMonitor()); Set<IInstallableUnit> units = new LinkedHashSet<IInstallableUnit>(); for (InstallableUnitDescription desc : parser.getUnits()) { units.add(MetadataFactory.createInstallableUnit(desc)); } return units; }
Source:
public PlaceholderType checkPlaceholders(String statement) { Matcher quoteMatcher = QUOTE_DETECTION_PATTERN.matcher(statement); Matcher positionMatcher = POSITIONAL_PLACEHOLDER_PATTERN.matcher(statement); Matcher namedMatcher = NAMED_PLACEHOLDER_PATTERN.matcher(statement); List<int[]> quotes = new ArrayList<int[]>(); while (quoteMatcher.find()) { quotes.add(new int[] { quoteMatcher.start(), quoteMatcher.end() }); } int posCount = 0; int namedCount = 0; while (positionMatcher.find()) { String placeholder = positionMatcher.group(1); if (checkNotQuoted(placeholder, positionMatcher.start(), positionMatcher.end(), quotes)) { LOGGER.trace("{}: Found positional placeholder {}", this.queryMethod.getName(), placeholder); posCount++; parameterNames.add(placeholder.substring(1)); } } while (namedMatcher.find()) { String placeholder = namedMatcher.group(1); if (checkNotQuoted(placeholder, namedMatcher.start(), namedMatcher.end(), quotes)) { LOGGER.trace("{}: Found named placeholder {}", this.queryMethod.getName(), placeholder); namedCount++; parameterNames.add(placeholder.substring(1)); } } if (posCount > 0 && namedCount > 0) { throw new IllegalArgumentException("Using both named (" + namedCount + ") and positional (" + posCount + ") placeholders is not supported, please choose one over the other in " + queryMethod.getClass().getName() + "." + this.queryMethod.getName() + "()"); } if (posCount > 0) { return placeHolderType = PlaceholderType.POSITIONAL; } else if (namedCount > 0) { return placeHolderType = PlaceholderType.NAMED; } else { return placeHolderType = PlaceholderType.NONE; } }

Target:
private void checkPlaceholders(String statement) { Matcher quoteMatcher = QUOTE_DETECTION_PATTERN.matcher(statement); Matcher positionMatcher = POSITIONAL_PLACEHOLDER_PATTERN.matcher(statement); Matcher namedMatcher = NAMED_PLACEHOLDER_PATTERN.matcher(statement); List<int[]> quotes = new ArrayList<int[]>(); while (quoteMatcher.find()) { quotes.add(new int[] { quoteMatcher.start(), quoteMatcher.end() }); } int posCount = 0; int namedCount = 0; while (positionMatcher.find()) { String placeholder = positionMatcher.group(1); if (checkNotQuoted(placeholder, positionMatcher.start(), positionMatcher.end(), quotes)) { LOGGER.trace("{}: Found positional placeholder {}", this.queryMethod.getName(), placeholder); posCount++; parameterNames.add(placeholder.substring(1)); } } while (namedMatcher.find()) { String placeholder = namedMatcher.group(1); if (checkNotQuoted(placeholder, namedMatcher.start(), namedMatcher.end(), quotes)) { LOGGER.trace("{}: Found named placeholder {}", this.queryMethod.getName(), placeholder); namedCount++; parameterNames.add(placeholder.substring(1)); } } if (posCount > 0 && namedCount > 0) { throw new IllegalArgumentException("Using both named (" + namedCount + ") and positional (" + posCount + ") placeholders is not supported, please choose one over the other in " + queryMethod.getClass().getName() + "." + this.queryMethod.getName() + "()"); } if (posCount > 0) { placeHolderType = PlaceholderType.POSITIONAL; } else if (namedCount > 0) { placeHolderType = PlaceholderType.NAMED; } else { placeHolderType = PlaceholderType.NONE; } }
Source:
public static FieldNode addNodeByPath( FieldNode fieldNode, String path) { if (path == null || path.isEmpty()) { return fieldNode; } boolean found = false; int index = 0; String[] ps = path.split("\\."); FieldNode c = fieldNode; if (fieldNode != null) { List<FieldNode> currentList = (c == null) ? null : Arrays.asList(c); while (index < ps.length) { found = false; for (FieldNode n : currentList) { if (n.getFieldName().equals(ps[index])) { found = true; if (n.getNodes().isEmpty()) { return fieldNode; } c = n; currentList = c.getNodes(); break; } } if (found) { index++; } else { break; } } } if (!found) { while (index < ps.length) { FieldNode n = new FieldNode(ps[index]); if (fieldNode == null) { fieldNode = n; } if (c != null) { c.addFieldNodes(n); } c = n; index++; } } return fieldNode; }

Target:
public static FieldNode addNodeByPath( FieldNode fieldNode, String path) { if (path == null || path.isEmpty()) { return fieldNode; } boolean found = false; int index = 0; String[] ps = path.split("\\."); FieldNode c = fieldNode; if (fieldNode != null) { List<FieldNode> currentList = Arrays.asList(c); while (index < ps.length) { found = false; for (FieldNode n : currentList) { if (n.getFieldName().equals(ps[index])) { found = true; if (n.getNodes().isEmpty()) { return fieldNode; } c = n; currentList = c.getNodes(); break; } } if (found) { index++; } else { break; } } } if (!found) { while (index < ps.length) { FieldNode n = new FieldNode(ps[index]); if (fieldNode == null) { fieldNode = n; } if (c != null) { c.addFieldNodes(n); } c = n; index++; } } else { if (index == ps.length) { c.getNodes().clear(); } } return fieldNode; }
Source:
public List<String> getNames() { final List<String> steps = new ArrayList<>(); if (battleState.getBattleSite().isWater() && Properties.getTransportCasualtiesRestricted(battleState.getGameData()) && (battleState.getAttackingUnits().stream().anyMatch(Matches.unitIsTransport()) || battleState.getDefendingUnits().stream().anyMatch(Matches.unitIsTransport()))) { steps.add(REMOVE_UNESCORTED_TRANSPORTS); } return steps; }

Target:
public List<String> getNames() { if (battleState.getBattleSite().isWater() && Properties.getTransportCasualtiesRestricted(battleState.getGameData()) && (battleState.getAttackingUnits().stream().anyMatch(Matches.unitIsTransport()) || battleState.getDefendingUnits().stream().anyMatch(Matches.unitIsTransport()))) { return List.of(REMOVE_UNESCORTED_TRANSPORTS); } return List.of(); }
Source:
private void createUpdateDialog(String content) { RssUpdate update = parser.parseUpdate(content); if(update != null) { Thread updateDialogThread = new Thread(() -> myUiFacade.showUpdateDialog(update)); updateDialogThread.start(); } }

Target:
private void createUpdateDialog(String content) { RssUpdate update = parser.parseUpdate(content); if (update != null) { UpdateDialog.show(myUiFacade, update); } }
Source:
public void scrape(HttpAction action) { try (ServletOutputStream out = action.response.getOutputStream()) { action.response.setContentType( WebContent.contentTypeTextPlain ); action.response.setCharacterEncoding( WebContent.charsetUTF8 ); out.write( meterRegistry.scrape().getBytes() ); } catch (Throwable t) { ServletOps.errorOccurred( t ); } }

Target:
public void scrape(HttpAction action) { try (ServletOutputStream out = action.response.getOutputStream()) { ServletOps.success(action); action.response.setContentType( WebContent.contentTypeTextPlain ); action.response.setCharacterEncoding( WebContent.charsetUTF8 ); out.write( meterRegistry.scrape().getBytes() ); } catch (Throwable t) { ServletOps.errorOccurred( t ); } }
Source:
public ITmfStateValue getValue(@Nullable ITmfEvent event, @Nullable TmfXmlScenarioInfo scenarioInfo) throws AttributeNotFoundException { Object result = null; ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName(fScriptEngine); for (TmfXmlStateValue stateValue : fChildStateValues) { ITmfStateValue value = stateValue.getValue(event, scenarioInfo); switch (value.getType()) { case LONG: engine.put(stateValue.getID(), value.unboxLong()); break; case INTEGER: engine.put(stateValue.getID(), value.unboxInt()); break; case STRING: engine.put(stateValue.getID(), value.unboxStr()); break; case DOUBLE: case CUSTOM: case NULL: default: } } try { result = engine.eval(fScript); } catch (ScriptException e) { Activator.logError("Script execution failed", e); return TmfStateValue.nullValue(); } return TmfStateValue.newValueObjectWithForcedType(result, fForcedType); }

Target:
public ITmfStateValue getValue(@Nullable ITmfEvent event, @Nullable TmfXmlScenarioInfo scenarioInfo) throws AttributeNotFoundException { Object result = null; ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName(fScriptEngine); for (TmfXmlStateValue stateValue : fChildStateValues) { String stateValueID = stateValue.getID(); if (stateValueID != null) { ITmfStateValue value = stateValue.getValue(event, scenarioInfo); switch (value.getType()) { case LONG: engine.put(stateValueID, value.unboxLong()); break; case INTEGER: engine.put(stateValueID, value.unboxInt()); break; case STRING: engine.put(stateValueID, value.unboxStr()); break; case DOUBLE: case CUSTOM: case NULL: default: } }else{ Activator.logWarning(Messages.TmfXmlStateValue_MissingScriptChildrenID); } } try { result = engine.eval(fScript); } catch (ScriptException e) { Activator.logError("Script execution failed", e); return TmfStateValue.nullValue(); } return TmfXmlUtils.newTmfStateValueFromObjectWithForcedType(result, fForcedType); }
Source:
public void matchShouldReturnAddressesWhenSubclassOfSpecifiedExceptionHasOccurred() throws MessagingException { mockedMail.setAttribute(Mail.MAILET_ERROR_ATTRIBUTE_NAME, new javax.mail.internet.AddressException()); FakeMatcherConfig matcherConfig = FakeMatcherConfig.builder().matcherName("HasException") .condition("javax.mail.MessagingException").build(); matcher.init(matcherConfig); assertThat(matcher.match(mockedMail)).containsExactlyElementsOf(mockedMail.getRecipients()); }

Target:
public void matchShouldReturnAddressesWhenSubclassOfSpecifiedExceptionHasOccurred() throws MessagingException { mockedMail.setAttribute(Mail.MAILET_ERROR_ATTRIBUTE_NAME, new javax.mail.internet.AddressException()); FakeMatcherConfig matcherConfig = FakeMatcherConfig.builder() .matcherName("HasException") .condition("javax.mail.MessagingException") .build(); testee.init(matcherConfig); assertThat(testee.match(mockedMail)).containsExactlyElementsOf(mockedMail.getRecipients()); }
Source:
protected IntegrationTest(final Class<? extends ResourceConfig> resourceConfig, String packageName) { this.resourceConfig = resourceConfig.getName(); this.packageName = packageName; if (dataStoreHarness == null) { dataStoreHarness = createHarness(); } this.dataStore = dataStoreHarness.getDataStore(); try { this.server = setUpServer(); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException(e); } }

Target:
protected IntegrationTest(final Class<? extends ResourceConfig> resourceConfig, String packageName) { this.resourceConfig = resourceConfig.getName(); this.packageName = packageName; if (dataStoreHarness == null) { dataStoreHarness = createHarness(); } this.dataStore = dataStoreHarness.getDataStore(); try { this.server = setUpServer(); } catch (Exception e) { throw new IllegalStateException(e); } }
Source:
public void cleanup() { if (solrClient != null) { try { solrClient.close(); } catch (IOException e) { LOG.debug("Error while closing solrClient", e); } } }

Target:
public void cleanup() { if (solrClient != null) { try { solrClient.close(); } catch (IOException e) { LOG.error("Error while closing solrClient", e); } } }
Source:
public FormValidation doCheckResourceNames(@QueryParameter String value, @QueryParameter String labelName, @QueryParameter boolean script) { String labelVal = Util.fixEmptyAndTrim(labelName); String names = Util.fixEmptyAndTrim(value); if (names == null) { return FormValidation.ok(); } else if (labelVal != null || script) { return FormValidation.error( "Only label, groovy expression, or resources can be defined, not more than one."); } else { List<String> wrongNames = new ArrayList<>(); List<String> varNames = new ArrayList<>(); for (String name : names.split("\\s+")) { if (name.startsWith("$")) { varNames.add(name); continue; } boolean found = false; for (LockableResource r : LockableResourcesManager.get() .getResources()) { if (r.getName().equals(name)) { found = true; break; } } if (!found) wrongNames.add(name); } if (wrongNames.isEmpty() && varNames.isEmpty()) { return FormValidation.ok(); } else if (wrongNames.isEmpty()) { return FormValidation .warning("The following resources cannot be validated as they are the environment variables: " + varNames); } else { return FormValidation .error("The following resources do not exist: " + wrongNames); } } }

Target:
public FormValidation doCheckResourceNames(@QueryParameter String value, @QueryParameter String labelName, @QueryParameter boolean script) { String labelVal = Util.fixEmptyAndTrim(labelName); String names = Util.fixEmptyAndTrim(value); if (names == null) { return FormValidation.ok(); } else if (labelVal != null || script) { return FormValidation.error( "Only label, groovy expression, or resources can be defined, not more than one."); } else { List<String> wrongNames = new ArrayList<>(); List<String> varNames = new ArrayList<>(); for (String name : names.split("\\s+")) { boolean found = false; for (LockableResource r : LockableResourcesManager.get() .getResources()) { if (r.getName().equals(name)) { found = true; break; } } if (!found) { if (name.contains("$")) { varNames.add(name); } else { wrongNames.add(name); } } } if (wrongNames.isEmpty() && varNames.isEmpty()) { return FormValidation.ok(); } else if (wrongNames.isEmpty()) { return FormValidation .warning("The following resources cannot be validated as they are the environment variables: " + varNames); } else { return FormValidation .error("The following resources do not exist: " + wrongNames); } } }
Source:
private void validateCascadedContainerElementsForCurrentGroup(Object value, ValidationContext<?> validationContext, ValueContext<?, ?> valueContext, List<ContainerCascadingMetaData> containerElementTypesCascadingMetaData) { for ( ContainerCascadingMetaData cascadingMetaData : containerElementTypesCascadingMetaData ) { if ( !cascadingMetaData.isMarkedForCascadingOnAnnotatedObjectOrContainerElements() ) { continue; } ValueExtractorDescriptor extractor = valueExtractorManager.getMaximallySpecificAndRuntimeContainerElementCompliantValueExtractor( cascadingMetaData.getEnclosingType(), value.getClass(), cascadingMetaData.getTypeParameter() ); if ( extractor == null ) { throw LOG.getNoValueExtractorFoundForTypeException( cascadingMetaData.getEnclosingType(), cascadingMetaData.getTypeParameter(), value.getClass() ); } CascadingValueReceiver receiver = new CascadingValueReceiver( validationContext, valueContext, cascadingMetaData ); ValueExtractorHelper.extractValues( extractor, value, receiver ); } }

Target:
private void validateCascadedContainerElementsForCurrentGroup(Object value, ValidationContext<?> validationContext, ValueContext<?, ?> valueContext, List<ContainerCascadingMetaData> containerElementTypesCascadingMetaData) { for ( ContainerCascadingMetaData cascadingMetaData : containerElementTypesCascadingMetaData ) { if ( !cascadingMetaData.isMarkedForCascadingOnAnnotatedObjectOrContainerElements() ) { continue; } ValueExtractorDescriptor extractor = valueExtractorManager.getMaximallySpecificAndRuntimeContainerElementCompliantValueExtractor( cascadingMetaData.getEnclosingType(), cascadingMetaData.getTypeParameter(), value.getClass(), cascadingMetaData.getValueExtractorCandidates() ); if ( extractor == null ) { throw LOG.getNoValueExtractorFoundForTypeException( cascadingMetaData.getEnclosingType(), cascadingMetaData.getTypeParameter(), value.getClass() ); } CascadingValueReceiver receiver = new CascadingValueReceiver( validationContext, valueContext, cascadingMetaData ); ValueExtractorHelper.extractValues( extractor, value, receiver ); } }
Source:
public GHRepository loadRepository(final String repositoryName) { try { if (gh != null && isAuthenticated() && (myRealm.hasScope("repo") || myRealm.hasScope("public_repo"))) { Optional<GHRepository> optionalRepo = repositoryCache.get(repositoryName, new Callable<Optional<GHRepository>>() { @Override public Optional<GHRepository> call() throws Exception { return Optional.fromNullable(getGitHub().getRepository(repositoryName)); } } ); return optionalRepo.orNull(); } } catch (Exception e) { LOGGER.log(Level.SEVERE, "an exception was thrown", e); LOGGER.log(Level.WARNING, "Looks like a bad GitHub URL OR the Jenkins user {0} does not have access to the repository {1}. May need to add 'repo' or 'public_repo' to the list of oauth scopes requested.", new Object[] { this.userName, repositoryName }); } return null; }

Target:
public RepoRights loadRepository(final String repositoryName) { try { if (gh != null && isAuthenticated() && (myRealm.hasScope("repo") || myRealm.hasScope("public_repo"))) { return repositoryCache.get(repositoryName, new Callable<RepoRights>() { @Override public RepoRights call() throws Exception { GHRepository repo = getGitHub().getRepository(repositoryName); return new RepoRights(repo); } } ); } } catch (Exception e) { LOGGER.log(Level.SEVERE, "an exception was thrown", e); LOGGER.log(Level.WARNING, "Looks like a bad GitHub URL OR the Jenkins user {0} does not have access to the repository {1}. May need to add 'repo' or 'public_repo' to the list of oauth scopes requested.", new Object[] { this.userName, repositoryName }); } return null; }
Source:
ContainerDelta(Set<PackingPlan.ContainerPlan> currentContainers, Set<PackingPlan.ContainerPlan> proposedContainers) { Set<PackingPlan.ContainerPlan> toAdd = new HashSet<>(); for (PackingPlan.ContainerPlan proposedContainerPlan : proposedContainers) { if (!currentContainers.contains(proposedContainerPlan)) { toAdd.add(proposedContainerPlan); } } this.containersToAdd = Collections.unmodifiableSet(toAdd); Set<PackingPlan.ContainerPlan> toRemove = new HashSet<>(); for (PackingPlan.ContainerPlan curentContainerPlan : currentContainers) { if (!proposedContainers.contains(curentContainerPlan)) { toRemove.add(curentContainerPlan); } } this.containersToRemove = Collections.unmodifiableSet(toRemove); }

Target:
ContainerDelta(Set<PackingPlan.ContainerPlan> currentContainers, Set<PackingPlan.ContainerPlan> proposedContainers) { Set<Integer> currentContainerIds = toIdSet(currentContainers); Set<Integer> proposedContainerIds = toIdSet(proposedContainers); Set<PackingPlan.ContainerPlan> toAdd = new HashSet<>(); for (PackingPlan.ContainerPlan proposedContainerPlan : proposedContainers) { if (!currentContainerIds.contains(proposedContainerPlan.getId())) { toAdd.add(proposedContainerPlan); } } this.containersToAdd = Collections.unmodifiableSet(toAdd); Set<PackingPlan.ContainerPlan> toRemove = new HashSet<>(); for (PackingPlan.ContainerPlan currentContainerPlan : currentContainers) { if (!proposedContainerIds.contains(currentContainerPlan.getId())) { toRemove.add(currentContainerPlan); } } this.containersToRemove = Collections.unmodifiableSet(toRemove); }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MessageInfo that = (MessageInfo) o; return size == that.size && expirationTimeInMs == that.expirationTimeInMs && isDeleted == that.isDeleted && isTtlUpdated == that.isTtlUpdated && accountId == that.accountId && containerId == that.containerId && operationTimeMs == that.operationTimeMs && Objects.equals(key, that.key) && updateVersion == that.updateVersion && Objects.equals(crc, that.crc); }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MessageInfo that = (MessageInfo) o; return size == that.size && expirationTimeInMs == that.expirationTimeInMs && isDeleted == that.isDeleted && isTtlUpdated == that.isTtlUpdated && isUndeleted == that.isUndeleted && accountId == that.accountId && containerId == that.containerId && operationTimeMs == that.operationTimeMs && Objects.equals(key, that.key) && lifeVersion == that.lifeVersion && Objects.equals(crc, that.crc); }
Source:
public S notPropagatedHeaders(String... headerPatterns) { assertHandler(); if (this.handler instanceof AbstractMessageProducingHandler) { ((AbstractMessageProducingHandler) this.handler).setNotPropagatedHeaders(headerPatterns); } else { logger.warn("'async' can be applied only for AbstractMessageProducingHandler"); } return _this(); }

Target:
public S notPropagatedHeaders(String... headerPatterns) { assertHandler(); if (this.handler instanceof AbstractMessageProducingHandler) { ((AbstractMessageProducingHandler) this.handler).setNotPropagatedHeaders(headerPatterns); } else { this.logger.warn("'headerPatterns' can be applied only for AbstractMessageProducingHandler"); } return _this(); }
Source:
public int execute(AtlasDbServices services) { if (epochTime == null) { throw new IllegalArgumentException("Required option '-e' is missing"); } if (epochTime < 0) { throw new IllegalArgumentException("Option '-e' should be a positive long, as epoch time" + " is never negative."); } Date date = new Date(epochTime); printer.info("Input in epoch millis is {}", SafeArg.of("epochMillis", epochTime), SafeArg.of("date", date)); KeyValueService keyValueService = services.getKeyValueService(); PuncherStore puncherStore = KeyValueServicePuncherStore.create(keyValueService, false); Long value = puncherStore.get(epochTime); printer.info("The first timestamp before is {}", SafeArg.of("date", date), SafeArg.of("timestamp", value)); return 0; }

Target:
public int execute(AtlasDbServices services) { if (epochTime == null) { throw new IllegalArgumentException("Required option '-e' is missing"); } if (epochTime < 0) { throw new IllegalArgumentException("Option '-e' should be a positive long, as epoch time" + " is never negative."); } Instant epochTimeInstant = Instant.ofEpochSecond(epochTime); ZonedDateTime date = ZonedDateTime.ofInstant(epochTimeInstant, ZoneId.systemDefault()); printer.info("Input in epoch millis is {}", SafeArg.of("epochMillis", epochTime), SafeArg.of("date", date.toString())); KeyValueService keyValueService = services.getKeyValueService(); PuncherStore puncherStore = KeyValueServicePuncherStore.create(keyValueService, false); Long value = puncherStore.get(epochTime); printer.info("The first timestamp before is {}", SafeArg.of("date", date.toString()), SafeArg.of("timestamp", value)); return 0; }
Source:
protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) { drawBackground(BACKGROUND); drawContainerName(); SmelteryTank liquids = tinkerTank.getTank(); if(liquids.getFluidAmount() > 0) { int capacity = Math.max(liquids.getFluidAmount(), liquids.getCapacity()); int[] heights = calcLiquidHeights(liquids.getFluids(), capacity); int x = 8 + guiLeft; int y = 16 + scala.h + guiTop; int w = scala.w; for(int i = 0; i < heights.length; i++) { int h = heights[i]; FluidStack liquid = liquids.getFluids().get(i); RenderUtil.renderTiledFluid(x, y - h, w, h, this.zLevel, liquid); y -= h; } } }

Target:
protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) { drawBackground(BACKGROUND); drawContainerName(); GuiUtil.drawGuiTank(tinkerTank.getTank(), 8 + guiLeft, 16 + guiTop, scala.w, scala.h, this.zLevel); }
Source:
private static Appendable writeComplexProps(Appendable o, Schema s) throws IOException { if (s.getDoc() !=null && !s.getDoc().isEmpty()) o.append(",\"doc\":\"").append(s.getDoc()).append("\""); if (s.getAliases() !=null && !s.getAliases().isEmpty()) o.append(",\"aliases\":").append(JacksonUtils.toJsonNode(s.getAliases()).toString()); return o; }

Target:
private static Appendable writeComplexProps(Appendable o, Schema s) throws IOException { if (s.getDoc() != null && !s.getDoc().isEmpty()) o.append(",\"doc\":\"").append(s.getDoc()).append("\""); if (s.getAliases() != null && !s.getAliases().isEmpty()) o.append(",\"aliases\":").append(JacksonUtils.toJsonNode(new TreeSet<String>(s.getAliases())).toString()); return o; }
Source:
public void populateDAG(DAG dag, Configuration conf) { InputDataGeneratorOperator modifier = dag.addOperator("datagenerator", new InputDataGeneratorOperator()); DelimitedParserModule parser = dag.addModule("delimitedParser", new DelimitedParserModule()); VerifierOperator verifier = dag.addOperator("verifier", new VerifierOperator()); dag.addStream("input", modifier.output, parser.input).setLocality(Locality.THREAD_LOCAL); dag.addStream("parsedObject", parser.parsedData, verifier.parsedObject); dag.addStream("pojo", parser.pojo, verifier.pojo); dag.addStream("error", parser.error, verifier.error); }

Target:
public void populateDAG(DAG dag, Configuration conf) { InputDataGeneratorOperator datagenerator = dag.addOperator("datagenerator", new InputDataGeneratorOperator()); DelimitedParserModule parser = dag.addModule("delimitedParser", new DelimitedParserModule()); VerifierOperator verifier = dag.addOperator("verifier", new VerifierOperator()); dag.addStream("input", datagenerator.output, parser.input).setLocality(Locality.THREAD_LOCAL); dag.addStream("parsedObject", parser.parsedData, verifier.parsedObject); dag.addStream("pojo", parser.pojo, verifier.pojo); dag.addStream("error", parser.error, verifier.error); }
Source:
public void characters(String text) { assertOpenBlock(); try { for (int x = 0; x < text.length(); ++x) { char c = text.charAt(x); switch (c) { case '\u00A0':// &nbsp; currentBlock.write(' '); break; case '\u00A9': currentBlock.write("(c)");break; case '\u00AE': currentBlock.write("(r)");break; default: currentBlock.write(c); break; } } } catch (IOException e) { throw new RuntimeException(e); } }

Target:
public void characters(String text) { assertOpenBlock(); try { for (int x = 0; x < text.length(); ++x) { char c = text.charAt(x); currentBlock.write(c); } } catch (IOException e) { throw new RuntimeException(e); } }
Source:
public void testDummyTransport() throws Exception { PDU pdu = makePdu(); LOG.debug(SnmpUtils.getHexString(Snmp4JUtils.convertPduToBytes(InetAddressUtils.ONE_TWENTY_SEVEN, 162, "hello", pdu))); }

Target:
public void testDummyTransport() throws Exception { PDU pdu = makePdu(); byte[] bytes = Snmp4JUtils.convertPduToBytes(InetAddressUtils.ONE_TWENTY_SEVEN, 162, "hello", pdu); LOG.debug(SnmpUtils.getHexString(bytes)); assertTrue(Bytes.indexOf(bytes, new byte[] { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o'}) >= 0); assertTrue(Bytes.indexOf(bytes, new byte[] { 127, 0, 0, 1 }) >= 0); assertTrue(Bytes.indexOf(bytes, new byte[] { 127, 0, 10, 1 }) < 0); assertTrue(Bytes.indexOf(bytes, new byte[] { (byte)'T', (byte)'r', (byte)'a', (byte)'p', (byte)' ', (byte)'M', (byte)'s', (byte)'g', (byte)' ', (byte)'v', (byte)'2', (byte)'-', (byte)'1' }) >= 0); }
Source:
private OsinfoResources matchFirstResourcesByArch(String cpuArch, OsinfoResourcesList resources) { if (resources == null || cpuArch == null) { return null; } for (int i = 0; i < lib.osinfo_list_get_length(resources.parent_instance); i++) { OsinfoEntity entity = lib.osinfo_list_get_nth(resources.parent_instance, i); String architecure = getResourceArchitecture(entity); if (cpuArch.equalsIgnoreCase(architecure)) { return new OsinfoResources(entity, null); } } return null; }

Target:
private Pointer matchFirstResourcesByArch(String cpuArch, OsinfoResourcesList resources) { if (resources == null || cpuArch == null) { return null; } for (int i = 0; i < lib.osinfo_list_get_length(resources.osList); i++) { Pointer osinfoEntity = lib.osinfo_list_get_nth(resources.osList, i); String architecure = getResourceArchitecture(osinfoEntity); if (cpuArch.equalsIgnoreCase(architecure)) { return osinfoEntity; } } return null; }
Source:
public static byte[] randomByteArray(Random random, int length) { byte[] result = new byte[length]; for (int k = 0; k < length; k++) { result[k] = (byte) random.nextInt(); } return result; }

Target:
public static byte[] randomByteArray(Random random, int length) { byte[] result = new byte[length]; random.nextBytes(result); return result; }
Source:
public void updateUI() { String name = "Visualizer View"; String description = "Displays visualizations of launches."; if (m_viewer != null) { name = m_viewer.getVisualizerDisplayName(); String secondaryId = this.getViewSite().getSecondaryId(); if (secondaryId != null) { name += " <" + PinCloneUtils.decodeClonedPartSecondaryId(secondaryId) +">"; } description = m_viewer.getVisualizerDescription(); } setTabName(name); setTabDescription(description); if (m_viewer != null) { IActionBars actionBars = getViewSite().getActionBars(); IToolBarManager toolBarManager = actionBars.getToolBarManager(); toolBarManager.removeAll(); m_viewer.populateToolBar(toolBarManager); toolBarManager.add(m_openNewViewAction); toolBarManager.update(true); IMenuManager menuManager = actionBars.getMenuManager(); menuManager.removeAll(); m_viewer.populateMenu(menuManager); menuManager.update(true); actionBars.updateActionBars(); } }

Target:
public void updateUI() { String name = "Visualizer View"; String description = "Displays visualizations of launches."; if (m_viewer != null) { name = m_viewer.getVisualizerDisplayName(); description = m_viewer.getVisualizerDescription(); } setTabName(name); PinCloneUtils.setPartTitle(this); setTabDescription(description); if (m_viewer != null) { IActionBars actionBars = getViewSite().getActionBars(); IToolBarManager toolBarManager = actionBars.getToolBarManager(); toolBarManager.removeAll(); m_viewer.populateToolBar(toolBarManager); toolBarManager.add(m_openNewViewAction); toolBarManager.update(true); IMenuManager menuManager = actionBars.getMenuManager(); menuManager.removeAll(); m_viewer.populateMenu(menuManager); menuManager.update(true); actionBars.updateActionBars(); } }
Source:
private void initSnapshotWork(final Object[] procParams) { final String procedureName = "@SnapshotRestore"; StoredProcedureInvocation spi = new StoredProcedureInvocation(); spi.setProcName(procedureName); spi.params = new FutureTask<ParameterSet>(new Callable<ParameterSet>() { @Override public ParameterSet call() throws Exception { ParameterSet params = ParameterSet.fromArrayWithCopy(procParams); return params; } }); spi.setClientHandle(m_restoreAdapter.registerCallback(m_clientAdapterCallback)); ClientResponseImpl cr = m_initiator.dispatch(spi, m_restoreAdapter, true, Check.NO_INVOCATION); if (cr != null) { m_clientAdapterCallback.handleResponse(cr); } }

Target:
private void initSnapshotWork(final Object[] procParams) { final String procedureName = "@SnapshotRestore"; StoredProcedureInvocation spi = new StoredProcedureInvocation(); spi.setProcName(procedureName); spi.params = new FutureTask<ParameterSet>(new Callable<ParameterSet>() { @Override public ParameterSet call() throws Exception { ParameterSet params = ParameterSet.fromArrayWithCopy(procParams); return params; } }); spi.setClientHandle(m_restoreAdapter.registerCallback(m_clientAdapterCallback)); ClientResponseImpl cr = m_initiator.dispatch(spi, m_restoreAdapter, true, OverrideCheck.INVOCATION); if (cr != null) { m_clientAdapterCallback.handleResponse(cr); } }
Source:
public boolean apply(Game game, Ability source) { Player player = game.getPlayer(source.getFirstTarget()); if (player == null || player.getHand().isEmpty()) { return false; } TargetCard target = new TargetDiscard(player.getId()); player.choose(Outcome.Detriment, player.getHand(), target, game); Cards cards = player.getHand().copy(); cards.removeIf(target.getTargets()::contains); return !player.discard(cards, source, game).isEmpty(); }

Target:
public boolean apply(Game game, Ability source) { Player player = game.getPlayer(source.getFirstTarget()); if (player == null || player.getHand().isEmpty()) { return false; } TargetCard target = new TargetDiscard(player.getId()); player.choose(Outcome.Benefit, player.getHand(), target, game); Cards cards = player.getHand().copy(); cards.removeIf(target.getTargets()::contains); return !player.discard(cards, source, game).isEmpty(); }
Source:
public void flush(final String value) { String actualValue = value != null && value.isEmpty() ? null : value; if (scenarioGridCell != null) { String cellValue = scenarioGridCell.getValue().getValue(); if (Objects.equals(actualValue, cellValue)) { return; } } internalFlush(actualValue); }

Target:
public void flush(final String value) { String actualValue = value != null && value.isEmpty() ? null : value; if (scenarioGridCell != null) { scenarioGridCell.setEditingMode(false); String cellValue = scenarioGridCell.getValue().getValue(); if (Objects.equals(actualValue, cellValue)) { return; } } internalFlush(actualValue); }
Source:
private static void printConfigurationInfo() throws IOException { log.info("Executing as " + System.getProperty("user.name") + '@' + InetAddress.getLocalHost().getHostName() + " on " + System.getProperty("os.name") + ' ' + System.getProperty("os.version") + ' ' + System.getProperty("os.arch") + "; " + System.getProperty("java.vm.name") + ' ' + System.getProperty("java.runtime.version") + ' ' + (DeflaterFactory.usingIntelDeflater() ? "IntelDeflater" : "JdkDeflater")); log.info("CREATE_INDEX:" + Defaults.CREATE_INDEX + ' ' + "CREATE_MD5:" + Defaults.CREATE_MD5 + ' ' + "USE_ASYNC_IO_FOR_SAMTOOLS:" + Defaults.USE_ASYNC_IO_FOR_SAMTOOLS + ' ' + "BUFFER_SIZE:" + Defaults.BUFFER_SIZE + ' ' + "COMPRESSION_LEVEL:" + Defaults.COMPRESSION_LEVEL + ' ' + "NON_ZERO_BUFFER_SIZE:" + Defaults.NON_ZERO_BUFFER_SIZE + ' ' + "CUSTOM_READER_FACTORY:" + Defaults.CUSTOM_READER_FACTORY); }

Target:
private static void printConfigurationInfo() throws IOException { log.info("Executing as " + System.getProperty("user.name") + '@' + InetAddress.getLocalHost().getHostName() + " on " + System.getProperty("os.name") + ' ' + System.getProperty("os.version") + ' ' + System.getProperty("os.arch") + "; " + System.getProperty("java.vm.name") + ' ' + System.getProperty("java.runtime.version") + ' ' + (DeflaterFactory.usingIntelDeflater() ? "IntelDeflater" : "JdkDeflater")); final List<String> list = Defaults.allDefaults().entrySet().stream().map(e -> e.getKey() + ':' + e.getValue()).collect(Collectors.toList()); log.info(String.join(" ", list)); }
Source:
public String deconstructSearchQuery(String searchQuery) { ArrayList<String> features = new ArrayList<>(); for (SearchQueryFeature f : SearchQueryFeature.values()) { if (f.getPattern().matcher(searchQuery).find()) { features.add(f.getDescription()); } } int doubleQuotesCount = 0; Matcher doubleQuotesMatcher = Pattern.compile("\\\"").matcher(searchQuery); while (doubleQuotesMatcher.find()) doubleQuotesCount++; if (doubleQuotesCount > 0) { if (doubleQuotesCount == 1) { features.add("has one double quote"); } features.add((doubleQuotesCount % 2) == 0 ? "has even double quotes" : "has odd double quotes"); } if (features.size() == 0) { features.add("is simple"); } return features.toString(); }

Target:
public String deconstructSearchQuery(String searchQuery) { ArrayList<String> features = new ArrayList<>(); for (SearchQueryFeature f : SearchQueryFeature.values()) { if (f.getPattern().matcher(searchQuery).find()) { features.add(f.getDescription()); } } int doubleQuotesCount = 0; for (int i = 0; i < searchQuery.length(); i++) { if (searchQuery.substring(i, i + 1).contains("\"")) { doubleQuotesCount++; } } if (doubleQuotesCount > 0) { if (doubleQuotesCount == 1) { features.add("has one double quote"); } features.add((doubleQuotesCount % 2) == 0 ? "has even double quotes" : "has odd double quotes"); } if (features.size() == 0) { features.add("is simple"); } return features.toString(); }
Source:
public ServiceResponse<Map<String, String>> readRunInfo() { Map<String, String> cfgMap = new LinkedHashMap<>(2); cfgMap.put("host", hostname); cfgMap.put("started", startTime.toString()); return ServiceResponse.serveView(cfgMap); }

Target:
public ServiceResponse<Map<String, String>> readRunInfo() { Map<String, String> cfgMap = ImmutableMap.of("host", hostname, "started", startTime.toString()); return ServiceResponse.serveView(cfgMap); }