auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public DataFileWriter<D> appendTo(File file) throws IOException { SeekableInput input = new SeekableFileInput(file); <START> OutputStream output = new SyncableFileOutputStream(file, true); <END> try { return appendTo(input, output); } finally { input.close(); } }</code><technical_language>I this line try block guarantee input is closed. Or, alternatively, line if order matter</technical_language>

Target:
public DataFileWriter<D> appendTo(File file) throws IOException { SeekableInput input = null; try { input = new SeekableFileInput(file); OutputStream output = new SyncableFileOutputStream(file, true); return appendTo(input, output); } finally { if (input != null) input.close(); } }
Source:
<code>public CompositeFileListFilter<F> addFilters(Collection<? extends FileListFilter<F>> filtersToAdd) { for (FileListFilter<F> elf : filtersToAdd) { if (elf instanceof DiscardAwareFileListFilter) { ((DiscardAwareFileListFilter<F>) elf).addDiscardCallback(this.discardCallback); } if (elf instanceof InitializingBean) { try { ((InitializingBean) elf).afterPropertiesSet(); } catch (Exception e) { throw new IllegalStateException(e); } } } this.fileFilters.addAll(filtersToAdd); <START> this.allSupportAccept &= filtersToAdd.stream().allMatch(f -> f.supportsSingleFileFiltering()); <END> return this; }</code><technical_language>method reference concern</technical_language>

Target:
public CompositeFileListFilter<F> addFilters(Collection<? extends FileListFilter<F>> filtersToAdd) { for (FileListFilter<F> elf : filtersToAdd) { if (elf instanceof DiscardAwareFileListFilter) { ((DiscardAwareFileListFilter<F>) elf).addDiscardCallback(this.discardCallback); } if (elf instanceof InitializingBean) { try { ((InitializingBean) elf).afterPropertiesSet(); } catch (Exception e) { throw new IllegalStateException(e); } } } this.fileFilters.addAll(filtersToAdd); this.allSupportAccept &= filtersToAdd.stream().allMatch(FileListFilter<F>::supportsSingleFileFiltering); return this; }
Source:
<code>public void testCrcOutputStream() throws IOException { byte[] buf = new byte[4000]; ByteBufferOutputStream stream = new ByteBufferOutputStream(ByteBuffer.wrap(buf)); CrcOutputStream crcStream = new CrcOutputStream(stream); byte[] bufOutput = new byte[4000]; new Random().nextBytes(bufOutput); try { crcStream.write(bufOutput); } catch (IOException e) { Assert.assertTrue(false); } Assert.assertArrayEquals(buf, bufOutput); long value1 = crcStream.getValue(); stream = new ByteBufferOutputStream(ByteBuffer.wrap(buf)); crcStream = new CrcOutputStream(stream); try { crcStream.write(bufOutput[0]); crcStream.write(bufOutput, 1, 3999); } catch (IOException e) { Assert.assertTrue(false); } Assert.assertArrayEquals(buf, bufOutput); long value2 = crcStream.getValue(); Assert.assertEquals(value1, value2); crcStream.close(); <START> } <END></code><technical_language>here. A case a mismatch is caught added</technical_language>

Target:
public void testCrcOutputStream() throws IOException { byte[] buf = new byte[4000]; ByteBufferOutputStream stream = new ByteBufferOutputStream(ByteBuffer.wrap(buf)); CrcOutputStream crcStream = new CrcOutputStream(stream); byte[] bufOutput = new byte[4000]; new Random().nextBytes(bufOutput); try { crcStream.write(bufOutput); } catch (IOException e) { Assert.assertTrue(false); } Assert.assertArrayEquals(buf, bufOutput); long value1 = crcStream.getValue(); stream = new ByteBufferOutputStream(ByteBuffer.wrap(buf)); crcStream = new CrcOutputStream(stream); try { crcStream.write(bufOutput[0]); crcStream.write(bufOutput, 1, 3999); } catch (IOException e) { Assert.assertTrue(false); } Assert.assertArrayEquals(buf, bufOutput); long value2 = crcStream.getValue(); Assert.assertEquals(value1, value2); bufOutput[0] = (byte) (~bufOutput[0]); stream = new ByteBufferOutputStream(ByteBuffer.wrap(buf)); crcStream = new CrcOutputStream(stream); try { crcStream.write(bufOutput[0]); crcStream.write(bufOutput, 1, 3999); } catch (IOException e) { Assert.assertTrue(false); } Assert.assertArrayEquals(buf, bufOutput); long value3 = crcStream.getValue(); Assert.assertFalse(value2 == value3); crcStream.close(); }
Source:
<code>private String selectAll(CairoEngine engine, SqlCompiler compiler, SqlExecutionContext sqlExecutionContext, String tableName) throws Exception { CompiledQuery compiledQuery = compiler.compile("select * from " + tableName, sqlExecutionContext); try (RecordCursorFactory factory = compiledQuery.getRecordCursorFactory(); RecordCursor cursor = factory.getCursor(sqlExecutionContext)) { sink.clear(); printer.print(cursor, factory.getMetadata(), true); <START> cursor.toTop(); <END> Record record = cursor.getRecord(); while (cursor.hasNext()) { printer.print(record, factory.getMetadata()); } } return sink.toString(); }</code><technical_language>in this instance necessary pass table</technical_language>

Target:
private String selectAll(CairoEngine engine, SqlCompiler compiler, SqlExecutionContext sqlExecutionContext, String tableName) throws Exception { CompiledQuery compiledQuery = compiler.compile("select * from " + tableName, sqlExecutionContext); try (RecordCursorFactory factory = compiledQuery.getRecordCursorFactory(); RecordCursor cursor = factory.getCursor(sqlExecutionContext)) { sink.clear(); printer.print(cursor, factory.getMetadata(), true); } return sink.toString(); }
Source:
<code>Set<Element> originatingElements() { <START> return FluentIterable.from(body.nestedTypeWriters) <END> .transformAndConcat(new Function<TypeWriter, Iterable<Element>>() { @Override public Iterable<Element> apply(TypeWriter input) { return input.originatingElements(); } }) .append(originatingElements) .toSet(); }</code><technical_language>topic: I functional style helps</technical_language>

Target:
Set<Element> originatingElements() { ImmutableSet.Builder<Element> elements = ImmutableSet.builder(); elements.addAll(originatingElements); for (TypeWriter nestedTypeWriter : body.nestedTypeWriters) { elements.addAll(nestedTypeWriter.originatingElements()); } return elements.build(); }
Source:
<code>public OWLOntology saveOntology( final OWLOntology ontology, OWLDocumentFormat format, IRI ontologyIRI, boolean checkOBO) throws IOException { logger.debug("Saving ontology as with to IRI {}", ontology, format, ontologyIRI); XMLWriterPreferences.getInstance().setUseNamespaceEntities(getXMLEntityFlag()); <START> if (ontologyIRI.toString().endsWith("gz")) { <END> byte[] data = getOntologyFileData(ontology, format, checkOBO); saveCompressedOntology(data, ontologyIRI); return ontology; } saveOntologyFile(ontology, format, ontologyIRI, checkOBO); return ontology; }</code><technical_language>gz</technical_language>

Target:
public OWLOntology saveOntology( final OWLOntology ontology, OWLDocumentFormat format, IRI ontologyIRI, boolean checkOBO) throws IOException { logger.debug("Saving ontology as with to IRI {}", ontology, format, ontologyIRI); XMLWriterPreferences.getInstance().setUseNamespaceEntities(getXMLEntityFlag()); if (ontologyIRI.toString().endsWith(".gz")) { byte[] data = getOntologyFileData(ontology, format, checkOBO); saveCompressedOntology(data, ontologyIRI); return ontology; } saveOntologyFile(ontology, format, ontologyIRI, checkOBO); return ontology; }
Source:
<code>public static Properties loadTrimmedProperties(File propsFile) throws IOException { Properties props = new Properties(); String charset = checkFileCharset(propsFile); <START> if (charset == null) throw new IOException("Can't identify input file charset"); <END> try (InputStreamReader propsIS = new InputStreamReader(new FileInputStream(propsFile), charset)) { loadTrimmedProperties(props, propsIS); } return props; }</code><technical_language>format add {}</technical_language>

Target:
public static Properties loadTrimmedProperties(File propsFile) throws IOException { Properties props = new Properties(); Charset charset = checkFileCharset(propsFile); log.debug("Opening " + propsFile.getName() + " in " + charset.name()); if (charset == null) { throw new IOException("Can't identify input file charset"); } try (InputStreamReader propsIS = new InputStreamReader(new FileInputStream(propsFile), charset)) { loadTrimmedProperties(props, propsIS); } return props; }
Source:
<code>public String docs() { <START> return "boolean {locationArray, [cmd]} Sets a command to a Command Block at the given location." <END> + "If no command is given, it sets the Command Block to an empty string."; }</code><technical_language>void, boolean</technical_language>

Target:
public String docs() { return "void {locationArray, [cmd]} Sets a command to a Command Block at the given location." + "If no command is given or parameter is null, it clears the Command Block."; }
Source:
<code>protected Iterable<Text> getLines(int page) throws CommandException { if (this.pages.size() == 0) { <START> return Lists.newArrayList(); <END> } else if (page < 1) { throw new CommandException(t("Page %s does not exist!", page)); } else if (page > this.pages.size()) { throw new CommandException(t("Page %s is too high", page)); } return this.pages.get(page - 1); }</code><technical_language>Assuming this is read-only: return ImmutableList.of() - a single instance</technical_language>

Target:
protected Iterable<Text> getLines(int page) throws CommandException { if (this.pages.size() == 0) { return ImmutableList.of(); } else if (page < 1) { throw new CommandException(t("Page %s does not exist!", page)); } else if (page > this.pages.size()) { throw new CommandException(t("Page %s is too high", page)); } return this.pages.get(page - 1); }
Source:
<code>private void updateFeedbackResponses() { Set<String> studentsEmails = new HashSet<>(testData.students.size()); for (StudentAttributes student : testData.students.values()) { studentsEmails.add(student.email); } Set<Integer> questionsNumbers = new HashSet<>(testData.feedbackQuestions.size()); for (FeedbackQuestionAttributes question : testData.feedbackQuestions.values()) { questionsNumbers.add(question.questionNumber); } Set<String> feedbackResponsesKeys = testDataMax.feedbackResponses.keySet(); String giver; String recipient; <START> String questionId; <END> for (String key : feedbackResponsesKeys) { giver = testDataMax.feedbackResponses.get(key).giver; recipient = testDataMax.feedbackResponses.get(key).recipient; questionId = testDataMax.feedbackResponses.get(key).feedbackQuestionId; if (studentsEmails.contains(giver) && studentsEmails.contains(recipient) && questionsNumbers.contains(questionId)) { if (!testData.feedbackResponses.containsKey(key)) { testData.feedbackResponses.put(key, testDataMax.feedbackResponses.get(key)); } } else if (testData.feedbackResponses.containsKey(key)) { testData.feedbackResponses.remove(key); } } }</code><technical_language>Is necessary declare variables foreach loop</technical_language>

Target:
private void updateFeedbackResponses() { Set<String> studentsEmails = new HashSet<>(testData.students.size()); for (StudentAttributes student : testData.students.values()) { studentsEmails.add(student.email); } Set<String> feedbackQuestionIds = new HashSet<>(testData.feedbackQuestions.size()); for (FeedbackQuestionAttributes question : testData.feedbackQuestions.values()) { feedbackQuestionIds.add(String.valueOf(question.questionNumber)); } List<String> keysOfFeedbackResponsesToDelete = new LinkedList<>(); for (String key : testDataMax.feedbackResponses.keySet()) { if (studentsEmails.contains(testDataMax.feedbackResponses.get(key).giver) && studentsEmails.contains(testDataMax.feedbackResponses.get(key).recipient) && feedbackQuestionIds.contains(testDataMax.feedbackResponses.get(key).feedbackQuestionId) && !testData.feedbackResponses.containsKey(key)) { testData.feedbackResponses.put(key, testDataMax.feedbackResponses.get(key)); } else if ((!studentsEmails.contains(testDataMax.feedbackResponses.get(key).giver) || !studentsEmails.contains(testDataMax.feedbackResponses.get(key).recipient) || !feedbackQuestionIds.contains(testDataMax.feedbackResponses.get(key).feedbackQuestionId)) && testData.feedbackResponses.containsKey(key)) { keysOfFeedbackResponsesToDelete.add(key); } } if (!keysOfFeedbackResponsesToDelete.isEmpty()) { for (String removeKey : keysOfFeedbackResponsesToDelete) { testData.feedbackResponses.remove(removeKey); } } }
Source:
<code>void bindInfrastructure() { bindCommonInfrastructure(UserPortalPlaceManager.class); bind(LoggedInExtendedPlaceGatekeeper.class).in(Singleton.class); bind(ApplicationInit.class).asEagerSingleton(); <START> bind(CurrentUserRole.class).to(UserPortalCurrentUserRole.class).in(Singleton.class); <END> }</code><technical_language>Please consider making BaseSystemModule.bindTypeAndImplAsSingleton method protected allow CurrentUserRole & UserPortalCurrentUserRole @Inject'ed instance: bindTypeAndImplAsSingleton(CurrentUserRole.class, UserPortalCurrentUserRole.class); This way, @Inject UserPortalCurrentUserRole directly, is practically @Inject'ing CurrentUserRole</technical_language>

Target:
void bindInfrastructure() { bindCommonInfrastructure(UserPortalPlaceManager.class); bind(LoggedInExtendedPlaceGatekeeper.class).in(Singleton.class); bind(CurrentUserRole.class).in(Singleton.class); bind(ApplicationInit.class).asEagerSingleton(); bindTypeAndImplAsSingleton(CurrentUserRole.class, UserPortalCurrentUserRole.class); }
Source:
<code>public CompletionStage<Void> preload() { if (!enabled) return CompletableFutures.completedNull(); AdvancedCacheLoader<Object, Object> preloadCl = null; storesMutex.readLock().lock(); try { for (CacheLoader l : loaders) { if (getStoreConfig(l).preload()) { if (!(l instanceof AdvancedCacheLoader)) { throw new PersistenceException("Cannot preload from cache loader '" + l.getClass().getName() + "' as it doesn't implement '" + AdvancedCacheLoader.class.getName() + "'"); } preloadCl = (AdvancedCacheLoader) l; if (preloadCl instanceof AdvancedAsyncCacheLoader) preloadCl = (AdvancedCacheLoader) ((AdvancedAsyncCacheLoader) preloadCl).undelegate(); break; } } } finally { storesMutex.readLock().unlock(); } if (preloadCl == null) { return CompletableFutures.completedNull(); } long start = timeService.time(); final long maxEntries = getMaxEntries(); final AdvancedCache<Object, Object> flaggedCache = getCacheForStateInsertion(); return Flowable.fromPublisher(preloadCl.entryPublisher(null, true, true)) .take(maxEntries) <START> .observeOn(blockingScheduler) <END> .doOnNext(me -> preloadKey(flaggedCache, me)) .count() .subscribeOn(blockingScheduler) .to(RxJavaInterop.singleToCompletionStage()) .thenAccept(insertAmount -> { this.preloaded = insertAmount < maxEntries; log.debugf("Preloaded %d keys in %s", insertAmount, Util.prettyPrintTime(timeService.timeDuration(start, MILLISECONDS))); }); }</code><technical_language>Actually, Pedro, move 1 more line. observeOn is count. N-1 context switches add a counter. counter send 1 downstream</technical_language>

Target:
public CompletionStage<Void> preload() { if (!enabled) return CompletableFutures.completedNull(); AdvancedCacheLoader<Object, Object> preloadCl = null; storesMutex.readLock().lock(); try { for (CacheLoader l : loaders) { if (getStoreConfig(l).preload()) { if (!(l instanceof AdvancedCacheLoader)) { throw new PersistenceException("Cannot preload from cache loader '" + l.getClass().getName() + "' as it doesn't implement '" + AdvancedCacheLoader.class.getName() + "'"); } preloadCl = (AdvancedCacheLoader) l; if (preloadCl instanceof AdvancedAsyncCacheLoader) preloadCl = (AdvancedCacheLoader) ((AdvancedAsyncCacheLoader) preloadCl).undelegate(); break; } } } finally { storesMutex.readLock().unlock(); } if (preloadCl == null) { return CompletableFutures.completedNull(); } long start = timeService.time(); final long maxEntries = getMaxEntries(); final AdvancedCache<Object, Object> flaggedCache = getCacheForStateInsertion(); return Flowable.fromPublisher(preloadCl.entryPublisher(null, true, true)) .take(maxEntries) .doOnNext(me -> preloadKey(flaggedCache, me)) .count() .observeOn(nonBlockingScheduler) .subscribeOn(blockingScheduler) .to(RxJavaInterop.singleToCompletionStage()) .thenAccept(insertAmount -> { this.preloaded = insertAmount < maxEntries; log.debugf("Preloaded %d keys in %s", insertAmount, Util.prettyPrintTime(timeService.timeDuration(start, MILLISECONDS))); }); }
Source:
<code><START> private void addParentheses(IASTNode node) throws BadLocationException{ <END> IASTNode[] children = node.getChildren(); if(children.length > 0 && !children[0].getRawSignature().contains("(")) { IASTNode childNode = children[0]; int childNodeLength = childNode.getFileLocation().getNodeLength(); int childNodeOffset = childNode.getFileLocation().getNodeOffset(); String childContent = document.get(childNodeOffset, childNodeLength); String newChild = "(".concat(childContent).concat(")"); document.replace(childNodeOffset, childNodeLength, newChild); } }</code><technical_language>NON-NLS flags for plain strings</technical_language>

Target:
private void addParentheses(IASTNode node) throws BadLocationException{ IASTNode[] children = node.getChildren(); if(children.length > 0 && !children[0].getRawSignature().contains("(")) { IASTNode childNode = children[0]; int childNodeLength = childNode.getFileLocation().getNodeLength(); int childNodeOffset = childNode.getFileLocation().getNodeOffset(); String childContent = document.get(childNodeOffset, childNodeLength); String newChild = "(".concat(childContent).concat(")"); document.replace(childNodeOffset - 1, childNodeLength + 1, newChild); } }
Source:
<code>public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException { try { String accesslog = invoker.getUrl().getParameter(Constants.ACCESS_LOG_KEY); if (ConfigUtils.isNotEmpty(accesslog)) { RpcContext context = RpcContext.getContext(); String serviceName = invoker.getInterface().getName(); String version = invoker.getUrl().getParameter(Constants.VERSION_KEY); String group = invoker.getUrl().getParameter(Constants.GROUP_KEY); StringBuilder sn = new StringBuilder(); <START> sn.append("[").append(MESSAGE_DATE_FORMATTER.get().format(new Date())).append("] ").append(context.getRemoteHost()).append(":").append(context.getRemotePort()) <END> .append(" -> ").append(context.getLocalHost()).append(":").append(context.getLocalPort()) .append(" - "); if (null != group && group.length() > 0) { sn.append(group).append("/"); } sn.append(serviceName); if (null != version && version.length() > 0) { sn.append(":").append(version); } sn.append(" "); sn.append(inv.getMethodName()); sn.append("("); Class<?>[] types = inv.getParameterTypes(); if (types != null && types.length > 0) { boolean first = true; for (Class<?> type : types) { if (first) { first = false; } else { sn.append(","); } sn.append(type.getName()); } } sn.append(") "); Object[] args = inv.getArguments(); if (args != null && args.length > 0) { sn.append(JSON.toJSONString(args)); } String msg = sn.toString(); if (ConfigUtils.isDefault(accesslog)) { LoggerFactory.getLogger(ACCESS_LOG_KEY + "." + invoker.getInterface().getName()).info(msg); } else { log(accesslog, msg); } } } catch (Throwable t) { logger.warn("Exception in AcessLogFilter of service(" + invoker + " -> " + inv + ")", t); } return invoker.invoke(inv); }</code><technical_language>Another consider is clear threadlocal's value. in memory time</technical_language>

Target:
public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException { try { String accessLogKey = invoker.getUrl().getParameter(Constants.ACCESS_LOG_KEY); if (ConfigUtils.isNotEmpty(accessLogKey)) { AccessLogData logData = buildAccessLogData(invoker, inv); log(accessLogKey, logData); } } catch (Throwable t) { logger.warn("Exception in AcessLogFilter of service(" + invoker + " -> " + inv + ")", t); } return invoker.invoke(inv); }
Source:
<code>public void startStatementWithinTransaction(Command command) { Transaction transaction = getTransaction(); if (transaction != null) { HashSet<MVMap<?, ?>> maps = new HashSet<>(); if (command != null) { Set<DbObject> dependencies = command.getDependencies(); switch (transaction.getIsolationLevel()) { case SNAPSHOT: case SERIALIZABLE: if (!transaction.hasStatementDependencies()) { for (Table table : database.getAllTablesAndViews(false)) { if (table instanceof MVTable) { addTableToDependencies((MVTable)table, maps); } } } case REPEATABLE_READ: HashSet<MVTable> processed = new HashSet<>(); for (DbObject dependency : dependencies) { if (dependency instanceof MVTable) { addTableToDependencies((MVTable)dependency, maps, processed); } } break; <START> case READ_COMMITTED: <END> for (DbObject dependency : dependencies) { if (dependency instanceof MVTable) { addTableToDependencies((MVTable)dependency, maps); } } break; } } transaction.markStatementStart(maps); } startStatement = -1; if (command != null) { setCurrentCommand(command); } }</code><technical_language>I READ UNCOMMITTED needs snapshot start of command too. difference this level default READ COMMITTED is visibility of uncommitted changes other transactions, other differences expected. a bug fixed some time consistency of statements. bug re-appear READ UNCOMMITTED isolation level. H2 optimization for MIN / MAX / COUNT(*) aggregates. evaluated separately (and indexes / maps). this weak level indexes / maps consistent other evaluation of query retain behavior unoptimized version</technical_language>

Target:
public void startStatementWithinTransaction(Command command) { Transaction transaction = getTransaction(); if (transaction != null) { HashSet<MVMap<?, ?>> maps = new HashSet<>(); if (command != null) { Set<DbObject> dependencies = command.getDependencies(); switch (transaction.getIsolationLevel()) { case SNAPSHOT: case SERIALIZABLE: if (!transaction.hasStatementDependencies()) { for (Table table : database.getAllTablesAndViews(false)) { if (table instanceof MVTable) { addTableToDependencies((MVTable)table, maps); } } break; } case READ_COMMITTED: case READ_UNCOMMITTED: for (DbObject dependency : dependencies) { if (dependency instanceof MVTable) { addTableToDependencies((MVTable)dependency, maps); } } break; case REPEATABLE_READ: HashSet<MVTable> processed = new HashSet<>(); for (DbObject dependency : dependencies) { if (dependency instanceof MVTable) { addTableToDependencies((MVTable)dependency, maps, processed); } } break; } } transaction.markStatementStart(maps); } startStatement = -1; if (command != null) { setCurrentCommand(command); } }
Source:
<code>public void evaluate() throws Throwable { List<Throwable> errors = new ArrayList<Throwable>(); try { nextStatement.evaluate(); } catch (Throwable e) { errors.add(e); } IAfterTest after = null; log.debug("Run after class extensions for test class " + testClass.getJavaClass().getName()); afters.sort(new PriorityComparator()); for (IAfterTest each : afters) { after = each; try { if (after.hasToRun()){ log.debug("Run method runAfterTestClass() of class " + after.getClass().getCanonicalName()); after.runAfterTestClass(config, testClass); } } catch (Throwable e) { <START> log.error("Run method runAfterTestClass() of class " + after.getClass().getCanonicalName() + " failed", e); <END> if (isScreenshotRequired(e)) { createScreenshot("AfterClassExt", after.getClass()); } errors.add(e); } } MultipleFailureException.assertEmpty(errors); }</code><technical_language>move error log condition body</technical_language>

Target:
public void evaluate() throws Throwable { List<Throwable> errors = new ArrayList<Throwable>(); try { nextStatement.evaluate(); } catch (Throwable e) { errors.add(e); } IAfterTest after = null; log.debug("Run after class extensions for test class " + testClass.getJavaClass().getName()); afters.sort(new PriorityComparator()); for (IAfterTest each : afters) { after = each; try { if (after.hasToRun()){ log.debug("Run method runAfterTestClass() of class " + after.getClass().getCanonicalName()); after.runAfterTestClass(config, testClass); } } catch (Throwable e) { if(ScreenshotCapturer.shouldCaptureScreenshotOnException(e)){ log.error("Run method runAfterTestClass() of class " + after.getClass().getCanonicalName() + " failed", e); createScreenshot("AfterClassExt", after.getClass()); } errors.add(e); } } MultipleFailureException.assertEmpty(errors); }
Source:
<code>public void onSearchedEvent(String search) { <START> DivElement listContainer = view.getListContainer(); <END> int children = listContainer.getChildCount(); for (int i = 0; i < children; i ++) { DivElement child = (DivElement) listContainer.getChild(i); String factName = child.getAttribute("id").replace("listGroupItem-", "").toLowerCase(); if (factName.contains(search.toLowerCase())) { child.removeAttribute("style"); } else { child.setAttribute("style", "display: none;"); } } }</code><technical_language>want leak UI elements presenter here. A. presenter framework widgets for view B. more importantly if 500+ classes UI slow this code run properly. I do search DMO fill UI based that. check UX do if is thousands of classes in list. show 20 what</technical_language>

Target:
public void onSearchedEvent(String search) { clearList(); if(factTypeFieldsMap.isEmpty()) { return; } factTypeFieldsMap .entrySet() .stream() .filter(entry -> entry.getKey().toLowerCase().contains(search.toLowerCase())) .forEach(filteredEntry -> addListGroupItemView(filteredEntry.getKey(), filteredEntry.getValue())); }
Source:
<code>public S3CmdPut( @NotNull(message = "name can't be NULL") final String label, @NotNull(message = "path can't be NULL") final String pth, @NotNull(message = "bucket can't be NULL") final String bkt, @NotNull(message = "prefix can't be NULL") final String pfx, @NotNull(message = "key can't be NULL") final String akey, @NotNull(message = "secret can't be NULL") final String scrt) { <START> this(label, pth, bkt, pfx, akey, scrt, "binary/octet-stream", "UTF-8"); <END> }</code><technical_language>set "text/plain" instead</technical_language>

Target:
public S3CmdPut( @NotNull(message = "name can't be NULL") final String label, @NotNull(message = "path can't be NULL") final String pth, @NotNull(message = "bucket can't be NULL") final String bkt, @NotNull(message = "prefix can't be NULL") final String pfx, @NotNull(message = "key can't be NULL") final String akey, @NotNull(message = "secret can't be NULL") final String scrt) { this(label, pth, bkt, pfx, akey, scrt, "text/plain", "UTF-8"); }
Source:
<code>public boolean isDslCompatibleWith(ElasticsearchFieldSortBuilderFactory obj) { if ( this == obj ) { return true; } if ( obj.getClass() != StandardFieldSortBuilderFactory.class ) { return false; } StandardFieldSortBuilderFactory other = (StandardFieldSortBuilderFactory) obj; <START> return converter.isDslCompatibleWith( other.converter ); <END> }</code><technical_language>for sort builder factories, check for "sortable" parameter compatible. way, "comparing" is a bit tricky, DEFAULT is, theroretically, compatible NO... compare values other, I convert "default" default is... a boolean this point? If so, I done in *TypeContext, a switch enum: add a boolean sortableDefaulted variable populate in switch</technical_language>

Target:
public boolean isDslCompatibleWith(ElasticsearchFieldSortBuilderFactory obj) { if ( this == obj ) { return true; } if ( obj.getClass() != StandardFieldSortBuilderFactory.class ) { return false; } StandardFieldSortBuilderFactory other = (StandardFieldSortBuilderFactory) obj; return sortable == other.sortable && converter.isDslCompatibleWith( other.converter ); }
Source:
<code>public ProviderSqlSource(Configuration configuration, Object provider, Class<?> mapperType, Method mapperMethod) { this(configuration, provider instanceof Annotation ? (Annotation) provider : (Annotation) Proxy.newProxyInstance(SelectProvider.class.getClassLoader(), new Class<?>[]{SelectProvider.class}, (proxy, method, args) -> { if (method.getName().equals("annotationType")) { return SelectProvider.class; } return provider.getClass().getMethod(method.getName()).invoke(provider); }), mapperType, mapperMethod); <START> } <END></code><technical_language>remove constructors? I understand compatibility, this code proxy tests Object unrealistic. this is internal class, I OK assume parameter is Annotation mapperType mapperMethod null</technical_language>

Target:
public ProviderSqlSource(Configuration configuration, Object provider, Class<?> mapperType, Method mapperMethod) { this(configuration, (Annotation) provider , mapperType, mapperMethod); }
Source:
<code>String key() { <START> return "temporal"; <END> }</code><technical_language>I guess assuming sub-types encoded in a way, mixing sub-types is possible. This reasonable considering main worry clashing string types, other clashes easy solve specific encodings</technical_language>

Target:
String key() { return "number"; }
Source:
<code>public void hoverClickAndViewPhotoOnTableCell(int questionBodyIndex, int tableRow, int tableCol, String urlRegex) throws Exception { String idOfQuestionBody = "questionBody-" + questionBodyIndex; JavascriptExecutor jsExecutor = (JavascriptExecutor) browser.driver; jsExecutor.executeScript("arguments[0].scrollIntoView(true); window.scrollBy(0, -200);", <START> browser.driver.findElement(By.id(idOfQuestionBody))); <END> jsExecutor.executeScript("$(document.getElementById('" + idOfQuestionBody + "')" + ".querySelectorAll('.dataTable tbody tr')['" + tableRow + "']" + ".querySelectorAll('td')['" + tableCol + "']" + ".getElementsByClassName('profile-pic-icon-hover')).mouseenter()"); waitForElementPresence(By.cssSelector(".popover-content")); jsExecutor.executeScript("document.getElementsByClassName('popover-content')[0]" + ".getElementsByTagName('a')[0].click();"); waitForElementPresence(By.cssSelector(".popover-content > img")); AssertHelper.assertContainsRegex(urlRegex, browser.driver.findElements(By.cssSelector(".popover-content > img")) .get(0) .getAttribute("src")); jsExecutor.executeScript("document.getElementsByClassName('popover')[0].parentNode.removeChild(document.getElementsByClassName('popover')[0])"); }</code><technical_language>this solve problem? abstract technique in other places</technical_language>

Target:
public void hoverClickAndViewPhotoOnTableCell(int questionBodyIndex, int tableRow, int tableCol, String urlRegex) throws Exception { String idOfQuestionBody = "questionBody-" + questionBodyIndex; JavascriptExecutor jsExecutor = (JavascriptExecutor) browser.driver; jsExecutor.executeScript("$(document.getElementById('" + idOfQuestionBody + "')" + ".querySelectorAll('.dataTable tbody tr')['" + tableRow + "']" + ".querySelectorAll('td')['" + tableCol + "']" + ".getElementsByClassName('profile-pic-icon-hover')).mouseenter()"); waitForElementPresence(By.cssSelector(".popover-content")); jsExecutor.executeScript("document.getElementsByClassName('popover-content')[0]" + ".getElementsByTagName('a')[0].click();"); waitForElementPresence(By.cssSelector(".popover-content > img")); AssertHelper.assertContainsRegex(urlRegex, browser.driver.findElements(By.cssSelector(".popover-content > img")) .get(0) .getAttribute("src")); jsExecutor.executeScript("document.getElementsByClassName('popover')[0].parentNode.removeChild(document.getElementsByClassName('popover')[0])"); }
Source:
<code>public OnLoadHeaderItem setNonce(String nonce) { <START> Args.notNull(nonce, "nonce"); <END> this.nonce = nonce; return this; }</code><technical_language>nonEmpty</technical_language>

Target:
public OnLoadHeaderItem setNonce(String nonce) { this.nonce = nonce; return this; }
Source:
<code>private static AuditStrategy initializeAuditStrategy( String auditStrategyName, Class<?> revisionInfoClass, PropertyData revisionInfoTimestampData, ServiceRegistry serviceRegistry) { AuditStrategy strategy; try { final Class<?> auditStrategyClass = loadClass( auditStrategyName, serviceRegistry ); strategy = (AuditStrategy) ReflectHelper.getDefaultConstructor( auditStrategyClass ).newInstance(); } catch (Exception e) { throw new MappingException( String.format( "Unable to create AuditStrategy [%s] instance.", auditStrategyName ), e ); } <START> strategy.initializeAdditional(revisionInfoClass, revisionInfoTimestampData, serviceRegistry); <END> return strategy; }</code><technical_language>Need some padding in parentheses (shoud strategy.initializeAdditional( revisionInfoClass, revisionInfoTimestampData, serviceRegistry );). excited name of method :)</technical_language>

Target:
private static AuditStrategy initializeAuditStrategy( String auditStrategyName, Class<?> revisionInfoClass, PropertyData revisionInfoTimestampData, ServiceRegistry serviceRegistry) { AuditStrategy strategy; try { final Class<?> auditStrategyClass = loadClass( auditStrategyName, serviceRegistry ); strategy = (AuditStrategy) ReflectHelper.getDefaultConstructor( auditStrategyClass ).newInstance(); } catch (Exception e) { throw new MappingException( String.format( "Unable to create AuditStrategy [%s] instance.", auditStrategyName ), e ); } strategy.postInitialize( revisionInfoClass, revisionInfoTimestampData, serviceRegistry ); return strategy; }
Source:
<code>public Response doSetLocaleProperties( @PathParam ( "pathId" ) String pathId, @QueryParam ( "locale" ) String locale, List<StringKeyStringValueDto> properties ) { boolean success = true; String responseMsg = ""; try { String[] pathSplit = pathId.split( ":" ); boolean isFileTitleFound = false; StringKeyStringValueDto fileTitle = null; for ( StringKeyStringValueDto property : properties ) { if ( property.getKey().equals( "file.title" ) ) { responseMsg = "Unable to rename File/Folder"; isFileTitleFound = true; fileTitle = property; properties.remove( fileTitle ); break; } } fileService.doSetLocaleProperties( pathId, locale, properties ); if ( isFileTitleFound && fileTitle != null && !pathSplit[ pathSplit.length - 1 ].equals( fileTitle.getValue() ) ) { success = fileService.doRename( pathId, fileTitle.getValue() ); } if ( success ) { <START> return buildOkResponse(); <END> } else { return buildOkResponse( responseMsg ); } } catch ( Throwable t ) { return Response.serverError().entity( t.getMessage() ).build(); } }</code><technical_language>send a response a HTTP status code of 200 content. For this specific case, send a noContent() response sends a 204 response code. This is correct tell: success content. Some HTTP clients complain receive a 200 response content is possibility wrong content lost</technical_language>

Target:
public Response doSetLocaleProperties( @PathParam ( "pathId" ) String pathId, @QueryParam ( "locale" ) String locale, List<StringKeyStringValueDto> properties ) { boolean success = true; String responseMsg = ""; try { String[] pathSplit = pathId.split( ":" ); String originalFilename = pathSplit[ pathSplit.length - 1 ]; StringKeyStringValueDto fileTitle = null; for ( StringKeyStringValueDto property : properties ) { if ( property.getKey().equals( "file.title" ) ) { responseMsg = Messages.getInstance().getString( "FileResource.FILE_RENAME_FAILED", originalFilename ); fileTitle = property; properties.remove( fileTitle ); break; } } fileService.doSetLocaleProperties( pathId, locale, properties ); if ( fileTitle != null && !originalFilename.equals( fileTitle.getValue() ) ) { success = fileService.doRename( pathId, fileTitle.getValue() ); } if ( success ) { return buildOkNoContentResponse(); } else { return buildOkResponse( responseMsg ); } } catch ( Throwable t ) { return Response.serverError().entity( t.getMessage() ).build(); } }
Source:
<code>public Iterator<String> getGcCandidates(DataLevel level, String continuePoint) { if (level == DataLevel.ROOT) { byte[] json = context.getZooCache() .get(context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_GC_CANDIDATES); Stream<String> candidates = RootGcCandidates.fromJson(json).stream().sorted(); if (continuePoint != null && !continuePoint.isEmpty()) { candidates = candidates.dropWhile(candidate -> candidate.compareTo(continuePoint) <= 0); } return candidates.iterator(); } else if (level == DataLevel.METADATA || level == DataLevel.USER) { Range range = DeletesSection.getRange(); if (continuePoint != null && !continuePoint.isEmpty()) { String continueRow = DeletesSection.encodeRow(continuePoint); range = new Range(new Key(continueRow).followingKey(PartialKey.ROW), true, range.getEndKey(), range.isEndKeyInclusive()); } Scanner scanner; try { scanner = context.createScanner(level.metaTable(), Authorizations.EMPTY); } catch (TableNotFoundException e) { throw new RuntimeException(e); } scanner.setRange(range); <START> return Iterators.transform( <END> Iterators.filter(scanner.iterator(), entry -> entry.getValue().equals(DeletesSection.SkewedKeyValue.NAME)), entry -> DeletesSection.decodeRow(entry.getKey().getRow().toString())); } else { throw new IllegalArgumentException(); } }</code><technical_language>Instead of more Guava code here, this Java streams. I wan't get stream for a scanner I experimented locally. I ended compiles. java return StreamSupport.stream(scanner.spliterator(), false) .filter(entry -> entry.getValue().equals(DeletesSection.SkewedKeyValue.NAME)) .map(entry -> DeletesSection.decodeRow(entry.getKey().getRow().toString())).iterator();</technical_language>

Target:
public Iterator<String> getGcCandidates(DataLevel level, String continuePoint) { if (level == DataLevel.ROOT) { byte[] json = context.getZooCache() .get(context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_GC_CANDIDATES); Stream<String> candidates = RootGcCandidates.fromJson(json).stream().sorted(); if (continuePoint != null && !continuePoint.isEmpty()) { candidates = candidates.dropWhile(candidate -> candidate.compareTo(continuePoint) <= 0); } return candidates.iterator(); } else if (level == DataLevel.METADATA || level == DataLevel.USER) { Range range = DeletesSection.getRange(); if (continuePoint != null && !continuePoint.isEmpty()) { String continueRow = DeletesSection.encodeRow(continuePoint); range = new Range(new Key(continueRow).followingKey(PartialKey.ROW), true, range.getEndKey(), range.isEndKeyInclusive()); } Scanner scanner; try { scanner = context.createScanner(level.metaTable(), Authorizations.EMPTY); } catch (TableNotFoundException e) { throw new RuntimeException(e); } scanner.setRange(range); return StreamSupport.stream(scanner.spliterator(), false) .filter(entry -> entry.getValue().equals(DeletesSection.SkewedKeyValue.NAME)) .map(entry -> DeletesSection.decodeRow(entry.getKey().getRow().toString())).iterator(); } else { throw new IllegalArgumentException(); } }
Source:
<code>public void regenerateCertificatesOf(Collection<Owner> owners, Collection<Product> products, boolean lazy) { List<Pool> pools = new LinkedList<Pool>(); Set<String> productIds = new HashSet<String>(); Date now = new Date(); for (Product product : products) { productIds.add(product.getId()); } for (Owner owner : owners) { if (lazy) { for (Product product : products) { <START> poolCurator.markCertificatesDirtyForOwnerProductId(owner, product.getId()); <END> } } else { pools.addAll( this.poolCurator.listAvailableEntitlementPools(null, owner, productIds, now) ); } } for (Pool pool : pools) { this.regenerateCertificatesOf(pool.getEntitlements(), lazy); } }</code><technical_language>optimize this a bit modifying this build set of product IDs, issue update statement (and disregarding request drop IN query below). aware of IN operator limit well</technical_language>

Target:
public void regenerateCertificatesOf(Collection<Owner> owners, Collection<Product> products, boolean lazy) { List<Pool> pools = new LinkedList<Pool>(); Set<String> productIds = new HashSet<String>(); Date now = new Date(); for (Product product : products) { productIds.add(product.getId()); } for (Owner owner : owners) { if (lazy) { poolCurator.markCertificatesDirtyForPoolsWithProducts(owner, productIds); } else { pools.addAll( this.poolCurator.listAvailableEntitlementPools(null, owner, productIds, now) ); } } for (Pool pool : pools) { this.regenerateCertificatesOf(pool.getEntitlements(), lazy); } }
Source:
<code>default boolean containsStream(UUID stream) { <START> return getBackpointerMap().keySet().contains(stream); <END> }</code><technical_language>a getBackpointerMap().containsKey(stream)</technical_language>

Target:
default boolean containsStream(UUID stream) { return getBackpointerMap().containsKey(stream); }
Source:
<code>public <D> D getDocumentAsType(Class<D> docType) { <START> D doc = null; <END> if(row.has("doc") && !row.has("error")) { doc = gson.fromJson(row.get("doc"), docType); } return doc; }</code><technical_language>If returning null need com.cloudant.client.internal.views.ViewResponseImpl#getDocsAs perform a null check adding list too</technical_language>

Target:
public <D> D getDocumentAsType(Class<D> docType) { D doc = null; if(row.has("doc")) { doc = gson.fromJson(row.get("doc"), docType); } return doc; }
Source:
<code>public FilterMultiJoinMergeRule(RelBuilderFactory relBuilderFactory) { <START> super( <END> operand(LogicalFilter.class, operand(MultiJoin.class, any())), relBuilderFactory, null); }</code><technical_language>I is telescoping constructor pattern here</technical_language>

Target:
public FilterMultiJoinMergeRule(RelBuilderFactory relBuilderFactory) { this(LogicalFilter.class, relBuilderFactory); }
Source:
<code>public void updateAlertInTree(Alert originalAlert, Alert alert) { if (Constant.isLowMemoryOptionSet()) { return; } <START> if (EventQueue.isDispatchThread()) { <END> updateAlertInTreeEventHandler(originalAlert, alert); } else { try { EventQueue.invokeAndWait(new Runnable() { @Override public void run() { updateAlertInTreeEventHandler(originalAlert, alert); } }); } catch (Exception e) { logger.error(e.getMessage(), e); } } }</code><technical_language>do this if view (e.g. getView() == null)</technical_language>

Target:
public void updateAlertInTree(Alert originalAlert, Alert alert) { if (Constant.isLowMemoryOptionSet()) { return; } this.getTreeModel().updatePath(originalAlert, alert); if (isInFilter(alert)) { this.getFilteredTreeModel().updatePath(originalAlert, alert); } this.recalcAlerts(); if (View.isInitialised()) { JTree alertTree = this.getAlertPanel().getTreeAlert(); TreePath alertPath = new TreePath(getTreeModel().getAlertNode(alert).getPath()); alertTree.setSelectionPath(alertPath); alertTree.scrollPathToVisible(alertPath); } }
Source:
<code>public void run() { try { Injector injector = makeInjector(); try { final Lifecycle lifecycle = initLifecycle(injector); Runtime.getRuntime().addShutdownHook( new Thread( new Runnable() { @Override public void run() { log.info("Running shutdown hook"); lifecycle.stop(); } } ) ); injector.getInstance(ExecutorLifecycle.class).join(); final Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); for (Thread thread : threadSet) { if (!thread.isDaemon() && thread != Thread.currentThread()) { <START> log.error("Thread [%s] is non daemon and would prevent shutdown! ", thread); <END> } } lifecycle.stop(); } catch (Throwable t) { log.error(t, "Error when starting up. Failing."); System.exit(1); } log.info("Finished peon task"); } catch (Exception e) { throw Throwables.propagate(e); } }</code><technical_language>This scary for users is in fact reporting a scare users. more for developers, right? info debug worded a scarily</technical_language>

Target:
public void run() { try { Injector injector = makeInjector(); try { final Lifecycle lifecycle = initLifecycle(injector); Runtime.getRuntime().addShutdownHook( new Thread( new Runnable() { @Override public void run() { log.info("Running shutdown hook"); lifecycle.stop(); } } ) ); injector.getInstance(ExecutorLifecycle.class).join(); final Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); for (Thread thread : threadSet) { if (!thread.isDaemon() && thread != Thread.currentThread()) { log.info("Thread [%s] is non daemon.", thread); } } lifecycle.stop(); } catch (Throwable t) { log.error(t, "Error when starting up. Failing."); System.exit(1); } log.info("Finished peon task"); } catch (Exception e) { throw Throwables.propagate(e); } }
Source:
<code>private Mac getMacInstance() { <START> int masterKeyLatestHashCode = this.cosmosKeyCredential.getMasterKey().hashCode(); <END> if (masterKeyLatestHashCode != this.masterKeyHashCode) { byte[] masterKeyBytes = this.cosmosKeyCredential.getMasterKey().getBytes(); byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes); SecretKey signingKey = new SecretKeySpec(masterKeyDecodedBytes, "HMACSHA256"); try { Mac macInstance = Mac.getInstance("HMACSHA256"); macInstance.init(signingKey); this.masterKeyHashCode = masterKeyLatestHashCode; return macInstance; } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new IllegalStateException(e); } } else { try { return (Mac)this.macInstance.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException(e); } } }</code><technical_language>evaluating masterkey#hashCode single call. intention is for comparing new hashcode hashcode. String comparison faster hashcode computation. for hashcode computation iteratring chars of string some arithmatic in string comparison comparing chars</technical_language>

Target:
private Mac getMacInstance() { int masterKeyLatestHashCode = this.cosmosKeyCredential.keyHashCode(); if (masterKeyLatestHashCode != this.masterKeyHashCode) { byte[] masterKeyBytes = this.cosmosKeyCredential.key().getBytes(); byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes); SecretKey signingKey = new SecretKeySpec(masterKeyDecodedBytes, "HMACSHA256"); try { Mac macInstance = Mac.getInstance("HMACSHA256"); macInstance.init(signingKey); this.masterKeyHashCode = masterKeyLatestHashCode; return macInstance; } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new IllegalStateException(e); } } else { try { return (Mac)this.macInstance.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException(e); } } }
Source:
<code>public void touch() { <START> log.debug("Stateless bean instance has been touched"); <END> }</code><technical_language>log.trace</technical_language>

Target:
public void touch() { log.trace("Stateless bean instance has been touched"); }
Source:
<code>public void testRenderPage() { final String page1Content = "Page 1 content."; Page p1 = createPage("/a/b", page1Content); final String page2Content = "Page 2 content."; Page p2 = createPage("/x/y", page2Content); Component cmp = new Component("cmp", null, "/cmp", ImmutableSortedSet.of(p1, p2), emptySet(), emptySet(), emptySet(), null); Component rootComponent = new Component("root", null, Component.ROOT_COMPONENT_CONTEXT_PATH, emptySortedSet(), <START> emptySet(), emptySet(), singleton(cmp), null); <END> Configuration configuration = createConfiguration(); PluginProvider pluginProvider = mock(PluginProvider.class); when(pluginProvider.getPluginInstance(SessionManager.class, configuration.getSessionManager(), this.getClass().getClassLoader())).thenReturn(new InMemorySessionManager()); App app = new App(null, "/test", ImmutableSet.of(cmp, rootComponent), emptySet(), createConfiguration(), null, null, pluginProvider); String html = app.renderPage(createRequest(app.getContextPath(), "/cmp/a/b"), null); Assert.assertEquals(html, page1Content); html = app.renderPage(createRequest(app.getContextPath(), "/cmp/x/y"), null); Assert.assertEquals(html, page2Content); }</code><technical_language>this block is repeated, move this a method</technical_language>

Target:
public void testRenderPage() { final String page1Content = "Page 1 content."; Page p1 = createPage("/a/b", page1Content); final String page2Content = "Page 2 content."; Page p2 = createPage("/x/y", page2Content); Component cmp = new Component("cmp", null, "/cmp", ImmutableSortedSet.of(p1, p2), emptySet(), emptySet(), emptySet(), null); Component rootComponent = new Component("root", null, Component.ROOT_COMPONENT_CONTEXT_PATH, emptySortedSet(), emptySet(), emptySet(), singleton(cmp), null); Configuration configuration = createConfiguration(); SessionManager sessionManager = mock(SessionManager.class); App app = new App(null, "/test", ImmutableSet.of(cmp, rootComponent), emptySet(), configuration, null, null, sessionManager); String html = app.renderPage(createRequest(app.getContextPath(), "/cmp/a/b"), null); Assert.assertEquals(html, page1Content); html = app.renderPage(createRequest(app.getContextPath(), "/cmp/x/y"), null); Assert.assertEquals(html, page2Content); }