auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private AbstractPlanNode applyOptimization(WindowFunctionPlanNode plan) { AbstractPlanNode child = (plan.getChildCount() > 0) ? plan.getChild(0) : null; if (child == null) { return plan; } if ( ! ( child instanceof OrderByPlanNode ) ) { return plan; } OrderByPlanNode onode = (OrderByPlanNode)child; child = onode.getChild(0); if ( ! ( child instanceof ReceivePlanNode) ) { return plan; } ReceivePlanNode receiveNode = (ReceivePlanNode)child; assert(plan.getChildCount() == 1); assert(receiveNode.getChildCount() == 1); child = receiveNode.getChild(0); if (! ( child instanceof SendPlanNode) ) { return plan; } SendPlanNode sendNode = (SendPlanNode)child; child = sendNode.getChild(0); <START> if (child.getWindowFunctionUsesIndex() != 0) { <END> return plan; } plan.clearChildren(); receiveNode.removeFromGraph(); MergeReceivePlanNode mrnode = new MergeReceivePlanNode(); mrnode.addInlinePlanNode(onode); mrnode.addAndLinkChild(sendNode); plan.addAndLinkChild(mrnode); return plan; }</code><technical_language>Equality 0 is obscure test for this. a defined constant a custom boolean accessor</technical_language>

Target:
private AbstractPlanNode applyOptimization(WindowFunctionPlanNode plan) { assert(plan.getChildCount() == 1); assert(plan.getChild(0) != null); AbstractPlanNode child = plan.getChild(0); assert(child != null); if ( ! ( child instanceof OrderByPlanNode ) ) { return plan; } OrderByPlanNode onode = (OrderByPlanNode)child; child = onode.getChild(0); if ( ! ( child instanceof ReceivePlanNode)) { return plan; } ReceivePlanNode receiveNode = (ReceivePlanNode)child; assert(receiveNode.getChildCount() == 1); child = receiveNode.getChild(0); assert( child instanceof SendPlanNode ); SendPlanNode sendNode = (SendPlanNode)child; child = sendNode.getChild(0); if ( ! ( child instanceof IndexSortablePlanNode)) { return plan; } IndexSortablePlanNode indexed = (IndexSortablePlanNode)child; if (indexed.indexUse().getWindowFunctionUsesIndex() != 0) { return plan; } plan.clearChildren(); receiveNode.removeFromGraph(); MergeReceivePlanNode mrnode = new MergeReceivePlanNode(); mrnode.addInlinePlanNode(onode); mrnode.addAndLinkChild(sendNode); plan.addAndLinkChild(mrnode); return plan; }
Source:
<code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (isEnabled()) { HttpServletRequest httpServletRequest = (HttpServletRequest) request; if (httpServletRequest.getRequestURI().contains("web/wicket") || httpServletRequest.getRequestURI().contains("geoserver/web")) { chain.doFilter(request, response); return; } UrlTransform urlTransform = new UrlTransform( httpServletRequest.getRequestURI(), httpServletRequest.getParameterMap()); String originalRequest = urlTransform.toString(); rules.forEach(rule -> rule.apply(urlTransform)); if (urlTransform.haveChanged()) { Utils.info( LOGGER, "Request '%s' transformed to '%s'.", originalRequest, urlTransform.toString()); chain.doFilter(new RequestWrapper(urlTransform, httpServletRequest), response); } else { <START> chain.doFilter(request, response); <END> } } else { chain.doFilter(request, response); } }</code><technical_language>Code is a bit convoluted 3 places call chain.doFilter... flipped is a single calling doFilter, is active, replaces request wrapper</technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (isEnabled()) { HttpServletRequest httpServletRequest = (HttpServletRequest) request; if (!httpServletRequest.getRequestURI().contains("web/wicket") && !httpServletRequest.getRequestURI().contains("geoserver/web")) { UrlTransform urlTransform = new UrlTransform( httpServletRequest.getRequestURI(), httpServletRequest.getParameterMap()); String originalRequest = urlTransform.toString(); rules.forEach(rule -> rule.apply(urlTransform)); if (urlTransform.haveChanged()) { Utils.info( LOGGER, "Request '%s' transformed to '%s'.", originalRequest, urlTransform.toString()); request = new RequestWrapper(urlTransform, httpServletRequest); } } } chain.doFilter(request, response); }
Source:
<code>public Authentication attemptAuthentication(final HttpServletRequest request, final HttpServletResponse response) throws AuthenticationException, <START> IOException, ServletException { <END> if (proxyReceptorRequest(request)) { logger.debug("Responding to proxy receptor request"); CommonUtils.readAndRespondToProxyReceptorRequest(request, response, this.proxyGrantingTicketStorage); return null; } final boolean serviceTicketRequest = serviceTicketRequest(request, response); final String username = serviceTicketRequest ? CAS_STATEFUL_IDENTIFIER : CAS_STATELESS_IDENTIFIER; String password = obtainArtifact(request); if (password == null) { logger.debug("Failed to obtain an artifact (cas ticket)"); password = ""; } final UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken( username, password); authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); return this.getAuthenticationManager().authenticate(authRequest); }</code><technical_language>Please do changes necessary for this PR. Please PR remove unnecessary changes</technical_language>

Target:
public Authentication attemptAuthentication(final HttpServletRequest request, final HttpServletResponse response) throws AuthenticationException, IOException { if (proxyReceptorRequest(request)) { logger.debug("Responding to proxy receptor request"); CommonUtils.readAndRespondToProxyReceptorRequest(request, response, this.proxyGrantingTicketStorage); return null; } final boolean serviceTicketRequest = serviceTicketRequest(request, response); final String username = serviceTicketRequest ? CAS_STATEFUL_IDENTIFIER : CAS_STATELESS_IDENTIFIER; String password = obtainArtifact(request); if (password == null) { logger.debug("Failed to obtain an artifact (cas ticket)"); password = ""; } final UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken( username, password); authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); return this.getAuthenticationManager().authenticate(authRequest); }
Source:
<code>public void testRecoverReadJobThrowsJobRecoveryExceptionForWrongRequestType() throws SignatureException, IOException, XmlProcessingException { final Ds3Client ds3Client = buildDs3ClientForBulk(); final ModifyJobResponse modifyWriteJobResponse = buildModifyWriteJobResponse(); Mockito.when(ds3Client.modifyJob(Mockito.any(ModifyJobRequest.class))).thenReturn(modifyWriteJobResponse); try { Ds3ClientHelpers.wrap(ds3Client).recoverReadJob(jobId); <START> Assert.fail("Should have failed with a JobRecoveryException before we got here."); <END> } catch (final JobRecoveryException e) { } }</code><technical_language>optionally test expect JobRecoveryException doing: @Test(expect=JobRecoveryException.class) remove try catch clause</technical_language>

Target:
public void testRecoverReadJobThrowsJobRecoveryExceptionForWrongRequestType() throws SignatureException, IOException, XmlProcessingException, JobRecoveryException { final Ds3Client ds3Client = buildDs3ClientForBulk(); final ModifyJobResponse modifyWriteJobResponse = buildModifyWriteJobResponse(); Mockito.when(ds3Client.modifyJob(Mockito.any(ModifyJobRequest.class))).thenReturn(modifyWriteJobResponse); Ds3ClientHelpers.wrap(ds3Client).recoverReadJob(jobId); }
Source:
<code>private LinkedHashMap<String, U> retrieveAll(final boolean readFromSession) { final LinkedHashMap<String, U> profiles = new LinkedHashMap<>(); final Object request = this.context.getRequestAttribute(Pac4jConstants.USER_PROFILES); if (request != null) { if (request instanceof LinkedHashMap) { profiles.putAll((LinkedHashMap<String, U>) request); } if (request instanceof CommonProfile) { <START> profiles.put(((CommonProfile) request).getClientName(), (U) request); <END> } } if (readFromSession) { final Object sessionAttribute = this.context.getSessionAttribute(Pac4jConstants.USER_PROFILES); if (sessionAttribute instanceof LinkedHashMap) { profiles.putAll((LinkedHashMap<String, U>) sessionAttribute); } if (sessionAttribute instanceof CommonProfile) { profiles.put(((CommonProfile) request).getClientName(), (U) sessionAttribute); } } return profiles; }</code><technical_language>In fact, clientName method exist version 1.9 this return null. able infer client name profile id some DEFAULT value</technical_language>

Target:
private LinkedHashMap<String, U> retrieveAll(final boolean readFromSession) { final LinkedHashMap<String, U> profiles = new LinkedHashMap<>(); final Object request = this.context.getRequestAttribute(Pac4jConstants.USER_PROFILES); if (request != null) { if (request instanceof LinkedHashMap) { profiles.putAll((LinkedHashMap<String, U>) request); } if (request instanceof CommonProfile) { profiles.put(retrieveClientName((U) request), (U) request); } } if (readFromSession) { final Object sessionAttribute = this.context.getSessionAttribute(Pac4jConstants.USER_PROFILES); if (sessionAttribute instanceof LinkedHashMap) { profiles.putAll((LinkedHashMap<String, U>) sessionAttribute); } if (sessionAttribute instanceof CommonProfile) { profiles.put(retrieveClientName((U) sessionAttribute), (U) sessionAttribute); } } return profiles; }
Source:
<code>public void createUtilityProject() { UtilityProjectWizard uw = new UtilityProjectWizard(); uw.open(); UtilityProjectFirstPage up = new UtilityProjectFirstPage(uw); up.setProjectName(PROJECT_NAME); if (isJavaLE8() || CDIVersion.equals("1.0")) { up.activateFacet("1.8", "Java"); } else { up.activateFacet("11", "Java"); } uw.finish(); new WaitUntil(new JobIsRunning(), TimePeriod.DEFAULT, false); new WaitWhile(new JobIsRunning(), TimePeriod.LONG); <START> setWorkspaceDefaultJREForJava8(); <END> }</code><technical_language>question above. well</technical_language>

Target:
public void createUtilityProject() { NewMenuWizard pw = new UtilityProjectWizard(); DataModelFacetCreationWizardPage fp = new UtilityProjectFirstPage(pw); createProject(pw, fp); }
Source:
<code>public void waitForNotificationsLoaded() { <START> waitForElementNotPresent("#WallNotifications .subnav > li.notifications-empty"); <END> }</code><technical_language>add this selector UI mapping beginning</technical_language>

Target:
public void waitForNotificationsLoaded() { waitForElementNotPresent(emptyNumberOfUnreadNotifications); }
Source:
<code>public void updateStartingAddress(long newStartingAddress) { <START> dataStore.put(newStartingAddress, STARTING_ADDRESS_RECORD); <END> startingAddress.set(newStartingAddress); }</code><technical_language>log entry trace level</technical_language>

Target:
public void updateStartingAddress(long newStartingAddress) { log.info("Update starting address to: {}", newStartingAddress); dataStore.put(STARTING_ADDRESS_RECORD, newStartingAddress); startingAddress.set(newStartingAddress); }
Source:
<code>private void sendNotification() { <START> if (!RCDevice.isServiceAttached && !RCDevice.messageReceivingInProgress){ <END> Log.d(TAG, "service is not attached"); Intent intent = new Intent(this, RCDevice.class); intent.setAction(RCDevice.ACTION_FCM); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O){ startForegroundService(intent); } else{ startService(intent); } } Log.d(TAG, "sendNotification is called"); }</code><technical_language>prefer expose another state variable RCDevice increases coupling. isServiceInitialized instead</technical_language>

Target:
private void sendNotification() { if (!RCDevice.isServiceAttached && !RCDevice.isServiceInitialized){ Log.d(TAG, "service is not attached"); Intent intent = new Intent(this, RCDevice.class); intent.setAction(RCDevice.ACTION_FCM); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O){ startForegroundService(intent); } else{ startService(intent); } } Log.d(TAG, "sendNotification is called"); }
Source:
<code>public void validateIndices(Pool pool, Pool beforeChange, Collection<ValidationError> errors) throws IOException { refreshPoolElements(pool); Set<String> indices = getAllBadIndices(pool); Set<String> bcIndices = getAllBadIndices(beforeChange); if(indices.size() > bcIndices.size()){ <START> String errorMessage = "Pools may not contain Library Aliquots with indices with 2 or fewer positions of " + <END> "difference, please address the following conflicts: "; indices.removeAll(bcIndices); for (String index : indices){ errorMessage += index + " "; } errors.add(new ValidationError("poolElements", errorMessage)); } }</code><technical_language>near-duplicate indices level is configurable, 2 changed indexChecker.getWarningMismatches()</technical_language>

Target:
public void validateIndices(Pool pool, Pool beforeChange, Collection<ValidationError> errors) throws IOException { refreshPoolElements(pool); Set<String> indices = getAllBadIndices(pool); Set<String> bcIndices = getAllBadIndices(beforeChange); if(indices.size() > bcIndices.size()){ String errorMessage = String.format("Pools may not contain Library Aliquots with indices with %d or " + "fewer positions of difference, please address the following conflicts: ", indexChecker.getWarningMismatches()); indices.removeAll(bcIndices); for (String index : indices){ errorMessage += index + " "; } errors.add(new ValidationError("poolElements", errorMessage)); } }
Source:
<code>public void testUnserializableResponseConvertedToNull() throws Exception { serializer = spy(new XStreamSerializer()); Object successResponse = new Object(); Exception failureResponse = new MockException("This cannot be serialized"); when(serializer.serialize(successResponse, byte[].class)).thenThrow(new SerializationException( "cannot serialize success")); when(serializer.serialize(failureResponse, byte[].class)).thenThrow(new SerializationException( "cannot serialize failure")); connector1 = JGroupsConnector.builder() .localSegment(mockCommandBus1) .channel(channel1) .clusterName(clusterName) .serializer(serializer) .routingStrategy(routingStrategy) .build(); <START> dcb1 = DistributedCommandBus.builder() <END> .commandRouter(connector1) .connector(connector1) .build(); dcb1.subscribe(String.class.getName(), c -> successResponse); dcb1.subscribe(Integer.class.getName(), c -> { throw failureResponse; }); connector1.connect(); FutureCallback<Object, Object> callback = new FutureCallback<>(); dcb1.dispatch(new GenericCommandMessage<>(1), callback); try { callback.getResult(); fail("Expected exception"); } catch (Exception e) { } verify(mockCommandBus1).dispatch(any(CommandMessage.class), isA(CommandCallback.class)); callback = new FutureCallback<>(); dcb1.dispatch(new GenericCommandMessage<>("string"), callback); assertNull(callback.getResult()); }</code><technical_language>nit: dcb1 -> distributedCommandBus1</technical_language>

Target:
public void testUnserializableResponseConvertedToNull() throws Exception { serializer = spy(new XStreamSerializer()); Object successResponse = new Object(); Exception failureResponse = new MockException("This cannot be serialized"); when(serializer.serialize(successResponse, byte[].class)).thenThrow(new SerializationException( "cannot serialize success")); when(serializer.serialize(failureResponse, byte[].class)).thenThrow(new SerializationException( "cannot serialize failure")); connector1 = JGroupsConnector.builder() .localSegment(mockCommandBus1) .channel(channel1) .clusterName(clusterName) .serializer(serializer) .routingStrategy(routingStrategy) .build(); distributedCommandBus1 = DistributedCommandBus.builder() .commandRouter(connector1) .connector(connector1) .build(); distributedCommandBus1.subscribe(String.class.getName(), c -> successResponse); distributedCommandBus1.subscribe(Integer.class.getName(), c -> { throw failureResponse; }); connector1.connect(); FutureCallback<Object, Object> callback = new FutureCallback<>(); distributedCommandBus1.dispatch(new GenericCommandMessage<>(1), callback); try { callback.getResult(); fail("Expected exception"); } catch (Exception e) { } verify(mockCommandBus1).dispatch(any(CommandMessage.class), isA(CommandCallback.class)); callback = new FutureCallback<>(); distributedCommandBus1.dispatch(new GenericCommandMessage<>("string"), callback); assertNull(callback.getResult().getPayload()); }
Source:
<code>private void writeHeadersFrame( final ChannelHandlerContext ctx, Http2HeadersFrame headersFrame, final ChannelPromise promise) { if (isStreamIdValid(headersFrame.stream().id())) { encoder().writeHeaders(ctx, headersFrame.stream().id(), headersFrame.headers(), headersFrame.padding(), headersFrame.isEndStream(), promise); } else { final DefaultHttp2FrameStream stream = (DefaultHttp2FrameStream) headersFrame.stream(); final Http2Connection connection = connection(); final int streamId = connection.local().incrementAndGetNextStreamId(); if (streamId < 0) { promise.setFailure(new Http2NoMoreStreamIdsException()); onHttp2Frame(ctx, new DefaultHttp2GoAwayFrame(connection.isServer() ? Integer.MAX_VALUE : Integer.MAX_VALUE - 1, NO_ERROR.code(), writeAscii(ctx.alloc(), "Stream IDs exhausted on local stream creation"))); return; } stream.id = streamId; Object old = frameStreamToInitializeMap.put(streamId, stream); assert old == null; encoder().writeHeaders(ctx, streamId, headersFrame.headers(), headersFrame.padding(), headersFrame.isEndStream(), promise); if (!promise.isDone()) { numBufferedStreams++; <START> promise.addListener(bufferedStreamsListener); <END> promise.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) { handleHeaderFuture(channelFuture, streamId); } }); } else { handleHeaderFuture(promise, streamId); } } }</code><technical_language>get rid of bufferedStreamsListener now, add numBufferedStreams-- new listener</technical_language>

Target:
private void writeHeadersFrame( final ChannelHandlerContext ctx, Http2HeadersFrame headersFrame, final ChannelPromise promise) { if (isStreamIdValid(headersFrame.stream().id())) { encoder().writeHeaders(ctx, headersFrame.stream().id(), headersFrame.headers(), headersFrame.padding(), headersFrame.isEndStream(), promise); } else { final DefaultHttp2FrameStream stream = (DefaultHttp2FrameStream) headersFrame.stream(); final Http2Connection connection = connection(); final int streamId = connection.local().incrementAndGetNextStreamId(); if (streamId < 0) { promise.setFailure(new Http2NoMoreStreamIdsException()); onHttp2Frame(ctx, new DefaultHttp2GoAwayFrame(connection.isServer() ? Integer.MAX_VALUE : Integer.MAX_VALUE - 1, NO_ERROR.code(), writeAscii(ctx.alloc(), "Stream IDs exhausted on local stream creation"))); return; } stream.id = streamId; Object old = frameStreamToInitializeMap.put(streamId, stream); assert old == null; encoder().writeHeaders(ctx, streamId, headersFrame.headers(), headersFrame.padding(), headersFrame.isEndStream(), promise); if (!promise.isDone()) { numBufferedStreams++; promise.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) { numBufferedStreams--; handleHeaderFuture(channelFuture, streamId); } }); } else { handleHeaderFuture(promise, streamId); } } }
Source:
<code>public void markPullRequestNeedsWork(PullRequestRef pr ) throws StashClientException { String request = MessageFormat.format(API_ONE_PR_NEEDS_WORK, baseUrl, pr.project(), pr.repository(), pr.pullRequestId(), credentials.getUserSlug()); JsonObject json = new JsonObject(); json.put("status","NEEDS_WORK"); put(request, json, <START> MessageFormat.format(PULL_REQUEST_APPROVAL_POST_ERROR_MESSAGE, pr.repository(), pr.pullRequestId())); <END> }</code><technical_language>A custom error message better</technical_language>

Target:
public void markPullRequestNeedsWork(PullRequestRef pr ) throws StashClientException { String request = MessageFormat.format(API_ONE_PR_NEEDS_WORK, baseUrl, pr.project(), pr.repository(), pr.pullRequestId(), credentials.getUserSlug()); JsonObject json = new JsonObject(); json.put("status", "NEEDS_WORK"); put(request, json, MessageFormat .format(PULL_REQUEST_MARK_NEEDS_WORK_PUT_ERROR_MESSAGE, pr.repository(), pr.pullRequestId())); }
Source:
<code>public void testParquetPageSourceSchemaEvolution(int rowCount) throws Exception <START> { <END> List<TestColumn> writeColumns = getTestColumnsSupportedByParquet(); boolean useParquetColumnNames = false; List<TestColumn> readColumns = writeColumns.stream() .map(column -> new TestColumn( column.getName() + "_new", column.getObjectInspector(), column.getWriteValue(), column.getExpectedValue(), column.isPartitionKey())) .collect(toList()); assertThatFileFormat(PARQUET) .withWriteColumns(writeColumns) .withReadColumns(readColumns) .withSession(parquetPageSourceSession) .withRowsCount(rowCount) .isReadableByPageSource(new ParquetPageSourceFactory(TYPE_MANAGER, useParquetColumnNames, HDFS_ENVIRONMENT, STATS)); useParquetColumnNames = true; readColumns = Lists.reverse(writeColumns); assertThatFileFormat(PARQUET) .withWriteColumns(writeColumns) .withReadColumns(readColumns) .withSession(parquetPageSourceSession) .isReadableByPageSource(new ParquetPageSourceFactory(TYPE_MANAGER, useParquetColumnNames, HDFS_ENVIRONMENT, STATS)); }</code><technical_language>reason for removing tests</technical_language>

Target:
public void testParquetPageSourceSchemaEvolution(int rowCount) throws Exception { List<TestColumn> writeColumns = getTestColumnsSupportedByParquet(); List<TestColumn> readColumns = writeColumns.stream() .map(column -> new TestColumn( column.getName() + "_new", column.getObjectInspector(), column.getWriteValue(), column.getExpectedValue(), column.isPartitionKey())) .collect(toList()); assertThatFileFormat(PARQUET) .withWriteColumns(writeColumns) .withReadColumns(readColumns) .withSession(parquetPageSourceSession) .withRowsCount(rowCount) .isReadableByPageSource(new ParquetPageSourceFactory(TYPE_MANAGER, HDFS_ENVIRONMENT, STATS)); readColumns = Lists.reverse(writeColumns); assertThatFileFormat(PARQUET) .withWriteColumns(writeColumns) .withReadColumns(readColumns) .withSession(parquetPageSourceSessionUseName) .isReadableByPageSource(new ParquetPageSourceFactory(TYPE_MANAGER, HDFS_ENVIRONMENT, STATS)); }
Source:
<code>public static List<ProjectRelationship<?, ?>> convertToDetachedRelationships( final Iterable<?> relationships ) { final List<ProjectRelationship<?, ?>> rels = new ArrayList<ProjectRelationship<?, ?>>(); Iterator<?> iterator = relationships.iterator(); while ( iterator.hasNext() ) { final AbstractNeoProjectRelationship<?, ?, ?> rel; Object next = iterator.next(); if ( next instanceof AbstractNeoProjectRelationship ) { rel = ( AbstractNeoProjectRelationship<?, ?, ?>) next; } else if ( next instanceof AbstractNeoProjectRelationship ) { rel = Conversions.toProjectRelationship( ( Relationship ) next ); <START> } <END> else { throw new IllegalArgumentException( "Relationship class " + next.getClass().getCanonicalName() + " cannot be converted to detached relationship." ); } if ( rel != null ) { rels.add( rel.detach() ); } } return rels; }</code><technical_language>Is this else-if dead code? condition initial if() statement</technical_language>

Target:
public static List<ProjectRelationship<?, ?>> convertToDetachedRelationships( final Iterable<?> relationships ) { final List<ProjectRelationship<?, ?>> rels = new ArrayList<ProjectRelationship<?, ?>>(); Iterator<?> iterator = relationships.iterator(); while ( iterator.hasNext() ) { final AbstractNeoProjectRelationship<?, ?, ?> rel; Object next = iterator.next(); if ( next instanceof AbstractNeoProjectRelationship ) { rel = ( AbstractNeoProjectRelationship<?, ?, ?>) next; } else if ( next instanceof Relationship ) { rel = Conversions.toProjectRelationship( ( Relationship ) next ); } else { throw new IllegalArgumentException( "Relationship class " + next.getClass().getCanonicalName() + " cannot be converted to detached relationship." ); } if ( rel != null ) { rels.add( rel.detach() ); } } return rels; }
Source:
<code>public DefaultMockitoSession(Object testClassInstance, Strictness strictness, MockitoLogger logger) { this.testClassInstance = testClassInstance; listener = new UniversalTestListener(strictness, logger); try { <START> Mockito.framework().addListener(listener); <END> } catch (RedundantListenerException e) { Reporter.unfinishedMocking(); } MockitoAnnotations.initMocks(testClassInstance); }</code><technical_language>Eventually wrap this try block in a private method explain itself</technical_language>

Target:
public DefaultMockitoSession(Object testClassInstance, Strictness strictness, MockitoLogger logger) { this.testClassInstance = testClassInstance; listener = new UniversalTestListener(strictness, logger); try { Mockito.framework().addListener(listener); } catch (RedundantListenerException e) { Reporter.unfinishedMockingSession(); } MockitoAnnotations.initMocks(testClassInstance); }
Source:
<code>public boolean isEnableForComponent(Component invoker) { getHttpSessionsPanel(); if (invoker.getName() != null && invoker.getName().equals(HttpSessionsPanel.PANEL_NAME) <START> && (httpSessionsPanel.getSelectedSession() != null)) { <END> this.setEnabled(true); return true; } this.setEnabled(false); return false; }</code><technical_language>Yes, if constant matter (e.g. HttpSessionsPanel.PANEL_NAME.equals(invoker.getName()))</technical_language>

Target:
public boolean isEnableForComponent(Component invoker) { if (HttpSessionsPanel.PANEL_NAME.equals(invoker.getName())) { this.setEnabled(httpSessionsPanel.getSelectedSession() != null); return true; } return false; }
Source:
<code>private static void assertEquals(ICVSFolder mFolder1, ICVSFolder mFolder2) throws CVSException { assertEquals(mFolder1.isCVSFolder(),mFolder2.isCVSFolder()); if (mFolder1.isCVSFolder()) { String root1 = removePassword(mFolder1.getFolderSyncInfo().getRoot()); String root2 = removePassword(mFolder2.getFolderSyncInfo().getRoot()); root1 = root1.substring(0,root1.lastIndexOf("@")); root2 = root2.substring(0,root2.lastIndexOf("@")); assertEquals(root1,root2); assertEquals(mFolder1.getFolderSyncInfo().getRepository(),mFolder2.getFolderSyncInfo().getRepository()); assertEquals(mFolder1.getFolderSyncInfo().getIsStatic(),mFolder2.getFolderSyncInfo().getIsStatic()); assertEquals(mFolder1.getFolderSyncInfo().getTag(),mFolder2.getFolderSyncInfo().getTag()); } ICVSResource[] resourceList1 = mFolder1.members(ICVSFolder.FILE_MEMBERS | ICVSFolder.FOLDER_MEMBERS); ICVSResource[] resourceList2 = mFolder2.members(ICVSFolder.FILE_MEMBERS | ICVSFolder.FOLDER_MEMBERS); assertEquals(resourceList1.length, resourceList2.length); for (ICVSResource <START> resourceList11 : <END> resourceList1) { boolean resourceFound = false; for (ICVSResource resourceList21 : resourceList2) { if (resourceList11.getName().equals(resourceList21.getName())) { assertEquals(resourceList11, resourceList21); resourceFound = true; break; } } assertTrue("Resource " + resourceList11.getName() + " not found in the list", resourceFound); } }</code><technical_language>find name</technical_language>

Target:
private static void assertEquals(ICVSFolder mFolder1, ICVSFolder mFolder2) throws CVSException { assertEquals(mFolder1.isCVSFolder(),mFolder2.isCVSFolder()); if (mFolder1.isCVSFolder()) { String root1 = removePassword(mFolder1.getFolderSyncInfo().getRoot()); String root2 = removePassword(mFolder2.getFolderSyncInfo().getRoot()); root1 = root1.substring(0,root1.lastIndexOf("@")); root2 = root2.substring(0,root2.lastIndexOf("@")); assertEquals(root1,root2); assertEquals(mFolder1.getFolderSyncInfo().getRepository(),mFolder2.getFolderSyncInfo().getRepository()); assertEquals(mFolder1.getFolderSyncInfo().getIsStatic(),mFolder2.getFolderSyncInfo().getIsStatic()); assertEquals(mFolder1.getFolderSyncInfo().getTag(),mFolder2.getFolderSyncInfo().getTag()); } ICVSResource[] resourceList1 = mFolder1.members(ICVSFolder.FILE_MEMBERS | ICVSFolder.FOLDER_MEMBERS); ICVSResource[] resourceList2 = mFolder2.members(ICVSFolder.FILE_MEMBERS | ICVSFolder.FOLDER_MEMBERS); assertEquals(resourceList1.length, resourceList2.length); for (ICVSResource r : resourceList1) { boolean resourceFound = false; for (ICVSResource _r : resourceList2) { if (r.getName().equals(_r.getName())) { assertEquals(r, _r); resourceFound = true; break; } } assertTrue("Resource " + r.getName() + " not found in the list", resourceFound); } }
Source:
<code>protected Collection<String> defaultSuppressionAnnotations() { <START> Collection defaultValues = new ArrayList<String>(); <END> defaultValues.add("java.lang.Deprecated"); return defaultValues; }</code><technical_language>This is a raw type, please a parameterized type (Collection<String>)</technical_language>

Target:
protected Collection<String> defaultSuppressionAnnotations() { Collection<String> defaultValues = new ArrayList<>(); defaultValues.add("java.lang.Deprecated"); return defaultValues; }
Source:
<code>public String getLineContent(Repository repository, int lineNumber) throws IOException { Line line = getLine(lineNumber); if (line == null) return null; ObjectLoader loader = repository.open(getBlob(), Constants.OBJ_BLOB); RawText text = new RawText(loader.getCachedBytes()); <START> return text.getString(lineNumber); <END> }</code><technical_language>a pass encoding</technical_language>

Target:
public String getLineContent(Repository repository, int lineNumber) throws IOException { Line line = getLine(lineNumber); if (line == null) return null; ObjectLoader loader = repository.open(blob, Constants.OBJ_BLOB); byte[] contents; if (loader.isLarge()) contents = IO.readWholeStream(loader.openStream(), (int) loader.getSize()).array(); else contents = loader.getCachedBytes(); return new RawText(contents).getString(lineNumber); }
Source:
<code>public int getModuleState(IModule[] module, IProgressMonitor monitor) { <START> return 0; <END> }</code><technical_language>0 mean? unknown state? a self-explaining constant for stupid reviewers</technical_language>

Target:
public int getModuleState(IModule[] module, IProgressMonitor monitor) { return IServer.STATE_UNKNOWN; }
Source:
<code>public void install() { DownloadResolver resolver = Entities.newDownloader(this); String saveAs = resolver.getFilename(); String expandedInstallDir = getInstallDir() + "/" + resolver.getUnpackedDirectoryName(format("riak-%s", getVersion())); setExpandedInstallDir(expandedInstallDir); OsDetails osDetails = getMachine().getMachineDetails().getOsDetails(); List<String> commands = Lists.newLinkedList(); if (osDetails.isLinux()) { commands.addAll(installLinux(expandedInstallDir)); } else if (osDetails.isMac()) { commands.addAll(installMac(saveAs)); } else if (osDetails.isWindows()) { throw new UnsupportedOperationException("RiakNode not supported on Windows instances"); } else { throw new IllegalStateException("Machine was not detected as linux, mac or windows! Installation does not know how to proceed with " + getMachine() + ". Details: " + getMachine().getMachineDetails().getOsDetails()); } newScript(INSTALLING) <START> .failOnNonZeroResultCode() <END> .body.append(commands) .execute(); }</code><technical_language>required for INSTALLING script, set</technical_language>

Target:
public void install() { DownloadResolver resolver = Entities.newDownloader(this); String saveAs = resolver.getFilename(); String expandedInstallDir = getInstallDir() + "/" + resolver.getUnpackedDirectoryName(format("riak-%s", getVersion())); setExpandedInstallDir(expandedInstallDir); OsDetails osDetails = getMachine().getMachineDetails().getOsDetails(); List<String> commands = Lists.newLinkedList(); if (osDetails.isLinux()) { commands.addAll(installLinux(expandedInstallDir)); } else if (osDetails.isMac()) { commands.addAll(installMac(saveAs)); } else if (osDetails.isWindows()) { throw new UnsupportedOperationException("RiakNode not supported on Windows instances"); } else { throw new IllegalStateException("Machine was not detected as linux, mac or windows! Installation does not know how to proceed with " + getMachine() + ". Details: " + getMachine().getMachineDetails().getOsDetails()); } newScript(INSTALLING) .body.append(commands) .execute(); }
Source:
<code>public List<CourseSignupDAO> findSignupByComponent(final String componentId, final Set<Status> statuses, final Integer year) { return getHibernateTemplate().executeFind(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Query query; LocalDate startYear = null; LocalDate endYear = null; <START> if (null != year) { <END> startYear = FIRST_DAY_OF_ACADEMIC_YEAR.toLocalDate(year); endYear = FIRST_DAY_OF_ACADEMIC_YEAR.toLocalDate(year+1); } StringBuffer querySQL = new StringBuffer(); querySQL.append("select cs from CourseSignupDAO cs " + "inner join fetch cs.components cc " + "where cc.presentationId = :componentId"); if (null != statuses && !statuses.isEmpty()) { querySQL.append(" and cs.status in (:statuses)"); } if (null != year) { querySQL.append(" and cc.starts between :starts and :ends"); } query = session.createQuery(querySQL.toString()); query.setString("componentId", componentId); if (null != statuses && !statuses.isEmpty()) { query.setParameterList("statuses", statuses); } if (null != year) { query.setDate("starts", startYear.toDate()); query.setDate("ends", endYear.toDate()); } return query.list(); } }); }</code><technical_language>a clearer test for year do sql append, date calculations parameter setting</technical_language>

Target:
public List<CourseSignupDAO> findSignupByComponent(final String componentId, final Set<Status> statuses, final Integer year) { return getHibernateTemplate().executeFind(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Query query; LocalDate startYear = null; LocalDate endYear = null; StringBuffer querySQL = new StringBuffer(); querySQL.append("select cs from CourseSignupDAO cs " + "inner join fetch cs.components cc " + "where cc.presentationId = :componentId"); if (null != statuses && !statuses.isEmpty()) { querySQL.append(" and cs.status in (:statuses)"); } if (null != year) { startYear = FIRST_DAY_OF_ACADEMIC_YEAR.toLocalDate(year); endYear = FIRST_DAY_OF_ACADEMIC_YEAR.toLocalDate(year+1); querySQL.append(" and cc.starts between :starts and :ends"); } query = session.createQuery(querySQL.toString()); query.setString("componentId", componentId); if (null != statuses && !statuses.isEmpty()) { query.setParameterList("statuses", statuses); } if (null != year) { query.setDate("starts", startYear.toDate()); query.setDate("ends", endYear.toDate()); } return query.list(); } }); }
Source:
<code>public void test01_03_redirectToExternalLink() { driver.findElement(By.id("listWithExternalPath")).click(); driver.findElement(By.id("btn1")).click(); inputFieldAccessor.overrideValue(By.id("username"), "user1", driver); inputFieldAccessor.overrideValue(By.id("password"), "user1", driver); assertThat( getRedirectValue(), is("<LINK_0>")); screenCapture.save(driver); ApServerName apServerName = webDriverOperations.getApServerName(); String apServerVersion = webDriverOperations.getApServerVersion(); driver.findElement(By.id("btn1")).click(); if (apServerName == ApServerName.WEBSPHERELP && "16".equals(apServerVersion) <START> || apServerName == ApServerName.WEBSPHERETR && "9".equals(apServerVersion)) { <END> assertThat(driver.findElement(By.xpath("/html/body/div/h2")).getText(), is("System Error...")); } else { assertThat(driver.findElement(By.xpath("/html/body/div/h2")).getText(), is("Page Not Found")); } }</code><technical_language>[x] Please remove check apServerVersion. this behavior is depend version of application server</technical_language>

Target:
public void test01_03_redirectToExternalLink() { ApServerName apServerName = webDriverOperations.getApServerName(); driver.findElement(By.id("listWithExternalPath")).click(); driver.findElement(By.id("btn1")).click(); inputFieldAccessor.overrideValue(By.id("username"), "user1", driver); inputFieldAccessor.overrideValue(By.id("password"), "user1", driver); assertThat( getRedirectValue(), is("<LINK_0>")); screenCapture.save(driver); driver.findElement(By.id("btn1")).click(); String expectedErrorMessage; if (apServerName == ApServerName.WEBSPHERELP || apServerName == ApServerName.WEBSPHERETR) { expectedErrorMessage = "System Error..."; } else { expectedErrorMessage = "Page Not Found"; } assertThat(driver.findElement(By.xpath("/html/body/div/h2")).getText(), is(expectedErrorMessage)); }
Source:
<code>public Mono<AccessToken> getToken(TokenRequestContext request) { <START> return identityClient.authenticateWithSharedTokenCache(request, username); <END> }</code><technical_language>authenticateWithSharedTokenCache searches shared token cache for account time. account saved time this method is called authenticateWithMsalAccount called instead</technical_language>

Target:
public Mono<AccessToken> getToken(TokenRequestContext request) { return Mono.defer(() -> { if (cachedToken.get() != null) { return identityClient.authenticateWithMsalAccount(request, cachedToken.get().getAccount()) .onErrorResume(t -> Mono.empty()); } else { return Mono.empty(); } }).switchIfEmpty( Mono.defer(() -> identityClient.authenticateWithSharedTokenCache(request, username))) .map(msalToken -> { cachedToken.set(msalToken); return msalToken; }); }
Source:
<code>public void testFailedReadAheadEviction() throws Exception { AbfsClient client = getMockAbfsClient(); AbfsRestOperation successOp = getMockRestOp(); ReadBufferManager.setThresholdAgeMilliseconds(INCREASED_READ_BUFFER_AGE_THRESHOLD); doThrow(new TimeoutException("Internal Server error")) .when(client) .read(any(String.class), any(Long.class), any(byte[].class), any(Integer.class), any(Integer.class), any(String.class), any(String.class)); AbfsInputStream inputStream = getAbfsInputStream(client, "testFailedReadAheadEviction.txt"); ReadBuffer buff = new ReadBuffer(); buff.setStatus( <START> org.apache.hadoop.fs.azurebfs.contracts.services.ReadBufferStatus.READ_FAILED); <END> ReadBufferManager.getBufferManager().testMimicFullUseAndAddFailedBuffer(buff); ReadBufferManager.getBufferManager().queueReadAhead(inputStream, 0, ONE_KB); }</code><technical_language>import field a full reference</technical_language>

Target:
public void testFailedReadAheadEviction() throws Exception { AbfsClient client = getMockAbfsClient(); AbfsRestOperation successOp = getMockRestOp(); ReadBufferManager.setThresholdAgeMilliseconds(INCREASED_READ_BUFFER_AGE_THRESHOLD); doThrow(new TimeoutException("Internal Server error")) .when(client) .read(any(String.class), any(Long.class), any(byte[].class), any(Integer.class), any(Integer.class), any(String.class), any(String.class)); AbfsInputStream inputStream = getAbfsInputStream(client, "testFailedReadAheadEviction.txt"); ReadBuffer buff = new ReadBuffer(); buff.setStatus(ReadBufferStatus.READ_FAILED); ReadBufferManager.getBufferManager().testMimicFullUseAndAddFailedBuffer(buff); ReadBufferManager.getBufferManager().queueReadAhead(inputStream, 0, ONE_KB); }
Source:
<code>public CompletionStage<Void> close() { if ( closed.compareAndSet( false, true ) ) { try { for ( Map.Entry<BoltServerAddress,ChannelPool> entry : pools.entrySet() ) { BoltServerAddress address = entry.getKey(); ChannelPool pool = entry.getValue(); log.info( "Closing connection pool towards %s", address ); <START> nettyChannelTracker.destructAllChannels(); <END> pool.close(); } pools.clear(); } finally { eventLoopGroup().shutdownGracefully(); } } return Futures.asCompletionStage( eventLoopGroup().terminationFuture() ) .thenApply( ignore -> null ); }</code><technical_language>a single channel tracker for pools. This method is invoked for pool. called of outer loop</technical_language>

Target:
public CompletionStage<Void> close() { if ( closed.compareAndSet( false, true ) ) { try { nettyChannelTracker.prepareToCloseChannels(); for ( Map.Entry<BoltServerAddress,ChannelPool> entry : pools.entrySet() ) { BoltServerAddress address = entry.getKey(); ChannelPool pool = entry.getValue(); log.info( "Closing connection pool towards %s", address ); pool.close(); } pools.clear(); } finally { eventLoopGroup().shutdownGracefully(); } } return Futures.asCompletionStage( eventLoopGroup().terminationFuture() ) .thenApply( ignore -> null ); }
Source:
<code>public static void threadDumpStartup() throws Exception { if (!logStartupPerformanceIssues) return; final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss"); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); final File f = new File(getRootDirectory(), "/startup-threadDump" + dateFormat.format(new Date()) + ".txt"); if (!f.exists()) { try { f.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } Thread t = new Thread("Support core plugin startup diagnostics") { @Override public void run() { while (true) { final Jenkins jenkins = Jenkins.getInstanceOrNull(); <START> if (jenkins == null || jenkins.getInitLevel() != InitMilestone.COMPLETED) { <END> continue; } final FileOutputStream fileOutputStream; try { fileOutputStream = new FileOutputStream(f, true); } catch (FileNotFoundException e) { throw new UncheckedIOException(e); } try (PrintStream ps = new PrintStream(fileOutputStream, false, "UTF-8")) { ps.println("=== Thread dump at " + new Date() + " ==="); ThreadDumps.threadDump(fileOutputStream); ps.flush(); Thread.sleep(TimeUnit.SECONDS.toMillis(secondsPerThreadDump)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); } } } }; t.start(); }</code><technical_language>a question understand purpose, name of thread startup diagnostics, wait instance is running start dumping ? (nothing related PR)</technical_language>

Target:
public static void threadDumpStartup() throws Exception { if (!logStartupPerformanceIssues) return; final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss"); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); final File f = new File(getRootDirectory(), "/startup-threadDump" + dateFormat.format(new Date()) + ".txt"); if (!f.exists()) { try { f.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } Thread t = new Thread("Support core plugin startup diagnostics") { @Override public void run() { while (true) { final Jenkins jenkins = Jenkins.getInstanceOrNull(); if (jenkins == null || jenkins.getInitLevel() != InitMilestone.COMPLETED) { continue; } try (PrintStream ps = new PrintStream(new FileOutputStream(f, true), false, "UTF-8")) { ps.println("=== Thread dump at " + new Date() + " ==="); ThreadDumps.threadDump(ps); ps.flush(); TimeUnit.SECONDS.sleep(secondsPerThreadDump); } catch (FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); } } } }; t.start(); }
Source:
<code>public static HaxeTarget matchOutputTarget(String compilerTargetArgument) { for (HaxeTarget t : HaxeTarget.values()) { if (t.getCompilerFlag().equals(compilerTargetArgument)) { return t; } } <START> if ("-as3".equals(compilerTargetArgument)) { <END> return HaxeTarget.JAVA_SCRIPT; } return null; }</code><technical_language>I thought for '-as3', target FLASH</technical_language>

Target:
public static HaxeTarget matchOutputTarget(String compilerTargetArgument) { for (HaxeTarget t : HaxeTarget.values()) { if (t.getCompilerFlag().equals(compilerTargetArgument)) { return t; } } if ("-as3".equals(compilerTargetArgument)) { return HaxeTarget.FLASH; } return null; }
Source:
<code>public static <T> Iterable<T> chain( final Iterable<? extends T>... itArray ) { return new Iterable<T>() { @Override public Iterator<T> iterator() { class MyIt implements Iterator<T> { ArrayList<Iterator<? extends T>> iL; <START> int indexA = 0; <END> public MyIt( ArrayList<Iterator<? extends T>> iL ) { this.iL = iL; } @Override public boolean hasNext() { if( indexA < iL.size() - 1 ) { if ( iL.get( indexA ).hasNext() ) { return true; } else { ++indexA; return hasNext(); } } if( indexA >= iL.size() ) { return false; } return iL.get( indexA ).hasNext() ; } @Override public T next() { return iL.get( indexA ).hasNext() ? iL.get( indexA ).next() : ( iL.get( ++indexA ).hasNext() ? iL.get( indexA ).next() : next() ); } @Override public void remove() { throw new UnsupportedOperationException(); } } ArrayList<Iterator<? extends T>> newIL = new ArrayList<Iterator<? extends T>>(); for ( Iterable<? extends T> it: itArray ) { newIL.add( it.iterator() ); } return new MyIt(newIL); } }; }</code><technical_language>iterator iL instead of index</technical_language>

Target:
public static <T> Iterable<T> chain( final Iterable<? extends T>... itArray ) { return new Iterable<T>() { @Override public Iterator<T> iterator() { class MyIt implements Iterator<T> { Iterator<Iterator<? extends T>> iI; Iterator<? extends T> i; public MyIt( Iterator<Iterator<? extends T>> iI ) { this.iI = iI; i = iI.next(); } @Override public boolean hasNext() { if ( i.hasNext() ) { return true; } else { if ( iI.hasNext() ) { i = iI.next(); return this.hasNext(); } else { return false; } } } @Override public T next() { if ( i.hasNext() ) { return i.next(); } else { i = iI.next(); return this.next(); } } @Override public void remove() { throw new UnsupportedOperationException(); } } List<Iterator<? extends T>> newIL = new ArrayList<Iterator<? extends T>>(); for ( Iterable<? extends T> it: itArray ) { newIL.add( it.iterator() ); } return new MyIt(newIL.iterator()); } }; }
Source:
<code>private static LinkedHashSet<String> getSuggestedNames(GoExpression expression) { if (expression instanceof GoCallExpr) { List<String> names = ContainerUtil.newArrayList(); GoReferenceExpression callReference = PsiTreeUtil.getChildOfType(expression, GoReferenceExpression.class); if (callReference != null) { String name = StringUtil.decapitalize(callReference.getIdentifier().getText()); if (name.startsWith("get")) { name = name.substring(3); } else if (name.startsWith("is")) { name = name.substring(2); } for (int i = 0; i < name.length(); i++) { if (i == 0 || (Character.isLowerCase(name.charAt(i - 1)) && Character.isUpperCase(name.charAt(i)))) { <START> names.add(StringUtil.decapitalize(name.substring(i))); <END> } } } return ContainerUtil.newLinkedHashSet(ContainerUtil.reverse(names)); } return ContainerUtil.newLinkedHashSet("i"); }</code><technical_language>Please com.google.common.base.CaseFormat</technical_language>

Target:
private static LinkedHashSet<String> getSuggestedNames(GoExpression expression) { LinkedHashSet<String> usedNames = getNamesInContext(PsiTreeUtil.getParentOfType(expression, GoBlock.class)); LinkedHashSet<String> names = ContainerUtil.newLinkedHashSet(); if (expression instanceof GoCallExpr) { GoReferenceExpression callReference = PsiTreeUtil.getChildOfType(expression, GoReferenceExpression.class); if (callReference != null) { String name = StringUtil.decapitalize(callReference.getIdentifier().getText()); for (String candidate : NameUtil.getSuggestionsByName(name, "", "", false, false, false)) { if (!usedNames.contains(candidate)) names.add(candidate); } } } if (names.isEmpty()) { if (usedNames.contains("i")) { int counter = 1; while (usedNames.contains("i" + counter)) counter++; names.add("i" + counter); } else { names.add("i"); } } return names; }
Source:
<code>private static CRAMFileReader writeAndReadFromInMemoryCram(Collection<SAMRecord> records, CRAMReferenceSource source, SAMFileHeader header) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); <START> CRAMFileWriter cramFileWriter = new CRAMFileWriter(baos, source, header, "whatever"); <END> for (SAMRecord record : records) { cramFileWriter.addAlignment(record); } cramFileWriter.close(); return new CRAMFileReader(new ByteArrayInputStream(baos.toByteArray()), (SeekableStream) null, source, ValidationStringency.SILENT); }</code><technical_language>try-with-resources avoid close() below. baos is closable put in try well</technical_language>

Target:
private static CRAMFileReader writeAndReadFromInMemoryCram(Collection<SAMRecord> records, CRAMReferenceSource source, SAMFileHeader header) throws IOException { try(ByteArrayOutputStream baos = new ByteArrayOutputStream(); CRAMFileWriter cramFileWriter = new CRAMFileWriter(baos, source, header, "whatever")){ records.forEach(cramFileWriter::addAlignment); cramFileWriter.close(); return new CRAMFileReader(new ByteArrayInputStream(baos.toByteArray()), (SeekableStream) null, source, ValidationStringency.SILENT); } }