auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public AzureStorageCompactor(AzureBlobDataAccessor azureBlobDataAccessor, CosmosDataAccessor cosmosDataAccessor, CloudConfig cloudConfig, VcrMetrics vcrMetrics, AzureMetrics azureMetrics) { this.azureBlobDataAccessor = azureBlobDataAccessor; this.cosmosDataAccessor = cosmosDataAccessor; this.vcrMetrics = vcrMetrics; this.azureMetrics = azureMetrics; this.retentionPeriodMs = TimeUnit.DAYS.toMillis(cloudConfig.cloudDeletedBlobRetentionDays); this.queryLimit = cloudConfig.cloudBlobCompactionQueryLimit; this.purgeLimit = cloudConfig.cloudCompactionPurgeLimit; this.queryBucketDays = cloudConfig.cloudCompactionQueryBucketDays; this.lookbackDays = cloudConfig.cloudCompactionLookbackDays; requestAgent = new CloudRequestAgent(cloudConfig, vcrMetrics); <START> emptyCheckpoints = new HashMap<>(); <END> emptyCheckpoints.put(CloudBlobMetadata.FIELD_DELETION_TIME, DEFAULT_TIME); emptyCheckpoints.put(CloudBlobMetadata.FIELD_EXPIRATION_TIME, DEFAULT_TIME); }</code><technical_language>references this map get returned method calls, consider wrapping in Collections.unmodifiableMap static</technical_language>

Target:
public AzureStorageCompactor(AzureBlobDataAccessor azureBlobDataAccessor, CosmosDataAccessor cosmosDataAccessor, CloudConfig cloudConfig, VcrMetrics vcrMetrics, AzureMetrics azureMetrics) { this.azureBlobDataAccessor = azureBlobDataAccessor; this.cosmosDataAccessor = cosmosDataAccessor; this.vcrMetrics = vcrMetrics; this.azureMetrics = azureMetrics; this.retentionPeriodMs = TimeUnit.DAYS.toMillis(cloudConfig.cloudDeletedBlobRetentionDays); this.queryLimit = cloudConfig.cloudBlobCompactionQueryLimit; this.purgeLimit = cloudConfig.cloudCompactionPurgeLimit; this.queryBucketDays = cloudConfig.cloudCompactionQueryBucketDays; this.lookbackDays = cloudConfig.cloudCompactionLookbackDays; requestAgent = new CloudRequestAgent(cloudConfig, vcrMetrics); }
Source:
<code>public void asUpdateUser() { NameCommand command = new NameCommand(); <START> String familyname = "Silamina"; <END> String formatted = "tarentius Silamina"; String givenname = "tarentius"; String honorificprefix = "Prof."; String honorificsuffix = "Prof. Dr."; String middlename = "osiamone"; command.setFamilyname(familyname); command.setFormatted(formatted); command.setGivenname(givenname); command.setHonorificprefix(honorificprefix); command.setHonorificsuffix(honorificsuffix); command.setMiddlename(middlename); assertEquals(familyname, command.getFamilyname()); assertEquals(formatted, command.getFormatted()); assertEquals(givenname, command.getGivenname()); assertEquals(honorificprefix, command.getHonorificprefix()); assertEquals(honorificsuffix, command.getHonorificsuffix()); assertEquals(middlename, command.getMiddlename()); }</code><technical_language>spelling class variables</technical_language>

Target:
public void asUpdateUser() { NameCommand command = new NameCommand(); String familyName = "Silamina"; String formatted = "tarentius Silamina"; String givenname = "tarentius"; String honorificprefix = "Prof."; String honorificsuffix = "Prof. Dr."; String middlename = "osiamone"; command.setFamilyname(familyName); command.setFormatted(formatted); command.setGivenname(givenname); command.setHonorificprefix(honorificprefix); command.setHonorificsuffix(honorificsuffix); command.setMiddlename(middlename); assertEquals(familyName, command.getFamilyname()); assertEquals(formatted, command.getFormatted()); assertEquals(givenname, command.getGivenname()); assertEquals(honorificprefix, command.getHonorificprefix()); assertEquals(honorificsuffix, command.getHonorificsuffix()); assertEquals(middlename, command.getMiddlename()); }
Source:
<code>private static HiveSortOrder decodeSortingColumn(String name) { <START> checkState(name != null && name.length() > 0 && (name.charAt(0) == '+' || name.charAt(0) == '-'), "Sort columns must be prefixed with +/- to specify ASC/DESC"); <END> return new HiveSortOrder( name.substring(1).toLowerCase(ENGLISH), name.charAt(0) == '+' ? ASCENDING : DESCENDING); }</code><technical_language>Strings.isNullOrEmpty()</technical_language>

Target:
private static HiveSortOrder decodeSortingColumn(String name) { checkState(!Strings.isNullOrEmpty(name) && (name.charAt(0) == '+' || name.charAt(0) == '-'), "Sort columns must be prefixed with +/- to specify ASC/DESC"); return new HiveSortOrder( name.substring(1).toLowerCase(ENGLISH), name.charAt(0) == '+' ? ASCENDING : DESCENDING); }
Source:
<code>public void releaseMacsOnCommit(List<String> macs) { log.debug("Non-tx, non-compensation state, <START> immediately releasing <END> macs {}.", Arrays.toString(macs.toArray())); macs.forEach(macPool::freeMac); }</code><technical_language>remove "immeditely" add in other cases</technical_language>

Target:
public void releaseMacsOnCommit(List<String> macs) { log.debug("Non-tx, non-compensation state, immediately releasing macs {}.", macs); macs.forEach(macPool::freeMac); }
Source:
<code>void translate(final LogicalAggregate aggregate, final TranslatorContext context) { MessageStream<SamzaSqlRelMessage> inputStream = context.getMessageStream(aggregate.getInput().getId()); Supplier<Long> initialValue = () -> (long) 0; FoldLeftFunction<SamzaSqlRelMessage, Long> foldLeftFn = (m, c) -> c + 1; MessageStream<SamzaSqlRelMessage> outputStream = <START> inputStream <END> .window(Windows.keyedTumblingWindow(m -> m, Duration.ofMillis(context.getExecutionContext().getSamzaSqlApplicationConfig().getWindowDurationMs()), initialValue, foldLeftFn, new SamzaSqlRelMessageSerdeFactory.SamzaSqlRelMessageSerde(), new LongSerde()) .setAccumulationMode(AccumulationMode.DISCARDING), "tumblingWindow_" + windowId) .map(windowPane -> { List<String> fieldNames = windowPane.getKey().getKey().getSamzaSqlRelRecord().getFieldNames(); List<Object> fieldValues = windowPane.getKey().getKey().getSamzaSqlRelRecord().getFieldValues(); fieldNames.add(aggregate.getAggCallList().get(0).getName()); fieldValues.add(windowPane.getMessage()); return new SamzaSqlRelMessage(fieldNames, fieldValues); }); context.registerMessageStream(aggregate.getId(), outputStream); }</code><technical_language>curious: do need expose early triggers for groupby</technical_language>

Target:
void translate(final LogicalAggregate aggregate, final TranslatorContext context) { validateAggregateFunctions(aggregate); MessageStream<SamzaSqlRelMessage> inputStream = context.getMessageStream(aggregate.getInput().getId()); Supplier<Long> initialValue = () -> (long) 0; FoldLeftFunction<SamzaSqlRelMessage, Long> foldCountFn = (m, c) -> c + 1; MessageStream<SamzaSqlRelMessage> outputStream = inputStream .window(Windows.keyedTumblingWindow(m -> m, Duration.ofMillis(context.getExecutionContext().getSamzaSqlApplicationConfig().getWindowDurationMs()), initialValue, foldCountFn, new SamzaSqlRelMessageSerdeFactory.SamzaSqlRelMessageSerde(), new LongSerde()) .setAccumulationMode(AccumulationMode.DISCARDING), "tumblingWindow_" + windowId) .map(windowPane -> { List<String> fieldNames = windowPane.getKey().getKey().getSamzaSqlRelRecord().getFieldNames(); List<Object> fieldValues = windowPane.getKey().getKey().getSamzaSqlRelRecord().getFieldValues(); fieldNames.add(aggregate.getAggCallList().get(0).getName()); fieldValues.add(windowPane.getMessage()); return new SamzaSqlRelMessage(fieldNames, fieldValues); }); context.registerMessageStream(aggregate.getId(), outputStream); }
Source:
<code>public DefaultResult call() throws Exception { final Ds3ClientHelpers.ObjectChannelBuilder getter; if (this.pipe) { <START> getter = new PipedFileObjectGetter(this.outputPath, FileUtils.normalizedObjectNames(this.pipedFileNames)); <END> } else if (this.discard) { getter = new MemoryObjectChannelBuilder(); } else { getter = new FileObjectGetter(this.outputPath); } LOG.info(getLogDescription()); return new DefaultResult(this.restore(getter)); }</code><technical_language>a bit confused need a new FileObjectGetter. FileObjectGetter do new PipedFileObjectGetter do</technical_language>

Target:
public DefaultResult call() throws Exception { final Ds3ClientHelpers.ObjectChannelBuilder getter; if (this.pipe) { getter = new PipedFileObjectGetter(this.outputPath, FileUtils.normalizedObjectNames(this.pipedFileNames)); } else if (this.discard) { getter = new MemoryObjectChannelBuilder(); } else { getter = new FileObjectGetter(this.outputPath); } LOG.info(buildLogDescription()); return new DefaultResult(this.restore(getter)); }
Source:
<code>public Response replaceWithBaselineTxVersion(String userId, long branchId, int txId, int artId, String comment) { boolean introduced = false; ArtifactReadable userReadable = newQueryFactory().fromBranch(CoreBranches.COMMON).andGuid(userId).getResults().getOneOrNull(); ArtifactReadable baselineArtifact = newQueryFactory().fromBranch(branchId).fromTransaction(txId).andLocalId(artId).getResults().getOneOrNull(); if (userReadable != null && baselineArtifact != null) { TransactionBuilder tx = newTxFactory().createTransaction(branchId, userReadable, comment); ArtifactReadable destination = newQueryFactory().fromBranch(branchId).includeDeletedArtifacts().andLocalId(artId).getResults().getOneOrNull(); tx.replaceWithVersion(baselineArtifact, destination); tx.commit(); introduced = true; } <START> <END> return asResponse(introduced); }</code><technical_language>Suggest logging reason introduce fails show difference userReadable null baselineArtifact null</technical_language>

Target:
public Response replaceWithBaselineTxVersion(String userId, long branchId, int txId, int artId, String comment) { boolean introduced = false; ArtifactReadable userReadable = newQueryFactory().fromBranch(CoreBranches.COMMON).andGuid(userId).getResults().getOneOrNull(); ArtifactReadable baselineArtifact = newQueryFactory().fromBranch(branchId).fromTransaction(txId).andLocalId(artId).getResults().getOneOrNull(); if (userReadable != null && baselineArtifact != null) { TransactionBuilder tx = newTxFactory().createTransaction(branchId, userReadable, comment); ArtifactReadable destination = newQueryFactory().fromBranch(branchId).includeDeletedArtifacts().andLocalId(artId).getResults().getOneOrNull(); tx.replaceWithVersion(baselineArtifact, destination); tx.commit(); introduced = true; } else { throw new OseeWebApplicationException(Status.BAD_REQUEST, "%s Error - The user and baseline artifact were not found.", comment); } return asResponse(introduced); }
Source:
<code>public void test() throws Exception { sink.input().send(MessageBuilder.withPayload("foo".getBytes()).build()); File file = new File("/tmp/dataflow-tests/file-sink"); file.deleteOnExit(); assertTrue("file does not exist", file.exists()); byte[] results = FileCopyUtils.copyToByteArray(file); <START> assertEquals(3, results.length); <END> assertEquals((byte)'f', results[0]); assertEquals((byte)'o', results[1]); assertEquals((byte)'o', results[2]); }</code><technical_language>Assert.assertArrayEquals()</technical_language>

Target:
public void test() throws Exception { sink.input().send(MessageBuilder.withPayload("foo".getBytes()).build()); File file = new File(ROOT_DIR, "file-sink"); file.deleteOnExit(); assertTrue("file does not exist", file.exists()); byte[] results = FileCopyUtils.copyToByteArray(file); assertEquals(3, results.length); assertArrayEquals("foo".getBytes(), results); }
Source:
<code>public void testMultiBranchWithClassic() throws Exception { String credential = auth.getId(); String format = "jenkins-${NODE_NAME}-${JOB_NAME}"; String includes = " SCMSource source = new BranchesScmSource("classic", credential, includes, null, format, null); WorkflowMultiBranchProject multi = jenkins.jenkins.createProject(WorkflowMultiBranchProject.class, "multi-classic"); multi.getSourcesList().add(new BranchSource(source)); multi.scheduleBuild2(0); jenkins.waitUntilNoActivity(); assertThat("We now have branches", <START> multi.getItems(), not(is((Collection<WorkflowJob>) Collections.<WorkflowJob>emptyList()))); <END> WorkflowJob job = multi.getItem("Ace-main"); assertThat("We now have a branch", job, notNullValue()); WorkflowRun build = job.getLastBuild(); assertThat("The branch was built", build, notNullValue()); assertThat("The branch was built", build.getNumber(), is(1)); }</code><technical_language>not(containsInAnyOrder()) is simpler requires generics mangling (and yep obvious verifies do empty collection)</technical_language>

Target:
public void testMultiBranchWithClassic() throws Exception { String credential = auth.getId(); String format = "jenkins-${NODE_NAME}-${JOB_NAME}"; String includes = " SCMSource source = new BranchesScmSource("classic", credential, includes, null, format, null); WorkflowMultiBranchProject multi = jenkins.jenkins.createProject(WorkflowMultiBranchProject.class, "multi-classic"); multi.getSourcesList().add(new BranchSource(source)); multi.scheduleBuild2(0); jenkins.waitUntilNoActivity(); assertThat("We now have branches", multi.getItems(), not(containsInAnyOrder())); WorkflowJob job = multi.getItem("Ace-main"); assertThat("We now have a branch", job, notNullValue()); WorkflowRun build = job.getLastBuild(); assertThat("The branch was built", build, notNullValue()); assertThat("The branch was built", build.getNumber(), is(1)); }
Source:
<code><START> public static void main(String[] args) { <END> try { Map<String, Object> argMap = parseArgs(args); setupLogger(argMap); List<String> others = (List<String>) argMap.get("__other__"); Map<String, ModuleService> moduleServices = loadModules(ModuleService.class); if (argMap.containsKey(ARG_HELP)) { List<String> modules = new ArrayList<>(moduleServices.keySet()); Collections.sort(modules); throw new ArgumentException("Modules: " + StringUtils.join(modules, ", ")); } if (others.isEmpty()) { throw new IllegalArgumentException("Module must be provided"); } String module = others.remove(0); ModuleService moduleService = moduleServices.get(module); if (moduleService == null) { throw new IllegalArgumentException( String.format("No such '%1$s' module exists.", module) ); } moduleService.parseArguments(others); if (moduleService.doHelp()) { throw new ArgumentException(module + " help"); } loadExtensions(moduleService, argMap); moduleService.run(); } catch(ArgumentException e) { System.out.println(e.getMessage()); System.exit(0); } catch (Throwable t) { String message = t.getMessage() != null ? t.getMessage() : t.getClass().getName(); logger.error(message); logger.debug(message, t); System.exit(1); } }</code><technical_language>int exitStatus = 1;</technical_language>

Target:
public static void main(String[] args) { int exitStatus = 1; try { Map<String, Object> argMap = parseArgs(args); setupLogger(argMap); List<String> others = (List<String>) argMap.get("__other__"); Map<String, ModuleService> moduleServices = loadModules(ModuleService.class); if (argMap.containsKey(ARG_HELP)) { List<String> modules = new ArrayList<>(moduleServices.keySet()); Collections.sort(modules); throw new ExitException("Modules: " + StringUtils.join(modules, ", "), 0); } if (others.isEmpty()) { throw new IllegalArgumentException("Module must be provided"); } String module = others.remove(0); ModuleService moduleService = moduleServices.get(module); if (moduleService == null) { throw new IllegalArgumentException( String.format("No such '%1$s' module exists.", module) ); } moduleService.parseArguments(others); if (moduleService.doHelp()) { throw new ExitException(module + " help", 0); } loadExtensions(moduleService, argMap); moduleService.run(); } catch(ExitException e) { System.out.println(e.getMessage()); exitStatus = e.getExitCode(); } catch (Throwable t) { String message = t.getMessage() != null ? t.getMessage() : t.getClass().getName(); logger.error(message); logger.debug(message, t); } System.exit(exitStatus); }
Source:
<code>public void execute() { int flag = 0; <START> Ode.getInstance().getTopToolbar().updateMoveToTrash(flag); <END> Ode.getInstance().switchToProjectsView(); Ode.getInstance().getTopToolbar().updateFileMenuButtons(0); }</code><technical_language>Again, need for flag here</technical_language>

Target:
public void execute() { Ode.getInstance().getTopToolbar().updateMoveToTrash("Move To Trash"); Ode.getInstance().switchToProjectsView(); Ode.getInstance().getTopToolbar().updateFileMenuButtons(0); }
Source:
<code>public void enqueueLog(Path wal) { if (!this.filterInWALs.test(wal)) { LOG.trace("NOT replicating {}", wal); return; <START> } <END> String walGroupId = AbstractFSWALProvider.getWALPrefixFromWALName(wal.getName()); PriorityBlockingQueue<Path> queue = queues.get(walGroupId); if (queue == null) { queue = new PriorityBlockingQueue<>(queueSizePerGroup, new AbstractFSWALProvider.WALsStartTimeComparator()); queues.put(walGroupId, queue); if (this.isSourceActive() && this.walEntryFilter != null) { tryStartNewShipper(walGroupId, queue); } } queue.put(wal); if (LOG.isTraceEnabled()) { LOG.trace("{} Added wal to queue of source {}.", this, walGroupId, this.replicationQueueInfo.getQueueId()); } this.metrics.incrSizeOfLogQueue(); int queueSize = queue.size(); if (queueSize > this.logQueueWarnThreshold) { LOG.warn("{} WAL group queue size={} exceeds 'replication.source.log.queue.warn'={}", this, walGroupId, queueSize, logQueueWarnThreshold); } }</code><technical_language>name walPrefix? method is called getWALPrefixFromWALName, name walGroupId adds new constraint</technical_language>

Target:
public void enqueueLog(Path wal) { if (!this.filterInWALs.test(wal)) { LOG.trace("NOT replicating {}", wal); return; } String walGroupId = AbstractFSWALProvider.getWALPrefixFromWALName(wal.getName()); PriorityBlockingQueue<Path> queue = queues.get(walGroupId); if (queue == null) { queue = new PriorityBlockingQueue<>(queueSizePerGroup, new LogsComparator()); queues.put(walGroupId, queue); if (this.isSourceActive() && this.walEntryFilter != null) { tryStartNewShipper(walGroupId, queue); } } queue.put(wal); if (LOG.isTraceEnabled()) { LOG.trace("{} Added wal to queue of source {}.", logPeerId(), walGroupId, this.replicationQueueInfo.getQueueId()); } this.metrics.incrSizeOfLogQueue(); int queueSize = queue.size(); if (queueSize > this.logQueueWarnThreshold) { LOG.warn("{} WAL group queue size: exceeds value of " + "replication.source.log.queue.warn: {}", logPeerId(), walGroupId, queueSize, logQueueWarnThreshold); } }
Source:
<code>private void resize(int size) { if (nResizes < maxResizes) { nResizes++; long kCapacity = (kLimit - kStart) << 1; long target = key.appendAddress + size - kStart; if (kCapacity < target) { kCapacity = Numbers.ceilPow2(target); } long kAddress = Unsafe.realloc(this.kStart, this.capacity, kCapacity); this.capacity = kCapacity; long d = kAddress - this.kStart; kPos += d; long colOffsetDelta = key.nextColOffset - key.startAddress; key.startAddress += d; key.appendAddress += d; key.nextColOffset = key.startAddress + colOffsetDelta; assert kPos > 0; assert key.startAddress > 0; assert key.appendAddress > 0; assert key.nextColOffset > 0; this.kStart = kAddress; this.kLimit = kAddress + kCapacity; } else { <START> throw LimitOverflowException.instance().put("limit of ").put(maxResizes).put(" resizes exceeded"); <END> } }</code><technical_language>throwing static instance of exception preserve correct stack trace. For reason need limit overflow from. Include name of class for example</technical_language>

Target:
private void resize(int size) { if (nResizes < maxResizes) { nResizes++; long kCapacity = (kLimit - kStart) << 1; long target = key.appendAddress + size - kStart; if (kCapacity < target) { kCapacity = Numbers.ceilPow2(target); } long kAddress = Unsafe.realloc(this.kStart, this.capacity, kCapacity); this.capacity = kCapacity; long d = kAddress - this.kStart; kPos += d; long colOffsetDelta = key.nextColOffset - key.startAddress; key.startAddress += d; key.appendAddress += d; key.nextColOffset = key.startAddress + colOffsetDelta; assert kPos > 0; assert key.startAddress > 0; assert key.appendAddress > 0; assert key.nextColOffset > 0; this.kStart = kAddress; this.kLimit = kAddress + kCapacity; } else { throw LimitOverflowException.instance().put("limit of ").put(maxResizes).put(" resizes exceeded in FastMap"); } }
Source:
<code>public static boolean isPublicKeyValid(String publicKey) { String[] words = publicKey.split("\\s+", 3); <START> if (words.length != 3) { <END> return false; } if (!words[0].matches("^[\\p{Alpha}\\p{Digit}-]*$")) { return false; } if (!Base64.isArrayByteBase64(words[1].getBytes())) { return false; } return true; }</code><technical_language>2</technical_language>

Target:
public static boolean isPublicKeyValid(String publicKey) { String[] words = publicKey.split("\\s+", 3); if (words.length < 2 || words.length > 3) { return false; } if (!words[0].matches("^[\\p{Alpha}\\p{Digit}-]*$")) { return false; } if (!Base64.isArrayByteBase64(words[1].getBytes())) { return false; } return true; }
Source:
<code>private String findMatch(Set<String> names, URIish uri) { String bestMatch = null; int bestMatchLength = -1; boolean withUser = false; String uPath = uri.getPath(); boolean hasPath = <START> uPath != null && !uPath.isEmpty(); <END> if (hasPath) { uPath = normalize(uPath); if (uPath == null) { return null; } } for (String s : names) { try { URIish candidate = new URIish(s); if (!compare(uri.getScheme(), candidate.getScheme()) || !compare(uri.getHost(), candidate.getHost())) { continue; } if (defaultedPort(uri.getPort(), uri.getScheme()) != defaultedPort(candidate.getPort(), candidate.getScheme())) { continue; } boolean hasUser = false; if (candidate.getUser() != null) { if (!candidate.getUser().equals(uri.getUser())) { continue; } hasUser = true; } String cPath = candidate.getPath(); int matchLength = -1; if (cPath == null || cPath.isEmpty()) { matchLength = 0; } else { if (!hasPath) { continue; } matchLength = segmentCompare(uPath, cPath); if (matchLength < 0) { continue; } } if (matchLength > bestMatchLength || !withUser && hasUser && matchLength >= 0 && matchLength == bestMatchLength) { bestMatch = s; bestMatchLength = matchLength; withUser = hasUser; } } catch (URISyntaxException e) { LOG.warn(MessageFormat .format(JGitText.get().httpConfigInvalidURL, s)); } } return bestMatch; }</code><technical_language>!StringUtils.isEmptyOrNull(uPath)</technical_language>

Target:
private String findMatch(Set<String> names, URIish uri) { String bestMatch = null; int bestMatchLength = -1; boolean withUser = false; String uPath = uri.getPath(); boolean hasPath = !StringUtils.isEmptyOrNull(uPath); if (hasPath) { uPath = normalize(uPath); if (uPath == null) { return null; } } for (String s : names) { try { URIish candidate = new URIish(s); if (!compare(uri.getScheme(), candidate.getScheme()) || !compare(uri.getHost(), candidate.getHost())) { continue; } if (defaultedPort(uri.getPort(), uri.getScheme()) != defaultedPort(candidate.getPort(), candidate.getScheme())) { continue; } boolean hasUser = false; if (candidate.getUser() != null) { if (!candidate.getUser().equals(uri.getUser())) { continue; } hasUser = true; } String cPath = candidate.getPath(); int matchLength = -1; if (StringUtils.isEmptyOrNull(cPath)) { matchLength = 0; } else { if (!hasPath) { continue; } matchLength = segmentCompare(uPath, cPath); if (matchLength < 0) { continue; } } if (matchLength > bestMatchLength || !withUser && hasUser && matchLength >= 0 && matchLength == bestMatchLength) { bestMatch = s; bestMatchLength = matchLength; withUser = hasUser; } } catch (URISyntaxException e) { LOG.warn(MessageFormat .format(JGitText.get().httpConfigInvalidURL, s)); } } return bestMatch; }
Source:
<code>boolean trustsDomain(final SecurityDomain domain) { Assert.checkNotNullParam("domain", domain); <START> return this == domain ? true : trustedSecurityDomain.test(domain); <END> }</code><technical_language>This simplified: return this == domain || trustedSecurityDomain.test(domain);</technical_language>

Target:
boolean trustsDomain(final SecurityDomain domain) { Assert.checkNotNullParam("domain", domain); return this == domain || trustedSecurityDomain.test(domain); }
Source:
<code>private void createFile(File parentDir, String name, String content) throws IOException { File file = new File(parentDir, name); <START> file.createNewFile(); <END> FileOutputStream fos = null; try { fos = new FileOutputStream(file); fos.write(content.getBytes("UTF-8")); } finally { if (fos != null) fos.close(); } }</code><technical_language>This necessary, new FileOutputStream(file) create file if exist yet</technical_language>

Target:
private void createFile(File parentDir, String name, String content) throws IOException { File file = new File(parentDir, name); FileOutputStream fos = new FileOutputStream(file); try { fos.write(content.getBytes("UTF-8")); } finally { fos.close(); } }
Source:
<code>public ExceptionEvent(String exMessage, boolean isRatioException) { super(); this.description(exMessage); <START> if (isRatioException) { <END> this.tags.add("exception"); } else { this.tags.add("ratio-exception"); } }</code><technical_language>I switched condition</technical_language>

Target:
public ExceptionEvent(String exMessage, boolean isRatioException) { super(); this.description(exMessage); if (isRatioException) { this.tags.add("ratio-exception"); } else { this.tags.add("exception"); } }
Source:
<code>public void setGridWidgetBACKGROUND() { testToolsPresenterSpy.setGridWidget(GridWidget.BACKGROUND); verify(testToolsPresenterSpy, times(1)).onDisableEditorTab(); verify(testToolsPresenterSpy, times(1)).hideInstances(); <START> verify(testToolsPresenterSpy, never()).showInstanceListContainerSeparator(eq(true)); <END> }</code><technical_language>@yesamer This removed, I</technical_language>

Target:
public void setGridWidgetBACKGROUND() { testToolsPresenterSpy.setGridWidget(GridWidget.BACKGROUND); verify(testToolsPresenterSpy, times(1)).onDisableEditorTab(); verify(testToolsPresenterSpy, times(1)).hideInstances(); }
Source:
<code><START> public OneSlotPerExecutionSlotAllocatorFactory( <END> final SlotProvider slotProvider, final boolean slotWillBeOccupiedIndefinitely, final Time allocationTimeout) { this.slotProvider = checkNotNull(slotProvider); this.slotWillBeOccupiedIndefinitely = slotWillBeOccupiedIndefinitely; this.allocationTimeout = checkNotNull(allocationTimeout); }</code><technical_language>suggestion OneSlotPerExecutionSlotAllocatorFactory(</technical_language>

Target:
OneSlotPerExecutionSlotAllocatorFactory( final SlotProvider slotProvider, final boolean slotWillBeOccupiedIndefinitely, final Time allocationTimeout) { this.slotProvider = checkNotNull(slotProvider); this.slotWillBeOccupiedIndefinitely = slotWillBeOccupiedIndefinitely; this.allocationTimeout = checkNotNull(allocationTimeout); }
Source:
<code>public void createNewPayment_withCardPayment_invokesCreatePaymentService() { final Account account = new Account("foo", TokenPaymentType.CARD); final CreatePaymentRequest createPaymentRequest = CreatePaymentRequest.builder() .amount(100) .returnUrl("<LINK_0>") .reference("my_ref") .description("New Passport") .build(); PaymentWithAllLinks injectedResponse = aSuccessfullyCreatedPayment(); <START> when(createPaymentService.create(eq(account), ArgumentMatchers.any())).thenReturn(injectedResponse); <END> final Response newPayment = paymentsResource.createNewPayment(account, createPaymentRequest); assertThat(newPayment.getStatus(), is(201)); assertThat(newPayment.getLocation(), is(URI.create(paymentUri))); assertThat(newPayment.getEntity(), sameInstance(injectedResponse)); }</code><technical_language>do any()? (Even any(CreatePaymentRequest.class) better!) Feel free add equals( ) method CreatePaymentRequest if this sort of matching easier</technical_language>

Target:
public void createNewPayment_withCardPayment_invokesCreatePaymentService() { final Account account = new Account("foo", TokenPaymentType.CARD); final CreatePaymentRequest createPaymentRequest = CreatePaymentRequest.builder() .amount(100) .returnUrl("<LINK_0>") .reference("my_ref") .description("New Passport") .build(); final ValidCreatePaymentRequest validCreatePaymentRequest = new ValidCreatePaymentRequest(createPaymentRequest); PaymentWithAllLinks injectedResponse = aSuccessfullyCreatedPayment(); when(createPaymentService.create(account, validCreatePaymentRequest)).thenReturn(injectedResponse); final Response newPayment = paymentsResource.createNewPayment(account, createPaymentRequest); assertThat(newPayment.getStatus(), is(201)); assertThat(newPayment.getLocation(), is(URI.create(paymentUri))); assertThat(newPayment.getEntity(), sameInstance(injectedResponse)); }
Source:
<code>public Collection<IteratorSetting> getIterators() { <START> return iterators.entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toSet()); <END> }</code><technical_language>do iterators.values()</technical_language>

Target:
public Collection<IteratorSetting> getIterators() { return iterators.values(); }
Source:
<code>public static Timestamp addMonths(final Timestamp refDate, final int nrOfMonthsToAdd) { Calendar calendar = Calendar.getInstance(); calendar.setTime(refDate); calendar.add(Calendar.MONTH, nrOfMonthsToAdd); <START> return new Timestamp(calendar.getTime().getTime()); <END> }</code><technical_language>2 (1) this is drop nanosecond component, need copy (2) calendar.getTimeInMillis(), intermediate object</technical_language>

Target:
public static Timestamp addMonths(final Timestamp refDate, final int nrOfMonthsToAdd) { Calendar calendar = Calendar.getInstance(); calendar.setTime(refDate); calendar.add(Calendar.MONTH, nrOfMonthsToAdd); Timestamp resultDate = new Timestamp(calendar.getTimeInMillis()); resultDate.setNanos(refDate.getNanos()); return resultDate; }
Source:
<code><START> public void endVisit(@Nonnull JDefinedClassOrInterface type) { <END> String binaryName = remapper.mapValue(formatter.getName(type)); String packageName = NamingTools.getPackageNameFromBinaryName(binaryName); JPackage newPackage = lookup.getOrCreatePackage(packageName); lookup.removeType(type); request.append(new ChangeEnclosingPackage(type, newPackage)); }</code><technical_language>Please, double check setName is mandatory</technical_language>

Target:
public void endVisit(@Nonnull JDefinedClassOrInterface type) { String binaryName = remapper.mapValue(formatter.getName(type)); String simpleName = NamingTools.getSimpleClassNameFromBinaryName(binaryName); type.setName(simpleName); String packageName = NamingTools.getPackageNameFromBinaryName(binaryName); JPackage newPackage = lookup.getOrCreatePackage(packageName); lookup.removeType(type); request.append(new ChangeEnclosingPackage(type, newPackage)); }
Source:
<code><START> private Void deleteScheduledTask(String taskId, SingularityUser user) { <END> SingularityTaskRequest taskRequest = getPendingTask(user, taskId); SingularityRequest request = taskRequest.getRequest(); authorizationHelper.checkForAuthorization(request, user, SingularityAuthorizationScope.WRITE); checkBadRequest(request.getRequestType() == RequestType.ON_DEMAND, "Only ON_DEMAND tasks may be deleted."); taskManager.markPendingTaskForDeletion(taskRequest.getPendingTask().getPendingTaskId()); return null; }</code><technical_language>here: - this public instead of private. methods called endpoint is hit, I generally consider publicly accessible. useful able test methods for endpoints end end (i.e. validation/etc) in other parts of code needed - returning a void, useful return actual object. If in other DELETE methods in Singularity generally return some sort of 'receipt' for delete. For example, killing a task returns task cleanup object created. Deleting a request returns request data deleted. For this case return SingularityPendingTaskId is deleted</technical_language>

Target:
public Optional<SingularityPendingTask> deleteScheduledTask(String taskId, SingularityUser user) { Optional<SingularityPendingTask> maybePendingTask = taskManager.getPendingTask(getPendingTaskIdFromStr(taskId)); if (maybePendingTask.isPresent()) { SingularityPendingTaskId pendingTaskId = maybePendingTask.get().getPendingTaskId(); Optional<SingularityRequestWithState> maybeRequest = requestManager.getRequest(pendingTaskId.getRequestId()); checkNotFound(maybeRequest.isPresent(), "Couldn't find: " + taskId); SingularityRequest request = maybeRequest.get().getRequest(); authorizationHelper.checkForAuthorizationByRequestId(request.getId(), user, SingularityAuthorizationScope.WRITE); checkBadRequest(request.getRequestType() == RequestType.ON_DEMAND, "Only ON_DEMAND tasks may be deleted."); taskManager.markPendingTaskForDeletion(pendingTaskId); } return maybePendingTask; }
Source:
<code>protected WorkDefinitionMatch getPeerToPeerWorkDefinitionFromTeamDefinitionAttributeValueRecurse(IAtsTeamDefinition teamDefinition) throws OseeCoreException { Conditions.notNull(teamDefinition); Collection<Object> attrs = workItemService.getAttributeValues(teamDefinition, AtsAttributeTypes.RelatedPeerWorkflowDefinition); if (attrs.isEmpty()) { IAtsTeamDefinition parentTeamDef = teamDefinition.getParentTeamDef(); if (parentTeamDef != null) { return getPeerToPeerWorkDefinitionFromTeamDefinitionAttributeValueRecurse(parentTeamDef); } } else { WorkDefinitionMatch match = getWorkDefinition((String) attrs.iterator().next()); match.addTrace("PeerToPeer from Team Definition"); return match; } <START> return new WorkDefinitionMatch(); <END> }</code><technical_language>Multiple return statements -</technical_language>

Target:
protected WorkDefinitionMatch getPeerToPeerWorkDefinitionFromTeamDefinitionAttributeValueRecurse(IAtsTeamDefinition teamDefinition) throws OseeCoreException { Conditions.notNull(teamDefinition, getClass().getSimpleName()); WorkDefinitionMatch match = new WorkDefinitionMatch(); Collection<Object> attrs = workItemService.getAttributeValues(teamDefinition, AtsAttributeTypes.RelatedPeerWorkflowDefinition); if (attrs.isEmpty()) { IAtsTeamDefinition parentTeamDef = teamDefinition.getParentTeamDef(); if (parentTeamDef != null) { match = getPeerToPeerWorkDefinitionFromTeamDefinitionAttributeValueRecurse(parentTeamDef); } } else { match = getWorkDefinition((String) attrs.iterator().next()); match.addTrace("PeerToPeer from Team Definition"); } return match; }
Source:
<code>public static <A> Hash<A> anyHash() { return new Hash<A>(a -> a.hashCode()); <START> } <END></code><technical_language>Hash.hash(F<A, Integer> advantage of type inference. Applies other changes this file too</technical_language>

Target:
public static <A> Hash<A> anyHash() { return hash(a -> a.hashCode()); }
Source:
<code>private List<Object> listInternal() { List<Object> results; try (CloseableIterator<ObjectFilter.FilterResult> iterator = getIterator()) { if (!iterator.hasNext()) { results = Collections.emptyList(); } else { Comparator<Comparable[]> comparator = getComparator(); if (comparator == null) { <START> if (iterator.hasNext()) { <END> results = new ArrayList<>(INITIAL_CAPACITY); while (iterator.hasNext()) { ObjectFilter.FilterResult entry = iterator.next(); resultSize++; if (resultSize > startOffset && (maxResults == -1 || results.size() < maxResults)) { results.add(projection != null ? entry.getProjection() : entry.getInstance()); } } } else { results = Collections.emptyList(); } } else { PriorityQueue<ObjectFilter.FilterResult> filterResults = new PriorityQueue<>(INITIAL_CAPACITY, new ReverseFilterResultComparator(comparator)); while (iterator.hasNext()) { ObjectFilter.FilterResult entry = iterator.next(); resultSize++; filterResults.add(entry); if (maxResults != -1 && filterResults.size() > startOffset + maxResults) { filterResults.remove(); } } if (filterResults.size() > startOffset) { Object[] res = new Object[filterResults.size() - startOffset]; int i = filterResults.size(); while (i-- > startOffset) { ObjectFilter.FilterResult r = filterResults.remove(); res[i - startOffset] = projection != null ? r.getProjection() : r.getInstance(); } results = Arrays.asList(res); } else { results = Collections.emptyList(); } } } } return results; }</code><technical_language>iterator.hasNext() check above</technical_language>

Target:
private List<Object> listInternal() { List<Object> results; try (CloseableIterator<ObjectFilter.FilterResult> iterator = getIterator()) { if (!iterator.hasNext()) { results = Collections.emptyList(); } else { Comparator<Comparable[]> comparator = getComparator(); if (comparator == null) { results = new ArrayList<>(INITIAL_CAPACITY); while (iterator.hasNext()) { ObjectFilter.FilterResult entry = iterator.next(); resultSize++; if (resultSize > startOffset && (maxResults == -1 || results.size() < maxResults)) { results.add(projection != null ? entry.getProjection() : entry.getInstance()); } } } else { PriorityQueue<ObjectFilter.FilterResult> filterResults = new PriorityQueue<>(INITIAL_CAPACITY, new ReverseFilterResultComparator(comparator)); while (iterator.hasNext()) { ObjectFilter.FilterResult entry = iterator.next(); resultSize++; filterResults.add(entry); if (maxResults != -1 && filterResults.size() > startOffset + maxResults) { filterResults.remove(); } } if (filterResults.size() > startOffset) { Object[] res = new Object[filterResults.size() - startOffset]; int i = filterResults.size(); while (i-- > startOffset) { ObjectFilter.FilterResult r = filterResults.remove(); res[i - startOffset] = projection != null ? r.getProjection() : r.getInstance(); } results = Arrays.asList(res); } else { results = Collections.emptyList(); } } } } return results; }
Source:
<code>public AggregateRoot(Command command) { <START> ApplyMore antThen = apply(new Event_1(command.getId(), 0)); <END> for (int i = 0; i < command.value; i++) { antThen = antThen.andThenApply(() -> new Event_1(id, value + 1)); } }</code><technical_language>Typo: andThen i.o. antThen</technical_language>

Target:
public AggregateRoot(Command command) { ApplyMore andThen = apply(new Event_1(command.getId(), 0)); for (int i = 0; i < command.value; i++) { andThen = andThen.andThenApply(() -> new Event_1(id, value + 1)); } }
Source:
<code>public static String randomCreditCardNumber(final String prefix) { <START> Check.matchesPattern("prefix", prefix, CARD_PREFIX_PATTERN); <END> final int length = randomIntInRange(13, 19); final int randomNumberLength = length - (prefix.length() + 1); final StringBuffer buffer = new StringBuffer(prefix); for (int i = 0; i < randomNumberLength; i++) { final int digit = Randoms.randomInt(10); buffer.append(digit); } final int checkDigit = getCheckDigit(buffer.toString()); buffer.append(checkDigit); return buffer.toString(); }</code><technical_language>This throw a ValidationException in case of failure, is appropriate. throw IllegalArgumentException: java if (!ALL_DIGITS_PATTERN.matcher(prefix).matches()) { throw new IllegalArgumentException("Invalid card prefix"); }</technical_language>

Target:
public static String randomCreditCardNumber(final String prefix) { if (!CARD_PREFIX_PATTERN.matcher(prefix).matches()) { throw new IllegalArgumentException(String.format("Invalid card prefix: %s", prefix)); } final int length = randomIntInRange(13, 19); final int randomNumberLength = length - (prefix.length() + 1); final StringBuffer buffer = new StringBuffer(prefix); for (int i = 0; i < randomNumberLength; i++) { final int digit = Randoms.randomInt(10); buffer.append(digit); } final int checkDigit = getCreditCardCheckDigit(buffer.toString()); buffer.append(checkDigit); return buffer.toString(); }
Source:
<code>public void testConcurrentWarningReadAndClear() throws SQLException, InterruptedException, ExecutionException, TimeoutException { final int iterations = 1000; final ExecutorService executor = Executors.newSingleThreadExecutor(); final PgStatement statement = (PgStatement) con.createStatement(); final Future warningReaderThread = executor.submit(new Callable<Object>() { @Override public Object call() throws SQLException, InterruptedException { SQLWarning lastProcessed = null; int warnings = 0; while (warnings < iterations) { final SQLWarning warn = lastProcessed != null && lastProcessed.getNextWarning() != null ? lastProcessed.getNextWarning() : statement.getWarnings(); if (warn != null) { warnings++; lastProcessed = warn; if (warn == statement.getWarnings()) { <START> statement.clearWarnings(); <END> } } else { Thread.sleep(10); } } assertEquals(lastProcessed.getMessage(), "Warning " + (iterations - 1)); return null; } }); for (int i = 0; i < iterations; i++) { statement.addWarning(new SQLWarning("Warning " + i)); if (i % 33 == 0 ) { Thread.sleep(1); } } warningReaderThread.get(2, TimeUnit.SECONDS); }</code><technical_language>I understand, a warning lost in scenario: Precondition: satement chain of 5 warnings. 1) Thread 1 acquires st.getWarnings() 2) Thread 2 acquires st.getWarnings() starts addWarning. suspended. 3) Thread 1 performs clear warnings 4) Thread 1 walks getNextWarning chain end, "processes" warnings 5) Thread 2 acquires CPU adds another warning chain (the chain head obtained step 2) Thread 1 warning step 5 walk chain</technical_language>

Target:
public void testConcurrentWarningReadAndClear() throws SQLException, InterruptedException, ExecutionException, TimeoutException { final int iterations = 1000; con.createStatement() .execute("CREATE OR REPLACE FUNCTION notify_loop() RETURNS VOID AS " + "$BODY$ " + "BEGIN " + "FOR i IN 1.. " + iterations + " LOOP " + " RAISE NOTICE 'Warning %', i; " + "END LOOP; " + "END " + "$BODY$ " + "LANGUAGE plpgsql;"); con.createStatement().execute("SET SESSION client_min_messages = 'NOTICE'"); final PreparedStatement statement = con.prepareStatement("SELECT notify_loop()"); final Callable<Void> warningReader = new Callable<Void>() { @Override public Void call() throws SQLException, InterruptedException { SQLWarning lastProcessed = null; int warnings = 0; while (warnings < iterations) { SQLWarning warn = statement.getWarnings(); if (lastProcessed != null && lastProcessed.getNextWarning() != null) { warn = lastProcessed.getNextWarning(); } if (warn != null) { warnings++; assertEquals("Received warning out of expected order", "Warning " + warnings, warn.getMessage()); lastProcessed = warn; if (warn == statement.getWarnings()) { statement.clearWarnings(); } } else { Thread.sleep(10); } } assertEquals("Didn't receive expected last warning", "Warning " + iterations, lastProcessed.getMessage()); return null; } }; final ExecutorService executor = Executors.newSingleThreadExecutor(); try { final Future warningReaderThread = executor.submit(warningReader); statement.execute(); warningReaderThread.get(2, TimeUnit.SECONDS); } finally { executor.shutdownNow(); } }
Source:
<code>public static void setup() { runRollersButton.send(runRollers); toggleRollersButton.send(new BooleanOutput() { public void set(boolean value) { if (value) { direction.set(!direction.get()); } } <START> }); <END> Igneous.globalPeriodic.send(new EventOutput() { public void event() { if (speed.get() != 0.0f) { float newSpeed = direction.get() ? 1.0f : -1.0f; allRollers.set(newSpeed); } else { allRollers.set(0.0f); } } }); }</code><technical_language>direction.toggleWhen here. Especially EventInputs inputs instead of BooleanInputs inputs</technical_language>

Target:
public static void setup() { running.toggleWhen(runRollersButton); direction.toggleWhen(toggleRollersButton); motorSpeed.send(allRollers); }
Source:
<code>private void sendInvalidJSonPayload(int size) throws JsonProcessingException { <START> thrown.expectCause(isA(BeatsParser.InvalidPayloadSize.class)); <END> Map mapData = Collections.singletonMap("message", "hola"); ByteBuf payload = Unpooled.buffer(); payload.writeByte(Protocol.VERSION_2); payload.writeByte('W'); payload.writeInt(1); payload.writeByte(Protocol.VERSION_2); payload.writeByte('J'); payload.writeInt(1); payload.writeInt(size); byte[] json = BeatsParser.MAPPER.writeValueAsBytes(mapData); payload.writeBytes(json); sendPayloadToParser(payload); }</code><technical_language>do want test message contents</technical_language>

Target:
private void sendInvalidJSonPayload(int size) throws JsonProcessingException { thrown.expectCause(isA(BeatsParser.InvalidFrameProtocolException.class)); thrown.expectMessage("Invalid json length, received: " + size); Map mapData = Collections.singletonMap("message", "hola"); ByteBuf payload = Unpooled.buffer(); payload.writeByte(Protocol.VERSION_2); payload.writeByte('W'); payload.writeInt(1); payload.writeByte(Protocol.VERSION_2); payload.writeByte('J'); payload.writeInt(1); payload.writeInt(size); byte[] json = BeatsParser.MAPPER.writeValueAsBytes(mapData); payload.writeBytes(json); sendPayloadToParser(payload); }
Source:
<code>public void update(long value, long timestamp) { rescaleIfNeeded(); lockForRegularUsage(); try { final double itemWeight = weight(timestamp - startTime); final WeightedSample sample = new WeightedSample(value, itemWeight); <START> final double priority = itemWeight / ThreadLocalRandomFactory.current().nextDouble(); <END> final long newCount = count.incrementAndGet(); if (newCount <= size) { values.put(priority, sample); } else { Double first = values.firstKey(); if (first < priority && values.putIfAbsent(priority, sample) == null) { while (values.remove(first) == null) { first = values.firstKey(); } } } } finally { unlockForRegularUsage(); } }</code><technical_language>Agreed, do for 3.2</technical_language>

Target:
public void update(long value, long timestamp) { rescaleIfNeeded(); lockForRegularUsage(); try { final double itemWeight = weight(timestamp - startTime); final WeightedSample sample = new WeightedSample(value, itemWeight); final double priority = itemWeight / ThreadLocalRandomProxy.current().nextDouble(); final long newCount = count.incrementAndGet(); if (newCount <= size) { values.put(priority, sample); } else { Double first = values.firstKey(); if (first < priority && values.putIfAbsent(priority, sample) == null) { while (values.remove(first) == null) { first = values.firstKey(); } } } } finally { unlockForRegularUsage(); } }
Source:
<code>public void setup() { client = helper.createClientForBasicAuth(); factory = new ResourceFactory(client); <START> OpenshiftProjectRequest projectRequest = factory.create(VERSION, ResourceKind.PROJECT_REQUEST); <END> projectRequest.setName(helper.generateNamespace()); project = (IProject) client.create(projectRequest); buildConfigs.add(createBuildConfigWithLabels(project, "build1", new HashMap<String, String>() {{ put("foo", "yes"); put("bar", "no"); put("baz", "no"); }})); buildConfigs.add(createBuildConfigWithLabels(project, "build2", new HashMap<String, String>() {{ put("foo", "no"); put("bar", "yes"); }})); buildConfigs.add(createBuildConfigWithLabels(project, "build3", new HashMap<String, String>() {{ put("foo", "yes"); put("bar", "yes"); }})); buildConfigs.add(createBuildConfigWithLabels(project, "build4", new HashMap<>())); }</code><technical_language>I change IProjectRequest is a reason manipulate implementation</technical_language>

Target:
public static void setup() { client = helper.createClientForBasicAuth(); factory = new ResourceFactory(client); OpenshiftProjectRequest projectRequest = factory.create(VERSION, ResourceKind.PROJECT_REQUEST); projectRequest.setName(helper.generateNamespace()); project = (IProject) client.create(projectRequest); createBuildConfigWithLabels(project, "build1", new HashMap<String, String>() {{ put("foo", "yes"); put("bar", "no"); put("baz", "no"); }}); createBuildConfigWithLabels(project, "build2", new HashMap<String, String>() {{ put("foo", "no"); put("bar", "yes"); }}); createBuildConfigWithLabels(project, "build3", new HashMap<String, String>() {{ put("foo", "yes"); put("bar", "yes"); }}); createBuildConfigWithLabels(project, "build4", new HashMap<>()); }
Source:
<code>public Document parse(Reader input) throws IOException { DocumentBlockParser documentBlockParser = new DocumentBlockParser(); activateBlockParser(documentBlockParser); BufferedReader bufferedReader; if (input instanceof BufferedReader) { bufferedReader = (BufferedReader) input; } else { bufferedReader = new BufferedReader(input); } String line; while ((line = bufferedReader.readLine()) != null) { incorporateLine(line); } finalizeBlocks(activeBlockParsers); this.processInlines(); <START> return documentBlockParser.getBlock(); <END> }</code><technical_language>lines shared extracting a method reusing it</technical_language>

Target:
public Document parse(Reader input) throws IOException { BufferedReader bufferedReader; if (input instanceof BufferedReader) { bufferedReader = (BufferedReader) input; } else { bufferedReader = new BufferedReader(input); } String line; while ((line = bufferedReader.readLine()) != null) { incorporateLine(line); } return finalizeAndProcess(); }