auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void run() { <START> while (true) { <END> try { registrationManager.updateRegistration(configuration.getConnectorId(), configuration.getContent()); LOGGER.info("successfully recreated connector from persistence", configuration.getConnectorId()); break; } catch (ConnectorValidationFailedException e) { LOGGER.error("connector that has been loaded from persistence was found to be invalid", configuration.getConnectorId(), e); break; } catch (OsgiServiceNotAvailableException e) { LOGGER.warn("connector that has been loaded from persistence could not be created because the" + "factory-service was missing", configuration.getConnectorId()); continue; } catch (Exception e) { LOGGER.error("connector that has been loaded from persistence could not be created because of an unexpected Error", e); break; } } semaphore.release(); }</code><technical_language>I know, Thread sleep for a short period if service available? this block something? long takes service is normally. interesting set a maximum number of tries</technical_language>

Target:
public void run() { while (true) { try { registrationManager.updateRegistration(configuration.getConnectorId(), configuration.getContent()); LOGGER.info("successfully recreated connector from persistence", configuration.getConnectorId()); break; } catch (ConnectorValidationFailedException e) { LOGGER.error("connector that has been loaded from persistence was found to be invalid", configuration.getConnectorId(), e); break; } catch (OsgiServiceNotAvailableException e) { LOGGER.warn("connector that has been loaded from persistence could not be created because the" + "factory-service was missing", configuration.getConnectorId()); continue; } catch (Exception e) { LOGGER.error("connector that has been loaded from persistence could not be created because of" + "an unexpected Error", e); break; } } semaphore.release(); }
Source:
<code>public void testNormalBinlogReplicationDiagnostic() throws Exception { MaxwellDiagnosticContext.Config config = new MaxwellDiagnosticContext.Config(); config.timeout = 5000; MaxwellContext maxwellContext = buildContext(); DiagnosticHealthCheck healthCheck = getDiagnosticHealthCheck(config, maxwellContext); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(outputStream); when(response.getWriter()).thenReturn(writer); final CountDownLatch latch = new CountDownLatch(1); Maxwell maxwell = new MaxwellWithContext(maxwellContext) { @Override protected void onReplicatorStart() { latch.countDown(); } }; new Thread(maxwell).start(); latch.await(); healthCheck.doGet(request, response); writer.flush(); String result = new String(outputStream.toByteArray()); <START> assertTrue(result.contains("\"name\":\"binlog-connector\",\"success\":true")); <END> maxwell.terminate(); writer.close(); }</code><technical_language>If horribly verbose (I tried), nice parse this a map check actual object instead of relying string comparison</technical_language>

Target:
public void testNormalBinlogReplicationDiagnostic() throws Exception { MaxwellDiagnosticContext.Config config = new MaxwellDiagnosticContext.Config(); config.timeout = 5000; MaxwellContext maxwellContext = buildContext(); DiagnosticHealthCheck healthCheck = getDiagnosticHealthCheck(config, maxwellContext); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); when(response.getWriter()).thenReturn(writer); final CountDownLatch latch = new CountDownLatch(1); Maxwell maxwell = new MaxwellWithContext(maxwellContext) { @Override protected void onReplicatorStart() { latch.countDown(); } }; new Thread(maxwell).start(); latch.await(); healthCheck.doGet(request, response); writer.flush(); JsonNode binlogNode = getBinlogNode(); assertThat(binlogNode.get("name").asText(), is("binlog-connector")); assertThat(binlogNode.get("success").asBoolean(), is(true)); assertTrue(binlogNode.get("mandatory").asBoolean()); assertTrue(binlogNode.get("message").asText().contains("Binlog replication lag")); maxwell.terminate(); }
Source:
<code>private static Expression toSymbolExpression(Symbol symbol) { if (symbol instanceof SymbolWithSubfieldPath) { SubfieldPath path = ((SymbolWithSubfieldPath) symbol).getPath(); Expression base = new SymbolReference(symbol.getName()); for (int i = 1; i < path.getPath().size(); i++) { SubfieldPath.PathElement element = path.getPath().get(i); if (element instanceof NestedField) { base = new DereferenceExpression(base, new Identifier(((NestedField) element).getName())); } else if (element instanceof LongSubscript) { <START> base = new SubscriptExpression(base, new LongLiteral(String.valueOf(((LongSubscript) element).getIndex()))); <END> } else if (element instanceof StringSubscript) { base = new SubscriptExpression(base, new StringLiteral(((StringSubscript) element).getIndex())); } else { throw new IllegalArgumentException("Unsupported path element: " + element.getClass().getSimpleName()); } } return base; } return symbol.toSymbolReference(); }</code><technical_language>I some extra parenthesis</technical_language>

Target:
private static Expression toSymbolExpression(Symbol symbol) { if (symbol instanceof SymbolWithSubfieldPath) { SubfieldPath path = ((SymbolWithSubfieldPath) symbol).getSubfieldPath(); Expression base = new SymbolReference(symbol.getName()); for (int i = 1; i < path.getPath().size(); i++) { SubfieldPath.PathElement element = path.getPath().get(i); if (element instanceof NestedField) { base = new DereferenceExpression(base, new Identifier(((NestedField) element).getName())); } else if (element instanceof LongSubscript) { base = new SubscriptExpression(base, new LongLiteral(String.valueOf(((LongSubscript) element).getIndex()))); } else if (element instanceof StringSubscript) { base = new SubscriptExpression(base, new StringLiteral(((StringSubscript) element).getIndex())); } else { throw new IllegalArgumentException("Unsupported path element: " + element.getClass().getSimpleName()); } } return base; } return symbol.toSymbolReference(); }
Source:
<code>void messageConsumptionSingleThreaded() { while (!activeMailboxes.isEmpty() || getFirstRederivable() != null) { RederivableNode node = getFirstRederivable(); while (node != null) { node.rederiveOne(); node = getFirstRederivable(); } <START> if (!activeMailboxes.isEmpty()) { <END> Mailbox mailbox = activeMailboxes.iterator().next(); activeMailboxes.remove(mailbox); mailbox.deliverMessages(); } } }</code><technical_language>steps reversed</technical_language>

Target:
void messageConsumptionSingleThreaded() { while (!activeMailboxes.isEmpty() || getFirstRederivable() != null) { while (!activeMailboxes.isEmpty()) { Mailbox mailbox = activeMailboxes.iterator().next(); activeMailboxes.remove(mailbox); mailbox.deliverMessages(); } RederivableNode node = getFirstRederivable(); if (node != null) { node.rederiveOne(); } } }
Source:
<code>public long populate(final ByteSource source, final Map<K, V> map) throws IOException { return source.asCharSource(Charsets.UTF_8).readLines( new LineProcessor<Long>() { private long count = 0L; @Override public boolean processLine(String line) throws IOException { final Map<K, V> kvMap = parser.parse(line); if (kvMap != null) { <START> map.putAll(kvMap); <END> count += map.size(); } return true; } @Override public Long getResult() { return count; } } ); }</code><technical_language>maps accept null values. This retains prior functionality of "potentially failing if target map handle null values", I wanted callout here</technical_language>

Target:
public PopulateResult populate(final ByteSource source, final Map<K, V> map) throws IOException { return source.asCharSource(Charsets.UTF_8).readLines( new LineProcessor<PopulateResult>() { private int lines = 0; private int entries = 0; @Override public boolean processLine(String line) throws IOException { if (lines == Integer.MAX_VALUE) { throw new ISE("Cannot read more than %,d lines", Integer.MAX_VALUE); } final Map<K, V> kvMap = parser.parse(line); map.putAll(kvMap); lines++; entries += kvMap.size(); return true; } @Override public PopulateResult getResult() { return new PopulateResult(lines, entries); } } ); }
Source:
<code>protected void channelRead0(ChannelHandlerContext ctx, Response msg) throws Exception { final SettableFuture f = futures.get(msg.getCommandId()); switch (msg.getCommand()) { case MUTATE: if (!msg.getMutate().getProcessed()) { f.setException(new IOException("Not Processed")); } <START> f.set(null); <END> break; case SCAN: final long scannerId = msg.getScan().getScannerId(); ClientScanner clientScanner; if (CLIENT_SCANNER_MANAGER.hasScanner(scannerId)) { clientScanner = CLIENT_SCANNER_MANAGER.get(scannerId); } else { clientScanner = CLIENT_SCANNER_MANAGER.createAndGet(ctx.channel(), scannerId, msg.getCommandId()); f.set(scannerId); } clientScanner.add(msg.getScan()); if (!msg.getScan().getMoreResults()) { clientScanner.close(); } break; default: f.set(msg); break; } }</code><technical_language>do feel unchecked warnings in this class? I if fixing kind of is scope of this of changes</technical_language>

Target:
protected void channelRead0(ChannelHandlerContext ctx, Response msg) throws Exception { switch (msg.getCommand()) { case MUTATE: final SettableFuture<Response> f = futures.get(msg.getCommandId()); if (!msg.getMutate().getProcessed()) { f.setException(new IOException("Not Processed")); } f.set(null); break; case SCAN: final long scannerId = msg.getScan().getScannerId(); ClientScanner clientScanner; if (CLIENT_SCANNER_MANAGER.hasScanner(scannerId)) { clientScanner = CLIENT_SCANNER_MANAGER.get(scannerId); } else { clientScanner = CLIENT_SCANNER_MANAGER.createAndGet(ctx.channel(), scannerId, msg.getCommandId()); scannerFutures.get(msg.getCommandId()).set(scannerId); } clientScanner.add(msg.getScan()); if (!msg.getScan().getMoreResults()) { clientScanner.close(); } break; default: futures.get(msg.getCommandId()).set(msg); break; } }
Source:
<code>public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } HibernateConstraintValidatorInitializationContextImpl hibernateConstraintValidatorInitializationContextImpl = (HibernateConstraintValidatorInitializationContextImpl) o; if ( scriptEvaluatorFactory != null ? scriptEvaluatorFactory != hibernateConstraintValidatorInitializationContextImpl.scriptEvaluatorFactory : hibernateConstraintValidatorInitializationContextImpl.scriptEvaluatorFactory != null ) { return false; } if ( clockProvider != null ? clockProvider != hibernateConstraintValidatorInitializationContextImpl.clockProvider : hibernateConstraintValidatorInitializationContextImpl.clockProvider != null ) { return false; } if ( temporalValidationTolerance != null ? !temporalValidationTolerance.equals( hibernateConstraintValidatorInitializationContextImpl.temporalValidationTolerance ) : hibernateConstraintValidatorInitializationContextImpl.temporalValidationTolerance != null ) { return false; } <START> if ( constraintValidatorPayload != null ? constraintValidatorPayload != hibernateConstraintValidatorInitializationContextImpl.constraintValidatorPayload : hibernateConstraintValidatorInitializationContextImpl.constraintValidatorPayload != null ) { <END> return false; } return true; }</code><technical_language>scriptEvaluatorFactory clockProvider temporalValidationTolerance null skip null checks for them, do a != check anyway</technical_language>

Target:
public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } HibernateConstraintValidatorInitializationContextImpl hibernateConstraintValidatorInitializationContextImpl = (HibernateConstraintValidatorInitializationContextImpl) o; if ( scriptEvaluatorFactory != hibernateConstraintValidatorInitializationContextImpl.scriptEvaluatorFactory ) { return false; } if ( clockProvider != hibernateConstraintValidatorInitializationContextImpl.clockProvider ) { return false; } if ( !temporalValidationTolerance.equals( hibernateConstraintValidatorInitializationContextImpl.temporalValidationTolerance ) ) { return false; } if ( constraintValidatorPayload != hibernateConstraintValidatorInitializationContextImpl.constraintValidatorPayload ) { return false; } return true; }
Source:
<code>public static Resource locateModuleResource(SimpleModuleDefinition definition, ClassLoader moduleClassLoader, String extension) { PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(moduleClassLoader); Resource result = null; String ext = extension.startsWith(".") ? extension : "." + extension; try { <START> Resource[] resources = resolver.getResources("/config/*" + ext); <END> if (resources.length > 1) { throw new IllegalStateException("Multiple top level module resources found :" + StringUtils .arrayToCommaDelimitedString(resources)); } else if (resources.length == 1) { result = resources[0]; } } catch (IOException e) { throw new RuntimeException(e); } return result; }</code><technical_language>need wary moduleClassLoader is currently constructed, return classpath resource is a /config/ dir (_e.g._ if log4j.jar /config/foo.properties, this **will** returned). need pass a "top level module classloader" for purpose</technical_language>

Target:
public static Resource locateModuleResource(SimpleModuleDefinition definition, ClassLoader moduleClassLoader, String extension) { PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(moduleClassLoader); Resource moduleLocation = resolver.getResource(definition.getLocation()); Assert.isTrue(moduleLocation.exists(), "module resource " + definition.getLocation() + " does not exist"); ClassLoader parentClassloader = moduleClassLoader == null? null : moduleClassLoader.getParent(); PathMatchingResourcePatternResolver moduleResolver = new PathMatchingResourcePatternResolver (createModuleClassLoader(moduleLocation, parentClassloader, false)); Resource result = null; String ext = extension.startsWith(".") ? extension : "." + extension; try { Resource[] resources = moduleResolver.getResources("classpath:/config/*" + ext); if (resources.length > 1) { throw new IllegalStateException("Multiple top level module resources found :" + StringUtils .arrayToCommaDelimitedString(resources)); } else if (resources.length == 1) { result = resources[0]; } } catch (IOException e) { return null; } return result; }
Source:
<code>private List<EmailWrapper> generateFeedbackSessionClosedEmail( CourseAttributes course, FeedbackSessionAttributes session, List<InstructorAttributes> instructors, List<StudentAttributes> students) { List<EmailWrapper> emails = new ArrayList<EmailWrapper>(); String instructorFragmentArgumentInstructors = "<p>The email below has been sent to students of course: " + SanitizationHelper.sanitizeForHtml(course.getId()) + ", " + SanitizationHelper.sanitizeForHtml(course.getName()) + ".<br>" + Const.EOL + "<br>" + Const.EOL <START> + "=== Email message as seen by the students ===</p>" + Const.EOL; <END> String instructorFragmentArgumentStudents = ""; for (InstructorAttributes instructor : instructors) { emails.add(generateFeedbackSessionClosedEmail(course, session, instructor.name, instructor.email, instructorFragmentArgumentInstructors)); } for (StudentAttributes student : students) { emails.add(generateFeedbackSessionClosedEmail(course, session, student.name, student.email, instructorFragmentArgumentStudents)); } return emails; }</code><technical_language>This fragment is similar in generateFeedbackSessionEmailBaseForInstructors good if extract a method generate this fragment some sort of html template generate this string reduce repetition</technical_language>

Target:
private List<EmailWrapper> generateFeedbackSessionClosedEmail( CourseAttributes course, FeedbackSessionAttributes session, List<InstructorAttributes> instructors, List<StudentAttributes> students) { List<EmailWrapper> emails = new ArrayList<EmailWrapper>(); String instructorPreamble = generateInstructorPreamble(course.getId(), course.getName()); String studentPreamble = ""; for (InstructorAttributes instructor : instructors) { emails.add(generateFeedbackSessionClosedEmail(course, session, instructor.name, instructor.email, instructorPreamble)); } for (StudentAttributes student : students) { emails.add(generateFeedbackSessionClosedEmail(course, session, student.name, student.email, studentPreamble)); } return emails; }
Source:
<code>private void createPerspectiveBarExtras() { String persps = PrefUtil.getAPIPreferenceStore() .getString(IWorkbenchPreferenceConstants.PERSPECTIVE_BAR_EXTRAS); String[] parts = persps.split("[, ]"); Set<String> perspSet = new LinkedHashSet<>(); for (String part : parts) { part = part.trim(); if (!part.isEmpty()) perspSet.add(part); } WorkbenchPage <START> page = <END> (WorkbenchPage) window.getContext().get(IWorkbenchPage.class); for (String perspId : perspSet) { MPerspective persp = (MPerspective) modelService.find(perspId, window); if (persp != null) continue; IPerspectiveDescriptor desc = getDescriptorFor(perspId); if (desc == null) continue; persp = page.createPerspective(desc); persp.setLabel(desc.getLabel()); getPerspectiveStack().getChildren().add(persp); } }</code><technical_language>Isnt this "this"? Meaning, arent in relevant Workbenchpage</technical_language>

Target:
private void createPerspectiveBarExtras() { String persps = PrefUtil.getAPIPreferenceStore() .getString(IWorkbenchPreferenceConstants.PERSPECTIVE_BAR_EXTRAS); String[] parts = persps.split("[, ]"); Set<String> perspSet = new LinkedHashSet<>(); for (String part : parts) { part = part.trim(); if (!part.isEmpty()) perspSet.add(part); } for (String perspId : perspSet) { MPerspective persp = (MPerspective) modelService.find(perspId, window); if (persp != null) continue; IPerspectiveDescriptor desc = getDescriptorFor(perspId); if (desc == null) continue; persp = createPerspective(desc); persp.setLabel(desc.getLabel()); getPerspectiveStack().getChildren().add(persp); } }
Source:
<code>private Instant getEndOfTheDayOffsetNowInAdminTimeZone(int dayOffset) { return TimeHelper.getInstantDaysOffsetFromNow(dayOffset).atZone(Const.SystemParams.ADMIN_TIME_ZONE_ID) <START> .toLocalDate().atTime(23, 59, 59).atZone(Const.SystemParams.ADMIN_TIME_ZONE_ID).toInstant(); <END> }</code><technical_language>atTime(LocalTime.MAX)</technical_language>

Target:
private Instant getEndOfTheDayOffsetNowInAdminTimeZone(int dayOffset) { return TimeHelper.getInstantDaysOffsetFromNow(dayOffset).atZone(Const.SystemParams.ADMIN_TIME_ZONE_ID) .toLocalDate().atTime(LocalTime.MAX).atZone(Const.SystemParams.ADMIN_TIME_ZONE_ID).toInstant(); }
Source:
<code>public Object handleValidationException(ValidationException e, HandlerMethod handlerMethod) { <START> LOG.info(e.getErrorCode(), e); <END> return handleTypedException(isHtmlRequest(handlerMethod), NotFoundController.URI, e.getLocalizedMessage(), BAD_REQUEST, e.getErrorCode()); }</code><technical_language>this get logged now? Is policy log here</technical_language>

Target:
public Object handleValidationException(ValidationException e, HandlerMethod handlerMethod) { LOG.info(e.getErrorCode(), e); return handleTypedException(isHtmlRequest(handlerMethod), BadRequestController.URI, e.getLocalizedMessage(), BAD_REQUEST, e.getErrorCode()); }
Source:
<code>ModelBuilder addRepeatGroup(String name) { <START> TreeElement child = new TreeElement(name, 0); <END> child.setDataType(DataType.NULL.value); child.setRepeatable(true); child.setParent(current); current.addChild(child); current = child; return this; }</code><technical_language>I INDEX_TEMPLATE is right if underlying form jr:template set DEFAULT_MULTIPLICITY is right if underlying form it. depends want match. I expect give results, though. Is case? I a constant raw value</technical_language>

Target:
ModelBuilder addRepeatGroup(String name) { TreeElement child = new TreeElement(name, DEFAULT_MULTIPLICITY); child.setDataType(DataType.NULL.value); child.setRepeatable(true); child.setParent(current); current.addChild(child); current = child; return this; }
Source:
<code>public AbstractExpression getFirstArgument() { <START> if (m_left != null) { <END> return m_left; } if (m_args != null && m_args.size() > 0) { return m_args.get(0); } return null; }</code><technical_language>values in m_left m_args? If not, is a debug assert somewhere</technical_language>

Target:
public AbstractExpression getFirstArgument() { if (m_left != null) { assert(m_args == null); return m_left; } if (m_args != null && m_args.size() > 0) { assert(m_left == null && m_right == null); return m_args.get(0); } return null; }
Source:
<code>public void deletePrefix(WinePrefixContainerDTO winePrefix, Consumer<Exception> errorCallback) { try { fileUtilities.remove(new File(winePrefix.getPath())); } catch (IOException e) { LOGGER.error("Cannot delete Wine prefix (" + winePrefix.getPath() + ")! Exception: " + e.toString()); errorCallback.accept(e); } List<ShortcutCategoryDTO> categories = libraryManager.fetchShortcuts(); for (ShortcutCategoryDTO shortcutCategoryDTO : categories) { for (ShortcutDTO shortcutDTO : shortcutCategoryDTO.getShortcuts()) { final InteractiveScriptSession interactiveScriptSession = scriptInterpreter.createInteractiveSession(); interactiveScriptSession.eval("include([\"Functions\", \"Shortcuts\", \"Reader\"]);", ignored -> interactiveScriptSession.eval("new ShortcutReader()", output -> { final ScriptObjectMirror shortcutReader = (ScriptObjectMirror) output; shortcutReader.callMember("of", shortcutDTO); final String container = (String) shortcutReader.callMember("container"); if (container.equals(winePrefix.getName())) { shortcutManager.deleteShortcut(shortcutDTO); } }, errorCallback), errorCallback); <START> } <END> } }</code><technical_language>I Streaming API nicer here: java categories.stream() .flatMap(category -> category.getShortcuts().stream()) .forEach(shortcut -> { ... });</technical_language>

Target:
public void deletePrefix(WinePrefixContainerDTO winePrefix, Consumer<Exception> errorCallback) { try { fileUtilities.remove(new File(winePrefix.getPath())); } catch (IOException e) { LOGGER.error("Cannot delete Wine prefix (" + winePrefix.getPath() + ")! Exception: " + e.toString()); errorCallback.accept(e); } List<ShortcutCategoryDTO> categories = libraryManager.fetchShortcuts(); categories.stream().flatMap(shortcutCategoryDTO -> shortcutCategoryDTO.getShortcuts().stream()) .forEach(shortcutDTO -> { final InteractiveScriptSession interactiveScriptSession = scriptInterpreter .createInteractiveSession(); interactiveScriptSession.eval("include([\"Functions\", \"Shortcuts\", \"Reader\"]);", ignored -> interactiveScriptSession.eval("new ShortcutReader()", output -> { final ScriptObjectMirror shortcutReader = (ScriptObjectMirror) output; shortcutReader.callMember("of", shortcutDTO); final String container = (String) shortcutReader.callMember("container"); if (container.equals(winePrefix.getName())) { shortcutManager.deleteShortcut(shortcutDTO); } }, errorCallback), errorCallback); }); }
Source:
<code>private boolean containsForbiddenFragment(String firstSentence) { final String javadocText = JAVADOC_MULTILINE_TO_SINGLELINE_PATTERN .matcher(firstSentence).replaceAll(" ").trim(); final StringBuilder finalText = new StringBuilder(100); boolean previousWhitespace = true; for (char letter : javadocText.toCharArray()) { final char print; if (Character.isWhitespace(letter)) { if (previousWhitespace) { continue; } previousWhitespace = true; print = ' '; } else { <START> previousWhitespace = false; <END> print = letter; } finalText.append(print); } return forbiddenSummaryFragments.matcher(finalText).find(); }</code><technical_language>Please move new code static method. helper method, stay method</technical_language>

Target:
private boolean containsForbiddenFragment(String firstSentence) { final String javadocText = JAVADOC_MULTILINE_TO_SINGLELINE_PATTERN .matcher(firstSentence).replaceAll(" ").trim(); return forbiddenSummaryFragments.matcher(trimExcessWhitespaces(javadocText)).find(); }
Source:
<code>public Response clearFlairTemplates(String type, String subreddit) { if (!type.equalsIgnoreCase("USER_FLAIR") && !type.equalsIgnoreCase("LINK_FLAIR")) { System.err.println("Type must be either USER_FLAIR or LINK_FLAIR."); Response response = new Response() { @Override public int getStatusCode() { return 400; } @Override public Object getResponseObject() { return null; } @Override public String getResponseText() { return "Bad request, type must be either USER_FLAIR or LINK_FLAIR. (Generated by FlairActions.clearFlairTemplates(String, String);)"; } }; return response; } String params = "" <START> + "api_type=" + "json" <END> + "&uh=" + user.getModhash() + "&flair_type=" + type; return restClient.post(params, String.format(ApiEndpointUtils.CLEAR_SUBREDDIT_FLAIR_TEMPLATES, subreddit), user.getCookie()); }</code><technical_language>**\+ "api_type=json"** better, imo</technical_language>

Target:
public Response clearFlairTemplates(String type, String subreddit) { if (!type.equalsIgnoreCase("USER_FLAIR") && !type.equalsIgnoreCase("LINK_FLAIR")) { System.err.println("Type must be either USER_FLAIR or LINK_FLAIR."); Response response = new Response() { @Override public int getStatusCode() { return 400; } @Override public Object getResponseObject() { return null; } @Override public String getResponseText() { return "Bad request, type must be either USER_FLAIR or LINK_FLAIR. (Generated by FlairActions.clearFlairTemplates(String, String);)"; } }; return response; } String params = "" + "api_type=json" + "&uh=" + user.getModhash() + "&flair_type=" + type; return restClient.post(params, String.format(ApiEndpointUtils.CLEAR_SUBREDDIT_FLAIR_TEMPLATES, subreddit), user.getCookie()); }
Source:
<code>protected String getValue(Environment env, Map params) throws TemplateModelException, IOException { String path = getStringValue(params.get("path")); String targetJournal = getStringValue(params.remove("journalKey")); <START> String handlerName = getStringValue(params.remove("handlerName")); END> SitePageContext sitePageContext = new SitePageContext(siteResolver, handlerMappingConfig, env); if (handlerName != null) { return targetJournal == null ? sitePageContext.buildLink(handlerName, params) : sitePageContext.buildLink(siteSet, targetJournal, handlerName, params); } else if (path != null) { return targetJournal == null ? sitePageContext.buildLink(path) : sitePageContext.buildLink(siteSet, targetJournal, path); } else { throw new RuntimeException("Either a path or handlerName parameter is required"); } }</code><technical_language>remove</technical_language>

Target:
protected String getValue(Environment env, Map params) throws TemplateModelException, IOException { String path = getStringValue(params.get("path")); String targetJournal = getStringValue(params.get("journalKey")); String handlerName = getStringValue(params.get("handlerName")); SitePageContext sitePageContext = new SitePageContext(siteResolver, env); Site site = sitePageContext.getSite(); Link.Factory linkFactory = (targetJournal == null) ? Link.toLocalSite(site) : Link.toForeignSite(site, targetJournal, siteSet); final Link link; if (handlerName != null) { Map<String, ?> variables = getValueAsMap(params.get("pathVariables")); ListMultimap<String, ?> queryParameters = getValueAsMultimap(params.get("queryParameters")); List<?> wildcardValues = getValueAsList(params.get("wildcardValues")); link = linkFactory.toPattern(requestHandlerPatternDictionary, handlerName, variables, queryParameters, wildcardValues); } else if (path != null) { link = linkFactory.toPath(path); } else { throw new RuntimeException("Either a path or handlerName parameter is required"); } return link.get(sitePageContext.getRequest()); }
Source:
<code>public Void read() { Table table = null; TableDescriptor tableDesc = null; <START> boolean regionTaskReadAllCF = <END> connection.getConfiguration().getBoolean(HConstants.HBASE_CANARY_READ_ALL_CF, true); try { LOG.debug("Reading table descriptor for table {}", region.getTable()); table = connection.getTable(region.getTable()); tableDesc = table.getDescriptor(); } catch (IOException e) { LOG.debug("sniffRegion of failed", region.getEncodedName(), e); sink.publishReadFailure(serverName, region, e); if (table != null) { try { table.close(); } catch (IOException ioe) { LOG.error("Close table failed", e); } } return null; } if (regionTaskReadAllCF) { for (ColumnFamilyDescriptor column : tableDesc.getColumnFamilies()) { readColumnFamily(table, column); } } else { readColumnFamily(table, randomPickOneColumnFamily(tableDesc.getColumnFamilies())); } try { table.close(); } catch (IOException e) { LOG.error("Close table failed", e); } return null; }</code><technical_language>Read conf time? this a global var read conf once</technical_language>

Target:
public Void read() { Table table = null; TableDescriptor tableDesc = null; try { LOG.debug("Reading table descriptor for table {}", region.getTable()); table = connection.getTable(region.getTable()); tableDesc = table.getDescriptor(); } catch (IOException e) { LOG.debug("sniffRegion of failed", region.getEncodedName(), e); sink.publishReadFailure(serverName, region, e); if (table != null) { try { table.close(); } catch (IOException ioe) { LOG.error("Close table failed", e); } } return null; } if (readAllCF) { for (ColumnFamilyDescriptor column : tableDesc.getColumnFamilies()) { readColumnFamily(table, column); } } else { readColumnFamily(table, randomPickOneColumnFamily(tableDesc.getColumnFamilies())); } try { table.close(); } catch (IOException e) { LOG.error("Close table failed", e); } return null; }
Source:
<code>public RelWriter explainTerms(RelWriter pw) { super.explainTerms(pw); <START> if (m_limit != null) { <END> pw.item("limit", m_limit); } if (m_offset != null) { pw.item("offset", m_offset); } return pw; }</code><technical_language>I itemIf (VoltDBLJoin) is more elegant IF () { pw.item }</technical_language>

Target:
public RelWriter explainTerms(RelWriter pw) { return super.explainTerms(pw) .itemIf("limit", m_limit, m_limit != null) .itemIf("offset", m_offset, m_offset != null); }
Source:
<code>private ExecutorService getBatchPool() { if (batchPool == null) { synchronized (this) { if (batchPool == null) { <START> int minThreads = getMinThreads(); <END> int maxThreads = getMaxThreads(); long keepAliveTime = conf.getLong( "hbase.hconnection.threads.keepalivetime", 60); LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>(128 * conf.getInt("hbase.client.max.total.tasks", 200)); this.batchPool = new ThreadPoolExecutor( minThreads, maxThreads, keepAliveTime, TimeUnit.SECONDS, workQueue, Threads.newDaemonThreadFactory("bigtable-connection-shared-executor")); } this.cleanupPool = true; } } return this.batchPool; }</code><technical_language>check minThreads <= maxThreads</technical_language>

Target:
private ExecutorService getBatchPool() { if (batchPool == null) { synchronized (this) { if (batchPool == null) { int maxThreads = getMaxThreads(); int minThreads = Math.min(getCoreThreads(), maxThreads); long keepAliveTime = conf.getLong("hbase.hconnection.threads.keepalivetime", 60); LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>(128 * conf.getInt("hbase.client.max.total.tasks", 200)); this.batchPool = new ThreadPoolExecutor( minThreads, maxThreads, keepAliveTime, TimeUnit.SECONDS, workQueue, Threads.newDaemonThreadFactory("bigtable-connection-shared-executor")); } this.cleanupPool = true; } } return this.batchPool; }
Source:
<code>private static void sendResponse(Channel channel, int device, long id, int crc) { if (channel != null) { ChannelBuffer response = ChannelBuffers.dynamicBuffer(ByteOrder.LITTLE_ENDIAN, 0); response.writeByte(device); response.writeByte(MSG_ACK); response.writeInt((int) id); response.writeShort(crc); response.writeShort(Checksum.crc16( <START> Checksum.CRC16_XMODEM, response.toByteBuffer(0, response.readableBytes()))); <END> ChannelBuffer encoded = ChannelBuffers.dynamicBuffer(); encoded.writeByte(0x01); while (response.readable()) { int b = response.readByte(); if (b == 0x01 || b == 0x04 || b == 0x10 || b == 0x11 || b == 0x13) { encoded.writeByte(0x10); b += 0x20; } encoded.writeByte(b); } encoded.writeByte(0x04); channel.write(encoded); } }</code><technical_language>response.toByteBuffer() parameters here</technical_language>

Target:
private static void sendResponse(Channel channel, int device, long id, int crc) { if (channel != null) { ChannelBuffer response = ChannelBuffers.dynamicBuffer(ByteOrder.LITTLE_ENDIAN, 0); response.writeByte(device); response.writeByte(MSG_ACK); response.writeInt((int) id); response.writeShort(crc); response.writeShort(Checksum.crc16( Checksum.CRC16_XMODEM, response.toByteBuffer())); ChannelBuffer encoded = ChannelBuffers.dynamicBuffer(); encoded.writeByte(0x01); while (response.readable()) { int b = response.readByte(); if (b == 0x01 || b == 0x04 || b == 0x10 || b == 0x11 || b == 0x13) { encoded.writeByte(0x10); b += 0x20; } encoded.writeByte(b); } encoded.writeByte(0x04); channel.write(encoded); } }
Source:
<code>public void testHierarchyView() { DockerImagesTab imageTab = openDockerImagesTab(); buildImage(IMAGE_TEST_BUILD, DOCKERFILE_FOLDER, imageTab); if (mockitoIsUsed()) { <START> setupDataForMockito(); <END> } DockerImageHierarchyTab hierarchyTab = openDockerImageHierarchyTab(); List<TreeItem> treeItems = hierarchyTab.getTreeItems(); compareTextInFirstNode(treeItems, "alpine:3.3"); List<TreeItem> treeItems2 = treeItems.get(0).getItems(); compareTextInFirstNode(treeItems2, IMAGE_TEST_BUILD + NAME_TAG_SEPARATOR + IMAGE_TAG_LATEST); }</code><technical_language>is setupDataForMockito() called is designated @Before keyword below? I this in a other tests well</technical_language>

Target:
public void testHierarchyView() { DockerImagesTab imageTab = openDockerImagesTab(); buildImage(IMAGE_TEST_BUILD, DOCKERFILE_FOLDER, imageTab); if (mockitoIsUsed()) { buildImage(); } DockerImageHierarchyTab hierarchyTab = openDockerImageHierarchyTab(); List<TreeItem> treeItems = hierarchyTab.getTreeItems(); compareTextInFirstNode(treeItems, "alpine:3.3"); List<TreeItem> treeItems2 = treeItems.get(0).getItems(); compareTextInFirstNode(treeItems2, IMAGE_TEST_BUILD + NAME_TAG_SEPARATOR + IMAGE_TAG_LATEST); }
Source:
<code>private long copyPackBypassCache(PackOutputStream out, ReadableChannel rc) throws IOException { ByteBuffer buf = newCopyBuffer(out, rc); long position = 12; long remaining = length - (12 + 20); boolean packHeadSkipped = false; while (0 < remaining) { DfsBlock b = cache.get(key, alignToBlock(position)); if (b != null) { int ptr = (int) (position - b.start); int n = (int) Math.min(b.size() - ptr, remaining); b.write(out, position, n); position += n; remaining -= n; rc.position(position); packHeadSkipped = true; continue; } buf.position(0); int bufLen = read(rc, buf); <START> if (bufLen <= 0) { <END> throw packfileIsTruncated(); } int ptr = packHeadSkipped ? 0 : 12; int n = (int) Math.min(bufLen - ptr, remaining); out.write(buf.array(), ptr, n); position += n; remaining -= n; packHeadSkipped = true; } return position; }</code><technical_language>if 0 < bufLen <= ptr</technical_language>

Target:
private long copyPackBypassCache(PackOutputStream out, ReadableChannel rc) throws IOException { ByteBuffer buf = newCopyBuffer(out, rc); long position = 12; long remaining = length - (12 + 20); boolean packHeadSkipped = false; while (0 < remaining) { DfsBlock b = cache.get(key, alignToBlock(position)); if (b != null) { int ptr = (int) (position - b.start); int n = (int) Math.min(b.size() - ptr, remaining); if (n <= 0) { throw packfileIsTruncated(); } b.write(out, position, n); position += n; remaining -= n; rc.position(position); packHeadSkipped = true; continue; } int ptr = packHeadSkipped ? 0 : 12; buf.position(0); int bufLen = read(rc, buf); if (bufLen <= ptr) { throw packfileIsTruncated(); } int n = (int) Math.min(bufLen - ptr, remaining); out.write(buf.array(), ptr, n); position += n; remaining -= n; packHeadSkipped = true; } return position; }
Source:
<code>private Map<String, List<String>> getServicesParameters(Collection<CheFeature> features) { Map<String, List<String>> parameters = new HashMap<>(); for (CheFeature feature : features) { for (CheServiceReference serviceReference : feature.getSpec().getServices()) { if (serviceReference.getParameters().isEmpty()) { continue; } String serviceName = serviceReference.getName(); String serviceVersion = serviceReference.getVersion(); for (CheServiceParameter cheServiceParameter : serviceReference.getParameters()) { String parameterKey = serviceName + "/" + serviceVersion + "/${" + cheServiceParameter.getName() + "}"; parameters.putIfAbsent(parameterKey, new ArrayList<>()); <START> List<String> cheServiceParameters = parameters.get(parameterKey); <END> cheServiceParameters.add(cheServiceParameter.getValue()); } } } return parameters; }</code><technical_language>parameters.putIfAbsent(parameterKey, new ArrayList<>()); List<String> cheServiceParameters = parameters.get(parameterKey); rewritten in Java 8 style List<String> cheServiceParameters = parameters.computeIfAbsent(parameterKey, (key) -> new ArrayList<>());</technical_language>

Target:
private Map<String, List<String>> getServicesParameters(Collection<CheFeature> features) { Map<String, List<String>> parameters = new HashMap<>(); for (CheFeature feature : features) { for (CheServiceReference serviceReference : feature.getSpec().getServices()) { if (serviceReference.getParameters().isEmpty()) { continue; } String serviceName = serviceReference.getName(); String serviceVersion = serviceReference.getVersion(); for (CheServiceParameter cheServiceParameter : serviceReference.getParameters()) { String parameterKey = serviceName + "/" + serviceVersion + "/${" + cheServiceParameter.getName() + "}"; List<String> cheServiceParameters = parameters.computeIfAbsent(parameterKey, key -> new ArrayList<>()); cheServiceParameters.add(cheServiceParameter.getValue()); } } } return parameters; }
Source:
<code>private static Optional<TupleDomainFilter> getFilter(Type type) { if (type == BOOLEAN) { return Optional.of(BooleanValue.of(true, true)); } if (type == TINYINT || type == BIGINT || type == INTEGER || type == SMALLINT || type == DATE) { return Optional.of(BigintRange.of(0, Long.MAX_VALUE, true)); } if (type == DOUBLE) { <START> return Optional.of(DoubleRange.of(Double.MIN_VALUE, false, false, Double.MAX_VALUE, false, false, false)); <END> } throw new UnsupportedOperationException("Unsupported type: " + type); }</code><technical_language>This filter allow double other null, e.g. filter anything, nulls. Is this intentional</technical_language>

Target:
private static Optional<TupleDomainFilter> getFilter(Type type) { if (type == BOOLEAN) { return Optional.of(BooleanValue.of(true, true)); } if (type == TINYINT || type == BIGINT || type == INTEGER || type == SMALLINT || type == DATE || type == TIMESTAMP) { return Optional.of(BigintRange.of(0, Long.MAX_VALUE, true)); } if (type == REAL) { return Optional.of(FloatRange.of(0, true, true, Integer.MAX_VALUE, true, true, true)); } if (type == DOUBLE) { return Optional.of(DoubleRange.of(.5, false, false, 2, false, false, false)); } throw new UnsupportedOperationException("Unsupported type: " + type); }
Source:
<code>public void testNameFinderWithTypes() throws Exception { InputStream in = getClass().getClassLoader().getResourceAsStream( "opennlp/tools/namefind/AnnotatedSentencesWithTypes.txt"); String encoding = "ISO-8859-1"; ObjectStream<NameSample> sampleStream = new NameSampleDataStream( new PlainTextByLineStream(new MockInputStreamFactory(in), encoding)); TrainingParameters params = new TrainingParameters(); params.put(TrainingParameters.ITERATIONS_PARAM, Integer.toString(70)); params.put(TrainingParameters.CUTOFF_PARAM, Integer.toString(1)); TokenNameFinderModel nameFinderModel = NameFinderME.train("en", TYPE, sampleStream, params, TokenNameFinderFactory.create(null, null, Collections.emptyMap(), <START> TokenNameFinderFactory.instantiateSequenceCodec(null))); <END> NameFinderME nameFinder = new NameFinderME(nameFinderModel); String[] sentence2 = new String[] { "Hi", "Mike", ",", "it's", "Stefanie", "Schmidt", "." }; Span[] names2 = nameFinder.find(sentence2); assertEquals(2, names2.length); assertEquals(new Span(1, 2, "person"), names2[0]); assertEquals(new Span(4, 6, "person"), names2[1]); assertEquals("person", names2[0].getType()); assertEquals("person", names2[1].getType()); String sentence[] = { "Alisa", "appreciated", "the", "hint", "and", "enjoyed", "a", "delicious", "traditional", "meal." }; Span names[] = nameFinder.find(sentence); assertEquals(1, names.length); assertEquals(new Span(0, 1, "person"), names[0]); assertTrue(hasOtherAsOutcome(nameFinderModel)); }</code><technical_language>codec name create it, e.g. new BioCodec()</technical_language>

Target:
public void testNameFinderWithTypes() throws Exception { InputStream in = getClass().getClassLoader().getResourceAsStream( "opennlp/tools/namefind/AnnotatedSentencesWithTypes.txt"); String encoding = "ISO-8859-1"; ObjectStream<NameSample> sampleStream = new NameSampleDataStream( new PlainTextByLineStream(new MockInputStreamFactory(in), encoding)); TrainingParameters params = new TrainingParameters(); params.put(TrainingParameters.ITERATIONS_PARAM, Integer.toString(70)); params.put(TrainingParameters.CUTOFF_PARAM, Integer.toString(1)); TokenNameFinderModel nameFinderModel = NameFinderME.train("en", TYPE, sampleStream, params, TokenNameFinderFactory.create(null, null, Collections.emptyMap(), new BioCodec())); NameFinderME nameFinder = new NameFinderME(nameFinderModel); String[] sentence2 = new String[] { "Hi", "Mike", ",", "it's", "Stefanie", "Schmidt", "." }; Span[] names2 = nameFinder.find(sentence2); assertEquals(2, names2.length); assertEquals(new Span(1, 2, "person"), names2[0]); assertEquals(new Span(4, 6, "person"), names2[1]); assertEquals("person", names2[0].getType()); assertEquals("person", names2[1].getType()); String sentence[] = { "Alisa", "appreciated", "the", "hint", "and", "enjoyed", "a", "delicious", "traditional", "meal." }; Span names[] = nameFinder.find(sentence); assertEquals(1, names.length); assertEquals(new Span(0, 1, "person"), names[0]); assertTrue(hasOtherAsOutcome(nameFinderModel)); }
Source:
<code>public AbstractComment() { <START> this.date = ZonedDateTime.now(UTC).toLocalDate(); <END> }</code><technical_language>clock injecten</technical_language>

Target:
public AbstractComment() { this.date = LocalDate.now(UTC); }
Source:
<code>public void shouldNotPutIfSameValuesAndGreaterTimestamp() { inner.put(eq(keyBytes), aryEq(valueAndTimestampBytes)); expectLastCall(); init(); metered.put(key, valueAndTimestamp); final ValueAndTimestampSerde<String> stringSerde = new ValueAndTimestampSerde<>(Serdes.String()); final byte[] encodedOldValue = stringSerde.serializer().serialize("TOPIC", valueAndTimestamp); final ValueAndTimestamp<String> newValueAndTimestamp = ValueAndTimestamp.make("value", 98L); <START> assertFalse(metered.putIfDifferentValues(key, newValueAndTimestamp, encodedOldValue)); <END> }</code><technical_language>Ah, say, more slipped before. verify(inner) end of of tests. fail for shouldNotPutIfSameValuesAndGreaterTimestamp _not_ call inner.put in this case. fix that, delete L202, set mock for inner.put. Then, mock initialized expect calls, verification fail if call it</technical_language>

Target:
public void shouldNotPutIfSameValuesAndGreaterTimestamp() { init(); metered.put(key, valueAndTimestamp); final ValueAndTimestampSerde<String> stringSerde = new ValueAndTimestampSerde<>(Serdes.String()); final byte[] encodedOldValue = stringSerde.serializer().serialize("TOPIC", valueAndTimestamp); final ValueAndTimestamp<String> newValueAndTimestamp = ValueAndTimestamp.make("value", 98L); assertFalse(metered.putIfDifferentValues(key, newValueAndTimestamp, encodedOldValue)); verify(inner); }
Source:
<code>protected File createFile(String fileName, String content) throws FileNotFoundException, <START> UnsupportedEncodingException { <END> String filePath = repositoryPath + "/" + fileName; PrintWriter writer = new PrintWriter(filePath, "UTF-8"); writer.println(content); writer.close(); return new File(filePath); }</code><technical_language>Sytem.getProperty("file.separator") instead of "/"</technical_language>

Target:
protected File createFile(String fileName, String content) throws FileNotFoundException, UnsupportedEncodingException { String filePath = repositoryPath + System.getProperty("file.separator") + fileName; PrintWriter writer = new PrintWriter(filePath, "UTF-8"); writer.println(content); writer.close(); return new File(filePath); }
Source:
<code>public Map<String, String> getShellEnvironment() { Map<String, String> orig = super.getShellEnvironment(); String kafkaJmxOpts = orig.remove("JAVA_OPTS"); <START> if (Strings.isBlank(kafkaJmxOpts)) kafkaJmxOpts = " "; END> return MutableMap.<String, String>builder() .putAll(orig) .putIfNotNull("KAFKA_JMX_OPTS", kafkaJmxOpts) .build(); }</code><technical_language>This line required. a temporary hack disable kafka-zookeeper jmx</technical_language>

Target:
public Map<String, String> getShellEnvironment() { Map<String, String> orig = super.getShellEnvironment(); String kafkaJmxOpts = orig.remove("JAVA_OPTS"); return MutableMap.<String, String>builder() .putAll(orig) .putIfNotNull("KAFKA_JMX_OPTS", kafkaJmxOpts) .build(); }
Source:
<code>public List<UserFromView> getTableFromView() { List<UserFromView> usersList = new LinkedList<>(); int pagination = 0; do { if (driver.findElements(AdministrationPageLocators.TABLE_ROWS.getBy()).size() <= 1) { } else { List<WebElement> rowsList = driver.findElements(AdministrationPageLocators.TABLE_ROWS.getBy()); for (int j = 1; j < rowsList.size(); j++) { List<WebElement> cellsList = rowsList.get(j).findElements(AdministrationPageLocators.ROW_CELLS.getBy()); usersList.add(new UserFromView.Builder() .withFirstName(cellsList.get(0).getText()) .withLastName(cellsList.get(1).getText()) .withLogin(cellsList.get(2).getText()) .withRole(cellsList.get(3).getText()) .withRegion(cellsList.get(4).getText()) .build()); } } pagination++; clickNextButton(); } while (pagination < getQuantityOfTablePages()); clickFirstButton(); <START> Reporter.log(String.format("<br>INFO&nbsp;&nbsp; - <b>We got a table.</b>")); <END> return usersList; }</code><technical_language>remove this logging</technical_language>

Target:
public List<UserFromView> getTableFromView() { List<UserFromView> usersList = new LinkedList<>(); int pagination = 0; do { if (driver.findElements(AdministrationPageLocators.TABLE_ROWS.getBy()).size() <= 1) { } else { List<WebElement> rowsList = driver.findElements(AdministrationPageLocators.TABLE_ROWS.getBy()); for (int j = 1; j < rowsList.size(); j++) { List<WebElement> cellsList = rowsList.get(j).findElements(AdministrationPageLocators.ROW_CELLS.getBy()); usersList.add(UserFromView.newBuilder() .firstName(cellsList.get(0).getText()) .lastName(cellsList.get(1).getText()) .login(cellsList.get(2).getText()) .role(cellsList.get(3).getText()) .region(cellsList.get(4).getText()) .build()); } } pagination++; clickNextButton(); } while (pagination < getQuantityOfTablePages()); clickFirstButton(); return usersList; }
Source:
<code>public void processStream(InputStream input) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(input)); int linenum = 0; while (linenum < numlines) { String line = reader.readLine(); if (line == null) { return; } lines.add(line); linenum++; } <START> while (reader.read() != -1) { <END> ; } }</code><technical_language>Technically this is needless byte char conversion. E.g. a multi-byte encoding, decoding is worthwhile. original thinking HeadHandler principal buffering byte-level. E.g. a BufferedReader(InputStreamReader, /*tiny*/200) atop a BufferedInputStream. needed readLine() calls done read() discard BufferedInputStream - a byte a time a small byte[1024] buffer. (Using readLine() defeat goal of avoiding needless heap allocation.)</technical_language>

Target:
public void processStream(InputStream input) throws IOException { try (BufferedInputStream bufStream = new BufferedInputStream(input); BufferedReader reader = new BufferedReader(new InputStreamReader(bufStream, this.charset), bufferedReaderSize)) { int lineNum = 0; while (lineNum < maxLines) { String line = reader.readLine(); if (line == null) { return; } lines.add(line); lineNum++; } byte[] buf = new byte[1024]; while ((bufStream.read(buf)) != -1) { ; } } }