auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testRandomCell() { for (int i = 0; i < 50; i++) { Optional<MockCell> c = grid.getRandomCell(cell -> cell.getX() < 3 && cell.getY() > CELL_HEIGHT); assertTrue(c.isPresent()); MockCell cell = c.get(); assertThat(cell.getX(), allOf(greaterThanOrEqualTo(0), lessThan(3))); assertThat(cell.getY(), allOf(greaterThanOrEqualTo(16), lessThan(20))); } assertThat(grid.getRandomCell(new Random(), c -> false).isPresent(), is(false)); }

Target:
public void testRandomCell() { for (int i = 0; i < 50; i++) { Optional<MockCell> c = grid.getRandomCell(cell -> cell.getX() < 3 && cell.getY() > 15); assertTrue(c.isPresent()); MockCell cell = c.get(); assertThat(cell.getX(), allOf(greaterThanOrEqualTo(0), lessThan(3))); assertThat(cell.getY(), allOf(greaterThanOrEqualTo(16), lessThan(20))); } assertThat(grid.getRandomCell(new Random(), c -> false).isPresent(), is(false)); }
Source:
public Codec getCodec() { return new NMFDataCodec(); }

Target:
public Codec getCodec() { return nmfDataCodec; }
Source:
public void refresh() { isRefreshCancelled = false; savedPagesCompleted = 0; progressDialog.show(); for (int i = 0; i < savedPages.size(); i++) { final SavedPage savedPage = savedPages.get(i); new RefreshSavedPageTask((WikipediaApp) context.getApplicationContext(), savedPage) { @Override public void onBeforeExecute() { if (isRefreshCancelled) { cancel(); return; } Log.d("Wikipedia", "refreshing start: " + savedPage.getTitle().getDisplayText()); } @Override public void onFinish(List<Section> result) { if (!progressDialog.isShowing()) { isRefreshCancelled = true; return; } savedPagesCompleted++; progressDialog.setProgress(savedPagesCompleted); Log.d("Wikipedia", "Count is " + savedPagesCompleted + " of " + savedPages.size()); if (savedPagesCompleted == savedPages.size()) { progressDialog.dismiss(); } Log.d("Wikipedia", "refreshing end: " + savedPage.getTitle().getDisplayText()); } @Override public void onCatch(Throwable caught) { isRefreshCancelled = true; if (!progressDialog.isShowing()) { return; } progressDialog.dismiss(); getErrorDialog().show(); } }.execute(); } }

Target:
public void refresh() { isRefreshCancelled = false; savedPagesCompleted = 0; progressDialog.show(); for (int i = 0; i < savedPages.size(); i++) { final SavedPage savedPage = savedPages.get(i); new RefreshSavedPageTask(WikipediaApp.getInstance(), savedPage) { @Override public void onBeforeExecute() { if (isRefreshCancelled) { cancel(); return; } Log.d("Wikipedia", "refreshing start: " + savedPage.getTitle().getDisplayText()); } @Override public void onFinish(List<Section> result) { if (!progressDialog.isShowing()) { isRefreshCancelled = true; return; } savedPagesCompleted++; progressDialog.setProgress(savedPagesCompleted); Log.d("Wikipedia", "Count is " + savedPagesCompleted + " of " + savedPages.size()); if (savedPagesCompleted == savedPages.size()) { progressDialog.dismiss(); } Log.d("Wikipedia", "refreshing end: " + savedPage.getTitle().getDisplayText()); } @Override public void onCatch(Throwable caught) { isRefreshCancelled = true; if (!progressDialog.isShowing()) { return; } progressDialog.dismiss(); getErrorDialog().show(); } }.execute(); } }
Source:
public void registerDefaults() { StatList.allStats.stream() .map(statistic -> (Statistic) statistic) .map(stat -> stat.getStatisticFormat().orElse(stat.getGroup().getDefaultStatisticFormat())) .distinct() .forEach(this::registerAdditionalCatalog); }

Target:
public void registerDefaults() { StatList.ALL_STATS.stream() .map(statistic -> (Statistic) statistic) .map(stat -> stat.getStatisticFormat().orElse(stat.getGroup().getDefaultStatisticFormat())) .distinct() .forEach(this::registerAdditionalCatalog); }
Source:
Stream<Host> getPrioritizedHostStream(Stream<Host> hostStream, Capabilities capabilities) { Set<Host> filteredHostSet = hostStream.collect(Collectors.toSet()); Map<String, Set<Host>> hostBuckets = sortHostsToBucketsByBrowser(filteredHostSet); if (allBucketsSameSize(hostBuckets)) { LOG.fine("All Hosts Prioritized prior to sorting"); return hostBuckets.values().stream().distinct().flatMap(Set::stream); } final List<Map.Entry<String, Set<Host>>> sorted = hostBuckets.entrySet().stream().sorted( Comparator.comparingInt(v -> v.getValue().size()) ).collect(Collectors.toList()); LOG.info(sorted.toString()); Map<String, Set<Host>> newHostBuckets; for (Map.Entry<String, Set<Host>> entry: sorted) { if (entry.getKey().equals(capabilities.getBrowserName())) { continue; } final Set<Host> filteredHosts = filteredHostSet.stream().filter(host -> !entry.getValue().contains(host)).collect(Collectors.toSet()); newHostBuckets = sortHostsToBucketsByBrowser(filteredHosts); if (allBucketsSameSize(newHostBuckets)) { LOG.fine("Hosts have been balanced according to browser priority"); return newHostBuckets.values().stream().distinct().flatMap(Set::stream); } } return hostBuckets.values().stream().distinct().flatMap(Set::stream); }

Target:
Stream<Host> getPrioritizedHostStream(Stream<Host> hostStream, Capabilities capabilities) { Set<Host> filteredHostSet = hostStream.collect(Collectors.toSet()); Map<String, Set<Host>> hostBuckets = sortHostsToBucketsByBrowser(filteredHostSet); if (allBucketsSameSize(hostBuckets)) { return hostBuckets.values().stream().distinct().flatMap(Set::stream); } final List<Map.Entry<String, Set<Host>>> sorted = hostBuckets.entrySet().stream().sorted( Comparator.comparingInt(v -> v.getValue().size()) ).collect(Collectors.toList()); Map<String, Set<Host>> newHostBuckets; for (Map.Entry<String, Set<Host>> entry: sorted) { if (entry.getKey().equals(capabilities.getBrowserName())) { continue; } final Set<Host> filteredHosts = filteredHostSet.stream().filter(host -> !entry.getValue().contains(host)).collect(Collectors.toSet()); newHostBuckets = sortHostsToBucketsByBrowser(filteredHosts); if (allBucketsSameSize(newHostBuckets)) { LOG.fine("Hosts have been balanced according to browser priority"); return newHostBuckets.values().stream().distinct().flatMap(Set::stream); } } return hostBuckets.values().stream().distinct().flatMap(Set::stream); }
Source:
public void setReference(String reference) { this.reference = (reference != null) ? reference : ""; }

Target:
private void setReference(String reference) { this.reference = (reference != null) ? reference : ""; }
Source:
public void testMetricsAggregations() throws Exception { CountDownLatch latch = new CountDownLatch(2); LogicalPlanConfiguration lpc = new LogicalPlanConfiguration(new Configuration()); TestGeneratorInputOperator inputOperator = dag.addOperator("input", TestGeneratorInputOperator.class); OperatorWithMetrics o1 = dag.addOperator("o1", OperatorWithMetrics.class); MockAggregator aggregator = new MockAggregator(latch); dag.setOperatorAttribute(o1, Context.OperatorContext.METRICS_AGGREGATOR, aggregator); dag.setAttribute(Context.OperatorContext.STORAGE_AGENT, new StramTestSupport.MemoryStorageAgent()); dag.setOperatorAttribute(o1, Context.OperatorContext.PARTITIONER, new StatelessPartitioner<TestGeneratorInputOperator>(4)); dag.addStream("TestTuples", inputOperator.outport, o1.inport1); lpc.prepareDAG(dag, null, "AutoMetricTest"); StramLocalCluster lc = new StramLocalCluster(dag); lc.runAsync(); latch.await(); Assert.assertEquals("progress", 4L, ((Long)aggregator.result.get("progress")).longValue()); lc.shutdown(); }

Target:
public void testMetricsAggregations() throws Exception { CountDownLatch latch = new CountDownLatch(2); LogicalPlanConfiguration lpc = new LogicalPlanConfiguration(new Configuration()); TestGeneratorInputOperator inputOperator = dag.addOperator("input", TestGeneratorInputOperator.class); OperatorWithMetrics o1 = dag.addOperator("o1", OperatorWithMetrics.class); MockAggregator aggregator = new MockAggregator(latch); dag.setOperatorAttribute(o1, Context.OperatorContext.METRICS_AGGREGATOR, aggregator); dag.setAttribute(Context.OperatorContext.STORAGE_AGENT, new StramTestSupport.MemoryStorageAgent()); dag.setOperatorAttribute(o1, Context.OperatorContext.PARTITIONER, new StatelessPartitioner<TestGeneratorInputOperator>(2)); dag.addStream("TestTuples", inputOperator.outport, o1.inport1); lpc.prepareDAG(dag, null, "AutoMetricTest"); StramLocalCluster lc = new StramLocalCluster(dag); lc.runAsync(); latch.await(); Assert.assertEquals("progress", 2L, ((Long)aggregator.result.get("progress")).longValue()); lc.shutdown(); }
Source:
public void registerDock() { editor.registerDock("test", mock(IsWidget.class)); verify(placeManager).registerOnOpenCallback(placeRequestArgumentCaptor.capture(), any(Command.class)); final PlaceRequest placeRequest = placeRequestArgumentCaptor.getValue(); assertEquals("org.docks.PlaceHolder", placeRequest.getIdentifier()); final Map<String, String> parameters = placeRequest.getParameters(); assertEquals(1, parameters.size()); assertEquals("test", parameters.get("name")); }

Target:
public void registerDock() { editor.registerDock("test", mock(IsWidget.class)); verify(placeManager).registerOnOpenCallback(placeRequestArgumentCaptor.capture(), any(Command.class)); final PlaceRequest placeRequest = placeRequestArgumentCaptor.getValue(); Assertions.assertThat(placeRequest) .hasFieldOrPropertyWithValue("identifier", "org.docks.PlaceHolder") .hasFieldOrPropertyWithValue("parameters", Collections.singletonMap("name", "test")); }
Source:
public Dialog onCreateDialog(Bundle savedInstanceState) { final LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View view = inflater.inflate(R.layout.fragment_dialog_rating, null); mRatingBar = (RatingBar) view.findViewById(R.id.ratingBar); mRatingBar.setOnRatingBarChangeListener(this); mAlertDialog = new AlertDialog.Builder(getContext()) .setPositiveButton(getString(R.string.label_submit), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int id) { submit(); } }) .setNegativeButton(android.R.string.cancel, null) .setView(view) .setCancelable(true) .create(); mAlertDialog.setOnShowListener(this); return mAlertDialog; }

Target:
public Dialog onCreateDialog(Bundle savedInstanceState) { binding = DataBindingUtil.inflate(getActivity().getLayoutInflater(), R.layout.fragment_dialog_rating, null, false); binding.ratingBar.setOnRatingBarChangeListener(this); binding.tvDescription.setText(R.string.rating_dialog_message); mAlertDialog = new AlertDialog.Builder(getContext()) .setPositiveButton(getString(R.string.label_submit), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int id) { submit(); } }) .setNegativeButton(android.R.string.cancel, null) .setView(binding.getRoot()) .create(); mAlertDialog.setCanceledOnTouchOutside(false); mAlertDialog.setOnShowListener(this); return mAlertDialog; }
Source:
public void getSupportedOutputSizes_targetResolutionLargerThan640x480() { setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY); SupportedSurfaceCombination supportedSurfaceCombination = new SupportedSurfaceCombination( mContext, CAMERA_ID, mMockCamcorderProfileHelper); FakeUseCase useCase = new FakeUseCaseConfig.Builder().setTargetRotation( Surface.ROTATION_90).setTargetResolution(new Size(1280, 960)).build(); List<Size> resultList = supportedSurfaceCombination.getSupportedOutputSizes(useCase); List<Size> expectedList = Arrays.asList(new Size[]{ new Size(1280, 960), new Size(640, 480), new Size(1920, 1080), new Size(1280, 720), new Size(1280, 720), new Size(960, 544), new Size(800, 450) }); assertEquals(expectedList, resultList); }

Target:
public void getSupportedOutputSizes_targetResolutionLargerThan640x480() { setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY); SupportedSurfaceCombination supportedSurfaceCombination = new SupportedSurfaceCombination( mContext, CAMERA_ID, mMockCamcorderProfileHelper); FakeUseCase useCase = new FakeUseCaseConfig.Builder().setTargetRotation( Surface.ROTATION_90).setTargetResolution(new Size(1280, 960)).build(); List<Size> resultList = supportedSurfaceCombination.getSupportedOutputSizes(useCase); List<Size> expectedList = Arrays.asList(new Size[]{ new Size(1280, 960), new Size(640, 480), new Size(1920, 1080), new Size(1280, 720), new Size(960, 544), new Size(800, 450) }); assertEquals(expectedList, resultList); }
Source:
public RegistryResponseType documentRegistryXDSRegisterDocumentSetB(RegisterDocumentSetRequestType body) { return new NhinDocDataSubmissionImpl(inboundDocDataSubmission).documentRepositoryRegisterDocumentSetB(body, context); }

Target:
public RegistryResponseType documentRegistryXDSRegisterDocumentSetB(RegisterDocumentSetRequestType body) { LOG.debug("Calling service with context and inbound submission class {}", context, inboundDocDataSubmission.getClass().getName()); return new NhinDocDataSubmissionImpl(inboundDocDataSubmission).documentRepositoryRegisterDocumentSetB(body, context); }
Source:
private void initLocalizationEditor() { localeBox = new ListBox(); localeBox.getElement().setId("AbstractLoginFormView_localeBox"); String currentLocale = LocaleInfo.getCurrentLocale().getLocaleName(); String[] localeNames = LocaleInfo.getAvailableLocaleNames(); boolean foundDefaultLocale = false; for (String localeName : localeNames) { if (!DEFAULT_LOCALE.equals(localeName)) { String nativeName = LocaleInfo.getLocaleNativeDisplayName(localeName); localeBox.addItem(nativeName, localeName); if (localeName.equals(currentLocale)) { setSelectedLocale(localeBox.getItemCount() - 1); foundDefaultLocale = true; } } } if (!foundDefaultLocale && localeNames.length > 0) { setSelectedLocale(0); } localeBox.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { String localeQueryParam = LocaleInfo.getLocaleQueryParam(); String localeString = "?" + localeQueryParam + "=" + localeBox.getValue(localeBox.getSelectedIndex()); Window.open(FrontendUrlUtils.getCurrentPageURL() + localeString, "_self", ""); } }); }

Target:
private void initLocalizationEditor() { localeBox = new ListBox(); String currentLocale = LocaleInfo.getCurrentLocale().getLocaleName(); String[] localeNames = LocaleInfo.getAvailableLocaleNames(); boolean foundDefaultLocale = false; for (String localeName : localeNames) { if (!DEFAULT_LOCALE.equals(localeName)) { String nativeName = LocaleInfo.getLocaleNativeDisplayName(localeName); localeBox.addItem(nativeName, localeName); if (localeName.equals(currentLocale)) { setSelectedLocale(localeBox.getItemCount() - 1); foundDefaultLocale = true; } } } if (!foundDefaultLocale && localeNames.length > 0) { setSelectedLocale(0); } localeBox.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { String localeQueryParam = LocaleInfo.getLocaleQueryParam(); String localeString = "?" + localeQueryParam + "=" + localeBox.getValue(localeBox.getSelectedIndex()); Window.open(FrontendUrlUtils.getCurrentPageURL() + localeString, "_self", ""); } }); }
Source:
private void createMarkers(Processor model, int severity, Collection<String> msgs, String markerType) throws Exception { Collection<String> msgsCopy = new ArrayList<String>(msgs); for (String msg : msgsCopy) { createMarker(model, severity, msg, markerType); } }

Target:
private void createMarkers(Processor model, int severity, Collection<String> msgs, String markerType) throws Exception { for (String msg : msgs.toArray(new String[0])) { createMarker(model, severity, msg, markerType); } }
Source:
public void testEncodeChunkedContent() throws Exception { EmbeddedChannel ch = new EmbeddedChannel(new ChunkedWriteHandler()); HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/"); HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(req, false); int length = 8077 + 8096; char[] array = new char[length]; Arrays.fill(array, 'a'); String longText = new String(array); encoder.addBodyAttribute("data", longText); encoder.addBodyAttribute("moreData", "abcd"); HttpRequest finalRequest = encoder.finalizeRequest(); ch.writeOutbound(finalRequest); ch.writeOutbound(encoder); ch.flushOutbound(); }

Target:
public void testEncodeChunkedContent() throws Exception { HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/"); HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(req, false); int length = 8077 + 8096; char[] array = new char[length]; Arrays.fill(array, 'a'); String longText = new String(array); encoder.addBodyAttribute("data", longText); encoder.addBodyAttribute("moreData", "abcd"); assertNotNull(encoder.finalizeRequest()); while (!encoder.isEndOfInput()) { encoder.readChunk((ByteBufAllocator) null).release(); } assertTrue(encoder.isEndOfInput()); encoder.cleanFiles(); }
Source:
private File generateSegment(File outputDir) throws Exception { TableConfig tableConfig = JsonUtils.fileToObject(new File(_tableConfigFileName), TableConfig.class); _tableName = tableConfig.getTableName(); Schema schema = JsonUtils.fileToObject(new File(_schemaFileName), Schema.class); RecordReaderConfig recordReaderConfig = RecordReaderFactory.getRecordReaderConfig(DEFAULT_FILE_FORMAT, _recordReaderConfigFileName); SegmentGeneratorConfig segmentGeneratorConfig = new SegmentGeneratorConfig(tableConfig, schema); segmentGeneratorConfig.setInputFilePath(_inputDataFileName); segmentGeneratorConfig.setFormat(DEFAULT_FILE_FORMAT); segmentGeneratorConfig.setOutDir(outputDir.getAbsolutePath()); segmentGeneratorConfig.setReaderConfig(recordReaderConfig); segmentGeneratorConfig.setTableName(_tableName); segmentGeneratorConfig.setSegmentName(_segmentName); SegmentIndexCreationDriver driver = new SegmentIndexCreationDriverImpl(); driver.init(segmentGeneratorConfig); driver.build(); String segmentName = driver.getSegmentName(); File indexDir = new File(outputDir, segmentName); LOGGER.info("Successfully created segment: at directory: {}", segmentName, indexDir); File segmentTarFile = new File(outputDir, segmentName + TarGzCompressionUtils.TAR_GZ_FILE_EXTENSION); TarGzCompressionUtils.createTarGzFile(indexDir, segmentTarFile); LOGGER.info("Tarring segment from: to: {}", indexDir, segmentTarFile); return segmentTarFile; }

Target:
private File generateSegment(File outputDir) throws Exception { TableConfig tableConfig = JsonUtils.fileToObject(new File(_tableConfigFileName), TableConfig.class); _tableName = tableConfig.getTableName(); Schema schema = JsonUtils.fileToObject(new File(_schemaFileName), Schema.class); RecordReaderConfig recordReaderConfig = RecordReaderFactory.getRecordReaderConfig(DEFAULT_FILE_FORMAT, _recordReaderConfigFileName); SegmentGeneratorConfig segmentGeneratorConfig = new SegmentGeneratorConfig(tableConfig, schema); segmentGeneratorConfig.setInputFilePath(_inputDataFileName); segmentGeneratorConfig.setFormat(DEFAULT_FILE_FORMAT); segmentGeneratorConfig.setOutDir(outputDir.getAbsolutePath()); segmentGeneratorConfig.setReaderConfig(recordReaderConfig); segmentGeneratorConfig.setTableName(_tableName); segmentGeneratorConfig.setSegmentName(_segmentName); SegmentIndexCreationDriver driver = new SegmentIndexCreationDriverImpl(); driver.init(segmentGeneratorConfig); driver.build(); File indexDir = new File(outputDir, _segmentName); LOGGER.info("Successfully created segment: at directory: {}", _segmentName, indexDir); File segmentTarFile = new File(outputDir, _segmentName + TarGzCompressionUtils.TAR_GZ_FILE_EXTENSION); TarGzCompressionUtils.createTarGzFile(indexDir, segmentTarFile); LOGGER.info("Tarring segment from: to: {}", indexDir, segmentTarFile); return segmentTarFile; }
Source:
public static RowKind fromByteValue(byte value) { switch (value) { case 0: return INSERT; case 1: return UPDATE_BEFORE; case 2: return UPDATE_AFTER; case 3: return DELETE; default: throw new UnsupportedOperationException( "Do not support to parse byte value " + value + " to RowKind."); } }

Target:
public static RowKind fromByteValue(byte value) { switch (value) { case 0: return INSERT; case 1: return UPDATE_BEFORE; case 2: return UPDATE_AFTER; case 3: return DELETE; default: throw new UnsupportedOperationException( "Unsupported byte value '" + value + "' for row kind."); } }
Source:
public FileBasedConfig openJGitConfig(Config parent, FS fs) { Path jgitConfigPath = Paths.get(getXDGConfigHome(fs), ".config", "jgit", "config"); return new FileBasedConfig(parent, jgitConfigPath.toFile(), fs); }

Target:
public FileBasedConfig openJGitConfig(Config parent, FS fs) { Path xdgPath = getXDGConfigHome(fs); if (xdgPath != null) { Path configPath = null; try { configPath = xdgPath.resolve("jgit"); Files.createDirectories(configPath); configPath = configPath.resolve(Constants.CONFIG); return new FileBasedConfig(parent, configPath.toFile(), fs); } catch (IOException e) { LOG.error(JGitText.get().createJGitConfigFailed, configPath, e); } } return new FileBasedConfig(parent, new File(fs.userHome(), ".jgitconfig"), fs); }
Source:
private Xpp3Dom getLibertyPluginConfig() { Plugin libertyPlugin = getLibertyPluging(); Xpp3Dom overrides = configuration(element(name("looseApplication"), "true")); return getPluginConfig(libertyPlugin, overrides); }

Target:
private Xpp3Dom getLibertyPluginConfig() { Plugin libertyPlugin = getLibertyPlugin(); Xpp3Dom overrides = configuration(element(name("looseApplication"), "true")); return getPluginConfig(libertyPlugin, overrides); }
Source:
public long getFirstRowIndex() { if (firstRowIndex < 0) { throw new IllegalStateException( "No row synchronization is required; all pages shall be read."); } return firstRowIndex; }

Target:
public long getFirstRowIndex() { if (firstRowIndex < 0) { throw new NotInPageFilteringModeException("First row index is not available"); } return firstRowIndex; }
Source:
public void intersectionTest() { DataUtil.IntersectionLambda intersectionLambda = new AndroidUtil.AndroidIntersectionLambda(); Vector<String> setOne = new Vector<>(); setOne.add("one"); setOne.add("two"); Vector<String> setTwo = new Vector<>(); setTwo.add("one"); setTwo.add("three"); Vector<String> unionSet = intersectionLambda.intersection(setOne, setTwo); assertFalse(unionSet == setOne); assertFalse(unionSet == setTwo); assertTrue(setOne.contains("one")); assertTrue(setOne.contains("two")); assertTrue(setTwo.contains("one")); assertTrue(setTwo.contains("three")); assertTrue(unionSet.contains("one")); assertFalse(unionSet.contains("two")); assertFalse(unionSet.contains("three")); }

Target:
public void intersectionTest() { DataUtil.IntersectionLambda intersectionLambda = new AndroidUtil.AndroidIntersectionLambda(); Vector<String> setOne = new Vector<>(); setOne.add("one"); setOne.add("two"); Vector<String> setTwo = new Vector<>(); setTwo.add("one"); setTwo.add("three"); Vector<String> intersectSet = intersectionLambda.intersection(setOne, setTwo); assertFalse(intersectSet == setOne); assertFalse(intersectSet == setTwo); assertTrue(setOne.contains("one")); assertTrue(setOne.contains("two")); assertTrue(setTwo.contains("one")); assertTrue(setTwo.contains("three")); assertTrue(intersectSet.contains("one")); assertFalse(intersectSet.contains("two")); assertFalse(intersectSet.contains("three")); }
Source:
static UriComponentsBuilder getBuilder() { HttpServletRequest request = getCurrentRequest(); String forwardedSsl = request.getHeader("X-Forwarded-Ssl"); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpRequest(new ServletServerHttpRequest(request)); if (hasText(forwardedSsl) && forwardedSsl.equalsIgnoreCase("on")) { builder.scheme("https"); } return builder; }

Target:
static UriComponentsBuilder getBuilder() { HttpServletRequest request = getCurrentRequest(); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpRequest(new ServletServerHttpRequest(request)); String forwardedSsl = request.getHeader("X-Forwarded-Ssl"); ForwardedHeader forwarded = ForwardedHeader.of(request.getHeader(ForwardedHeader.NAME)); String proto = hasText(forwarded.getProto()) ? forwarded.getProto() : request.getHeader("X-Forwarded-Proto"); if (!hasText(proto) && hasText(forwardedSsl) && forwardedSsl.equalsIgnoreCase("on")) { builder.scheme("https"); } return builder; }
Source:
public boolean seek(final CtfLocationData ctfLocationData) { boolean ret = false; long currTimestamp = ctfLocationData.getTimestamp(); final long offsetTimestamp = currTimestamp - this.getTrace().getOffset(); if (offsetTimestamp < 0) { ret = super.seek(0L); } else { ret = super.seek(offsetTimestamp); } currTimestamp = this.getCurrentEvent().getTimestampValue(); long offset = 0; for (long i = 0; i < ctfLocationData.getIndex(); i++) { if (currTimestamp == this.getCurrentEvent().getTimestampValue()) { offset++; } else { offset = 0; } this.advance(); } if (ret) { curLocation.setLocation(new CtfLocationData(getCurrentEvent().getTimestampValue(), offset)); } else { curLocation = NULL_LOCATION; } return ret; }

Target:
public boolean seek(final CtfLocationData ctfLocationData) { boolean ret = false; long currTimestamp = ctfLocationData.getTimestamp(); final long offsetTimestamp = currTimestamp - this.getTrace().getOffset(); if (offsetTimestamp < 0) { ret = super.seek(0L); } else { ret = super.seek(offsetTimestamp); } currTimestamp = this.getCurrentEvent().getTimestampValue(); long index = 0; for (long i = 0; i < ctfLocationData.getIndex(); i++) { if (currTimestamp == this.getCurrentEvent().getTimestampValue()) { index++; } else { index = 0; } this.advance(); } if (ret) { curLocation.setLocation(new CtfLocationData(getCurrentEvent().getTimestampValue(), index)); } else { curLocation = NULL_LOCATION; } return ret; }
Source:
public boolean isFinished() { return (finishing && inputPage == null) || (remainingLimit == 0 && inputPage == null && unfinishedWork == null); }

Target:
public boolean isFinished() { return !hasUnfinishedInput() && (finishing || remainingLimit == 0); }
Source:
public Handles setForceEndTransactions(boolean forceEndTransactions) { this.forceEndTransactions = forceEndTransactions; return this; }

Target:
public void setForceEndTransactions(boolean forceEndTransactions) { this.forceEndTransactions = forceEndTransactions; }
Source:
public void parsePartOneTwo_WithFailedRerun() { configuration.addReducingMethod(MERGE_FEATURES_AND_SCENARIOS_WITH_LATEST); setUpWithJson(PART_ONE, PART_TWO, PART_TWO_RERUN_FAILED); assertThat(reportResult.getAllFeatures()).hasSize(3); Reportable current = reportResult.getFeatureReport(); assertThat(current.getFailedScenarios()).isEqualTo(1); }

Target:
public void parsePartOneTwo_WithFailedRerun() { configuration.addReducingMethod(MERGE_FEATURES_WITH_RETEST); setUpWithJson(PART_ONE, PART_TWO, PART_TWO_RERUN_FAILED); Reportable current = reportResult.getFeatureReport(); assertThat(reportResult.getAllFeatures()).hasSize(3); assertThat(current.getFailedScenarios()).isEqualTo(1); }
Source:
public List<HudsonModelRun> getDownstreamBuilds(final HudsonModelJob job, final HudsonModelRun build, final IOperationMonitor monitor) throws HudsonException { return new HudsonOperation<List<HudsonModelRun>>(client) { @Override public List<HudsonModelRun> execute() throws IOException, HudsonException, JAXBException { String include = " String url = HudsonUrl.create(getBuildUrl(job, build)) .include(include) .depth(0) .tree("runs[*]") .toUrl(); HttpRequestBase request = createGetRequest(url); CommonHttpResponse response = execute(request, monitor); return processAndRelease(response, monitor); } @Override protected List<HudsonModelRun> doProcess(CommonHttpResponse response, IOperationMonitor monitor) throws IOException, HudsonException, JAXBException { InputStream in = response.getResponseEntityAsStream(); List<HudsonModelRun> hudsonBuilds = new ArrayList<HudsonModelRun>(); try { Document doc = getDocumentBuilder().parse(in); NodeList nodeList = doc.getElementsByTagName("url"); for (int i = 0; i < nodeList.getLength(); i++) { Element element = (Element) nodeList.item(i); String url = element.getTextContent(); HudsonModelRun hudsonBuild = getDownstreamBuild(job, build, url, monitor); hudsonBuilds.add(hudsonBuild); } } catch (OperationCanceledException e) { throw e; } catch (SAXException e) { throw new HudsonException(NLS.bind("Failed to parse response from {0}", response.getRequestPath()), e); } catch (Exception e) { throw new HudsonException(NLS.bind("Failed to parse response from {0}", response.getRequestPath()), e); } return hudsonBuilds; } }.run(); }

Target:
public List<HudsonModelRun> getDownstreamBuilds(final HudsonModelJob job, final HudsonModelRun build, final IOperationMonitor monitor) throws HudsonException { return new HudsonOperation<List<HudsonModelRun>>(client) { @Override public List<HudsonModelRun> execute() throws IOException, HudsonException, JAXBException { String include = " String url = HudsonUrl.create(getBuildUrl(job, build)) .include(include) .depth(0) .tree("runs[*]") .toUrl(); HttpRequestBase request = createGetRequest(url); CommonHttpResponse response = execute(request, monitor); return processAndRelease(response, monitor); } @Override protected List<HudsonModelRun> doProcess(CommonHttpResponse response, IOperationMonitor monitor) throws IOException, HudsonException, JAXBException { InputStream in = response.getResponseEntityAsStream(); List<HudsonModelRun> hudsonBuilds = new ArrayList<HudsonModelRun>(); try { Document doc = getDocumentBuilder().parse(in); NodeList nodeList = doc.getElementsByTagName("url"); for (int i = 0; i < nodeList.getLength(); i++) { Element element = (Element) nodeList.item(i); String url = element.getTextContent(); HudsonModelRun hudsonBuild = getBuildFromUrl(job, build, url, monitor); hudsonBuilds.add(hudsonBuild); } } catch (OperationCanceledException e) { throw e; } catch (SAXException e) { throw new HudsonException(NLS.bind("Failed to parse response from {0}", response.getRequestPath()), e); } catch (Exception e) { throw new HudsonException(NLS.bind("Failed to parse response from {0}", response.getRequestPath()), e); } return hudsonBuilds; } }.run(); }
Source:
protected void updateSlider() { if (dragging && draggable) { if (mouseY < sliderTopY + slider.height / 2) { slider.y = sliderTopY; sliderProgress = (slider.y - sliderTopY) / (float) (sliderBotY - sliderTopY); } else if (mouseY > sliderBotY + slider.height / 2) { slider.y = sliderBotY; sliderProgress = (slider.y - sliderTopY) / (float) (sliderBotY - sliderTopY); } else { slider.y = mouseY - slider.height / 2; sliderProgress = (slider.y - sliderTopY) / (float) (sliderBotY - sliderTopY); } System.out.println(sliderProgress); } else { if (draggable == false) slider.enabled = false; slider.y = (int) (sliderTopY + (sliderBotY - sliderTopY) * sliderProgress); } }

Target:
protected void updateSlider() { if (dragging && draggable) { slider.y = MathHelper.clamp(mouseY - slider.height / 2, sliderTopY, sliderBotY); } else { if (draggable == false) slider.enabled = false; slider.y = (int) (sliderTopY + (sliderBotY - sliderTopY) * sliderProgress); } }
Source:
private void checkNetworkAddressCacheSettings() { final String property = Security.getProperty("networkaddress.cache.ttl"); if (property == null) { return; } int cacheTTL = Integer.parseInt(property); if (cacheTTL == -1) { logger.warn( "networkaddress.cache.ttl is currently set to cache DNS lookups forever. If you use domain names " + "for the Riak server connection, and an IP address changes (riak host or a load balancer)" + ", this will block the client from creating connections with the new IP addresses."); } }

Target:
private void checkNetworkAddressCacheSettings() { final String property = Security.getProperty("networkaddress.cache.ttl"); final boolean usingSecurityMgr = System.getSecurityManager() != null; final boolean propertyUndefined = property == null; boolean logWarning = false; if(propertyUndefined && usingSecurityMgr) { logWarning = true; } else if(!propertyUndefined) { final int cacheTTL = Integer.parseInt(property); logWarning = (cacheTTL == -1); } if (logWarning) { logger.warn( "The Java Security \"networkaddress.cache.ttl\" property may be set to cache DNS lookups forever. " + "Using domain names for Riak nodes or an intermediate load balancer could result in stale IP " + "addresses being used for new connections, causing connection errors. " + "If you use domain names for Riak nodes, please set this property to a value greater than zero."); } }
Source:
@Test public void queryWithRawQuery() { final List<User> users = TestFactory.newUsers(20); int counter = 1; for (User user : users) { char[] chars = new char[counter++]; Arrays.fill(chars, '*'); user.setEmail(new String(chars)); } putUsers(users); final List<User> usersWithLongName = new ArrayList<>(users.size()); int lengthSum = 0; for (User user : users) { lengthSum += user.getEmail().length(); } final int avrLength = lengthSum / users.size(); for (User user : users) { if (user.getEmail().length() > avrLength) { usersWithLongName.add(user); } } final String query = "Select * from " + User.TABLE + " where length(" + User.COLUMN_EMAIL + ") > " + "(select avg(length(" + User.COLUMN_EMAIL + ")) from users)"; final List<User> usersFromQuery = storIODb .get() .listOfObjects(User.class) .withMapFunc(User.MAP_FROM_CURSOR) .withQuery(new RawQuery.Builder() .query(query) .build()) .prepare() .executeAsBlocking(); checkNotEmptyAndEquals(usersWithLongName, usersFromQuery); }

Target:
@Test public void queryWithRawQuery() { final List<User> users = TestFactory.newUsers(20); int counter = 1; for (User user : users) { char[] chars = new char[counter++]; Arrays.fill(chars, '*'); user.setEmail(new String(chars)); } putUsers(users); final List<User> usersWithLongName = new ArrayList<>(users.size()); int lengthSum = 0; for (User user : users) { lengthSum += user.getEmail().length(); } final int avrLength = lengthSum / users.size(); for (User user : users) { if (user.getEmail().length() > avrLength) { usersWithLongName.add(user); } } final String query = "Select * from " + User.TABLE + " where length(" + User.COLUMN_EMAIL + ") > " + "(select avg(length(" + User.COLUMN_EMAIL + ")) from users)"; final List<User> usersFromQuery = storIODb .get() .listOfObjects(User.class) .withMapFunc(User.MAP_FROM_CURSOR) .withQuery(new RawQuery.Builder() .query(query) .build()) .prepare() .executeAsBlocking(); assertEquals(usersWithLongName, usersFromQuery); }
Source:
public static String parseUserVisibleError(Response<ResponseBody> response) { String message; try { JSONObject errorKeyAndDefault = new JSONObject(response.errorBody().string()); message = Localization.getWithDefault( errorKeyAndDefault.getString("error"), errorKeyAndDefault.getString("default_response")); } catch (JSONException | IOException e) { message = "Unknown issue"; } return message; }

Target:
public static String parseUserVisibleError(Response<ResponseBody> response) { String message; String responseStr = null; try { responseStr = response.errorBody().string(); JSONObject errorKeyAndDefault = new JSONObject(responseStr); message = Localization.getWithDefault( errorKeyAndDefault.getString("error"), errorKeyAndDefault.getString("default_response")); } catch (JSONException | IOException e) { message = responseStr != null ? responseStr : "Unknown issue"; } return message; }
Source:
private synchronized void initServer() { LOG.debug("Creating journal with max segment size {}", mConf.getMaxLogSize()); Storage storage = Storage.builder() .withDirectory(mConf.getPath()) .withStorageLevel(StorageLevel.valueOf(mConf.getStorageLevel().name())) .withMinorCompactionInterval(Duration.ofDays(200)) .withMaxSegmentSize((int) mConf.getMaxLogSize()) .build(); if (mStateMachine != null) { mStateMachine.close(); } mStateMachine = new JournalStateMachine(mJournals, () -> this.getJournalSinks(null)); GrpcMessagingProxy serverProxy = null; if (mConf.getProxyAddress() != null) { serverProxy = new GrpcMessagingProxy(); serverProxy.addProxy(getLocalAddress(mConf), new Address(mConf.getProxyAddress())); } mServer = CopycatServer.builder(getLocalAddress(mConf)) .withStorage(storage) .withElectionTimeout(Duration.ofMillis(mConf.getElectionTimeoutMs())) .withHeartbeatInterval(Duration.ofMillis(mConf.getHeartbeatIntervalMs())) .withSnapshotAllowed(mSnapshotAllowed) .withSerializer(createSerializer()) .withTransport(new GrpcMessagingTransport( ServerConfiguration.global(), ServerUserState.global(), RAFTSERVER_CLIENT_TYPE) .withServerProxy(serverProxy)) .withStateMachine(new OnceSupplier<>(mStateMachine)) .withAppenderBatchSize((int) ServerConfiguration .getBytes(PropertyKey.MASTER_EMBEDDED_JOURNAL_APPENDER_BATCH_SIZE)) .build(); mPrimarySelector.init(mServer); }

Target:
private synchronized void initServer() { LOG.debug("Creating journal with max segment size {}", mConf.getMaxLogSize()); Storage storage = Storage.builder() .withDirectory(mConf.getPath()) .withStorageLevel(StorageLevel.valueOf(mConf.getStorageLevel().name())) .withMinorCompactionInterval(Duration.ofDays(200)) .withMaxSegmentSize((int) mConf.getMaxLogSize()) .build(); if (mStateMachine != null) { mStateMachine.close(); } mStateMachine = new JournalStateMachine(mJournals, () -> this.getJournalSinks(null)); GrpcMessagingProxy serverProxy = new GrpcMessagingProxy(); if (mConf.getProxyAddress() != null) { serverProxy.addProxy(getLocalAddress(mConf), new Address(mConf.getProxyAddress())); } mServer = CopycatServer.builder(getLocalAddress(mConf)) .withStorage(storage) .withElectionTimeout(Duration.ofMillis(mConf.getElectionTimeoutMs())) .withHeartbeatInterval(Duration.ofMillis(mConf.getHeartbeatIntervalMs())) .withSnapshotAllowed(mSnapshotAllowed) .withSerializer(createSerializer()) .withTransport(new GrpcMessagingTransport( ServerConfiguration.global(), ServerUserState.global(), RAFTSERVER_CLIENT_TYPE) .withServerProxy(serverProxy)) .withStateMachine(new OnceSupplier<>(mStateMachine)) .withAppenderBatchSize((int) ServerConfiguration .getBytes(PropertyKey.MASTER_EMBEDDED_JOURNAL_APPENDER_BATCH_SIZE)) .build(); mPrimarySelector.init(mServer); }
Source:
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { final AudioRecorderViewModel viewModel = new ViewModelProvider(requireActivity(), audioRecorderViewModelFactory).get(AudioRecorderViewModel.class); viewModel.getCurrentSession().observe(getViewLifecycleOwner(), session -> { if (session == null) { binding.getRoot().setVisibility(GONE); } else if (session.getFile() == null) { binding.getRoot().setVisibility(VISIBLE); binding.timeCode.setText(LengthFormatterKt.formatLength(session.getDuration())); if (session.getPaused()) { binding.pauseRecording.setIcon(ContextCompat.getDrawable(getContext(), R.drawable.ic_play_arrow_24dp)); binding.pauseRecording.setOnClickListener(v -> viewModel.resume()); } else { binding.pauseRecording.setIcon(ContextCompat.getDrawable(getContext(), R.drawable.ic_pause_24dp)); binding.pauseRecording.setOnClickListener(v -> viewModel.pause()); } if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.N) { binding.pauseRecording.setVisibility(GONE); } } else { binding.getRoot().setVisibility(GONE); } }); binding.stopRecording.setOnClickListener(v -> viewModel.stop()); }

Target:
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { final AudioRecorderViewModel viewModel = new ViewModelProvider(requireActivity(), audioRecorderViewModelFactory).get(AudioRecorderViewModel.class); viewModel.getCurrentSession().observe(getViewLifecycleOwner(), session -> { if (session == null) { binding.getRoot().setVisibility(GONE); } else if (session.getFile() == null) { binding.getRoot().setVisibility(VISIBLE); binding.timeCode.setText(LengthFormatterKt.formatLength(session.getDuration())); if (session.getPaused()) { binding.pauseRecording.setIcon(ContextCompat.getDrawable(getContext(), R.drawable.ic_baseline_mic_24)); binding.pauseRecording.setContentDescription(getString(R.string.resume_recording)); binding.pauseRecording.setOnClickListener(v -> viewModel.resume()); binding.recordingStatus.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.ic_pause_24dp)); } else { binding.pauseRecording.setIcon(ContextCompat.getDrawable(getContext(), R.drawable.ic_pause_24dp)); binding.pauseRecording.setContentDescription(getString(R.string.pause_recording)); binding.pauseRecording.setOnClickListener(v -> viewModel.pause()); binding.recordingStatus.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.ic_baseline_mic_24)); } if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.N) { binding.pauseRecording.setVisibility(GONE); } } else { binding.getRoot().setVisibility(GONE); } }); binding.stopRecording.setOnClickListener(v -> viewModel.stop()); }
Source:
public void testBadCallback() throws Exception { testWithErrorCodes(Collections.singletonMap(ServerErrorCode.No_Error, 9), serverLayout, null, new ErrorCodeChecker() { @Override public void check(RouterErrorCode expectedError) throws Exception { final CountDownLatch callbackCalled = new CountDownLatch(1); List<Future> futures = new ArrayList<>(); for (int i = 0; i < 5; i++) { if (i == 1) { futures.add(router.deleteBlob(blobIdString, new Callback<Void>() { @Override public void onCompletion(Void result, Exception exception) { callbackCalled.countDown(); throw new RuntimeException("Throwing an exception in the user callback"); } })); } else { futures.add(router.deleteBlob(blobIdString)); } } for (Future future : futures) { future.get(); } Assert.assertTrue("Callback not called.", callbackCalled.await(2, TimeUnit.SECONDS)); Assert.assertEquals("All operations should be finished.", 0, router.getOperationsCount()); Assert.assertTrue("Router should not be closed", router.isOpen()); router.deleteBlob(blobIdString, new ClientCallback()).get(); Assert.assertTrue("Callback not called.", operationCompleteLatch.await(2, TimeUnit.SECONDS)); } }); }

Target:
public void testBadCallback() throws Exception { testWithErrorCodes(Collections.singletonMap(ServerErrorCode.No_Error, 9), serverLayout, null, new ErrorCodeChecker() { @Override public void testAndAssert(RouterErrorCode expectedError) throws Exception { final CountDownLatch callbackCalled = new CountDownLatch(1); List<Future> futures = new ArrayList<>(); for (int i = 0; i < 5; i++) { if (i == 1) { futures.add(router.deleteBlob(blobIdString, new Callback<Void>() { @Override public void onCompletion(Void result, Exception exception) { callbackCalled.countDown(); throw new RuntimeException("Throwing an exception in the user callback"); } })); } else { futures.add(router.deleteBlob(blobIdString)); } } for (Future future : futures) { future.get(AWAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS); } Assert.assertTrue("Callback not called.", callbackCalled.await(AWAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS)); Assert.assertEquals("All operations should be finished.", 0, router.getOperationsCount()); Assert.assertTrue("Router should not be closed", router.isOpen()); router.deleteBlob(blobIdString).get(); } }); }
Source:
public int getPurgingAge(){ int numberOfDays = 0; String line = null; try { File file = new File("config.txt"); if (file.createNewFile()){ FileWriter fileWriter = new FileWriter(file); fileWriter.append("100"); fileWriter.close(); return 100; }else{ FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileReader); while((line = bufferedReader.readLine() )!= null){ numberOfDays = Integer.parseInt(line.trim()); return numberOfDays; } } } catch (IOException e) { logger.log(Level.FINE, e.getMessage(), e); } return numberOfDays; }

Target:
public int getPurgingAge(){ int numberOfDays = 0; String line; try { File file = new File("config.txt"); if (file.createNewFile()){ FileWriter fileWriter = new FileWriter(file); fileWriter.append("100"); fileWriter.close(); return 100; }else{ FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileReader); while((line = bufferedReader.readLine() )!= null){ numberOfDays = Integer.parseInt(line.trim()); return numberOfDays; } bufferedReader.close(); } } catch (IOException e) { logger.log(Level.FINE, e.getMessage(), e); } finally { return numberOfDays; } }
Source:
private static HttpCookie parseLine(@NonNull String line, @NonNull Date creationDate) { if (line.isEmpty() || (line.startsWith("#") && !line.startsWith(HTTP_ONLY_PREAMBLE))) { return null; } String[] cookieLineParts = line.split(COLUMN_SEPARATOR, 7); if (cookieLineParts == null) { throw new IllegalArgumentException(MessageFormat .format(JGitText.get().couldNotFindTabInLine, line)); } if (cookieLineParts.length < 7) { throw new IllegalArgumentException(MessageFormat.format( JGitText.get().couldNotFindSixTabsInLine, new Integer(cookieLineParts.length), line)); } String name = cookieLineParts[5]; String value = cookieLineParts[6]; HttpCookie cookie = new HttpCookie(name, value); String domain = cookieLineParts[0]; if (domain.startsWith(HTTP_ONLY_PREAMBLE)) { cookie.setHttpOnly(true); domain = domain.substring(HTTP_ONLY_PREAMBLE.length()); } if (domain.startsWith(".")) { domain = domain.substring(1); } cookie.setDomain(domain); cookie.setPath(cookieLineParts[2]); cookie.setSecure(Boolean.parseBoolean(cookieLineParts[3])); long expires = Long.parseLong(cookieLineParts[4]); long maxAge = (expires - creationDate.getTime()) / 1000; if (maxAge <= 0) { return null; } cookie.setMaxAge(maxAge); return cookie; }

Target:
private static HttpCookie parseLine(@NonNull String line, @NonNull Date creationDate) { if (line.isEmpty() || (line.startsWith("#") && !line.startsWith(HTTP_ONLY_PREAMBLE))) { return null; } String[] cookieLineParts = line.split(COLUMN_SEPARATOR, 7); if (cookieLineParts == null) { throw new IllegalArgumentException(MessageFormat .format(JGitText.get().couldNotFindTabInLine, line)); } if (cookieLineParts.length < 7) { throw new IllegalArgumentException(MessageFormat.format( JGitText.get().couldNotFindSixTabsInLine, Integer.valueOf(cookieLineParts.length), line)); } String name = cookieLineParts[5]; String value = cookieLineParts[6]; HttpCookie cookie = new HttpCookie(name, value); String domain = cookieLineParts[0]; if (domain.startsWith(HTTP_ONLY_PREAMBLE)) { cookie.setHttpOnly(true); domain = domain.substring(HTTP_ONLY_PREAMBLE.length()); } if (domain.startsWith(".")) { domain = domain.substring(1); } cookie.setDomain(domain); cookie.setPath(cookieLineParts[2]); cookie.setSecure(Boolean.parseBoolean(cookieLineParts[3])); long expires = Long.parseLong(cookieLineParts[4]); long maxAge = (expires - creationDate.getTime()) / 1000; if (maxAge <= 0) { return null; } cookie.setMaxAge(maxAge); return cookie; }
Source:
protected void onDestroy() { super.onDestroy(); if (mIdpProviders != null) { for (final IDPProvider provider : mIdpProviders) { if (GoogleProvider.class.isInstance(provider)) { ((GoogleProvider) provider).disconnect(); } } } }

Target:
protected void onDestroy() { super.onDestroy(); if (mIdpProviders != null) { for (final IDPProvider provider : mIdpProviders) { if (provider instanceof GoogleProvider) { ((GoogleProvider) provider).disconnect(); } } } }
Source:
public void itInsertsABranchWhenNonePresent() throws Exception { long before = Math.floorDiv(System.currentTimeMillis(), 1000L) * 1000; GitInfo original = newGitInfo(123, "Overwatch", "master"); GitInfo inserted = branchService.upsert(original); assertThat(inserted.getId().isPresent()).isTrue(); Optional<GitInfo> retrieved = branchService.get(inserted.getId().get()); assertThat(retrieved.isPresent()).isTrue(); assertThat(retrieved.get()).isEqualTo(inserted); assertThat(retrieved.get().getCreatedTimestamp()).isBetween(before, System.currentTimeMillis()); assertThat(retrieved.get().getUpdatedTimestamp()) .isBetween(before, System.currentTimeMillis()) .isEqualTo(retrieved.get().getCreatedTimestamp()); }

Target:
public void itInsertsABranchWhenNonePresent() throws Exception { long before = System.currentTimeMillis() - 1000; GitInfo original = newGitInfo(123, "Overwatch", "master"); GitInfo inserted = branchService.upsert(original); assertThat(inserted.getId().isPresent()).isTrue(); Optional<GitInfo> retrieved = branchService.get(inserted.getId().get()); assertThat(retrieved.isPresent()).isTrue(); assertThat(retrieved.get()).isEqualTo(inserted); assertThat(retrieved.get().getCreatedTimestamp()).isBetween(before, System.currentTimeMillis()); assertThat(retrieved.get().getUpdatedTimestamp()) .isBetween(before, System.currentTimeMillis()) .isEqualTo(retrieved.get().getCreatedTimestamp()); }