auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void requestUpdate(@Nullable IConcurrentModelListener listener) { ISegment[] segmentArray = <START> Lists.newArrayList(fWrappedStore.iterator()).toArray(new ISegment[0]); <END> NonNullUtils.checkNotNull(listener).setContents(segmentArray); }</code><technical_language>I this: Iterables.toArray(fWrappedStore, ISegment.class)</technical_language>

Target:
public void requestUpdate(@Nullable IConcurrentModelListener listener) { ISegment[] segmentArray = Iterables.toArray(fWrappedStore, ISegment.class); NonNullUtils.checkNotNull(listener).setContents(segmentArray); }
Source:
<code>public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { LOG.debug("doFilter() started"); HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; HttpServletResponse httpServletResponse = (HttpServletResponse) response; String authorizationHeader = httpServletRequest.getHeader(ConcurConstants.AUTHORIZATION_PROPERTY); if (StringUtils.isBlank(authorizationHeader)) { httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); LOG.debug("doFilter(): Concur authentication failed"); return; } else { final String encodedUserNameAndPasswordAsToken = authorizationHeader.replaceFirst(ConcurConstants.BASIC_AUTHENTICATION_SCHEME + " ", ""); if (!getConcurAuthenticationService().isConcurTokenValid(encodedUserNameAndPasswordAsToken)) { httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); <START> LOG.debug("doFilter(): Concur authentication failed"); <END> return; } } LOG.debug("doFilter(): Concur authentication was successful"); filterChain.doFilter(servletRequest, response); }</code><technical_language>Do care login failed (no auth token wrong auth token)? If so, want debug statements. I inclined errors want in log</technical_language>

Target:
public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { LOG.debug("doFilter() started"); HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; HttpServletResponse httpServletResponse = (HttpServletResponse) response; String authorizationHeader = httpServletRequest.getHeader(ConcurConstants.AUTHORIZATION_PROPERTY); if (StringUtils.isBlank(authorizationHeader)) { httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); LOG.error("doFilter(): Concur authentication failed: missing authorization header."); return; } else { final String encodedUserNameAndPasswordAsToken = authorizationHeader.replaceFirst(ConcurConstants.BASIC_AUTHENTICATION_SCHEME + " ", ""); if (!getConcurAuthenticationService().isConcurTokenValid(encodedUserNameAndPasswordAsToken)) { httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); LOG.error("doFilter(): Concur authentication failed: invalid token."); return; } } LOG.debug("doFilter(): Concur authentication was successful"); filterChain.doFilter(servletRequest, response); }
Source:
<code><START> public void testDeleteStudyButNotAnalysys() { <END> Analysis analysis1 = new Analysis("An1", "Analysis 1", "This is one analysis"); Analysis analysis2 = new Analysis("An2", "Analysis 2", "This is other analysis"); study1.addFileGenerator(analysis1); study1.addFileGenerator(analysis2); Study savedStudy = repository.save(study1); assertEquals(1, repository.count()); assertEquals(2, analysisRepository.count()); repository.delete(savedStudy); assertEquals(0, repository.count()); assertEquals(2, analysisRepository.count()); }</code><technical_language>analysis</technical_language>

Target:
public void testDeleteStudyButNotAnalysys() { Analysis analysis1 = new Analysis("An1", "Analysis 1", "This is one analysis"); Analysis analysis2 = new Analysis("An2", "Analysis 2", "This is other analysis"); study1.addFileGenerator(analysis1); study1.addFileGenerator(analysis2); Study savedStudy = repository.save(study1); assertEquals(1, repository.count()); assertEquals(2, analysisRepository.count()); assertEquals(2, fileGeneratorRepository.count()); repository.delete(savedStudy); assertEquals(0, repository.count()); assertEquals(2, analysisRepository.count()); assertEquals(2, fileGeneratorRepository.count()); }
Source:
<code>public void publish(Object message, Map<String, String> dynamicProperties) { if (message instanceof Map) { String uuid = UUID.randomUUID().toString(); try { for (Map.Entry<String, Object> entry : ((Map<String, Object>) message).entrySet()) { mutator.insert(uuid, columnFamilyName, HFactory.createStringColumn(entry.getKey(), entry.getValue().toString())); } mutator.execute(); } catch (Throwable t) { <START> TenantConfigHolder.logAndDrop(eventAdapterConfiguration.getName(), message, null, t, log, tenantId); <END> } } else { TenantConfigHolder.logAndDrop(eventAdapterConfiguration.getName(), message, "Event is not type of Map.", log, tenantId); } }</code><technical_language>@ramindu90 EventAdapterUtil class logAndDrop() method. In case, if class is renamed TenantConfigHolder, keeping logAndDrop() method class wrong. i.e. a call TenantConfigHolder.logAndDrop() sense. create a new class named EventAdapterUtil logAndDrop() method there, getAxisConfig() addTenantConigContext() methods in TenantConfigHolder class</technical_language>

Target:
public void publish(Object message, Map<String, String> dynamicProperties) { if (message instanceof Map) { String uuid = UUID.randomUUID().toString(); try { for (Map.Entry<String, Object> entry : ((Map<String, Object>) message).entrySet()) { mutator.insert(uuid, columnFamilyName, HFactory.createStringColumn(entry.getKey(), entry.getValue().toString())); } mutator.execute(); } catch (Throwable t) { EventAdapterUtil.logAndDrop(eventAdapterConfiguration.getName(), message, null, t, log, tenantId); } } else { EventAdapterUtil.logAndDrop(eventAdapterConfiguration.getName(), message, "Event is not type of Map.", log, tenantId); } }
Source:
<code><START> public void setLayoutManager(LayoutManager layout) { <END> super.setLayoutManager(layout); }</code><technical_language>this override is useless</technical_language>

Target:
public void setLayoutManager(LayoutManager layout) { super.setLayoutManager(layout); if (mAdapter != null) { mAdapter.setLayoutManager(getLayoutManager()); } }
Source:
<code>private boolean filterDeaggregatedRecord(final UserRecord record) { <START> if (lastSequenceNum.isAggregated()) { <END> return !record.getSequenceNumber().equals(lastSequenceNum.getSequenceNumber()) || record.getSubSequenceNumber() > lastSequenceNum.getSubSequenceNumber(); } return true; }</code><technical_language>this function means</technical_language>

Target:
private boolean filterDeaggregatedRecord(final UserRecord record) { if (!lastSequenceNum.isAggregated()) { return true; } return !record.getSequenceNumber().equals(lastSequenceNum.getSequenceNumber()) || record.getSubSequenceNumber() > lastSequenceNum.getSubSequenceNumber(); }
Source:
<code><START> public void verifyURLStatus(int desiredStatus, String URL) { <END> int timeOut = 500; int status = getURLStatus(URL); while (!(status == desiredStatus)) { try { status = getURLStatus(URL); System.out.println(timeOut + " " + status + " " + URL); Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } timeOut += 500; if (timeOut > 20000) { break; } } Assertion.assertEquals(status, desiredStatus); PageObjectLogging.log("verifyURLStatus", URL + " has status " + status, true); }</code><technical_language>add a short description, method is non-trivial</technical_language>

Target:
public void verifyURLStatus(int desiredStatus, String URL) { int timeOut = 500; int statusCode = 0; boolean status = false; while (!status) { try { statusCode = getURLStatus(URL); if (statusCode == desiredStatus){ status = true; } else { Thread.sleep(500); timeOut += 500; } if (timeOut > 20000) { break; } } catch (InterruptedException e) { throw new RuntimeException(e); } } Assertion.assertEquals(statusCode, desiredStatus); PageObjectLogging.log("verifyURLStatus", URL + " has status " + statusCode, true); }
Source:
<code>private void loadData() { okHttpClient.newCall(new Request.Builder() .url(courseData.getCourse().getCourse_handouts()) .get() .build()) .enqueue(new ErrorHandlingOkCallback<HandoutModel>(getActivity(), HandoutModel.class, CallTrigger.LOADING_CACHED) { @Override protected void onResponse(@NonNull final HandoutModel result) { if (getActivity() == null) { return; } <START> if (result != null && (!TextUtils.isEmpty(result.handouts_html))) { <END> populateHandouts(result); } else { CourseHandoutFragment.this.showErrorMessage(R.string.no_handouts_to_display, FontAwesomeIcons.fa_exclamation_circle); } isHandoutFetched = true; } @Override protected void onFailure(@NonNull final Throwable error) { super.onFailure(error); if (getActivity() == null) { return; } isHandoutFetched = false; CourseHandoutFragment.this.showErrorMessage(R.string.no_handouts_to_display, FontAwesomeIcons.fa_exclamation_circle); } }); }</code><technical_language>Unnecessary null-check</technical_language>

Target:
private void loadData() { okHttpClientProvider.getWithOfflineCache().newCall(new Request.Builder() .url(courseData.getCourse().getCourse_handouts()) .get() .build()) .enqueue(new ErrorHandlingOkCallback<HandoutModel>(getActivity(), HandoutModel.class, CallTrigger.LOADING_CACHED) { @Override protected void onResponse(@NonNull final HandoutModel result) { if (getActivity() == null) { return; } if (!TextUtils.isEmpty(result.handouts_html)) { populateHandouts(result); } else { CourseHandoutFragment.this.showErrorMessage(R.string.no_handouts_to_display, FontAwesomeIcons.fa_exclamation_circle); } isHandoutFetched = true; } @Override protected void onFailure(@NonNull final Throwable error) { super.onFailure(error); if (getActivity() == null) { return; } isHandoutFetched = false; CourseHandoutFragment.this.showErrorMessage(R.string.no_handouts_to_display, FontAwesomeIcons.fa_exclamation_circle); } }); }
Source:
<code>@Override protected void doEnqueue(Callback<V> callback) { sendRequest().handle((response, t) -> { if (t != null) { callback.onError(t); } else { V value = null; try { value = parseResponse(response, bodyConverter); } catch (Throwable t1) { propagateIfFatal(t1); callback.onError(t1); } <START> if (value != null) callback.onSuccess(value); <END> } return null; }); }</code><technical_language>this needs right line 91. parseResponse return null (line 133), this future complete</technical_language>

Target:
@Override protected void doEnqueue(Callback<V> callback) { sendRequest().handle((response, t) -> { if (t != null) { callback.onError(t); } else { try { V value = parseResponse(response, bodyConverter); callback.onSuccess(value); } catch (Throwable t1) { propagateIfFatal(t1); callback.onError(t1); } } return null; }); }
Source:
<code>public void setupGraph(final QueryPipelineContext context, final QueryNodeConfig config, final QueryPlanner planner) { if (((TimeSeriesDataSourceConfig) config).timeShifts() == null) { <START> return; <END> } final TimeShiftConfig shift_config = (TimeShiftConfig) TimeShiftConfig.newBuilder() .setConfig((TimeSeriesDataSourceConfig) config) .setId(config.getId() + "-timeShift") .addSource(config.getId()) .build(); ((HAClusterConfig) config).getPushDownNodes().add(shift_config); }</code><technical_language>timeShift check Schema factory MockDataStore factories verify please</technical_language>

Target:
public void setupGraph(final QueryPipelineContext context, final QueryNodeConfig config, final QueryPlanner planner) { if (((TimeSeriesDataSourceConfig) config).timeShifts() == null) { return; } TimeSeriesDataSourceConfig new_config = ((Builder) config.toBuilder()) .setTimeShifts(((TimeSeriesDataSourceConfig) config).timeShifts()) .setTimeShiftInterval(((TimeSeriesDataSourceConfig) config).getTimeShiftInterval()) .build(); planner.replace(config, new_config); final TimeShiftConfig shift_config = (TimeShiftConfig) TimeShiftConfig.newBuilder() .setTimeshiftInterval(new_config.getTimeShiftInterval()) .setId(new_config.getId() + "-timeShift") .addSource(new_config.getId()) .build(); for (QueryNodeConfig pushdown : new_config.getPushDownNodes()) { if (pushdown.getSources().contains(new_config.getId())) { pushdown.getSources().remove(new_config.getId()); pushdown.getSources().add(shift_config.getId()); } } if (new_config.getPushDownNodes().size() == 0) { List<QueryNodeConfig> pushdown = new ArrayList<>(); pushdown.add(shift_config); BaseTimeSeriesDataSourceConfig.Builder builder = (BaseTimeSeriesDataSourceConfig.Builder) new_config.toBuilder(); ((BaseTimeSeriesDataSourceConfig)new_config).newBuilder(new_config, builder).setPushDownNodes(pushdown); } else { new_config.getPushDownNodes().add(shift_config); } }
Source:
<code>private void fillLocationByGeoLocationProperties(final List<GeolocationProperty> geolocationProperties, final SampleDetailsDTO samplesDetailsDto) { <START> for (GeolocationProperty properties:geolocationProperties) { <END> if (properties.getTypeId().equals(TermId.TRIAL_LOCATION.getId()) && StringUtils.isNotBlank(properties.getValue())) { samplesDetailsDto.setLocationName(properties.getValue()); } else if (properties.getTypeId().equals(TermId.LOCATION_ID.getId()) && StringUtils.isNotBlank(properties.getValue())) { samplesDetailsDto.setLocationDbId(Integer.valueOf(properties.getValue())); } } }</code><technical_language>add final</technical_language>

Target:
private void fillLocationByGeoLocationProperties(final List<GeolocationProperty> geolocationProperties, final SampleDetailsDTO samplesDetailsDto) { for (final GeolocationProperty properties : geolocationProperties) { if (properties.getTypeId().equals(TermId.TRIAL_LOCATION.getId()) && StringUtils.isNotBlank(properties.getValue())) { samplesDetailsDto.setLocationName(properties.getValue()); } else if (properties.getTypeId().equals(TermId.LOCATION_ID.getId()) && StringUtils.isNotBlank(properties.getValue())) { samplesDetailsDto.setLocationDbId(Integer.valueOf(properties.getValue())); } } }
Source:
<code>public LogicalPlan visitQueryNoWith(QueryNoWithContext ctx) { LogicalPlan plan = plan(ctx.queryTerm()); if (!ctx.orderBy().isEmpty()) { List<OrderByContext> orders = ctx.orderBy(); OrderByContext endContext = orders.get(orders.size() - 1); plan = new OrderBy(source(ctx.ORDER(), endContext), plan, visitList(ctx.orderBy(), Order.class)); } LimitClauseContext limitClause = ctx.limitClause(); if (limitClause != null) { Token limit = limitClause.limit; if (limit != null && limitClause.INTEGER_VALUE() != null) { if (plan instanceof Limit) { <START> throw new ParsingException(source(limitClause), "Cannot use both TOP and LIMIT in the same query"); <END> } else { plan = limit(plan, source(limitClause), limit); } } } return plan; }</code><technical_language>I rephrase error a bit - TOP LIMIT allowed in query - other</technical_language>

Target:
public LogicalPlan visitQueryNoWith(QueryNoWithContext ctx) { LogicalPlan plan = plan(ctx.queryTerm()); if (!ctx.orderBy().isEmpty()) { List<OrderByContext> orders = ctx.orderBy(); OrderByContext endContext = orders.get(orders.size() - 1); plan = new OrderBy(source(ctx.ORDER(), endContext), plan, visitList(ctx.orderBy(), Order.class)); } LimitClauseContext limitClause = ctx.limitClause(); if (limitClause != null) { Token limit = limitClause.limit; if (limit != null && limitClause.INTEGER_VALUE() != null) { if (plan instanceof Limit) { throw new ParsingException(source(limitClause), "TOP and LIMIT are not allowed in the same query - use one or the other"); } else { plan = limit(plan, source(limitClause), limit); } } } return plan; }
Source:
<code>public void untag(CoreSession session, String docId, String label) throws DocumentSecurityException { if (!session.exists(new IdRef(docId)) || canUntag(session, docId, label)) { CoreInstance.doPrivileged(session, s -> { <START> doUntag(s, docId, cleanLabel(label, true, false)); <END> }); if (label != null) { fireUpdateEvent(session, docId); } } else { String principalName = session.getPrincipal().getName(); throw new DocumentSecurityException("User '" + principalName + "' is not allowed to remove tag '" + label + "' on document '" + docId + "'"); } }</code><technical_language>Move cleanLabel out of doPrivileged</technical_language>

Target:
public void untag(CoreSession session, String docId, String label) throws DocumentSecurityException { if (!session.exists(new IdRef(docId)) || canUntag(session, docId, label)) { String cleanLabel = cleanLabel(label, true, false); CoreInstance.doPrivileged(session, s -> { doUntag(s, docId, cleanLabel); }); if (label != null) { fireUpdateEvent(session, docId); } } else { String principalName = session.getPrincipal().getName(); throw new DocumentSecurityException("User '" + principalName + "' is not allowed to remove tag '" + label + "' on document '" + docId + "'"); } }
Source:
<code>public void shouldShowMyResourcesAndUpdatePermissions() { assertEquals(6, myResourcesPage.getResourcesListCount()); final int row = 1; myResourcesPage.clickExpandButton(row); <START> pause(2000); <END> assertEquals("Resource is shared with jdoe.", myResourcesPage.getSharedWith(row)); myResourcesPage.clickEditButton(row); waitForModalFadeIn(); myResourcesPage.removeAllPermissions(); waitForModalFadeOut(); assertEquals("This resource is not shared.", myResourcesPage.getSharedWith(row)); }</code><technical_language>move explicit pauses Page Object? better, wait for a specific amount of time for box expanded. ;)</technical_language>

Target:
public void shouldShowMyResourcesAndUpdatePermissions() { final int row = 1; myResourcesPage.clickExpandButton(row); myResourcesPage.clickCollapseButton(row); myResourcesPage.clickExpandButton(row); assertEquals("Resource is shared with jdoe.", myResourcesPage.getSharedWith(row)); myResourcesPage.clickEditButton(row); assertEquals("jdoe", myResourcesPage.getEditDialogUsername(0)); myResourcesPage.removeAllPermissions(); myResourcesPage.alert().assertSuccess(); assertEquals("This resource is not shared.", myResourcesPage.getSharedWith(row)); }
Source:
<code>public void run() { tryingAgain = false; <START> for (Project.NameKey projectName : projectCache.all()) { <END> ProjectConfig config = projectCache.get(projectName).getConfig(); GroupReference ref = config.getGroup(uuid); if (ref == null || newName.equals(ref.getName())) { continue; } try { MetaDataUpdate md = metaDataUpdateFactory.create(projectName); try { rename(md); } finally { md.close(); } } catch (RepositoryNotFoundException noProject) { continue; } catch (ConfigInvalidException err) { log.error("Cannot rename group " + oldName + " in " + projectName, err); } catch (IOException err) { log.error("Cannot rename group " + oldName + " in " + projectName, err); } } }</code><technical_language>a project is in project cache for this project renaming of group is done</technical_language>

Target:
public void run() { Iterable<NameKey> names = tryingAgain ? retryOn : projectCache.all(); for (Project.NameKey projectName : names) { ProjectConfig config = projectCache.get(projectName).getConfig(); GroupReference ref = config.getGroup(uuid); if (ref == null || newName.equals(ref.getName())) { continue; } try { MetaDataUpdate md = metaDataUpdateFactory.create(projectName); try { rename(md); } finally { md.close(); } } catch (RepositoryNotFoundException noProject) { continue; } catch (ConfigInvalidException err) { log.error("Cannot rename group " + oldName + " in " + projectName, err); } catch (IOException err) { log.error("Cannot rename group " + oldName + " in " + projectName, err); } } if (!retryOn.isEmpty() && !tryingAgain) { tryingAgain = true; start(5, TimeUnit.MINUTES); } }
Source:
<code>public void shutdown() throws ReplicationException { try { for (ReplicaThread replicaThread : replicaThreads) { replicaThread.shutdown(); } persistor.write(); } catch (Exception e) { logger.error("Error shutting down replica manager {}", e); <START> throw new ReplicationException("Error shuting down replica manager"); <END> } }</code><technical_language>shutting</technical_language>

Target:
public void shutdown() throws ReplicationException { try { for (ReplicaThread replicaThread : replicaThreads) { replicaThread.shutdown(); } persistor.write(); } catch (Exception e) { logger.error("Error shutting down replica manager {}", e); throw new ReplicationException("Error shutting down replica manager"); } }
Source:
<code>public DefaultCompilationResponse(final Boolean successful, final List<String> mavenOutput, final Path workingDir, final List<String> targetContent, final List<String> projectDependencies) { this.successful = successful; this.mavenOutput = mavenOutput; this.workingDir = workingDir; <START> this.targetContent = targetContent; <END> this.projectDependencies = projectDependencies; }</code><technical_language>lists copied, copy them; java this.targetContent = new ArrayList<>(targetContent); if holds access parameter list, modify</technical_language>

Target:
public DefaultCompilationResponse(final Boolean successful, final List<String> mavenOutput, final Path workingDir, final List<String> targetContent, final List<String> projectDependencies) { this.successful = successful; this.mavenOutput = mavenOutput; this.workingDir = workingDir; this.targetContent = new ArrayList<>(targetContent); this.projectDependencies = new ArrayList<>(projectDependencies); }
Source:
<code>public void testCRAMThroughBAMRoundTrip(final File originalCRAMFile, final File referenceFile) throws IOException { List<SAMRecord> originalCRAMRecords = getSAMRecordsFromFile(originalCRAMFile, referenceFile); List<SAMRecord> copiedCRAMRecords = new ArrayList<>(); originalCRAMRecords.forEach(origRec -> copiedCRAMRecords.add(origRec.deepCopy())); final File tempBamFile = File.createTempFile("testCRAMToBAMToCRAM", BamFileIoUtils.BAM_FILE_EXTENSION); tempBamFile.deleteOnExit(); SAMFileHeader samHeader = getFileHeader(originalCRAMFile, referenceFile); writeRecordsToFile(copiedCRAMRecords, tempBamFile, referenceFile, samHeader); List<SAMRecord> bamRecords = getSAMRecordsFromFile(tempBamFile, referenceFile); int i = 0; for (SAMRecord rec : bamRecords) { rec.setIndexingBin(null); Assert.assertTrue(rec.equals(originalCRAMRecords.get(i++))); } Assert.assertEquals(i, originalCRAMRecords.size()); final File tempCRAMFile = File.createTempFile("testCRAMToBAMToCRAM", CramIO.CRAM_FILE_EXTENSION); tempCRAMFile.deleteOnExit(); writeRecordsToFile(bamRecords, tempCRAMFile, referenceFile, samHeader); List<SAMRecord> roundTripCRAMRecords = getSAMRecordsFromFile(tempCRAMFile, referenceFile); i = 0; for (SAMRecord rec : roundTripCRAMRecords) { if (!rec.equals(originalCRAMRecords.get(i))) { System.out.println(originalCRAMRecords.get(i).getSAMString() + rec.getSAMString()); <START> rec.equals(originalCRAMRecords.get(i)); <END> } i++; } i = 0; for (SAMRecord rec : roundTripCRAMRecords) { Assert.assertTrue(rec.equals(originalCRAMRecords.get(i++))); } Assert.assertEquals(i, originalCRAMRecords.size()); }</code><technical_language>this block, dumps stuff stdout? Is meant assert something? Also, this rec.equals is ignored</technical_language>

Target:
public void testCRAMThroughBAMRoundTrip(final File originalCRAMFile, final File referenceFile) throws IOException { List<SAMRecord> originalCRAMRecords = getSAMRecordsFromFile(originalCRAMFile, referenceFile); List<SAMRecord> copiedCRAMRecords = new ArrayList<>(); originalCRAMRecords.forEach(origRec -> copiedCRAMRecords.add(origRec.deepCopy())); final File tempBamFile = File.createTempFile("testCRAMToBAMToCRAM", BamFileIoUtils.BAM_FILE_EXTENSION); tempBamFile.deleteOnExit(); SAMFileHeader samHeader = getFileHeader(originalCRAMFile, referenceFile); writeRecordsToFile(copiedCRAMRecords, tempBamFile, referenceFile, samHeader); List<SAMRecord> bamRecords = getSAMRecordsFromFile(tempBamFile, referenceFile); int i = 0; for (SAMRecord rec : bamRecords) { rec.setIndexingBin(null); Assert.assertTrue(rec.equals(originalCRAMRecords.get(i++))); } Assert.assertEquals(i, originalCRAMRecords.size()); final File tempCRAMFile = File.createTempFile("testCRAMToBAMToCRAM", CramIO.CRAM_FILE_EXTENSION); tempCRAMFile.deleteOnExit(); writeRecordsToFile(bamRecords, tempCRAMFile, referenceFile, samHeader); List<SAMRecord> roundTripCRAMRecords = getSAMRecordsFromFile(tempCRAMFile, referenceFile); i = 0; for (SAMRecord rec : roundTripCRAMRecords) { Assert.assertTrue(rec.equals(originalCRAMRecords.get(i++))); } Assert.assertEquals(i, originalCRAMRecords.size()); }
Source:
<code>public static int getTemporalLayerIndex(byte[] buf, int off, int len) { if (buf == null || buf.length < off + len || len < 2) { return -1; } if ((buf[off] & X_BIT) == 0 || (buf[off+1] & T_BIT) == 0) { return -1; } int sz = getSize(buf, off); <START> <END> return (buf[off + sz - 1] & 0xc0) >> 6; }</code><technical_language>trust getSize return -1 here</technical_language>

Target:
public static int getTemporalLayerIndex(byte[] buf, int off, int len) { if (buf == null || buf.length < off + len || len < 2) { return -1; } if ((buf[off] & X_BIT) == 0 || (buf[off+1] & T_BIT) == 0) { return -1; } int sz = getSize(buf, off); if (buf.length < off + sz || sz < 1) { return -1; } return (buf[off + sz - 1] & 0xc0) >> 6; }
Source:
<code>public Flux<String> getServices() { return Flux.defer(getServicesFromZookeeper()) <START> .subscribeOn(Schedulers.elastic()); <END> }</code><technical_language>boundedElastic</technical_language>

Target:
public Flux<String> getServices() { return Flux.defer(getServicesFromZookeeper()) .subscribeOn(Schedulers.boundedElastic()); }
Source:
<code>void repaintPositionOverlay() { final long currentTimeMillis = System.currentTimeMillis(); if (currentTimeMillis > timeLastRepaintPositionOverlay + MIN_UPDATE_INTERVAL) { <START> timeLastRepaintPositionOverlay = currentTimeMillis; <END> try { if (mapView != null) { if (overlayPosition == null) { overlayPosition = mapView.createAddPositionOverlay(activity); } boolean needsRepaintForDistance = needsRepaintForDistance(); boolean needsRepaintForHeading = needsRepaintForHeading(); if (needsRepaintForDistance) { if (followMyLocation) { centerMap(new Geopoint(currentLocation)); } } if (needsRepaintForDistance || needsRepaintForHeading) { overlayPosition.setCoordinates(currentLocation); overlayPosition.setHeading(currentHeading); mapView.repaintRequired(overlayPosition); } } } catch (Exception e) { Log.w("Failed to update location."); } } }</code><technical_language>I restart repaint interval only, if a repaint occurs</technical_language>

Target:
void repaintPositionOverlay() { final long currentTimeMillis = System.currentTimeMillis(); if (currentTimeMillis > timeLastPositionOverlayCalculation + MIN_UPDATE_INTERVAL) { timeLastPositionOverlayCalculation = currentTimeMillis; try { if (mapView != null) { if (overlayPosition == null) { overlayPosition = mapView.createAddPositionOverlay(activity); } boolean needsRepaintForDistance = needsRepaintForDistance(); boolean needsRepaintForHeading = needsRepaintForHeading(); if (needsRepaintForDistance) { if (followMyLocation) { centerMap(new Geopoint(currentLocation)); } } if (needsRepaintForDistance || needsRepaintForHeading) { overlayPosition.setCoordinates(currentLocation); overlayPosition.setHeading(currentHeading); mapView.repaintRequired(overlayPosition); } } } catch (Exception e) { Log.w("Failed to update location."); } } }
Source:
<code>public static void addHeader(Headers target, String key, Object value) { Assert.notNull(target, () -> "target may not be null"); if (value instanceof Instant) { target.add(key, toBytes((Number) ((Instant) value).toEpochMilli())); } else if (value instanceof Number) { target.add(key, toBytes((Number) value)); } else if (value instanceof String) { <START> target.add(key, ((String) value).getBytes()); <END> } else if (value == null) { target.add(key, null); } else { target.add(key, value.toString().getBytes()); } }</code><technical_language>define a Charset here: UTF_8</technical_language>

Target:
public static void addHeader(Headers target, String key, Object value) { Assert.notNull(target, () -> "target may not be null"); if (value instanceof Instant) { target.add(key, toBytes((Number) ((Instant) value).toEpochMilli())); } else if (value instanceof Number) { target.add(key, toBytes((Number) value)); } else if (value instanceof String) { target.add(key, ((String) value).getBytes(UTF_8)); } else if (value == null) { target.add(key, null); } else { target.add(key, value.toString().getBytes(UTF_8)); } }
Source:
<code>public void forceDestroyRaftGroup(String groupName) { checkNotNull(groupName); <START> checkFalse(metadataGroupId.name().equalsIgnoreCase(groupName), "Cannot force-destroy the METADATA CP group!"); <END> boolean found = false; for (CPGroupInfo group : groups.values()) { if (group.name().equals(groupName)) { if (group.forceSetDestroyed()) { logger.info(group.id() + " is force-destroyed."); sendDestroyRaftNodeOps(group); } else if (logger.isFineEnabled()) { logger.fine(group.id() + " is already force-destroyed."); } found = true; } } if (!found) { throw new IllegalArgumentException("CP group with name: " + groupName + " does not exist to force-destroy!"); } }</code><technical_language>additionally check if destroying default group</technical_language>

Target:
public void forceDestroyRaftGroup(String groupName) { checkNotNull(groupName); checkFalse(METADATA_CP_GROUP_NAME.equalsIgnoreCase(groupName), "Cannot force-destroy the METADATA CP group!"); checkMetadataGroupInitSuccessful(); boolean found = false; for (CPGroupInfo group : groups.values()) { if (group.name().equals(groupName)) { if (group.forceSetDestroyed()) { logger.info(group.id() + " is force-destroyed."); sendDestroyRaftNodeOps(group); } else if (logger.isFineEnabled()) { logger.fine(group.id() + " is already force-destroyed."); } found = true; } } if (!found) { throw new IllegalArgumentException("CP group with name: " + groupName + " does not exist to force-destroy!"); } }
Source:
<code><START> public void shouldNotMatchUrlStaringWithAPI() <END> throws DotDataException { final String newsPatternPrefix = "/testpattern" + System.currentTimeMillis() + "/"; final UrlMapContext context = getUrlMapContext(systemUser, host, "/api/v1/page/render" + newsPatternPrefix + "u-s-labor-department-moves-forward-on-retirement-advice-proposal-esp" + System.currentTimeMillis()); assertFalse(urlMapAPI.isUrlPattern(context)); }</code><technical_language>is purpose of this test? renaming test clear</technical_language>

Target:
public void shouldNotMatchUrlStaringWithAPI() throws DotDataException { final String newsPatternPrefix = "/testpattern" + System.currentTimeMillis() + "/"; final Contentlet newsTestContent = createURLMapperContentType(newsPatternPrefix); final UrlMapContext context = getUrlMapContext(systemUser, host, "/api" + newsPatternPrefix + newsTestContent.getStringProperty("urlTitle")); assertFalse(urlMapAPI.isUrlPattern(context)); }
Source:
<code>private void deleteOldRedisplayedInAppMessages() { new Thread(new Runnable() { @Override public void run() { Thread.currentThread().setPriority(Process.THREAD_PRIORITY_BACKGROUND); inAppMessageRepository.deleteOldRedisplayedInAppMessages(); } <START> }, OS_SAVE_IN_APP_MESSAGE).start(); <END> }</code><technical_language>I marked this in #951 already</technical_language>

Target:
private void deleteOldRedisplayedInAppMessages() { new Thread(new Runnable() { @Override public void run() { Thread.currentThread().setPriority(Process.THREAD_PRIORITY_BACKGROUND); inAppMessageRepository.deleteOldRedisplayedInAppMessages(); } }, OS_DELETE_IN_APP_MESSAGE).start(); }
Source:
<code>public Iterable<ValidationResult> doHealthChecks(RuntimeContainer container) { List<ValidationResult> checks = new ArrayList<>(1); TMarkLogicConnectionStandalone standalone = new TMarkLogicConnectionStandalone(); try { standalone.initialize(container, properties); standalone.connect(container); checks.add(ValidationResult.OK); } catch (ComponentException ce) { checks.add(new ValidationResult(ce)); } <START> return checks; <END> }</code><technical_language>return Collections.singletonList(ValidationResult) instead of creating list of 1 element</technical_language>

Target:
public Iterable<ValidationResult> doHealthChecks(RuntimeContainer container) { TMarkLogicConnectionStandalone standalone = new TMarkLogicConnectionStandalone(); ValidationResult validationResult; try { standalone.initialize(container, properties); standalone.connect(container); validationResult = ValidationResult.OK; } catch (ComponentException ce) { validationResult = new ValidationResult(ce); } return Collections.singletonList(validationResult); }
Source:
<code>public void process(Writable value) throws HiveException { ExecMapperContext context = getExecContext(); if (context != null && context.inputFileChanged()) { cleanUpInputFileChanged(); } int childrenDone = 0; for (MapOpCtx current : currentCtxs) { Object row = null; try { row = current.readRow(value, context); if (!current.forward(row)) { childrenDone++; } } catch (Exception e) { String message = null; try { message = toErrorMessage(value, row, current.rowObjectInspector); } catch (Throwable t) { message = "[" + row + ", " + value + "]: cannot get error message " + t.getMessage(); } if (row == null) { deserialize_error_count.set(deserialize_error_count.get() + 1); <START> throw new HiveException("Hive Runtime Error while processing writable " + message, e); <END> } LOG.debug("Hive Runtime Error while processing row " + message); throw new HiveException("Hive Runtime Error while processing row", e); } } rowsForwarded(childrenDone, 1); }</code><technical_language>log "message" row (which is null) includes "value" input argument potentially sensitive data. Need put "message" debug log</technical_language>

Target:
public void process(Writable value) throws HiveException { ExecMapperContext context = getExecContext(); if (context != null && context.inputFileChanged()) { cleanUpInputFileChanged(); } int childrenDone = 0; for (MapOpCtx current : currentCtxs) { Object row = null; try { row = current.readRow(value, context); if (!current.forward(row)) { childrenDone++; } } catch (Exception e) { String message = null; try { message = toErrorMessage(value, row, current.rowObjectInspector); } catch (Throwable t) { message = "[" + row + ", " + value + "]: cannot get error message " + t.getMessage(); } if (row == null) { deserialize_error_count.set(deserialize_error_count.get() + 1); LOG.trace("Hive Runtime Error while processing writable " + message); throw new HiveException("Hive Runtime Error while processing writable", e); } LOG.trace("Hive Runtime Error while processing row " + message); throw new HiveException("Hive Runtime Error while processing row", e); } } rowsForwarded(childrenDone, 1); }
Source:
<code>public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws InterruptedException, IOException { final GitHubPRTrigger trigger = JobInfoHelpers.triggerFrom(run.getParent(), GitHubPRTrigger.class); if (trigger == null) { return; } GitHubPRCause cause = run.getCause(GitHubPRCause.class); if (cause == null) { return; } try { if (statusMessage != null) { String url = trigger.getDescriptor().getJenkinsURL() + run.getUrl(); String expandedMessage; if (run instanceof AbstractBuild<?, ?>) { final AbstractBuild<?, ?> build = (AbstractBuild<?, ?>) run; expandedMessage = statusMessage.expandAll(build, listener); } else { <START> expandedMessage = statusMessage.getContent(); <END> } trigger.getRemoteRepo().createCommitStatus( cause.getHeadSha(), GHCommitState.PENDING, url, expandedMessage, run.getParent().getFullName() ); } } catch (IOException e) { listener.getLogger().println("Can't update build description"); LOGGER.error("Can't set commit status", e); } }</code><technical_language>need specifically expand ${GITHUB_PR_COND_REF}</technical_language>

Target:
public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws InterruptedException, IOException { final GitHubPRTrigger trigger = JobInfoHelpers.triggerFrom(run.getParent(), GitHubPRTrigger.class); if (trigger == null) { return; } GitHubPRCause cause = run.getCause(GitHubPRCause.class); if (cause == null) { return; } try { if (statusMessage != null) { String url = trigger.getDescriptor().getJenkinsURL() + run.getUrl(); trigger.getRemoteRepo().createCommitStatus( cause.getHeadSha(), GHCommitState.PENDING, url, statusMessage.expandAll(run, listener), run.getParent().getFullName() ); } } catch (IOException e) { listener.getLogger().println("Can't update build description"); LOGGER.error("Can't set commit status", e); } }
Source:
<code>public void stop() { for (PageSubscription cursor : activeCursors.values()) { cursor.stop(); } <START> int pendingCleanupTasks = scheduledCleanup.get(); <END> if (pendingCleanupTasks > 0) { logger.tracef("Try to wait %d cleanup tasks to complete", pendingCleanupTasks); if (!executor.flush(10, TimeUnit.SECONDS)) { pendingCleanupTasks = scheduledCleanup.get(); if (pendingCleanupTasks > 0) { logger.warnf("Stopping while leaving %d cleanup tasks undone", pendingCleanupTasks); } } } final List<Runnable> pendingTasks = new ArrayList<>(); final int pendingTasksWhileShuttingDown = executor.shutdownNow(pendingTasks::add); if (pendingTasksWhileShuttingDown > 0) { logger.tracef("Try executing %d pending tasks on stop", pendingTasksWhileShuttingDown); for (Runnable pendingTask : pendingTasks) { try { pendingTask.run(); } catch (Throwable t) { logger.warn("Error while executing a pending task on shutdown", t); } } } }</code><technical_language>Nice catch.. nice... However.. calling shutdown here. PageCursor executor... this is ArtemisExecutor. shutdownNow call empty method.. getPendingTasks return empty array. I do is call flush method</technical_language>

Target:
public void stop() { for (PageSubscription cursor : activeCursors.values()) { cursor.stop(); } final int pendingCleanupTasks = scheduledCleanup.get(); if (pendingCleanupTasks > 0) { logger.tracef("Stopping with %d cleanup tasks to be completed yet", pendingCleanupTasks); } }
Source:
<code>public boolean isStatusIssued(@NonNull final HuId huId){ <START> return isStatusIssued(InterfaceWrapperHelper.load(huId, I_M_HU.class)); <END> }</code><technical_language>pls IHandlingUnitsDAO.getById</technical_language>

Target:
public boolean isStatusIssued(@NonNull final HuId huId){ return isStatusIssued(handlingUnitsDAO.getById(huId)); }
Source:
<code><START> public LargeText(final File file, Charset charset, boolean completed, boolean transparentUnGZIP) { <END> this.charset = charset; if (transparentUnGZIP) { this.source = new Source() { public Session open() throws IOException { return new GzipAwareSession(file); } public long length() { return GzipAwareSession.getGzipStreamSize(file); } public boolean exists() { return file.exists(); } }; } else { this.source = new Source() { public Session open() throws IOException { return new FileSession(file); } public long length() { return file.length(); } public boolean exists() { return file.exists(); } }; } this.completed = completed; }</code><technical_language>BTW Unix command is gunzip, a more familiar term (or not)</technical_language>

Target:
public LargeText(final File file, Charset charset, boolean completed, boolean transparentUnGZIP) { this.charset = charset; if (transparentUnGZIP && GzipAwareSession.isGzipStream(file)) { this.source = new Source() { public Session open() throws IOException { return new GzipAwareSession(file); } public long length() { return GzipAwareSession.getGzipStreamSize(file); } public boolean exists() { return file.exists(); } }; } else { this.source = new Source() { public Session open() throws IOException { return new FileSession(file); } public long length() { return file.length(); } public boolean exists() { return file.exists(); } }; } this.completed = completed; }
Source:
<code>private Properties readPropertiesFromOverrideFile() { final Properties properties = new Properties(); findOverrideFile() .ifPresent( overrideFile -> { try { <START> properties.load(new FileInputStream(overrideFile)); <END> } catch (final IOException e) { log.log( Level.SEVERE, "Failed to read override file: " + overrideFile.getAbsolutePath(), e); } }); return properties; }</code><technical_language>If decide java.nio here, this FileInputStream closed this</technical_language>

Target:
private Properties readPropertiesFromOverrideFile() { final Properties properties = new Properties(); findOverrideFile() .ifPresent( overrideFile -> { try (InputStream fileInput = Files.newInputStream(overrideFile)) { properties.load(fileInput); } catch (final IOException e) { log.log( Level.SEVERE, "Failed to read override file: " + overrideFile.toAbsolutePath(), e); } }); return properties; }
Source:
<code>public void testReflectionHierarchyArrayList() { assumeFalse("IBM Corporation".equals(SystemUtils.JAVA_VENDOR) && "1.6".equals(SystemUtils.JAVA_SPECIFICATION_VERSION)); assumeFalse("Oracle Corporation".equals(SystemUtils.JAVA_VENDOR) && "1.6".compareTo(SystemUtils.JAVA_SPECIFICATION_VERSION) < 0); <START> final List<Object> list = new ArrayList<>(10); <END> final String baseString = this.toBaseString(list); final String expectedWithTransients = baseString + "[elementData={<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>},size=0,modCount=0]"; final String toStringWithTransients = ToStringBuilder.reflectionToString(list, null, true); if (!expectedWithTransients.equals(toStringWithTransients)) { assertEquals(expectedWithTransients, toStringWithTransients); } final String expectedWithoutTransients = baseString + "[size=0]"; final String toStringWithoutTransients = ToStringBuilder.reflectionToString(list, null, false); if (!expectedWithoutTransients.equals(toStringWithoutTransients)) { assertEquals(expectedWithoutTransients, toStringWithoutTransients); } }</code><technical_language>Thanks! If test fails initial size arg is omitted, affect behaviour of method tested? i.e. do apps ensure min size ToStringBuilder.reflectionToString()</technical_language>

Target:
public void testReflectionHierarchyArrayList() { assumeFalse("IBM Corporation".equals(SystemUtils.JAVA_VENDOR) && "1.6".equals(SystemUtils.JAVA_SPECIFICATION_VERSION)); assumeFalse("Oracle Corporation".equals(SystemUtils.JAVA_VENDOR) && "1.6".compareTo(SystemUtils.JAVA_SPECIFICATION_VERSION) < 0); final List<Object> list = new ArrayList<>(ARRAYLIST_INITIAL_CAPACITY); final String baseString = this.toBaseString(list); final String expectedWithTransients = baseString + "[elementData={<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>},size=0,modCount=0]"; final String toStringWithTransients = ToStringBuilder.reflectionToString(list, null, true); if (!expectedWithTransients.equals(toStringWithTransients)) { assertEquals(expectedWithTransients, toStringWithTransients); } final String expectedWithoutTransients = baseString + "[size=0]"; final String toStringWithoutTransients = ToStringBuilder.reflectionToString(list, null, false); if (!expectedWithoutTransients.equals(toStringWithoutTransients)) { assertEquals(expectedWithoutTransients, toStringWithoutTransients); } }
Source:
<code>public CtfTmfEventField resolve(ITmfEvent event) { if (!(event instanceof CtfTmfEvent)) { return null; } ICompositeDefinition eventContext = ((CtfTmfEvent) event).getEventContext(); if (eventContext == null) { return null; } <START> return CtfTmfEventField.parseField(eventContext, "Context.Event"); <END> }</code><technical_language>this ("Context.Event") defined statically somewhere</technical_language>

Target:
public ITmfEventField resolve(ITmfEvent event) { if (!(event instanceof CtfTmfEvent)) { return null; } ICompositeDefinition eventContext = ((CtfTmfEvent) event).getEventContext(); if (eventContext == null) { return null; } return CtfTmfEventField.parseField(eventContext, CONTEXT_EVENT); }
Source:
<code>RtRepos(final Github github, final Request req) { this.ghub = github; this.entry = req; this.createRequest = this.entry.uri().path("user/repos").back(); <START> this.removeRequest = this.entry.uri().path("/repos").back(); <END> }</code><technical_language>is point of saving in class variables, if once</technical_language>

Target:
RtRepos(final Github github, final Request req) { this.ghub = github; this.entry = req; }
Source:
<code>private void readVersion() { final String command = fScriptCommand.get(0); final List<String> commandLine = ImmutableList.<@NonNull String> builder() .add(command).add(MI_VERSION_FLAG).build(); final String output = getOutputFromCommand(commandLine); if (output == null) { Activator.instance().logInfo(String.format(LOG_NO_MI_VERSION_FMT, command)); return; } final String versionString = output.trim(); if (!versionString.matches("\\d{1,3}\\.\\d{1,3}")) { Activator.instance().logInfo(String.format(LOG_NO_MI_VERSION_FMT, command)); return; } final String logMsg = String.format("Command \"%s\" reports MI version %s", command, versionString); <START> Activator.instance().logInfo(logMsg); <END> final String[] parts = versionString.split("\\."); final int major = Integer.valueOf(parts[0]); final int minor = Integer.valueOf(parts[1]); fMiVersion = major * 100 + minor; }</code><technical_language>log logInfo() for script is called, clutters command-line output. do LOGGER.info() though</technical_language>

Target:
private void readVersion() { final String command = fScriptCommand.get(0); final List<String> commandLine = ImmutableList.<@NonNull String> builder() .add(command).add(MI_VERSION_FLAG).build(); final String output = getOutputFromCommand(commandLine); if (output == null) { LOGGER.info(() -> String.format(LOG_NO_MI_VERSION_FMT, command)); return; } final String versionString = output.trim(); if (!versionString.matches("\\d{1,3}\\.\\d{1,3}")) { LOGGER.info(() -> String.format(LOG_NO_MI_VERSION_FMT, command)); return; } LOGGER.info(() -> String.format("[LamiAnalysis:MIVersionReport] Command \"%s\" reports MI version %s", command, versionString)); final String[] parts = versionString.split("\\."); final int major = Integer.valueOf(parts[0]); final int minor = Integer.valueOf(parts[1]); fMiVersion = major * 100 + minor; }
Source:
<code>public static String toLongString(final Change.Status status) { if (status == null) { return ""; } switch (status) { case NEW: return C.statusLongNew(); case SUBMITTED: return C.statusLongSubmitted(); case MERGED: return C.statusLongMerged(); case ABANDONED: return C.statusLongAbandoned(); <START> case DRAFT: <END> return C.statusLongDraft(); default: return status.name(); } }</code><technical_language>Nit: this NEW</technical_language>

Target:
public static String toLongString(final Change.Status status) { if (status == null) { return ""; } switch (status) { case DRAFT: return C.statusLongDraft(); case NEW: return C.statusLongNew(); case SUBMITTED: return C.statusLongSubmitted(); case MERGED: return C.statusLongMerged(); case ABANDONED: return C.statusLongAbandoned(); default: return status.name(); } }