auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public MutableMessageHeaders(@Nullable Map<String, Object> headers) { <START> super(headers, null, headers != null ? (Long) headers.get(MessageHeaders.TIMESTAMP) : null); <END> if (headers!=null && headers.containsKey(MessageHeaders.ID)) { Object uuid = headers.get(MessageHeaders.ID); if (uuid instanceof String) { this.put(MessageHeaders.ID, UUID.fromString((String) uuid)); } else { this.put(MessageHeaders.ID, (UUID) uuid); } } }</code><technical_language>This is change. super ctor: if (id == null) { this.headers.put(ID, getIdGenerator().generateId()); } If inbound headers id, do call generateId(). this change coming issue. I suggest is static methods extract id timestamp delegate super avoid regeneration. Right, timestamp String is hard call Long.parseLong() matter</technical_language>

Target:
public MutableMessageHeaders(@Nullable Map<String, Object> headers) { super(headers, MutableMessageHeaders.extractId(headers), MutableMessageHeaders.extractTimestamp(headers)); }
Source:
<code>public List<DataPartition> findMatchingPartitions(FileFilter filter) throws HpccFileException { createDataParts(); List<DataPartition> matchedPartitions = this.partitionProcessor.findMatchingPartitions(filter); <START> for (DataPartition partition : matchedPartitions) <END> { partition.setFilter(filter); } return matchedPartitions; }</code><technical_language>is worthwhile forego loop if filter == null? if drop filter if applicable (based invalid field)</technical_language>

Target:
public List<DataPartition> findMatchingPartitions(FileFilter filter) throws HpccFileException { createDataParts(); List<DataPartition> matchedPartitions = this.partitionProcessor.findMatchingPartitions(filter); return matchedPartitions; }
Source:
<code>protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitCallExpr(@NotNull GoCallExpr o) { PsiReference psiReference = o.getExpression().getReference(); PsiElement resolved = psiReference != null ? psiReference.resolve() : null; if (!(resolved instanceof GoFunctionOrMethodDeclaration)) return; String functionName = ((GoFunctionOrMethodDeclaration)resolved).getName(); <START> if (functionName == null) return; <END> functionName = StringUtil.toLowerCase(functionName); GoPlaceholderChecker checker = new GoPlaceholderChecker(holder, o, (GoFunctionOrMethodDeclaration)resolved); if (FORMATTING_FUNCTIONS.containsKey(functionName)) { checker.checkPrintf(); } else if (PRINT_FUNCTIONS.contains(functionName)) { checker.checkPrint(); } } }; }</code><technical_language>toLowerCase return null for null argument, needed check function name here, check avoid variable reassignments</technical_language>

Target:
protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitCallExpr(@NotNull GoCallExpr o) { PsiReference psiReference = o.getExpression().getReference(); PsiElement resolved = psiReference != null ? psiReference.resolve() : null; if (!(resolved instanceof GoFunctionOrMethodDeclaration)) return; String functionName = StringUtil.toLowerCase(((GoFunctionOrMethodDeclaration)resolved).getName()); if (functionName == null) return; if (GoPlaceholderChecker.isFormattingFunction(functionName)) { checkPrintf(holder, o, (GoFunctionOrMethodDeclaration)resolved); } else if (GoPlaceholderChecker.isPrintingFunction(functionName)) { checkPrint(holder, o, (GoFunctionOrMethodDeclaration)resolved); } } }; }
Source:
<code>private void removeFromCache(Set<IResource> toRemove) { Set<IContainer> dirtyLeafContainers = new HashSet<>(); for (IResource resource : toRemove) { final IContainer <START> initialContainer = <END> resource instanceof IContainer ? (IContainer) resource : resource.getParent(); dirtyLeafContainers .removeIf(leafContainer -> leafContainer.getLocation().isPrefixOf(initialContainer.getLocation())); if (dirtyLeafContainers.stream().noneMatch( leafContainer -> initialContainer.getLocation().isPrefixOf(leafContainer.getLocation()))) { dirtyLeafContainers.add(initialContainer); } if (resource.getType() == IResource.FILE) { cache.remove(resource); modifiedSeveritySinceLastRun.add(resource); } IContainer container = initialContainer; while (container != null && cache.containsKey(container)) { cache.remove(container); modifiedSeveritySinceLastRun.add(container); container = getParentInView(container); } } dirtyLeafContainers.forEach(leafContainer -> { IContainer container = leafContainer; while (container != null) { int severity = getMaxChildrenSeverityInCache(container); if (severity >= 0) { propagateSeverityToCache(container, severity); } container = getParentInView(container); } }); }</code><technical_language>workspace root deleted resource return null</technical_language>

Target:
private void removeFromCache(Set<IResource> toRemove) { Set<IContainer> dirtyLeafContainers = new HashSet<>(); for (IResource resource : toRemove) { final IContainer currentContainer = resource instanceof IContainer ? (IContainer) resource : resource.getParent(); if (currentContainer == null) { continue; } IPath currentLocation = currentContainer.getLocation(); if (currentLocation == null) { continue; } dirtyLeafContainers .removeIf(leafContainer -> { IPath leafLocation = leafContainer.getLocation(); return leafLocation != null && leafLocation.isPrefixOf(currentLocation); }); if (dirtyLeafContainers.stream().noneMatch( leafContainer -> { IPath leafLocation = leafContainer.getLocation(); return leafLocation != null && currentLocation.isPrefixOf(leafLocation); })) { dirtyLeafContainers.add(currentContainer); } if (resource.getType() == IResource.FILE) { cache.remove(resource); modifiedSeveritySinceLastRun.add(resource); } IContainer container = currentContainer; while (container != null && cache.containsKey(container)) { cache.remove(container); modifiedSeveritySinceLastRun.add(container); container = getParentInView(container); } } dirtyLeafContainers.forEach(leafContainer -> { IContainer container = leafContainer; while (container != null) { int severity = getMaxChildrenSeverityInCache(container); if (severity >= 0) { propagateSeverityToCache(container, severity); } container = getParentInView(container); } }); }
Source:
<code>public boolean equals(final Object other) { if (this == other) { return true; } if (other == null) { return false; } <START> if (this.getClass() != other.getClass()) { <END> return false; } Interval that = (Interval)other; return (this.compareTo(that) == 0); }</code><technical_language>This is another problems. @lbergelson done a lot of refactoring pull interval/region-like methods out a single class; do changing Interval.equals() accept subclasses</technical_language>

Target:
public boolean equals(final Object other) { if (this == other) return true; if (other == null) return false; if (this.getClass() != other.getClass()) return false; Interval that = (Interval)other; return (this.compareTo(that) == 0); }
Source:
<code><START> @Override public void onPartitionsRevoked(Collection<TopicPartition> partitions) { <END> log.debug("controlLoop partitions revoked"); try { Map<TopicPartition, OffsetAndMetadata> removedOffsetData = acknowlegmentHandler.removePartitions(partitions); for (TopicPartition partition : partitions) { flowControl.remove(partition); } kafkaConsumer.commitSync(removedOffsetData); } catch (InterruptedException e) { log.debug("controlLoop partition rebalance interrupted", e); Thread.currentThread().interrupt(); } }</code><technical_language>A weird inline @Override in class (or else)</technical_language>

Target:
public void onPartitionsRevoked(Collection<TopicPartition> partitions) { log.debug("controlLoop partitions revoked"); try { Map<TopicPartition, OffsetAndMetadata> removedOffsets = acknowledgmentHandler.removePartitions(partitions); for (TopicPartition partition : partitions) { flowControl.remove(partition); } kafkaConsumer.commitSync(removedOffsets); } catch (InterruptedException e) { log.debug("controlLoop partition rebalance interrupted", e); Thread.currentThread().interrupt(); } }
Source:
<code>private void assembleInheritance( List<ModelData> lineage, ModelBuildingRequest request, ModelProblemCollector problems ) { <START> for ( int i = lineage.size() - 2; i >= 1; i-- ) <END> { Model parent = lineage.get( i + 1 ).getModel(); Model child = lineage.get( i ).getModel(); inheritanceAssembler.assembleModelInheritance( child, parent, request, problems ); } if ( Boolean.getBoolean( "maven.experimental.buildconsumer" ) && request.isTransformPom() ) { try { Model parent = lineage.get( 1 ).getModel(); Model child = modelProcessor.read( transformData( lineage.get( 0 ) ), null ); inheritanceAssembler.assembleModelInheritance( child, parent, request, problems ); child.setPomFile( lineage.get( 0 ).getModel().getPomFile() ); lineage.get( 0 ).setModel( child ); } catch ( IOException | TransformException | SAXException | ParserConfigurationException e ) { e.printStackTrace(); } } else { Model parent = lineage.get( 1 ).getModel(); Model child = lineage.get( 0 ).getModel(); inheritanceAssembler.assembleModelInheritance( child, parent, request, problems ); } }</code><technical_language>this change existing code</technical_language>

Target:
private void assembleInheritance( List<ModelData> lineage, ModelBuildingRequest request, ModelProblemCollector problems ) { for ( int i = lineage.size() - 2; i >= 0; i-- ) { Model parent = lineage.get( i + 1 ).getModel(); Model child = lineage.get( i ).getModel(); inheritanceAssembler.assembleModelInheritance( child, parent, request, problems ); } }
Source:
<code>public void visit(LwM2mResourceInstance instance) { LOG.trace("Encoding resource instance into JSON", instance); if (!requestPath.isResourceInstance()) { throw new CodecException("Invalid request path %s for JSON resource instance encoding", requestPath); } <START> baseName = new LwM2mPath(requestPath.getObjectId(), <END> requestPath.getObjectInstanceId(), requestPath.getResourceId()).toString(); ResourceModel rSpec = model.getResourceModel(objectId, instance.getId()); Type expectedType = rSpec != null ? rSpec.type : instance.getType(); JsonArrayEntry jsonArrayEntry = resourceElement(new LwM2mPath(instance.getId()).toString(), timestamp, instance.getType(), expectedType, instance.getValue()); resourceList = new ArrayList<>(); resourceList.add(jsonArrayEntry); }</code><technical_language>baseName = requestPath; null calling resourceElement</technical_language>

Target:
public void visit(LwM2mResourceInstance instance) { LOG.trace("Encoding resource instance into JSON", instance); if (!requestPath.isResourceInstance()) { throw new CodecException("Invalid request path %s for JSON resource instance encoding", requestPath); } baseName = requestPath.toString(); ResourceModel rSpec = model.getResourceModel(objectId, instance.getId()); Type expectedType = rSpec != null ? rSpec.type : instance.getType(); JsonArrayEntry jsonArrayEntry = createJsonArrayEntry(null, timestamp, instance.getType(), expectedType, instance.getValue()); resourceList = new ArrayList<>(); resourceList.add(jsonArrayEntry); }
Source:
<code>protected void startBackgroundDiscovery() { <START> for (MDNSDiscoveryParticipant participant : participants) { <END> mdnsClient.addServiceListener(participant.getServiceType(), this); } }</code><technical_language>background discovery do initial scan anymore</technical_language>

Target:
protected void startBackgroundDiscovery() { for (MDNSDiscoveryParticipant participant : participants) { mdnsClient.addServiceListener(participant.getServiceType(), this); } startScan(); }
Source:
<code>private FeedbackResultsQuestionDetails createQuestionDetails( int questionIndex, FeedbackQuestionAttributes question, FeedbackQuestionDetails questionDetailsBundle, List<FeedbackResponseAttributes> responsesBundle) { String questionText = questionDetailsBundle.questionText; String additionalInfo = questionDetailsBundle.getQuestionAdditionalInfoHtml(questionIndex, ""); <START> String studentEmail; <END> try { studentEmail = this.student.email; } catch (NullPointerException e) { studentEmail = null; } String questionResultStatistics = questionDetailsBundle.getQuestionResultStatisticsHtml( responsesBundle, question, studentEmail, bundle, "student"); boolean isIndividualResponsesShownToStudents = questionDetailsBundle.isIndividualResponsesShownToStudents(); return new FeedbackResultsQuestionDetails(Integer.toString(questionIndex), questionText, additionalInfo, questionResultStatistics, isIndividualResponsesShownToStudents); }</code><technical_language>if test for null catch a null pointer exception</technical_language>

Target:
private FeedbackResultsQuestionDetails createQuestionDetails( int questionIndex, FeedbackQuestionAttributes question, FeedbackQuestionDetails questionDetailsBundle, List<FeedbackResponseAttributes> responsesBundle) { String questionText = questionDetailsBundle.questionText; String additionalInfo = questionDetailsBundle.getQuestionAdditionalInfoHtml(questionIndex, ""); String studentEmail = (student != null) ? student.email : null; String questionResultStatistics = questionDetailsBundle.getQuestionResultStatisticsHtml( responsesBundle, question, studentEmail, bundle, "student"); boolean isIndividualResponsesShownToStudents = questionDetailsBundle.isIndividualResponsesShownToStudents(); return new FeedbackResultsQuestionDetails(Integer.toString(questionIndex), questionText, additionalInfo, questionResultStatistics, isIndividualResponsesShownToStudents); }
Source:
<code>private boolean correctStorageDomainFormat() { final Set<StorageFormatType> supportedStorageFormats = getSupportedStorageFormatSet(getVds().getvds_group_compatibility_version()); final StorageFormatType storageFormat = getStorageDomain().getStorageFormat(); <START> final StorageType storageType = getStorageDomain().getstorage_type(); <END> if (!supportedStorageFormats.contains(storageFormat)) { return false; } if ((storageFormat == StorageFormatType.V2) && (storageType != StorageType.ISCSI) && (storageType != StorageType.FCP)) { return false; } return true; }</code><technical_language>storageType initialized if command is for storage type V2</technical_language>

Target:
private boolean correctStorageDomainFormat() { final Set<StorageFormatType> supportedStorageFormats = getSupportedStorageFormatSet(getVds().getvds_group_compatibility_version()); final StorageFormatType storageFormat = getStorageDomain().getStorageFormat(); if (!supportedStorageFormats.contains(storageFormat)) { return false; } if (storageFormat == StorageFormatType.V2) { final StorageType storageType = getStorageDomain().getstorage_type(); if (storageType != StorageType.ISCSI && storageType != StorageType.FCP) { return false } } return true; }
Source:
<code>protected List<Field> createFields(HttpServletRequest request, boolean retainPassword) { List<Field> fields = new ArrayList<>(); for (Field templateField : formFields) { Field clone = templateField.copy(); if (clone.isEnabled()) { String val = fieldValueResolver.getValue(request, clone.getName()); if (clone.getName().equals("password") && retainPassword) { clone.setValue(val); } else { clone.setValue(val); } String label = i18n(request, clone.getLabel()); <START> if (!label.startsWith("!")) { <END> ((DefaultField) clone).setLabel(label); } String placeholder = i18n(request, clone.getPlaceholder()); if (!placeholder.startsWith("!")) { ((DefaultField) clone).setPlaceholder(placeholder); } fields.add(clone); } } return fields; }</code><technical_language>change message source accept a default hide this logic away</technical_language>

Target:
protected List<Field> createFields(HttpServletRequest request, boolean retainPassword) { List<Field> fields = new ArrayList<>(); for (Field templateField : formFields) { Field clone = templateField.copy(); if (clone.isEnabled()) { String val = fieldValueResolver.getValue(request, clone.getName()); if (retainPassword && "password".equals(clone.getName())) { clone.setValue(val); } else { clone.setValue(val); } ((DefaultField) clone).setLabel(i18n(request, clone.getLabel(), clone.getLabel())); ((DefaultField) clone).setPlaceholder(i18n(request, clone.getPlaceholder(), clone.getPlaceholder())); fields.add(clone); } } return fields; }
Source:
<code>public synchronized void close() { if (closed) { return; } <START> closed = true; <END> log.info("Firehose closing."); Uninterruptibles.putUninterruptibly(buffer, FIREHOSE_CLOSED); eventReceiverFirehoseRegister.unregister(serviceName); if (chatHandlerProvider != null) { chatHandlerProvider.unregister(serviceName); } Thread delayedCloseExecutor = this.delayedCloseExecutor; if (delayedCloseExecutor != null && !delayedCloseExecutor.equals(Thread.currentThread())) { delayedCloseExecutor.interrupt(); } }</code><technical_language>do closed = true right synchronized block end (in case of exception)</technical_language>

Target:
public synchronized void close() { if (closed) { return; } closed = true; log.info("Firehose closing."); Uninterruptibles.putUninterruptibly(buffer, FIREHOSE_CLOSED); eventReceiverFirehoseRegister.unregister(serviceName); if (chatHandlerProvider != null) { chatHandlerProvider.unregister(serviceName); } if (delayedCloseExecutor != null && !delayedCloseExecutor.equals(Thread.currentThread())) { delayedCloseExecutor.interrupt(); } }
Source:
<code>public static <T> Predicate<T> instantiatePredicateClass(Class<? extends Predicate<T>> clazz) { try { Constructor<? extends Predicate> c = clazz.getConstructor(); if (c != null) { return c.newInstance(); } else { return null; } } catch (Exception e) { <START> throw new RuntimeException("Unable to create instance of class: " + clazz.getName()); <END> } }</code><technical_language>create a custom InstantiationException is a RuntimeException</technical_language>

Target:
public static <T> Predicate<T> instantiatePredicateClass(Class<? extends Predicate<T>> clazz) { try { Constructor<? extends Predicate> c = clazz.getConstructor(); if (c != null) { return c.newInstance(); } else { return null; } } catch (Exception e) { throw new InstantiationException("Unable to create instance of class: " + clazz.getName(), e); } }
Source:
<code>public void testNopPaddingWithAnnotation() throws Exception { myExpectedException.expect(IonException.class); myExpectedException.expectMessage("Annotations are not allowed for NOP padding"); IonDatagram datagram = loadTestFile("bad/nopPadWithAnnotations.10n"); <START> assertEquals(1, datagram.size()); <END> final IonStruct struct = (IonStruct) datagram.get(0); assertTrue(struct.isEmpty()); }</code><technical_language>code test failed previous line (as expected)? remaining lines testing</technical_language>

Target:
public void testNopPaddingWithAnnotation() throws Exception { myExpectedException.expect(IonException.class); myExpectedException.expectMessage("NOP padding is not allowed within annotation wrappers."); loadTestFile("bad/nopPadWithAnnotations.10n"); }
Source:
<code><START> public void testSingleParentFamily() throws IOException { <END> final IntegrationTestSpec spec = new IntegrationTestSpec( " -O %s" + " -ped " + threeMemberNonTrioFamilyFile + " -V " + getThreeMemberNonTrioTest + " -skipPop", Collections.singletonList(dir + "expectedCGP_testSingleParentFamily.vcf") ); spec.executeTest("testFamilyPriors", this); }</code><technical_language>I remember supposed happen here. I I put in code for posteriors if parent is called, informative for genotype combinations</technical_language>

Target:
public void testSingleParentFamily() throws IOException { final IntegrationTestSpec spec = new IntegrationTestSpec( " -O %s" + " -ped " + threeMemberNonTrioFamilyFile + " -V " + getThreeMemberNonTrioTest + " -skipPop", Collections.singletonList(dir + "expectedCGP_testSingleParentFamily_chr1.vcf") ); spec.executeTest("testFamilyPriors", this); }
Source:
<code>public List<Container> getContainersInTemplate(Template template, User user, boolean respectFrontendRoles) throws DotDataException, DotSecurityException { <START> List<Contentlet> pages = APILocator.getHTMLPageAssetAPI().findPagesByTemplate(template, user, respectFrontendRoles, 100); <END> List<Container> containers = new ArrayList<>(); for (Contentlet page : pages) { Set<String> containerId = MultiTreeFactory.getMultiTrees(page.getIdentifier()) .stream() .map(mtree -> mtree.getContainer()) .collect(Collectors.toSet()); for (String cont : containerId) { Container container = APILocator.getContainerAPI().getWorkingContainerById(cont, user, false); if(container==null) { continue; } containers.add(container); } } return containers; }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') Assign this magic number 100 a well-named constant, constant instead. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
public List<Container> getContainersInTemplate(Template template, User user, boolean respectFrontendRoles) throws DotDataException, DotSecurityException { List<Contentlet> pages = APILocator.getHTMLPageAssetAPI().findPagesByTemplate(template, user, respectFrontendRoles, 100); List<Container> containers = new ArrayList<>(); for (Contentlet page : pages) { Set<String> containerId = MultiTreeFactory.getMultiTrees(page.getIdentifier()) .stream() .map(MultiTree::getContainer) .collect(Collectors.toSet()); for (String cont : containerId) { Container container = APILocator.getContainerAPI().getWorkingContainerById(cont, user, false); if(container==null) { continue; } containers.add(container); } } return containers; }
Source:
<code>static @Nullable IChartViewer createChart(Composite parent, ChartData data, ChartModel model) { switch (model.getChartType()) { case BAR_CHART: SwtXYChartViewer barChart = new SwtBarChart(parent, data, model); <START> barChart.populate(); <END> return barChart; case SCATTER_CHART: SwtXYChartViewer scatterChart = new SwtScatterChart(parent, data, model); scatterChart.populate(); return scatterChart; case PIE_CHART: default: return null; } }</code><technical_language>fold populate() in constructor</technical_language>

Target:
static @Nullable IChartViewer createChart(Composite parent, ChartData data, ChartModel model) { switch (model.getChartType()) { case BAR_CHART: return new SwtBarChart(parent, data, model); case SCATTER_CHART: return new SwtScatterChart(parent, data, model); case PIE_CHART: default: return null; } }
Source:
<code>public void unsubscribe() { if (unsubscribed) { return; } <START> unsubscribed = true; <END> unsubscribeFromAll(subscriptions); }</code><technical_language>field subscriptions nulled free memory</technical_language>

Target:
public void unsubscribe() { if (unsubscribed) { return; } unsubscribed = true; unsubscribeFromAll(subscriptions); subscriptions = null; }
Source:
<code>protected boolean canDoAction() { <START> if (!super.canDoAction()) { <END> return false; } IscsiBondValidator validator = new IscsiBondValidator(); return validate(validator.isIscsiBondExist(getIscsiBond())); }</code><technical_language>do need check if iSCSI bond is supported if is exists in Data Center</technical_language>

Target:
protected boolean canDoAction() { IscsiBondValidator validator = new IscsiBondValidator(); return validate(validator.isIscsiBondExist(getIscsiBond())); }
Source:
<code><START> public Valid(T value) { <END> this.value = value; }</code><technical_language>Please constructor private (see Invalid)</technical_language>

Target:
private Valid(T value) { this.value = value; }
Source:
<code>private void collectStackFrame(boolean endOfTrace, StackFrame stackFrame) { long methodId = stackFrame.getMethodId(); callCountsByMethodId.onFrameAppearance(methodId, endOfTrace); callCountsByFrame.onFrameAppearance(stackFrame, endOfTrace); if (currentTreeNode == null) { <START> currentTreeNode = treesByThreadId.compute(currentThread, (id, previous) -> <END> { if (previous != null) { return previous.callAgain(); } return new NodeCollector(methodId); }); } else { currentTreeNode = currentTreeNode.newChildCall(methodId); } }</code><technical_language>whitespace/style</technical_language>

Target:
private void collectStackFrame(boolean endOfTrace, StackFrame stackFrame) { long methodId = stackFrame.getMethodId(); callCountsByMethodId.onFrameAppearance(methodId, endOfTrace); callCountsByFrame.onFrameAppearance(stackFrame, endOfTrace); if (currentTreeNode == null) { currentTreeNode = treesByThreadId.compute(currentThread, (id, previous) -> { if (previous != null) return previous.callAgain(); return new NodeCollector(methodId); }); } else { currentTreeNode = currentTreeNode.newChildCall(methodId); } }
Source:
<code>public void run() { ConfigContext config = buildConfig(); try (MantaClient client = new MantaClient(config)) { OutputStream out = System.out; if (inferOutputFileName) { outputFileName = MantaUtils.lastItemInPath(filePath); } if (outputFileName != null) { out = new FileOutputStream(outputFileName); } BufferedOutputStream bout = new BufferedOutputStream(out, 1024); InputStream objectStream = client.getAsInputStream(filePath); int oneByte; <START> while ((oneByte = objectStream.read()) != -1) { <END> bout.write(oneByte); } objectStream.close(); bout.flush(); out.flush(); bout.close(); if (outputFileName != null) { out.close(); } } catch (IOException e) { throw new UncheckedIOException(e); } }</code><technical_language>reason reimplement IOUtils.copy loop for a single byte a time</technical_language>

Target:
public void run() { ConfigContext config = buildConfig(); try (MantaClient client = new MantaClient(config)) { OutputStream out = System.out; if (inferOutputFileName) { outputFileName = MantaUtils.lastItemInPath(filePath); } if (outputFileName != null) { out = new FileOutputStream(outputFileName); } InputStream objectStream = client.getAsInputStream(filePath); IOUtils.copyLarge(objectStream, out); objectStream.close(); out.flush(); if (outputFileName != null) { out.close(); } } catch (IOException e) { throw new UncheckedIOException(e); } }
Source:
<code>public ModuleDeclaration(String name, List imports, List<GenericParameter> generics, List<NameBindingImpl> args, TypedAST inner, NamedType type, FileLocation location, boolean isResource, boolean isAnnotated, String effects) { this.name = name; this.inner = inner; this.location = location; this.resourceFlag = isResource; ascribedType = type; this.args = args; this.imports = imports; this.generics = generics; this.isAnnotated = isAnnotated; this.effectSet = EffectSet.parseEffects(name, effects, false, location); if (args.isEmpty() && imports.isEmpty() && this.effectSet != null && !this.effectSet.getEffects().isEmpty()) { <START> ToolError.reportError(ErrorMessage.PURE_MODULE_ANNOTATION, FileLocation.UNKNOWN); <END> } }</code><technical_language>FileLocation.UNKNOWN if it. location</technical_language>

Target:
public ModuleDeclaration(String name, List imports, List<GenericParameter> generics, List<NameBindingImpl> args, TypedAST inner, NamedType type, FileLocation location, boolean isResource, boolean isAnnotated, String effects) { this.name = name; this.inner = inner; this.location = location; this.resourceFlag = isResource; ascribedType = type; this.args = args; this.imports = imports; this.generics = generics; this.isAnnotated = isAnnotated; this.effectSet = EffectSet.parseEffects(name, effects, false, location); if (args.isEmpty() && imports.isEmpty() && this.effectSet != null && !this.effectSet.getEffects().isEmpty()) { ToolError.reportError(ErrorMessage.PURE_MODULE_ANNOTATION, location); } }
Source:
<code>public void asyncTryReadLastConfirmed(final ReadLastConfirmedCallback cb, final Object ctx) { if (clientCtx.getConf().useExplicitLacForReads) { asyncTryReadExplicitLastConfirmed(cb, ctx); } else { <START> asyncTryReadLastConfirmedInternal(cb, ctx); <END> } }</code><technical_language>name is consistent asyncReadPiggybackLastConfirmed</technical_language>

Target:
public void asyncTryReadLastConfirmed(final ReadLastConfirmedCallback cb, final Object ctx) { if (clientCtx.getConf().useExplicitLacForReads) { asyncTryReadExplicitLastConfirmed(cb, ctx); } else { asyncTryReadPiggybackLastConfirmed(cb, ctx); } }
Source:
<code>private void close_sub() { Options.saveOptions(); UI.getCursor().reset(); InternalTextureLoader.get().clear(); GameImage.clearReferences(); GameData.Grade.clearReferences(); Beatmap.clearBackgroundImageCache(); MusicController.reset(); SoundController.stopTrack(); BeatmapGroup.set(BeatmapGroup.ALL); BeatmapSortOrder.set(BeatmapSortOrder.TITLE); if (BeatmapSetList.get() != null) BeatmapSetList.get().reset(); CurveRenderState.shutdown(); LegacyCurveRenderState.shutdown(); if (!Options.isWatchServiceEnabled()) BeatmapWatchService.destroy(); BeatmapWatchService.removeListeners(); Utils.deleteDirectory(Options.TEMP_DIR); <START> Log.info("opsu! is closing"); <END> }</code><technical_language>Remove</technical_language>

Target:
private void close_sub() { Options.saveOptions(); UI.getCursor().reset(); InternalTextureLoader.get().clear(); GameImage.clearReferences(); GameData.Grade.clearReferences(); Beatmap.clearBackgroundImageCache(); MusicController.reset(); SoundController.stopTrack(); BeatmapGroup.set(BeatmapGroup.ALL); BeatmapSortOrder.set(BeatmapSortOrder.TITLE); if (BeatmapSetList.get() != null) BeatmapSetList.get().reset(); CurveRenderState.shutdown(); LegacyCurveRenderState.shutdown(); if (!Options.isWatchServiceEnabled()) BeatmapWatchService.destroy(); BeatmapWatchService.removeListeners(); Utils.deleteDirectory(Options.TEMP_DIR); }
Source:
<code>public void testMakeCellRenderContextThreeRows() { final double headerRowsHeight = 100.0; final BaseGridRow row1 = new BaseGridRow(); final BaseGridRow row2 = new BaseGridRow(); final BaseGridRow row3 = new BaseGridRow(); final List<GridColumn<?>> allColumns = new ArrayList<>(); <START> final List<Double> allRowHeights = new ArrayList<>(Collections.nCopies(3, row1.getHeight())); <END> final GridColumn<?> uiColumn1 = mockGridColumn(25.0); final GridColumn<?> uiColumn2 = mockGridColumn(60.0); final GridColumn<?> uiColumn3 = mockGridColumn(100.0); allColumns.add(uiColumn1); allColumns.add(uiColumn2); allColumns.add(uiColumn3); gridWidget.getModel().appendRow(row1); gridWidget.getModel().appendRow(row2); gridWidget.getModel().appendRow(row3); doReturn(allColumns).when(ri).getAllColumns(); doReturn(headerRowsHeight).when(ri).getHeaderRowsHeight(); doReturn(allRowHeights).when(ri).getAllRowHeights(); doReturn(uiColumn3).when(ci).getColumn(); doReturn(25.0).when(ci).getOffsetX(); doReturn(3).when(ci).getUiColumnIndex(); final GridBodyCellEditContext context = CellContextUtilities.makeCellRenderContext(gridWidget, ri, ci, 2); assertNotNull(context); assertThat(context.getAbsoluteCellX()) .as("Should be column offset") .isEqualTo(25.0); assertThat(context.getAbsoluteCellY()) .as("Should be sum of header height plus preceding row heights") .isEqualTo(headerRowsHeight + row1.getHeight() + row2.getHeight()); }</code><technical_language>Please Collections.singletonList(row.getHeight()), I do change number of elements in allRowHeights test</technical_language>

Target:
public void testMakeCellRenderContextThreeRows() { final double headerRowsHeight = 100.0; final BaseGridRow row1 = new BaseGridRow(); final BaseGridRow row2 = new BaseGridRow(); final BaseGridRow row3 = new BaseGridRow(); final List<GridColumn<?>> allColumns = new ArrayList<>(); final List<Double> allRowHeights = Collections.nCopies(3, row1.getHeight()); final GridColumn<?> uiColumn1 = mockGridColumn(25.0); final GridColumn<?> uiColumn2 = mockGridColumn(60.0); final GridColumn<?> uiColumn3 = mockGridColumn(100.0); allColumns.add(uiColumn1); allColumns.add(uiColumn2); allColumns.add(uiColumn3); gridWidget.getModel().appendRow(row1); gridWidget.getModel().appendRow(row2); gridWidget.getModel().appendRow(row3); doReturn(allColumns).when(ri).getAllColumns(); doReturn(headerRowsHeight).when(ri).getHeaderRowsHeight(); doReturn(allRowHeights).when(ri).getAllRowHeights(); doReturn(uiColumn3).when(ci).getColumn(); doReturn(25.0).when(ci).getOffsetX(); doReturn(3).when(ci).getUiColumnIndex(); final GridBodyCellEditContext context = CellContextUtilities.makeCellRenderContext(gridWidget, ri, ci, 2); assertNotNull(context); assertThat(context.getAbsoluteCellX()) .as("Should be column offset") .isEqualTo(25.0); assertThat(context.getAbsoluteCellY()) .as("Should be sum of header height plus preceding row heights") .isEqualTo(headerRowsHeight + row1.getHeight() + row2.getHeight()); }
Source:
<code>public CoordinateReferenceSystem readPrjToCRS() throws IOException { Resource prj = getPrjFile(); if (prj == null || !Resources.exists(prj)) { return null; } InputStream is = prj.in(); String wkt = IOUtils.toString(is); <START> is.close(); <END> try { return CRS.parseWKT(wkt); } catch (Exception e) { throw (IOException) new IOException().initCause(e); } }</code><technical_language>@NielsCharlier is this a resource leak? Needs a try-with-resource</technical_language>

Target:
public CoordinateReferenceSystem readPrjToCRS() throws IOException { Resource prj = getPrjFile(); if (prj == null || !Resources.exists(prj)) { return null; } try (InputStream is = prj.in()) { return CRS.parseWKT(IOUtils.toString(is)); } catch (Exception e) { throw (IOException) new IOException().initCause(e); } }
Source:
<code><START> public @Nullable Hashtable<String,RangeSet> getUsages() { <END> return usages; }</code><technical_language>use... suggestion public @CheckForNull Hashtable<String,RangeSet> getUsages() { Nullable is a soft requirement trigger warnings in static analysis tools</technical_language>

Target:
public @CheckForNull Hashtable<String,RangeSet> getUsages() { return usages; }
Source:
<code>private boolean hasBundleLocation(Map<String, Object> service, Set<String> bundleLocations) { return Stream.of(service) <START> .filter(m -> m.containsKey("configurations")) <END> .map(m -> m.get("configurations")) .map(List.class::cast) .flatMap(List::stream) .map(Map.class::cast) .filter(m -> m.containsKey("bundle_location")) .map(m -> m.get("bundle_location")) .map(String.class::cast) .anyMatch(bundleLocations::contains); }</code><technical_language>Replace filter() map() .map(m -> m.get("configuration")).filter(Objects::nonNull). This avoid double hashing/searching in map. for "bundle_location"</technical_language>

Target:
private boolean hasBundleLocation(Map<String, Object> service, Set<String> bundleLocations) { return Stream.of(service) .map(m -> m.get("configurations")) .filter(Objects::nonNull) .map(List.class::cast) .flatMap(List::stream) .map(Map.class::cast) .map(m -> m.get("bundle_location")) .filter(Objects::nonNull) .map(String.class::cast) .anyMatch(bundleLocations::contains); }
Source:
<code><START> private static Optional<ExecutableElement> findDefaultBuilder(TypeElement autoValueClass, TypeElement builderClass) { <END> return ElementFilter.methodsIn(autoValueClass.getEnclosedElements()) .stream() .filter(e -> MoreElements.isAnnotationPresent(e, GsonDefaultBuilder.class)) .filter(MoreElements.hasModifiers(Modifier.STATIC)::apply) .filter(e -> MoreTypes.equivalence().equivalent(e.getReturnType(), builderClass.asType())) .filter(e -> e.getParameters().isEmpty()) .findFirst(); }</code><technical_language>Nit: I prefer type + @Nullable Optional implementation details differentiating null absent (that is, sort of "three" implications of Optionals). other find method below</technical_language>

Target:
private static ExecutableElement findDefaultBuilder(TypeElement autoValueClass, TypeElement builderClass) { Set<ExecutableElement> builderMethods = ElementFilter.methodsIn(autoValueClass.getEnclosedElements()) .stream() .filter(MoreElements.hasModifiers(PRIVATE).negate()) .filter(MoreElements.hasModifiers(Modifier.STATIC)) .filter(e -> e.getParameters().isEmpty()) .filter(e -> MoreTypes.equivalence().equivalent(e.getReturnType(), builderClass.asType())) .collect(Collectors.toSet()); if (builderMethods.isEmpty()) { return null; } else if (builderMethods.size() == 1) { return Iterables.getOnlyElement(builderMethods); } else { return builderMethods.stream() .filter(e -> MoreElements.isAnnotationPresent(e, AutoValueGsonBuilder.class)) .findFirst().orElse(null); } }
Source:
<code>private void handleAJAXAction(final HttpServletRequest req, final HttpServletResponse resp, final Session session) throws ServletException, IOException { final HashMap<String, Object> ret = new HashMap<>(); final String ajaxName = getParam(req, "ajax"); if (ajaxName.equals("fetchTrigger")) { if (checkProjectIdAndFlowId(req)) { final int projectId = getIntParam(req, "projectId"); final String flowId = getParam(req, "flowId"); ajaxFetchTrigger(projectId, flowId, session, ret); } } else if (ajaxName.equals("pauseTrigger") || ajaxName.equals("resumeTrigger")) { if (checkProjectIdAndFlowId(req)) { final int projectId = getIntParam(req, "projectId"); <START> final String flowId = getParam(req, "flowId"); <END> final Project project = this.projectManager.getProject(projectId); if (project == null) { ret.put("error", "please specify a valid project id"); } else if (!hasPermission(project, session.getUser(), Type.ADMIN)) { ret.put("error", "Permission denied. Need ADMIN access."); } else { try { if(ajaxName.equals("pauseTrigger")) { this.scheduler.pauseFlowTrigger(projectId, flowId); } else { this.scheduler.resumeFlowTrigger(projectId, flowId); } ret.put("status", "success"); } catch (SchedulerException ex) { ret.put("status", "error"); ret.put("message", ex); } } } } if (ret != null) { this.writeJSON(resp, ret); } }</code><technical_language>Please check if "flowID" is valid not</technical_language>

Target:
private void handleAJAXAction(final HttpServletRequest req, final HttpServletResponse resp, final Session session) throws ServletException, IOException { final HashMap<String, Object> ret = new HashMap<>(); final String ajaxName = getParam(req, "ajax"); if (ajaxName.equals("fetchTrigger")) { if (checkProjectIdAndFlowId(req)) { final int projectId = getIntParam(req, "projectId"); final String flowId = getParam(req, "flowId"); ajaxFetchTrigger(projectId, flowId, session, ret); } } else if (ajaxName.equals("pauseTrigger") || ajaxName.equals("resumeTrigger")) { if (checkProjectIdAndFlowId(req)) { final int projectId = getIntParam(req, "projectId"); final String flowId = getParam(req, "flowId"); final Project project = this.projectManager.getProject(projectId); if (project == null) { ret.put("error", "please specify a valid project id"); } else if (!hasPermission(project, session.getUser(), Type.ADMIN)) { ret.put("error", "Permission denied. Need ADMIN access."); } else { try { if(ajaxName.equals("pauseTrigger")) { this.scheduler.pauseFlowTrigger(projectId, flowId); } else { this.scheduler.resumeFlowTrigger(projectId, flowId); } ret.put("status", "success"); } catch (SchedulerException ex) { ret.put("error", ex.getMessage()); } } } } if (ret != null) { this.writeJSON(resp, ret); } }
Source:
<code>public static String replaceNodeName(Document document, String containerNodeName, String childNodeNameToReplace, String childNodeNameReplacement) throws Exception { <START> final NodeList containerNodes = document.getElementsByTagName(containerNodeName); <END> for (int i = 0; i < containerNodes.getLength(); i ++) { Node containerNode = containerNodes.item(i); final NodeList childNodes = containerNode.getChildNodes(); for (int j = 0; j < childNodes.getLength(); j ++) { Node childNode = childNodes.item(j); if (childNode.getNodeName().equals(childNodeNameToReplace)) { document.renameNode(childNode, null, childNodeNameReplacement); } } } return getString(document); }</code><technical_language>In cleanupNodes do a NPE check like: java if (nodeList != null) { // ... } do here</technical_language>

Target:
public static String replaceNodeName(Document document, String containerNodeName, String childNodeNameToReplace, String childNodeNameReplacement) throws Exception { final NodeList containerNodes = document.getElementsByTagName(containerNodeName); if (containerNodes != null) { for (int i = 0; i < containerNodes.getLength(); i++) { Node containerNode = containerNodes.item(i); final NodeList childNodes = containerNode.getChildNodes(); for (int j = 0; j < childNodes.getLength(); j++) { Node childNode = childNodes.item(j); if (Objects.equals(childNode.getNodeName(), childNodeNameToReplace)) { document.renameNode(childNode, null, childNodeNameReplacement); } } } } return getString(document); }
Source:
<code>public static boolean canApplyExtractionInPost(TopNQuery query) { <START> return query != null <END> && query.getDimensionSpec() != null && query.getDimensionSpec().getExtractionFn() != null && ExtractionFn.ExtractionType.ONE_TO_ONE.equals(query.getDimensionSpec().getExtractionFn().getExtractionType()) && query.getTopNMetricSpec().canBeOptimizedUnordered(); }</code><technical_language>I need check for null here. Precondition.checkNotNull, of instances this is called a null query</technical_language>

Target:
public static boolean canApplyExtractionInPost(TopNQuery query) { return query.getDimensionSpec() != null && query.getDimensionSpec().getExtractionFn() != null && ExtractionFn.ExtractionType.ONE_TO_ONE.equals(query.getDimensionSpec().getExtractionFn().getExtractionType()) && query.getTopNMetricSpec().canBeOptimizedUnordered(); }
Source:
<code>public BioWorkflow initializeWorkflowFromGitHub(String repositoryId, String subclass, String workflowName) { BioWorkflow workflow = (BioWorkflow)initializeWorkflow(repositoryId, new BioWorkflow()); workflow.setWorkflowName(workflowName); workflow.setMode(WorkflowMode.DOCKSTORE_YML); <START> if (Objects.equals(DescriptorLanguage.CWL.getLowerShortName(), subclass)) { <END> workflow.setDescriptorType(DescriptorLanguage.CWL); } else if (Objects.equals(DescriptorLanguage.WDL.getLowerShortName(), subclass)) { workflow.setDescriptorType(DescriptorLanguage.WDL); } else if (Objects.equals(DescriptorLanguage.NEXTFLOW.getLowerShortName(), subclass)) { workflow.setDescriptorType(DescriptorLanguage.NEXTFLOW); } else { LOG.info("Invalid descriptor type " + subclass); } workflow.setDefaultWorkflowPath("/.dockstore.yml"); return workflow; }</code><technical_language><LINK_0> similar need touch this need get Galaxy in too</technical_language>

Target:
public BioWorkflow initializeWorkflowFromGitHub(String repositoryId, String subclass, String workflowName) { BioWorkflow workflow = new BioWorkflow(); workflow.setOrganization(repositoryId.split("/")[0]); workflow.setRepository(repositoryId.split("/")[1]); workflow.setSourceControl(SourceControl.GITHUB); workflow.setGitUrl("git@github.com:" + repositoryId + ".git"); workflow.setLastUpdated(new Date()); workflow.setMode(WorkflowMode.DOCKSTORE_YML); workflow.setWorkflowName(workflowName); DescriptorLanguage descriptorLanguage; try { descriptorLanguage = DescriptorLanguage.convertShortStringToEnum(subclass); workflow.setDescriptorType(descriptorLanguage); } catch (UnsupportedOperationException ex) { String msg = "The given descriptor type is not supported: " + subclass; LOG.info(msg); throw new CustomWebApplicationException(msg, LAMBDA_FAILURE); } workflow.setDefaultWorkflowPath("/.dockstore.yml"); return workflow; }
Source:
<code>public AbstractPartTreeBlazePersistenceQuery(EntityViewAwareJpaQueryMethod method, EntityManager em, PersistenceProvider persistenceProvider, CriteriaBuilderFactory cbf, EntityViewManager evm) { super(method, em); this.cbf = cbf; this.evm = evm; this.entityViewClass = method.getEntityViewClass(); this.domainClass = method.getEntityInformation().getJavaType(); this.tree = new PartTree(method.getName(), domainClass); this.parameters = method.getJpaParameters(); <START> boolean recreateQueries = parameters.potentiallySortsDynamically(); <END> this.query = isCountProjection(tree) ? new AbstractPartTreeBlazePersistenceQuery.CountQueryPreparer(persistenceProvider, recreateQueries) : new AbstractPartTreeBlazePersistenceQuery.QueryPreparer(persistenceProvider, recreateQueries); }</code><technical_language>This boolean recreateQueries = parameters.potentiallySortsDynamically() || parameters.hasOptionalParameters(); no? cached a invocation add optional parameters</technical_language>

Target:
public AbstractPartTreeBlazePersistenceQuery(EntityViewAwareJpaQueryMethod method, EntityManager em, PersistenceProvider persistenceProvider, CriteriaBuilderFactory cbf, EntityViewManager evm) { super(method, em); this.cbf = cbf; this.evm = evm; this.entityViewClass = method.getEntityViewClass(); this.domainClass = method.getEntityInformation().getJavaType(); this.tree = new PartTree(method.getName(), domainClass); this.parameters = method.getJpaParameters(); boolean recreateQueries = parameters.potentiallySortsDynamically() || entityViewClass != null; this.query = isCountProjection(tree) ? new AbstractPartTreeBlazePersistenceQuery.CountQueryPreparer(persistenceProvider, recreateQueries) : new AbstractPartTreeBlazePersistenceQuery.QueryPreparer(persistenceProvider, recreateQueries); }
Source:
<code>public static List<OvfEntityData> getOvfEntities(byte[] tarByte, Guid storageDomainId) { List<OvfEntityData> ovfEntityDataFromTar = new ArrayList<>(); InputStream is = new ByteArrayInputStream(tarByte); Map<String, String> filesFromTar; <START> try (OutMemoryTar memoryTar = new OutMemoryTar(is)) { <END> filesFromTar = memoryTar.unTar(); } catch (IOException e) { throw new RuntimeException(String.format("Exception while getting OVFs files from tar file for domain %s", storageDomainId), e); } for (String fileName : filesFromTar.keySet()) { if (fileName.contains(OVF_FILE_EXT)) { String ovfData = filesFromTar.get(fileName); OvfEntityData ovfEntityData = createOvfEntityData(storageDomainId, ovfData, getVmEntityType(ovfData), getEntityName(ovfData), storageDomainId); ovfEntityDataFromTar.add(ovfEntityData); } } return ovfEntityDataFromTar; }</code><technical_language>please try-with-resources</technical_language>

Target:
public static List<OvfEntityData> getOvfEntities(byte[] tarByte, Guid storageDomainId) { List<OvfEntityData> ovfEntityDataFromTar = new ArrayList<>(); InputStream is = new ByteArrayInputStream(tarByte); Map<String, String> filesFromTar; try (OutMemoryTar memoryTar = new OutMemoryTar(is)) { filesFromTar = memoryTar.unTar(); } catch (IOException e) { throw new RuntimeException(String.format("Exception while getting OVFs files from tar file for domain %s", storageDomainId), e); } for (Entry<String, String> fileEntry : filesFromTar.entrySet()) { if (fileEntry.getKey().endsWith(OVF_FILE_EXT)) { String ovfData = fileEntry.getValue(); OvfEntityData ovfEntityData = createOvfEntityData(storageDomainId, ovfData, getVmEntityType(ovfData), getEntityName(ovfData), storageDomainId); ovfEntityDataFromTar.add(ovfEntityData); } } return ovfEntityDataFromTar; }
Source:
<code>public InfoboxBuilderPage changeHeaderCollapsibilityState(int index) { JavascriptExecutor js = (JavascriptExecutor)driver; headers.get(index).click(); wait.forElementVisible(collapsibilityCheckbox); collapsibilityCheckbox.click(); String script = "return window.getComputedStyle(document" + ".querySelector('.pi-header'),':after').content"; <START> String chevronContent = js.executeScript(script).toString(); <END> if (collapsibilityCheckbox.isSelected()) { Assertion.assertTrue(!chevronContent.isEmpty()); } else { Assertion.assertTrue(chevronContent.isEmpty()); } return this; }</code><technical_language>execute i mentioned</technical_language>

Target:
public InfoboxBuilderPage changeHeaderCollapsibilityState(int index) { JavascriptExecutor js = (JavascriptExecutor)driver; headers.get(index).click(); wait.forElementVisible(collapsibilityCheckbox); collapsibilityCheckbox.click(); String script = "return window.getComputedStyle(document" + ".querySelector('.pi-header'),':after').content"; String chevronContent = js.executeScript(script).toString(); if (collapsibilityCheckbox.isSelected()) { Assertion.assertFalse(chevronContent.isEmpty()); } else { Assertion.assertTrue(chevronContent.isEmpty()); } return this; }