auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>HistogramMetricImpl createHistogram(String srvcName, Method method) { MetricRegistry metricRegistry = ctx.metric().registry(serviceMetricRegistryName(srvcName)); HistogramMetricImpl histogram = null; for (int i = 0; i <= MAX_ABBREVIATE_NAME_LVL; ++i) { String methodMetricName = methodMetricName(method, i); <START> synchronized (metricRegistry) { <END> if (metricRegistry.findMetric(methodMetricName) == null) { histogram = metricRegistry.histogram(methodMetricName, DEFAULT_INVOCATION_BOUNDS, DESCRIPTION_OF_INVOCATION_METRIC); break; } } } assert histogram != null; return histogram; }</code><technical_language>I looked MetricRegistry#findMetric MetricRegistry#histogram implementations thread safe. synchronize metricRegistry avoid contention</technical_language>

Target:
HistogramMetricImpl createHistogram(String srvcName, Method method) { MetricRegistry metricRegistry = ctx.metric().registry(serviceMetricRegistryName(srvcName)); HistogramMetricImpl histogram = null; for (int i = 0; i <= MAX_ABBREVIATE_NAME_LVL; ++i) { String methodMetricName = methodMetricName(method, i); if (metricRegistry.findMetric(methodMetricName) == null) { histogram = metricRegistry.histogram(methodMetricName, DEFAULT_INVOCATION_BOUNDS, DESCRIPTION_OF_INVOCATION_METRIC); break; } } assert histogram != null; return histogram; }
Source:
<code>public void authenticateNotEnabledUserShouldFail() throws Exception { String password = "password"; String passwordHash = "5f4dcc3b5aa765d61d8327deb882cf99"; LoginUserDto loginUserDto = createDefaultLoginUserDto(); JCUser oldUser = prepareOldUser(loginUserDto.getUserName()); <START> when(userDao.getByUsername(oldUser.getUsername())).thenReturn(oldUser); <END> when(encryptionService.encryptPassword(password)).thenReturn(passwordHash); when(securityFacade.getContext()).thenReturn(securityContext); when(authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class))) .thenThrow(new DisabledException(null)); preparePlugin(oldUser.getUsername(), passwordHash, Collections.EMPTY_MAP); AuthenticationStatus result = authenticator.authenticate(loginUserDto, httpRequest, httpResponse); assertEquals(result, AuthenticationStatus.NOT_ENABLED, "Authenticate user with bad credentials should fail."); }</code><technical_language>Do is a shortening test method removing extra when()</technical_language>

Target:
public void authenticateNotEnabledUserShouldFail() throws Exception { LoginUserDto loginUserDto = createDefaultLoginUserDto(); prepareOldUser(loginUserDto.getUserName()); when(authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class))) .thenThrow(new DisabledException(null)); AuthenticationStatus result = authenticator.authenticate(loginUserDto, httpRequest, httpResponse); assertEquals(result, AuthenticationStatus.NOT_ENABLED, "Authenticate user with bad credentials should fail."); }
Source:
<code>public StatisticsResource getStatisticsResource() { <START> GlusterTaskStatisticalQuery query = new GlusterTaskStatisticalQuery(new TaskQueryResolver<Guid>(), newModel(id)); <END> return inject(new BackendStatisticsResource<Step, GlusterVolumeTaskStatusEntity>(GlusterVolumeTaskStatusEntity.class, guid, query)); }</code><technical_language>I simply do Step step = get(); if (step.getExternalType==....) { }</technical_language>

Target:
public StatisticsResource getStatisticsResource() { StepStatisticalQuery query = new StepStatisticalQuery(new TaskQueryResolver<Guid>(), newModel(id)); return inject(new BackendStatisticsResource<Step, GlusterVolumeTaskStatusEntity>(GlusterVolumeTaskStatusEntity.class, guid, query)); }
Source:
<code>private void checkCodeValidation() { <START> final int expectedValueOfErrorMarkers = 9; <END> editor.waitActive(); editor.goToPosition(13, 2); editor.typeTextIntoEditor(SPACE.toString()); final int actualValueErrorMarkers = editor.getMarkersQuantity(ERROR); assertEquals( actualValueErrorMarkers, expectedValueOfErrorMarkers, String.format( "The expected value of errors marker should be %d but actual %d", expectedValueOfErrorMarkers, actualValueErrorMarkers)); editor.waitMarkerInPositionAndMoveCursor(ERROR_OVERVIEW, 13); editor.waitTextInToolTipPopup("Cannot find name 'c'"); editor.goToPosition(13, 2); editor.typeTextIntoEditor(DELETE.toString()); editor.waitAllMarkersInvisibility(ERROR); }</code><technical_language>readability point divide verification given/when/then sections</technical_language>

Target:
private void checkCodeValidation() { final int expectedAmountOfErrorMarkers = 9; String tooltipWithErrorMessage = "Cannot find name 'c'"; editor.waitActive(); editor.goToPosition(13, 2); editor.typeTextIntoEditor(SPACE.toString()); final int actualValueErrorMarkers = editor.getMarkersQuantity(ERROR); assertEquals( actualValueErrorMarkers, expectedAmountOfErrorMarkers, String.format( "The expected value of errors marker should be %d but actual %d", expectedAmountOfErrorMarkers, actualValueErrorMarkers)); editor.moveToMarker(ERROR_OVERVIEW, 13); editor.waitTextInToolTipPopup(tooltipWithErrorMessage); editor.goToPosition(13, 2); editor.typeTextIntoEditor(DELETE.toString()); editor.waitAllMarkersInvisibility(ERROR); }
Source:
<code>public static void setup() throws IOException, SolrServerException { author = new User("Leonardo", "leo@leo"); author.confirmEmail(); hibernateSession.save(author); eli5 = new Tag("eli5", "Explain Like I'm 5", author); hibernateSession.save(eli5); eli12 = new Tag("eli12", "Explain Like I'm 12", author); hibernateSession.save(eli12); science = new Tag("science", "Science!", author); hibernateSession.save(science); hobby = new Tag("hobby", "Hobbies and stuff", author); hibernateSession.save(hobby); tolstoy = new Tag("tolstoy", "Long-winded russian author", author); hibernateSession.save(tolstoy); sut = new QuestionIndex(solrServer); data(); <START> } <END></code><technical_language>@BeforeClass method, sorry. try leave @Before, @After methods test cases</technical_language>

Target:
public static void setup() throws IOException, SolrServerException { author = new User("Leonardo", "leo@leo"); author.confirmEmail(); hibernateSession.save(author); sut = new QuestionIndex(solrServer); data(); }
Source:
<code>public boolean isLowerThan(Version other) { <START> return Version.compare(other, this) > 0; <END> }</code><technical_language>prefer symmetry of Version.compare(this, other) < 0</technical_language>

Target:
public boolean isLowerThan(Version other) { return Version.compare(this, other) < 0; }
Source:
<code>private void invalidateSession(String id) { SessionHandler[] tmp = (SessionHandler[]) _server.getChildHandlersByClass(SessionHandler.class); if (tmp != null && tmp.length > 0) { <START> tmp[0].getSession(id).invalidate(); <END> } }</code><technical_language>tmp[0]</technical_language>

Target:
private void invalidateSession(String id) { Iterator handlerIterator = this.getSessionHandlers().iterator(); while (handlerIterator.hasNext()) { SessionHandler currSessionHandler = (SessionHandler) handlerIterator.next(); Session session = currSessionHandler.getSession(id); if (session != null && session.isValid()) { session.invalidate(); break; } } }
Source:
<code>public MonstrousStepEffect(Duration duration) { super(duration); <START> staticText = "Target creature blocks target creature this turn if able"; <END> }</code><technical_language>text is incorrect</technical_language>

Target:
public MonstrousStepEffect(Duration duration) { super(duration); staticText = "Up to one target creature blocks it this turn if able."; }
Source:
<code>private String[] getIndices(TransportClient client, GetIndexRequest request) { try { return retry() .maxAttempts(maxAttempts) .exponentialBackoff(maxRetryTime, 2.0) <START> .run("getIndices", () -> { <END> return client.admin() .indices() .getIndex(request) .actionGet(requestTimeout.toMillis()) .getIndices(); }); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } }</code><technical_language>nit: expression lambda here. Please fix L236 L317. .run("getIndices", () -> client.admin() .indices() .getIndex(request) .actionGet(requestTimeout.toMillis()) .getIndices());</technical_language>

Target:
private String[] getIndices(TransportClient client, GetIndexRequest request) { try { return retry() .maxAttempts(maxAttempts) .exponentialBackoff(maxRetryTime) .run("getIndices", () -> client.admin() .indices() .getIndex(request) .actionGet(requestTimeout.toMillis()) .getIndices()); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
<code>public TemplateProfile prepare(RegisterIsoCmd cmd) throws ResourceAllocationException { Account caller = CallContext.current().getCallingAccount(); Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId()); _accountMgr.checkAccess(caller, null, true, owner); List<Long> zoneList = null; Long zoneId = cmd.getZoneId(); List<ImageStoreVO> stores = _imgStoreDao.findRegionImageStores(); <START> if (!(stores != null && stores.size() > 0) && zoneId != null && zoneId != -1L) { <END> zoneList = new ArrayList<>(); zoneList.add(zoneId); } return prepare(true, CallContext.current().getCallingUserId(), cmd.getIsoName(), cmd.getDisplayText(), 64, false, true, cmd.getUrl(), cmd.isPublic(), cmd.isFeatured(), cmd.isExtractable(), ImageFormat.ISO.toString(), cmd.getOsTypeId(), zoneList, HypervisorType.None, cmd.getChecksum(), cmd.isBootable(), null, owner, null, false, cmd.getImageStoreUuid(), cmd.isDynamicallyScalable(), TemplateType.USER, cmd.isDirectDownload()); }</code><technical_language>do zoneId>0 instead of != - 1</technical_language>

Target:
public TemplateProfile prepare(RegisterIsoCmd cmd) throws ResourceAllocationException { Account caller = CallContext.current().getCallingAccount(); Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId()); _accountMgr.checkAccess(caller, null, true, owner); List<Long> zoneList = null; Long zoneId = cmd.getZoneId(); List<ImageStoreVO> stores = _imgStoreDao.findRegionImageStores(); if (CollectionUtils.isEmpty(stores) && zoneId != null && zoneId > 0L) { zoneList = new ArrayList<>(); zoneList.add(zoneId); } return prepare(true, CallContext.current().getCallingUserId(), cmd.getIsoName(), cmd.getDisplayText(), 64, false, true, cmd.getUrl(), cmd.isPublic(), cmd.isFeatured(), cmd.isExtractable(), ImageFormat.ISO.toString(), cmd.getOsTypeId(), zoneList, HypervisorType.None, cmd.getChecksum(), cmd.isBootable(), null, owner, null, false, cmd.getImageStoreUuid(), cmd.isDynamicallyScalable(), TemplateType.USER, cmd.isDirectDownload()); }
Source:
<code>private MapWrapper(String category, Field field, Object instance) { super(category, field, instance); try { theMap = (Map<String, Object>) field.get(instance); } catch (ClassCastException cce) { throw new IllegalArgumentException(String.format("The map '%s' of class '%s' must have the key type String!", field.getName(), field.getDeclaringClass().getCanonicalName()), cce); } <START> catch (Exception e) <END> { Throwables.throwIfUnchecked(e); throw new RuntimeException(e); } ParameterizedType type = (ParameterizedType) field.getGenericType(); mType = type.getActualTypeArguments()[1]; this.adapter = ADAPTERS.get(mType); if (this.adapter == null && mType instanceof GenericArrayType) { this.adapter = ADAPTERS.get(ARRAY_REMAP.get(((GenericArrayType)mType).getGenericComponentType())); } if (mType instanceof Class && Enum.class.isAssignableFrom((Class<?>)mType)) { this.adapter = TypeAdapters.Str; } if (this.adapter == null) throw new IllegalArgumentException(String.format("The map '%s' of class '%s' has target values which are neither primitive nor an enum!", field.getName(), field.getDeclaringClass().getCanonicalName())); }</code><technical_language>cases of catch (Exception e) this immediately rethrow logging, if limit catch? This catch (IllegalAccessException e). I if avoid catching rethrowing some improvement, able avoid Throwables depending catch</technical_language>

Target:
private MapWrapper(String category, Field field, Object instance) { super(category, field, instance); try { theMap = (Map<String, Object>) field.get(instance); } catch (ClassCastException cce) { throw new IllegalArgumentException(String.format("The map '%s' of class '%s' must have the key type String!", field.getName(), field.getDeclaringClass().getCanonicalName()), cce); } catch (IllegalAccessException e) { throw new RuntimeException(e); } ParameterizedType type = (ParameterizedType) field.getGenericType(); mType = type.getActualTypeArguments()[1]; this.adapter = ADAPTERS.get(mType); if (this.adapter == null && mType instanceof GenericArrayType) { this.adapter = ADAPTERS.get(ARRAY_REMAP.get(((GenericArrayType)mType).getGenericComponentType())); } if (mType instanceof Class && Enum.class.isAssignableFrom((Class<?>)mType)) { this.adapter = TypeAdapters.Str; } if (this.adapter == null) throw new IllegalArgumentException(String.format("The map '%s' of class '%s' has target values which are neither primitive nor an enum!", field.getName(), field.getDeclaringClass().getCanonicalName())); }
Source:
<code>public void reset() { for (int i = 0; i < 2; i++) { <START> offset[i] = encoders[i].get(); <END> } }</code><technical_language>For loop</technical_language>

Target:
public void reset() { offset[0] = encoders[0].get(); offset[1] = encoders[1].get(); }
Source:
<code>public Iterator<TupleBatch> tupleBatchIteratorFromQuery(final String queryString, final Schema outputSchema) throws CatalogException { try { return queue.execute(new SQLiteJob<Iterator<TupleBatch>>() { @Override protected Iterator<TupleBatch> job(final SQLiteConnection sqliteConnection) throws CatalogException, SQLiteException { SQLiteStatement statement = sqliteConnection.prepare(queryString); List<TupleBatch> tuples = Lists.newLinkedList(); <START> Iterator<TupleBatch> iter = new SQLiteTupleBatchIterator(statement, sqliteConnection, outputSchema); <END> while (iter.hasNext()) { tuples.add(iter.next()); } return tuples.iterator(); } }).get(); } catch (InterruptedException | ExecutionException e) { throw new CatalogException(e); } }</code><technical_language>Iterators.addAll(tuples, new SQLiteTupleBatchIterator(statement, sqliteConnection, outputSchema))</technical_language>

Target:
public Iterator<TupleBatch> tupleBatchIteratorFromQuery(final String queryString, final Schema outputSchema) throws CatalogException { try { return queue.execute(new SQLiteJob<Iterator<TupleBatch>>() { @Override protected Iterator<TupleBatch> job(final SQLiteConnection sqliteConnection) throws CatalogException, SQLiteException { SQLiteStatement statement = sqliteConnection.prepare(queryString); List<TupleBatch> tuples = Lists.newLinkedList(); Iterators.addAll(tuples, new SQLiteTupleBatchIterator(statement, sqliteConnection, outputSchema)); return tuples.iterator(); } }).get(); } catch (InterruptedException | ExecutionException e) { throw new CatalogException(e); } }
Source:
<code>public static void main(String[] args) throws InterruptedException { Semaphore semaphore = new Semaphore(1); String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey};EntityPath={eventHubPath}"; EventHubClient client = new EventHubClientBuilder() .connectionString(connectionString) .build(); semaphore.acquire(); client.getPartitionIds().flatMap(partitionId -> client.getPartitionProperties(partitionId)) .subscribe(properties -> { System.out.println("The Event Hub has the following properties:"); <START> System.out.println(String.format( <END> "Event Hub Name: %s; Partition Id: %s; Is partition empty? %s; First Sequence Number: %s; " + "Last Enqueued Time: %s; Last Enqueued Sequence Number: %s; Last Enqueued Offset: %s", properties.eventHubPath(), properties.id(), properties.isEmpty(), properties.beginningSequenceNumber(), properties.lastEnqueuedTime(), properties.lastEnqueuedSequenceNumber(), properties.lastEnqueuedOffset())); }, error -> { System.err.println("Error occurred while fetching partition properties: " + error.toString()); }, () -> { semaphore.release(); }); System.out.println("Waiting for partition properties to complete..."); semaphore.acquire(); System.out.println("Finished."); }</code><technical_language>System.out.printf, String.format a println</technical_language>

Target:
public static void main(String[] args) throws InterruptedException { Semaphore semaphore = new Semaphore(1); String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey};EntityPath={eventHubPath}"; EventHubClient client = new EventHubClientBuilder() .connectionString(connectionString) .buildAsyncClient(); semaphore.acquire(); client.getPartitionIds().flatMap(partitionId -> client.getPartitionProperties(partitionId)) .subscribe(properties -> { System.out.println("The Event Hub has the following properties:"); System.out.printf( "Event Hub Name: %s; Partition Id: %s; Is partition empty? %s; First Sequence Number: %s; " + "Last Enqueued Time: %s; Last Enqueued Sequence Number: %s; Last Enqueued Offset: %s \n", properties.eventHubPath(), properties.id(), properties.isEmpty(), properties.beginningSequenceNumber(), properties.lastEnqueuedTime(), properties.lastEnqueuedSequenceNumber(), properties.lastEnqueuedOffset()); }, error -> { System.err.println("Error occurred while fetching partition properties: " + error.toString()); }, () -> { semaphore.release(); }); System.out.println("Waiting for partition properties to complete..."); semaphore.acquire(); System.out.println("Finished."); }
Source:
<code>public void releaseWhenMergeCumulateThrows() { final Error error = new Error(); ByteBuf cumulation = new UnpooledHeapByteBuf(UnpooledByteBufAllocator.DEFAULT, 0, 64) { @Override public ByteBuf writeBytes(ByteBuf src) { throw error; } }; <START> cumulation.writeByte(1); <END> ByteBuf in = Unpooled.buffer().writeZero(12); try { ByteToMessageDecoder.MERGE_CUMULATOR.cumulate(UnpooledByteBufAllocator.DEFAULT, cumulation, in); fail(); } catch (Error expected) { assertSame(error, expected); assertEquals(0, in.refCnt()); } }</code><technical_language>is this needed</technical_language>

Target:
public void releaseWhenMergeCumulateThrows() { final Error error = new Error(); ByteBuf cumulation = new UnpooledHeapByteBuf(UnpooledByteBufAllocator.DEFAULT, 0, 64) { @Override public ByteBuf writeBytes(ByteBuf src) { throw error; } }; cumulation.writeByte(1); ByteBuf in = Unpooled.buffer().writeZero(12); try { MERGE_CUMULATOR.cumulate(UnpooledByteBufAllocator.DEFAULT, cumulation, in); fail(); } catch (Error expected) { assertSame(error, expected); assertEquals(0, in.refCnt()); } }
Source:
<code>public final void testLog() { File loggingFile = logger.getLoggingFile(); logger.log("log_write_test"); try { <START> BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream( <END> loggingFile), "UTF-8")); assertEquals("--------------------SCRUMBLEDORE LOGGING FILE", reader.readLine()); String lastLine = ""; String line; while ((line = reader.readLine()) != null) { lastLine = line; } assertEquals("log_write_test", lastLine); reader.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }</code><technical_language>This test case reading files anymore. getFirstLine getLastLine methods, do need do I/O in test suite, is bad practice requires try-catch statements. refactor try-catch, while loops cetera? <testing</technical_language>

Target:
public final void testLog() { logger.log("log_write_test"); ArrayList<String> fetchedLog = logger.getLines(); assertEquals("--------------------SCRUMBLEDORE LOGGING FILE", fetchedLog.get(0)); assertEquals("log_write_test", fetchedLog.get(fetchedLog.size() - 1)); }
Source:
<code>public String index(Request request, Response response) throws IOException { String pipelineName = request.params("pipeline_name"); <START> Integer fromCounter = Integer.valueOf(request.params("from_counter")); <END> Integer toCounter = Integer.valueOf(request.params("to_counter")); HttpLocalizedOperationResult result = new HttpLocalizedOperationResult(); if (fromCounter < 1 || toCounter < 1) { throw new UnprocessableEntityException("The instance counters cannot be less than 1."); } boolean isBisect = pipelineService.isPipelineBisect(pipelineName, fromCounter, toCounter); List<MaterialRevision> materialRevisions = changesetService.revisionsBetween(pipelineName, fromCounter, toCounter, currentUsername(), result, true); if (result.isSuccessful()) { return writerForTopLevelObject(request, response, outputWriter -> ComparisonRepresenter.toJSON(outputWriter, pipelineName, fromCounter, toCounter, isBisect, materialRevisions)); } else { return renderHTTPOperationResult(result, request, response); } }</code><technical_language>do handle invalid counters, consider throwing a UnprocessableEntityException for a invalid counter if 1</technical_language>

Target:
public String index(Request request, Response response) throws IOException { String pipelineName = request.params("pipeline_name"); Integer fromCounter = getCounterValue(request, "from_counter"); Integer toCounter = getCounterValue(request, "to_counter"); HttpLocalizedOperationResult result = new HttpLocalizedOperationResult(); boolean isBisect = pipelineService.isPipelineBisect(pipelineName, fromCounter, toCounter); List<MaterialRevision> materialRevisions = changesetService.revisionsBetween(pipelineName, fromCounter, toCounter, currentUsername(), result, true); if (result.isSuccessful()) { return writerForTopLevelObject(request, response, outputWriter -> ComparisonRepresenter.toJSON(outputWriter, pipelineName, fromCounter, toCounter, isBisect, materialRevisions)); } else { return renderHTTPOperationResult(result, request, response); } }
Source:
<code>public void scan(HttpMessage msg, String param, String value) { String newValue = value.trim(); newValue = JWTUtils.extractingJWTFromParamValue(newValue); if (!JWTUtils.isTokenValid(newValue)) { LOGGER.info("Token: " + newValue + " is not a valid JWT token."); return; } try { sendAndReceive(msg); } catch (IOException e) { LOGGER.error(e); return; } <START> JWTTokenBean jwtTokenBean; <END> try { jwtTokenBean = JWTTokenBean.parseJWTToken(newValue); } catch (JWTException e) { LOGGER.error("Unable to parse JWT Token", e); return; } if (!JWTConfiguration.getInstance().isIgnoreClientConfigurationScan()) { if (performAttackClientSideConfigurations(msg, param, jwtTokenBean, value)) { return; } this.decreaseRequestCount(); } performAttackServerSideConfigurations(msg, param, jwtTokenBean, value); }</code><technical_language>discussed this avoid 'bean' naming</technical_language>

Target:
public void scan(HttpMessage msg, String param, String value) { String newValue = value.trim(); newValue = JWTUtils.extractingJWTFromParamValue(newValue); if (!JWTUtils.isTokenValid(newValue)) { LOGGER.info("Token: " + newValue + " is not a valid JWT token."); return; } try { sendAndReceive(msg); } catch (IOException e) { LOGGER.error(e); return; } JWTHolder jwtHolder; try { jwtHolder = JWTHolder.parseJWTToken(newValue); } catch (JWTException e) { LOGGER.error("Unable to parse JWT Token", e); return; } if (!JWTConfiguration.getInstance().isIgnoreClientConfigurationScan()) { if (performAttackClientSideConfigurations(msg, param)) { return; } this.decreaseRequestCount(); } performAttackServerSideConfigurations(msg, param, jwtHolder, value); }
Source:
<code>private String getEndpoint() { String endpointValue = this.getOptionValue(ENDPOINT.getOpt()); if (Guard.isStringNullOrEmpty(endpointValue)) { endpointValue = System.getenv("DS3_ENDPOINT"); } if (ENDPOINT == null) { <START> missingArgs.add(ENDPOINT.getOpt()); <END> return ""; } return endpointValue; }</code><technical_language>This check done caller</technical_language>

Target:
private String getEndpoint() { return this.getOptionValue(ENDPOINT.getOpt()); }
Source:
<code>public void reset() { long endSegment = Math.max(logMetadata.getGlobalTail(), 0L) / RECORDS_PER_LOG_FILE; log.warn("Global Tail:{}, endSegment={}", logMetadata.getGlobalTail(), endSegment); closeSegmentHandlers(endSegment); deleteFilesMatchingFilter(file -> { try { String segmentStr = file.getName().split("\\.")[0]; return Long.parseLong(segmentStr) <= endSegment; } catch (Exception e) { log.warn("reset: ignoring file {}", file.getName()); return false; } }); dataStore.resetStartingAddress(); dataStore.resetTailSegment(); logMetadata = new LogMetadata(); writeChannels.clear(); <START> logSizeQuota.release(Long.MIN_VALUE); <END> log.info("reset: Completed, end segment {}", endSegment); }</code><technical_language>is a hack. reset() a choice</technical_language>

Target:
public void reset() { long endSegment = Math.max(logMetadata.getGlobalTail(), 0L) / RECORDS_PER_LOG_FILE; log.warn("Global Tail:{}, endSegment={}", logMetadata.getGlobalTail(), endSegment); closeSegmentHandlers(endSegment); deleteFilesMatchingFilter(file -> { try { String segmentStr = file.getName().split("\\.")[0]; return Long.parseLong(segmentStr) <= endSegment; } catch (Exception e) { log.warn("reset: ignoring file {}", file.getName()); return false; } }); dataStore.resetStartingAddress(); dataStore.resetTailSegment(); logMetadata = new LogMetadata(); writeChannels.clear(); logSizeQuota.updateAndGet(resourceQuota -> new ResourceQuota("LogSizeQuota", estimateSize(logDir), logSizeLimit)); log.info("reset: Completed, end segment {}", endSegment); }
Source:
<code>public PacketTransformer getRTPTransformer() { <START> return this.retransmissionRequesterDelegate.getRTPTransformer(); <END> }</code><technical_language>I this hooks delagate transformer, bypassing RetransmissionRequesterImpl#reverseTransform()</technical_language>

Target:
public PacketTransformer getRTPTransformer() { return this; }
Source:
<code>private void restoreCommandState() { setVmTemplateId(getParameters().getVmTemplateId()); setVmId(getVmIdFromImageParameters()); isVmInDb = <START> !getVmId().equals(Guid.Empty) <END> && getVm() != null; }</code><technical_language>this changed in master</technical_language>

Target:
private void restoreCommandState() { setVmTemplateId(getParameters().getVmTemplateId()); setVmId(getVmIdFromImageParameters()); isVmInDb = getVm() != null; }
Source:
<code>private void ensureAccessToken() { if(isMaterialized()) { try { JwsHeader header = Jwts.parser() .setSigningKey(getDataStore().getApiKey().getSecret().getBytes("UTF-8")) .parseClaimsJws(getString(JWT)).getHeader(); String tokenType = (String) header.get("stt"); Assert.isTrue(tokenType.equals("access")); } catch (RuntimeException e) { <START> throw new InvalidJwtException(InvalidJwtException.JWT_INVALID_VALUE_ERROR, e); <END> } catch (UnsupportedEncodingException e) { log.error("Unsupported encoding for API secret"); throw new RuntimeException(e); } } else { String href = getStringProperty(HREF_PROP_NAME); if (href != null) { Assert.isTrue(href.contains("/accessTokens/"), "href does not belong to an access token."); } } }</code><technical_language>This incorrect me. JWT_INVALID_VALUE_ERROR means jwt format is correct. exception caused (like a wrong key). This error is misleading. I care of this</technical_language>

Target:
private void ensureAccessToken() { if(isMaterialized()) { try { JwsHeader header = Jwts.parser() .setSigningKey(getDataStore().getApiKey().getSecret().getBytes("UTF-8")) .parseClaimsJws(getString(JWT)).getHeader(); if (header == null || !"access".equals(header.get("stt"))) { String message = "Missing 'stt' property in header. This jwt is not a valid access_token."; log.debug(message); throw new InvalidJwtException(message); } } catch (UnsupportedJwtException uje) { String message = InvalidJwtException.UNSUPPORTED_JWT_ERROR; log.debug(message); throw new InvalidJwtException(message, uje); } catch (MalformedJwtException mje) { String message = "The JWT was not correctly constructed and therefore was rejected (it is not a valid JWS)."; log.debug(message); throw new InvalidJwtException(message, mje); } catch (SignatureException se) { String message = InvalidJwtException.INVALID_JWT_SIGNATURE_ERROR; log.debug(message); throw new InvalidJwtException(message, se); } catch (ExpiredJwtException eje) { String message = InvalidJwtException.EXPIRED_JWT_ERROR; log.debug(message); throw new InvalidJwtException(message, eje); } catch (IllegalArgumentException iae) { String message = "The JWT is null, empty or only contains whitespaces."; log.debug(message); throw new InvalidJwtException(message, iae); } catch (UnsupportedEncodingException uee) { String message = "The character encoding for the API secret is not supported."; log.debug(message); throw new InvalidJwtException(message, uee); } catch (InvalidJwtException e) { log.debug(e.getMessage()); throw e; } catch (Exception e) { throw new JwtException("JWT failed validation; it cannot be trusted.", e); } } else { String href = getStringProperty(HREF_PROP_NAME); if (href != null) { Assert.isTrue(href.contains("/accessTokens/"), "href does not belong to an access token."); } } }
Source:
<code>public void inputChanged(@Nullable Viewer viewer, @Nullable Object oldInput, @Nullable Object newInput) { fTableViewer = (TableViewer) viewer; if (newInput instanceof ISegmentStore<?>) { ISegmentStore<?> segmentStore = (ISegmentStore<?>) newInput; fSegmentArray = Iterables.toArray(segmentStore, ISegment.class); if (fComparator != null) { Arrays.sort(fSegmentArray, fComparator); } } else if (newInput instanceof ISegment[]) { fSegmentArray = (ISegment[]) newInput; if (fComparator != null) { <START> Arrays.sort(fSegmentArray, fComparator); <END> } } else { fSegmentArray = null; } }</code><technical_language>This modifies input array, is OK</technical_language>

Target:
public void inputChanged(@Nullable Viewer viewer, @Nullable Object oldInput, @Nullable Object newInput) { fTableViewer = (TableViewer) viewer; if (newInput instanceof ISegmentStore<?>) { ISegmentStore<?> segmentStore = (ISegmentStore<?>) newInput; fSegmentArray = Iterables.toArray(segmentStore, ISegment.class); if (fComparator != null) { Arrays.sort(fSegmentArray, fComparator); } } else if (newInput instanceof ISegment[]) { fSegmentArray = ((ISegment[]) newInput).clone(); if (fComparator != null) { Arrays.sort(fSegmentArray, fComparator); } } else { fSegmentArray = null; } }
Source:
<code>private boolean isConnectableByWkrdProtocol(String applicationIdentifier) { int attempts = 2; try { return checkForAvailabilityIn(applicationIdentifier, attempts) && getApplication(applicationIdentifier).isConnectableByWkrdProtocol(); } catch (InterruptedException e) { if (log.isLoggable(Level.FINE)) { <START> log.log(Level.FINE, "InterruptedException while checking availability."); <END> } } catch (IllegalStateException illegalStateException) { log.log(Level.WARNING, "Unknown error, application with identifier: " + applicationIdentifier + ", is not retrievable from list of registered applications"); } return false; }</code><technical_language>"InterruptedException occurred while ..."</technical_language>

Target:
private boolean isConnectableByWkrdProtocol(String applicationIdentifier) { int attempts = 2; try { return checkForAvailabilityIn(applicationIdentifier, attempts) && getApplication(applicationIdentifier).isConnectableByWkrdProtocol(); } catch (InterruptedException e) { if (log.isLoggable(Level.FINE)) { log.log(Level.FINE, "InterruptedException occured while checking availability of application in list of registered applications."); } } catch (IllegalStateException illegalStateException) { log.log(Level.WARNING, "Unknown error, application with identifier: " + applicationIdentifier + " is not retrievable from the list of registered applications"); } return false; }
Source:
<code>public EhcacheDataSyncMessage(final String cacheId, final Map<Long, Chain> chainMap) { this.cacheId = cacheId; <START> this.chainMap = chainMap; <END> }</code><technical_language>wrapped in Collections.unmodifiableMap() for peace of mind</technical_language>

Target:
public EhcacheDataSyncMessage(final String cacheId, final Map<Long, Chain> chainMap) { this.cacheId = cacheId; this.chainMap = Collections.unmodifiableMap(chainMap); }
Source:
<code>public boolean nextBatch(ObjectColumnVector<T> vector) throws IOException { boolean recordFound = false; while (!recordFound) { if (current >= total) { return false; } try { checkRead(); recordReader.readVector(vector, current, totalCountLoadedSoFar); current += vector.size(); recordFound = true; } catch (RuntimeException e) { throw new ParquetDecodingException(format("Can not read value at %d in block %d in file %s", current, currentBlock, file), e); } } <START> return true; <END> }</code><technical_language>return record count</technical_language>

Target:
public boolean nextBatch(ObjectColumnVector<T> vector) throws IOException { boolean recordFound = false; while (!recordFound) { if (current >= total) { return false; } try { checkRead(); ((VectorizedRecordReader) recordReader).readVector(vector, current, totalCountLoadedSoFar); current += vector.size(); recordFound = true; } catch (RuntimeException e) { throw new ParquetDecodingException(format("Can not read value at %d in block %d in file %s", current, currentBlock, file), e); } } return true; }
Source:
<code>@Override public int parseArguments(Parameters params) throws CmdLineException { final Jenkins j = Jenkins.get(); final String src = params.getParameter(0); T s = j.getItemByFullName(src, type()); if (s == null) { final Authentication who = Jenkins.getAuthentication(); <START> try (ACLContext aclContext = ACL.as(ACL.SYSTEM)) { <END> Item actual = j.getItemByFullName(src); if (actual == null) { LOGGER.log(Level.FINE, "really no item exists named {0}", src); } else { LOGGER.log(Level.WARNING, "running as {0} could not find {1} of {2}", new Object[] {who.getPrincipal(), actual, type()}); } } T nearest = Items.findNearest(type(), src, j); if (nearest != null) { throw new IllegalArgumentException("No such job '" + src + "'; perhaps you meant '" + nearest.getFullName() + "'?"); } else { throw new IllegalArgumentException("No such job '" + src + "'"); } } setter.addValue(s); return 1; }</code><technical_language>Good point _ a reserved keyword</technical_language>

Target:
@Override public int parseArguments(Parameters params) throws CmdLineException { final Jenkins j = Jenkins.get(); final String src = params.getParameter(0); T s = j.getItemByFullName(src, type()); if (s == null) { final Authentication who = Jenkins.getAuthentication(); try (ACLContext acl = ACL.as(ACL.SYSTEM)) { Item actual = j.getItemByFullName(src); if (actual == null) { LOGGER.log(Level.FINE, "really no item exists named {0}", src); } else { LOGGER.log(Level.WARNING, "running as {0} could not find {1} of {2}", new Object[] {who.getPrincipal(), actual, type()}); } } T nearest = Items.findNearest(type(), src, j); if (nearest != null) { throw new IllegalArgumentException("No such job '" + src + "'; perhaps you meant '" + nearest.getFullName() + "'?"); } else { throw new IllegalArgumentException("No such job '" + src + "'"); } } setter.addValue(s); return 1; }
Source:
<code><START> private String dumpTaskResult(final RunTaskResult result) <END> { final StringBuilder sb = new StringBuilder(); sb.append("["); for (Task task : result.getTasks()) { sb.append("{"); if (task.getTaskArn() != null) { sb.append("TaskArn: ").append(task.getTaskArn()).append(","); } if (task.getClusterArn() != null) { sb.append("ClusterArn: ").append(task.getClusterArn()).append(","); } if (task.getContainerInstanceArn() != null) { sb.append("ContainerInstanceArn: ").append(task.getContainerInstanceArn()).append(","); } if (task.getTaskDefinitionArn() != null) { sb.append("TaskDefinitionArn: ").append(task.getTaskDefinitionArn()).append(","); } if (task.getHealthStatus() != null) { sb.append("HealthStatus: ").append(task.getHealthStatus()).append(","); } if (task.getPlatformVersion() != null) { sb.append("PlatformVersion: ").append(task.getPlatformVersion()).append(","); } if (task.getCreatedAt() != null) { sb.append("CreatedAt: ").append(task.getCreatedAt()).append(","); } if (task.getStartedAt() != null) { sb.append("StartedAt: ").append(task.getStartedAt()); } sb.append("}"); sb.append(","); } sb.append("]"); return sb.toString(); }</code><technical_language>ditto. static method</technical_language>

Target:
private static String dumpTaskResult(final RunTaskResult result) { final StringBuilder sb = new StringBuilder(); sb.append("["); for (Task task : result.getTasks()) { sb.append("{"); if (task.getTaskArn() != null) { sb.append("TaskArn: ").append(task.getTaskArn()).append(","); } if (task.getClusterArn() != null) { sb.append("ClusterArn: ").append(task.getClusterArn()).append(","); } if (task.getContainerInstanceArn() != null) { sb.append("ContainerInstanceArn: ").append(task.getContainerInstanceArn()).append(","); } if (task.getTaskDefinitionArn() != null) { sb.append("TaskDefinitionArn: ").append(task.getTaskDefinitionArn()).append(","); } if (task.getHealthStatus() != null) { sb.append("HealthStatus: ").append(task.getHealthStatus()).append(","); } if (task.getPlatformVersion() != null) { sb.append("PlatformVersion: ").append(task.getPlatformVersion()).append(","); } if (task.getCreatedAt() != null) { sb.append("CreatedAt: ").append(task.getCreatedAt()).append(","); } if (task.getStartedAt() != null) { sb.append("StartedAt: ").append(task.getStartedAt()); } sb.append("}"); sb.append(","); } sb.append("]"); return sb.toString(); }
Source:
<code>public Subscription loadGallery(final Section section, Observer<List<Image>> observer) { final List<Image> images = galleryCache.get(section); if (images != null) { observer.onNext(images); } PublishSubject<List<Image>> galleryRequest = galleryRequests.get(section); if (galleryRequest != null) { return galleryRequest.subscribe(observer); } galleryRequest = PublishSubject.create(); galleryRequests.put(section, galleryRequest); Subscription subscription = galleryRequest.subscribe(observer); <START> galleryRequest.finallyDo(new Action0() { <END> @Override public void call() { galleryRequests.remove(section); } }); galleryRequest.doOnEach(new Action1<Notification<? super List<Image>>>() { @Override public void call(Notification<? super List<Image>> notification) { galleryCache.put(section, images); } }); galleryService.listGallery(section, Sort.VIRAL, 1) .map(new GalleryToImageList()) .flatMap(new Func1<List<Image>, Observable<Image>>() { @Override public Observable<Image> call(List<Image> images) { return Observable.from(images); } }) .filter(new Func1<Image, Boolean>() { @Override public Boolean call(Image image) { return !image.is_album; } }) .toList() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(galleryRequest); return subscription; }</code><technical_language>commit message disagrees this method name. Is doOnCompleted mutates Observable subscribing</technical_language>

Target:
public Subscription loadGallery(final Section section, Observer<List<Image>> observer) { final List<Image> images = galleryCache.get(section); if (images != null) { observer.onNext(images); } PublishSubject<List<Image>> galleryRequest = galleryRequests.get(section); if (galleryRequest != null) { return galleryRequest.subscribe(observer); } galleryRequest = PublishSubject.create(); galleryRequests.put(section, galleryRequest); Subscription subscription = galleryRequest.subscribe(observer); galleryRequest.doOnTerminate(new Action0() { @Override public void call() { galleryRequests.remove(section); } }); galleryRequest.doOnEach(new Action1<Notification<? super List<Image>>>() { @Override public void call(Notification<? super List<Image>> notification) { galleryCache.put(section, images); } }); galleryService.listGallery(section, Sort.VIRAL, 1) .map(new GalleryToImageList()) .flatMap(new Func1<List<Image>, Observable<Image>>() { @Override public Observable<Image> call(List<Image> images) { return Observable.from(images); } }) .filter(new Func1<Image, Boolean>() { @Override public Boolean call(Image image) { return !image.is_album; } }) .toList() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(galleryRequest); return subscription; }
Source:
<code>private boolean closeEnough(double left, double right) { <START> return Math.abs(left - right) < 0.001; <END> }</code><technical_language>Please define a constant for tolerance</technical_language>

Target:
private boolean closeEnough(double left, double right) { return Math.abs(left - right) < CLOSE_ENOUGH; }
Source:
<code><START> public static long getLeapYearsBefore(final long prolepticYear) { <END> long yearBefore = prolepticYear - 1; return (yearBefore / 4) - (yearBefore / 100) + (yearBefore / 400); }</code><technical_language>getLeapYearsBefore(...) public</technical_language>

Target:
static long getLeapYearsBefore(final long prolepticYear) { long yearBefore = prolepticYear - 1; return (yearBefore / 4) - (yearBefore / 100) + (yearBefore / 400); }
Source:
<code><START> public BaseDataCenterResponseHandler(DateCodecFactory dateCodecFactory) { <END> super(dateCodecFactory); this.builder = DataCenter.builder(); }</code><technical_language>Guice practices: this constructor visible package level</technical_language>

Target:
BaseDataCenterResponseHandler(DateCodecFactory dateCodecFactory) { super(dateCodecFactory); this.builder = DataCenter.builder(); }
Source:
<code>public void signInSilently(Promise promise) { if (_apiClient == null) { rejectWithNullClientError(promise); return; } <START> if (promiseWrapper.setPromiseWithInProgressCheck(promise, "restorePreviousSignIn")) { <END> UiThreadUtil.runOnUiThread(new Runnable() { @Override public void run() { Task<GoogleSignInAccount> result = _apiClient.silentSignIn(); if (result.isSuccessful()) { handleSignInTaskResult(result); } else { result.addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(Task task) { handleSignInTaskResult(task); } }); } } }); } }</code><technical_language>please code here, thanks</technical_language>

Target:
public void signInSilently(Promise promise) { if (_apiClient == null) { rejectWithNullClientError(promise); return; } if (promiseWrapper.setPromiseWithInProgressCheck(promise, "signInSilently")) { UiThreadUtil.runOnUiThread(new Runnable() { @Override public void run() { Task<GoogleSignInAccount> result = _apiClient.silentSignIn(); if (result.isSuccessful()) { handleSignInTaskResult(result); } else { result.addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(Task task) { handleSignInTaskResult(task); } }); } } }); } }
Source:
<code>public void byTriplet() throws Exception { TestRepository<InMemoryRepository> repo = createProject("repo"); Change change = newChange(repo, null, null, null, "branch").insert(); String k = change.getKey().get(); assertResultEquals(change, queryOne("repo~branch~" + k)); assertResultEquals(change, queryOne("change:repo~branch~" + k)); assertResultEquals(change, queryOne("repo~refs/heads/branch~" + k)); assertResultEquals(change, queryOne("change:repo~refs/heads/branch~" + k)); assertResultEquals(change, queryOne("repo~branch~" + k.substring(0, 10))); assertResultEquals(change, queryOne("change:repo~branch~" + k.substring(0, 10))); assertThat(query("foo~bar")).isEmpty(); assertBadQuery("change:foo~bar"); <START> assertThat(query("change:otherrepo~branch~" + k)).isEmpty(); assertThat(query("change:otherrepo~branch~" + k)).isEmpty(); <END> assertThat(query("change:repo~otherbranch~" + k)).isEmpty(); assertThat(query( "change:repo~branch~I0000000000000000000000000000000000000000")) .isEmpty(); }</code><technical_language>A duplicate</technical_language>

Target:
public void byTriplet() throws Exception { TestRepository<InMemoryRepository> repo = createProject("repo"); Change change = newChange(repo, null, null, null, "branch").insert(); String k = change.getKey().get(); assertResultEquals(change, queryOne("repo~branch~" + k)); assertResultEquals(change, queryOne("change:repo~branch~" + k)); assertResultEquals(change, queryOne("repo~refs/heads/branch~" + k)); assertResultEquals(change, queryOne("change:repo~refs/heads/branch~" + k)); assertResultEquals(change, queryOne("repo~branch~" + k.substring(0, 10))); assertResultEquals(change, queryOne("change:repo~branch~" + k.substring(0, 10))); assertThat(query("foo~bar")).isEmpty(); assertBadQuery("change:foo~bar"); assertThat(query("otherrepo~branch~" + k)).isEmpty(); assertThat(query("change:otherrepo~branch~" + k)).isEmpty(); assertThat(query("repo~otherbranch~" + k)).isEmpty(); assertThat(query("change:repo~otherbranch~" + k)).isEmpty(); assertThat(query("repo~branch~I0000000000000000000000000000000000000000")) .isEmpty(); assertThat(query( "change:repo~branch~I0000000000000000000000000000000000000000")) .isEmpty(); }
Source:
<code>private void findForgottenFiles(File snapshotDir) { try { Collection<File> snapshotFiles = FileUtils.listFiles(snapshotDir, FileFilterUtils.fileFileFilter(), null); File columnfamilyDir = snapshotDir.getParentFile().getParentFile(); Collection<File> columnfamilyFiles = FileUtils.listFiles(columnfamilyDir, FileFilterUtils.fileFileFilter(), null); for (File file : snapshotFiles) { File originalFile = new File(columnfamilyDir, file.getName()); columnfamilyFiles.remove(originalFile); } if (columnfamilyFiles.size() == 0) return; Collection<File> forgottenFiles = columnfamilyFiles.stream().filter(file -> file.isFile()).filter(file -> { Instant fileModification = Instant.ofEpochMilli(file.lastModified()); return fileModification.isBefore(snapshotInstant); }).collect(Collectors.toList()); forgottenFiles.parallelStream().forEach(file -> logger.info("Forgotten file: for CF: {}", file.getAbsolutePath(), columnfamilyDir.getName())); if (forgottenFiles == null || forgottenFiles.size() == 0) return; backupMetrics.incrementForgottenFiles(forgottenFiles.size()); logger.warn("Forgotten files: found for CF: {}", forgottenFiles.size(), columnfamilyDir.getName()); <START> }catch (Exception e) <END> { logger.error("Exception occurred while trying to find forgottenFile. Ignoring the error and continue with backup.", e); } }</code><technical_language>nit: formatting</technical_language>

Target:
private void findForgottenFiles(File snapshotDir) { try { Collection<File> snapshotFiles = FileUtils.listFiles(snapshotDir, FileFilterUtils.fileFileFilter(), null); File columnfamilyDir = snapshotDir.getParentFile().getParentFile(); IOFileFilter tmpFileFilter1 = FileFilterUtils.suffixFileFilter(TMP_EXT); IOFileFilter tmpFileFilter2 = FileFilterUtils.asFileFilter(pathname -> tmpFilePattern.matcher(pathname.getName()).matches()); IOFileFilter tmpFileFilter = FileFilterUtils.or(tmpFileFilter1, tmpFileFilter2); IOFileFilter ageFilter = FileFilterUtils.ageFileFilter(snapshotInstant.minus(config.getForgottenFileGracePeriodDays(), ChronoUnit.DAYS).toEpochMilli()); IOFileFilter fileFilter = FileFilterUtils.and(FileFilterUtils.notFileFilter(tmpFileFilter), FileFilterUtils.fileFileFilter(), ageFilter); Collection<File> columnfamilyFiles = FileUtils.listFiles(columnfamilyDir, fileFilter, null); for (File file : snapshotFiles) { File originalFile = new File(columnfamilyDir, file.getName()); columnfamilyFiles.remove(originalFile); } if (columnfamilyFiles.size() == 0) return; columnfamilyFiles.parallelStream().forEach(file -> logger.info("Forgotten file: found for CF: {}", file.getAbsolutePath(), columnfamilyDir.getName())); backupMetrics.incrementForgottenFiles(columnfamilyFiles.size()); logger.warn("# of forgotten files: found for CF: {}", columnfamilyFiles.size(), columnfamilyDir.getName()); } catch (Exception e) { logger.error("Exception occurred while trying to find forgottenFile. Ignoring the error and continuing with remaining backup", e); } }