auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void shouldUploadIdentifiersFromSource() throws Exception { String uploadIdentifiers = "{\"batchSizeToUpload\": \"10\"," + "\"sourceUuid\": \""+POOL_SOURCE_UUID+"\"}"; MockHttpServletRequest getRequest = newGetRequest(getURI() + "/" + POOL_SOURCE_UUID); getRequest.addParameter("v", "custom:(identifiers)"); SimpleObject initialIdentifiers = deserialize(handle(getRequest)); assertEquals(initialIdentifiers.get("identifiers").toString(), "[]"); newPostRequest(getURI() + "/" + POOL_SOURCE_UUID, uploadIdentifiers); MockHttpServletRequest getRequestAfterPost = newGetRequest(getURI() + "/" + POOL_SOURCE_UUID); getRequestAfterPost.addParameter("v", "custom:(identifiers)"); SimpleObject identifiersAfterUpload = deserialize(handle(getRequestAfterPost)); <START> assertTrue(identifiersAfterUpload.get("identifiers").toString().length() > 2); <END> }</code><technical_language>supposed compare actual expected instead of length</technical_language>

Target:
public void shouldUploadIdentifiersFromSource() throws Exception { String uploadIdentifiers = "{\"batchSize\": \"2\"," + "\"operation\": \"uploadFromSource\"}"; MockHttpServletRequest postRequest = newPostRequest(getURI() + "/" + POOL_SOURCE_UUID, uploadIdentifiers); SimpleObject uploadResult = deserialize(handle(postRequest)); assertThat( uploadResult.toString(), containsString(POOL_SOURCE_UUID) ); MockHttpServletRequest getRequestAfterUpload = newGetRequest(getURI() + "/" + POOL_SOURCE_UUID); getRequestAfterUpload.addParameter("v", "custom:(identifiers)"); SimpleObject identifiersAfterUpload = deserialize(handle(getRequestAfterUpload)); assertThat( identifiersAfterUpload.get("identifiers").toString(), allOf( containsString("Test Identifier Pool: G-0"), containsString("Test Identifier Pool: H-8") )); }
Source:
<code>private List<JobID> tryExecuteJobs(final DispatcherGateway dispatcherGateway, final PackagedProgram program, final Configuration configuration) { checkState(!configuration.get(DeploymentOptions.ATTACHED)); final List<JobID> applicationJobIds = new ArrayList<>(); final PipelineExecutorServiceLoader executorServiceLoader = new EmbeddedExecutorServiceLoader(applicationJobIds, dispatcherGateway); try { ClientUtils.executeProgram(executorServiceLoader, configuration, program); } catch (ProgramInvocationException e) { LOG.warn("Could not execute application: ", e); <START> throw new CompletionException("Could not execute application.", e); <END> } return applicationJobIds; }</code><technical_language>FlinkRuntimeException handle in supplyAsync caller site. tight this method run in future context. do we</technical_language>

Target:
private List<JobID> tryExecuteJobs(final DispatcherGateway dispatcherGateway, final PackagedProgram program, final Configuration configuration) { configuration.set(DeploymentOptions.ATTACHED, false); final List<JobID> applicationJobIds = new ArrayList<>(); final PipelineExecutorServiceLoader executorServiceLoader = new EmbeddedExecutorServiceLoader(applicationJobIds, dispatcherGateway); try { ClientUtils.executeProgram(executorServiceLoader, configuration, program, enforceSingleJobExecution, forbidBlockingJobClient); } catch (ProgramInvocationException e) { LOG.warn("Could not execute application: ", e); throw new FlinkRuntimeException("Could not execute application.", e); } return applicationJobIds; }
Source:
<code>public MockitoSession startMocking() { List<Object> effectiveTestClassInstances; String effectiveName; if (testClassInstances.isEmpty()) { effectiveTestClassInstances = emptyList(); <START> effectiveName = this.name == null ? UUID.randomUUID().toString() : this.name; <END> } else { effectiveTestClassInstances = new ArrayList<Object>(testClassInstances); Object lastTestClassInstance = testClassInstances.get(testClassInstances.size() - 1); effectiveName = this.name == null ? lastTestClassInstance.getClass().getName() : this.name; } Strictness effectiveStrictness = this.strictness == null ? Strictness.STRICT_STUBS : this.strictness; MockitoLogger logger = this.logger == null ? new ConsoleMockitoLogger() : new MockitoLoggerAdapter(this.logger); return new DefaultMockitoSession(effectiveTestClassInstances, effectiveName, effectiveStrictness, logger); }</code><technical_language>Random String provide great user experience. more self-describing in case users name? empty String "test". current functionality of Mockito, circumstances random UUID visible user</technical_language>

Target:
public MockitoSession startMocking() { List<Object> effectiveTestClassInstances; String effectiveName; if (testClassInstances.isEmpty()) { effectiveTestClassInstances = emptyList(); effectiveName = this.name == null ? "<Unnamed Session>" : this.name; } else { effectiveTestClassInstances = new ArrayList<Object>(testClassInstances); Object lastTestClassInstance = testClassInstances.get(testClassInstances.size() - 1); effectiveName = this.name == null ? lastTestClassInstance.getClass().getName() : this.name; } Strictness effectiveStrictness = this.strictness == null ? Strictness.STRICT_STUBS : this.strictness; MockitoLogger logger = this.logger == null ? new ConsoleMockitoLogger() : new MockitoLoggerAdapter(this.logger); return new DefaultMockitoSession(effectiveTestClassInstances, effectiveName, effectiveStrictness, logger); }
Source:
<code>public static Container full() { <START> return new RunContainer(1, new short[]{0, -1, 0, 0, 0, 0, 0, 0}); <END> }</code><technical_language>point of 6 trailing zeros</technical_language>

Target:
public static Container full() { return new RunContainer(1, new short[]{0, -1}); }
Source:
<code>protected void entryRetrieved(long entryAddress) { lruLock.lock(); try { if (trace) { <START> log.tracef("Moving node 0x%016x to the end", entryAddress); <END> } moveToEnd(entryAddress); super.entryRetrieved(entryAddress); } finally { lruLock.unlock(); } }</code><technical_language>too, "Moving entry 0x%016x end of LRU list"</technical_language>

Target:
protected void entryRetrieved(long entryAddress) { lruLock.lock(); try { if (trace) { log.tracef("Moving entry 0x%016x to the end of the LRU list", entryAddress); } moveToEnd(entryAddress); super.entryRetrieved(entryAddress); } finally { lruLock.unlock(); } }
Source:
<code>private ComponentMetric extractMetric(String componentName, Map<String, ?> componentMap) { Long inputRecords = 0L; Long outputRecords = 0L; Double processedTime = 0.0d; <START> if (componentMap.containsKey("executed")) { <END> Number executed = (Number) componentMap.get("executed"); inputRecords = executed.longValue(); } if (componentMap.containsKey("emitted")) { Number emitted = (Number) componentMap.get("emitted"); outputRecords = emitted.longValue(); } if (componentMap.containsKey("processLatency")) { String processLatencyStr = (String) componentMap.get("processLatency"); try { processedTime = Double.parseDouble(processLatencyStr); } catch (NumberFormatException e) { } } return new ComponentMetric(componentName, inputRecords, outputRecords, processedTime); }</code><technical_language>capture "executed" constants in a single file String Constants</technical_language>

Target:
private ComponentMetric extractMetric(String componentName, Map<String, ?> componentMap) { Long inputRecords = 0L; Long outputRecords = 0L; Double processedTime = 0.0d; Long failedRecords = 0L; if (componentMap.containsKey(StormMetricsConstant.COMPONENT_EXECUTED_TUPLES)) { Number executed = (Number) componentMap.get(StormMetricsConstant.COMPONENT_EXECUTED_TUPLES); inputRecords = executed.longValue(); } if (componentMap.containsKey(StormMetricsConstant.COMPONENT_EMITTED_TUPLES)) { Number emitted = (Number) componentMap.get(StormMetricsConstant.COMPONENT_EMITTED_TUPLES); outputRecords = emitted.longValue(); } if (componentMap.containsKey(StormMetricsConstant.COMPONENT_PROCESS_LATENCY)) { String processLatencyStr = (String) componentMap.get(StormMetricsConstant.COMPONENT_PROCESS_LATENCY); try { processedTime = Double.parseDouble(processLatencyStr); } catch (NumberFormatException e) { } } if (componentMap.containsKey(StormMetricsConstant.COMPONENT_FAILED_TUPLES)) { Number failed = (Number) componentMap.get(StormMetricsConstant.COMPONENT_FAILED_TUPLES); failedRecords = failed.longValue(); } return new ComponentMetric(componentName, inputRecords, outputRecords, failedRecords, processedTime); }
Source:
<code>public boolean isSortedSelectFacet() { <START> return facet.getType().equals(SORTED_SELECT); <END> }</code><technical_language>extract a private method for of takes type parameter</technical_language>

Target:
public boolean isSortedSelectFacet() { return isFacetType(SORTED_SELECT); }
Source:
<code>protected Object doTransform(Message<?> message) { <START> Assert.state(message.getPayload() instanceof SpecificRecordBase, <END> "Payload must be a subclass of 'SpecificRecordBase'"); SpecificRecord specific = (SpecificRecord) message.getPayload(); ByteArrayOutputStream out = new ByteArrayOutputStream(); BinaryEncoder encoder = this.encoderFactory.directBinaryEncoder(out, null); DatumWriter<Object> writer = new SpecificDatumWriter<>(specific.getSchema()); try { writer.write(specific, encoder); encoder.flush(); } catch (IOException e) { throw new UncheckedIOException(e); } return out.toByteArray(); }</code><technical_language>SpecificRecord enough here? is asking next line for casting is is contract for deserialization</technical_language>

Target:
protected Object doTransform(Message<?> message) { Assert.state(message.getPayload() instanceof SpecificRecord, "Payload must be an implementation of 'SpecificRecord'"); SpecificRecord specific = (SpecificRecord) message.getPayload(); ByteArrayOutputStream out = new ByteArrayOutputStream(); BinaryEncoder encoder = this.encoderFactory.directBinaryEncoder(out, null); DatumWriter<Object> writer = new SpecificDatumWriter<>(specific.getSchema()); try { writer.write(specific, encoder); encoder.flush(); } catch (IOException e) { throw new UncheckedIOException(e); } return getMessageBuilderFactory().withPayload(out.toByteArray()) .copyHeaders(message.getHeaders()) .setHeader(AvroHeaders.TYPE, specific.getClass()) .build(); }
Source:
<code>public Response getPayment(@ApiParam(value = "accountId", hidden = true) @Auth Account account, @PathParam("paymentId") String paymentId) { logger.info("Payment request - paymentId={}", paymentId); String url = account.getPaymentType().equals(DIRECT_DEBIT) ? connectorDDUrl : connectorUrl; UriBuilder builder = UriBuilder .fromPath(url) .path(format("/v1/api/accounts/%s/charges/%s", account.getAccountId(), paymentId)); <START> Collections.<Pair<String, String>>emptyList().stream().forEach(pair -> { <END> if (isNotBlank(pair.getRight())) { builder.queryParam(pair.getKey(), pair.getValue()); } }); Response connectorResponse = client .target(builder.toString()) .request() .get(); if (connectorResponse.getStatus() == SC_OK) { ChargeFromResponse chargeFromResponse = connectorResponse.readEntity(ChargeFromResponse.class); URI paymentURI = publicApiUriGenerator.getPaymentURI(baseUrl, chargeFromResponse.getChargeId()); PaymentWithAllLinks payment = PaymentWithAllLinks.getPaymentWithLinks( account.getPaymentType(), chargeFromResponse, paymentURI, publicApiUriGenerator.getPaymentEventsURI(baseUrl, chargeFromResponse.getChargeId()), publicApiUriGenerator.getPaymentCancelURI(baseUrl, chargeFromResponse.getChargeId()), publicApiUriGenerator.getPaymentRefundsURI(baseUrl, chargeFromResponse.getChargeId())); logger.info("Payment returned - [ ]", payment); return Response.ok(payment).build(); } throw new GetChargeException(connectorResponse); }</code><technical_language>streaming empty list here</technical_language>

Target:
public Response getPayment(@ApiParam(value = "accountId", hidden = true) @Auth Account account, @PathParam("paymentId") String paymentId) { logger.info("Payment request - paymentId={}", paymentId); Response connectorResponse = client .target(connectorUriGenerator.chargeURI(account, paymentId)) .request() .get(); if (connectorResponse.getStatus() == SC_OK) { ChargeFromResponse chargeFromResponse = connectorResponse.readEntity(ChargeFromResponse.class); URI paymentURI = publicApiUriGenerator.getPaymentURI(chargeFromResponse.getChargeId()); PaymentWithAllLinks payment = PaymentWithAllLinks.getPaymentWithLinks( account.getPaymentType(), chargeFromResponse, paymentURI, publicApiUriGenerator.getPaymentEventsURI(chargeFromResponse.getChargeId()), publicApiUriGenerator.getPaymentCancelURI(chargeFromResponse.getChargeId()), publicApiUriGenerator.getPaymentRefundsURI(chargeFromResponse.getChargeId())); logger.info("Payment returned - [ ]", payment); return Response.ok(payment).build(); } throw new GetChargeException(connectorResponse); }
Source:
<code>public Object resolveArtifact(EObject artifact) { <START> ArtifactWrapper wrapper = (ArtifactWrapper) artifact; <END> String uri = wrapper.getUri(); CapraOfficeObject object = new CapraOfficeObject(); object.setUri(uri); return object; }</code><technical_language>I pretty unchecked cast warning. I pertinent add a check here, code more robust</technical_language>

Target:
public Object resolveArtifact(EObject artifact) { if (artifact instanceof ArtifactWrapper) { ArtifactWrapper wrapper = (ArtifactWrapper) artifact; String uri = wrapper.getUri(); CapraOfficeObject object = new CapraOfficeObject(); object.setUri(uri); return object; } else return null; }
Source:
<code>public Map<String, Collection<String>> credentialTypeToParameterNames() { Map<String, Collection<String>> options = new LinkedHashMap<String, Collection<String>>(); options.put("clientCertificate", Arrays.asList("keystore", "password")); <START> return options; <END> }</code><technical_language>change this options.put("pem", Arrays.asList("pem"); depending ultimate approach</technical_language>

Target:
public Map<String, Collection<String>> credentialTypeToParameterNames() { Map<String, Collection<String>> options = new LinkedHashMap<String, Collection<String>>(); options.put("clientCertificate", Arrays.asList("certificatePem", "keyPem")); return options; }
Source:
<code>public static void main(String[] args) throws Exception { Crypto crypto = Crypto.initJava(); NetworkAccess network = NetworkAccess.buildJava(new URL("<LINK_0>")).get(); String username = args[0]; Console console = System.console(); String password = new String(console.readPassword("Enter password for " + username + ":")); UserContext context = UserContext.signIn(username, password, network, crypto).get(); <START> LOG.info("Logged in " + username + " successfully!"); <END> }</code><technical_language>This is designed a cmd line class, this System.out</technical_language>

Target:
public static void main(String[] args) throws Exception { Crypto crypto = Crypto.initJava(); NetworkAccess network = NetworkAccess.buildJava(new URL("<LINK_0>")).get(); String username = args[0]; Console console = System.console(); String password = new String(console.readPassword("Enter password for " + username + ":")); UserContext context = UserContext.signIn(username, password, network, crypto).get(); System.out.println("Logged in " + username + " successfully!"); }
Source:
<code>public void testCreateTableOnExistingCache() throws Exception { client().getOrCreateCache("new"); try { doTestCustomNames("new", null, null); GridTestUtils.assertThrows(null, new Callable<Object>() { @Override public Object call() throws Exception { doTestCustomNames("new", null, null); return null; } }, IgniteSQLException.class, "Table already exists: NameTest"); <START> <END> } finally { client().destroyCache("new"); } }</code><technical_language>Typo: empty line omitted</technical_language>

Target:
public void testCreateTableOnExistingCache() { String cacheName = "new"; try { client().getOrCreateCache(cacheName); doTestCustomNames("new", null, null); String createTemplate = "CREATE TABLE \"%s\" (id int primary key, x varchar) WITH " + "\"wrap_key,wrap_value,cache_name=%s\""; GridTestUtils.assertThrows(null, () -> { execute(client(), String.format(createTemplate, "NameTest", cacheName)); return null; }, IgniteSQLException.class, "Table already exists: NameTest"); GridTestUtils.assertThrows(null, () -> { execute(client(), String.format(createTemplate, "NameTest1", cacheName)); return null; }, IgniteSQLException.class, "Cache is already indexed: " + cacheName); } finally { client().destroyCache("new"); } }
Source:
<code>private String wrapValueWithTypeInformation(Object object, String valueToHash) { <START> return object.getClass().getCanonicalName() <END> + TYPE_VALUE_DELIMITER + NESTED_HASHABLE_START + valueToHash + NESTED_HASHABLE_END; }</code><technical_language>String.format making format string a constant instead of of delimiters a separate this more readable</technical_language>

Target:
private String wrapValueWithTypeInformation(Object object, String valueToHash) { return String.format( CLASS_TYPE_VALUE_FORMAT_STRING, object.getClass().getCanonicalName(), valueToHash ); }
Source:
<code>protected static void configureFhirRequest(String resourceFormat, HttpRequest request) { request.addHeader("User-Agent", "Java FHIR Client for FHIR"); LOG.info("Resource format: " + resourceFormat + ", Feed Format: " + FeedFormat.FEED_XML.getHeader()); request.addHeader("Accept", resourceFormat); <START> request.addHeader("Accept", FeedFormat.FEED_XML.getHeader()); <END> request.addHeader("Content-Type", ResourceFormat.RESOURCE_XML.getHeader() + ";charset=" + DEFAULT_CHARSET); request.addHeader("Accept-Charset", DEFAULT_CHARSET); }</code><technical_language>"Accept" header is set twice, is this intentional</technical_language>

Target:
protected static void configureFhirRequest(String resourceFormat, HttpRequest request) { request.addHeader("User-Agent", "Java FHIR Client for FHIR"); LOG.info("Resource format: " + resourceFormat + ", Feed Format: " + FeedFormat.FEED_XML.getHeader()); request.addHeader("Accept", resourceFormat + ", " + FeedFormat.FEED_XML.getHeader()); request.addHeader("Content-Type", ResourceFormat.RESOURCE_XML.getHeader() + ";charset=" + DEFAULT_CHARSET); request.addHeader("Accept-Charset", DEFAULT_CHARSET); }
Source:
<code><START> public void updateEventSourceGlobally(final Map<String, String> attributes) { <END> clearEventSourceAttributes(); for (final Map.Entry<String, String> entry : attributes.entrySet()) { if (entry.getValue() != null) { addGlobalAttribute(entry.getKey(), entry.getValue()); } } this.eventSourceAttributes = attributes; }</code><technical_language>is this called from? part of public API, no? If pinpointManager.getAnalyticsClient().setCampaignAttributes(...) in code base, this a breaking change. for other method, _add_ this method, pass @Deprecated public void setCampaignAttributes(....)</technical_language>

Target:
public void updateEventSourceGlobally(final Map<String, String> attributes) { clearEventSourceAttributes(); for (final Map.Entry<String, String> entry : attributes.entrySet()) { if (entry.getValue() != null) { addGlobalAttribute(entry.getKey(), entry.getValue()); } } eventSourceAttributes.putAll(attributes); }
Source:
<code>public void testReplicationFailure() throws Exception { controlledRpcManager.failFor(VersionedPrepareCommand.class); try { TransactionManager tm = cache(0).getAdvancedCache().getTransactionManager(); tm.begin(); cache(0).put("k0", "v"); try { tm.commit(); <START> AssertJUnit.fail(); <END> } catch (RollbackException e) { } } finally { controlledRpcManager.stopFailing(); } }</code><technical_language>expectException</technical_language>

Target:
public void testReplicationFailure() throws Exception { controlledRpcManager.failFor(VersionedPrepareCommand.class); try { TransactionManager tm = cache(0).getAdvancedCache().getTransactionManager(); tm.begin(); cache(0).put("k0", "v"); Exceptions.expectException(RollbackException.class, tm::commit); } finally { controlledRpcManager.stopFailing(); } }
Source:
<code><START> static String from(final ServerError serverError) { <END> final String message = serverError.getMessage(); if (message != null && message.matches(AUTH_ERROR_PATTERN)) { final int code = Integer.parseInt(message.substring(CODE_START_POSITION)); if (code < 1 || code > AUTH_MESSAGES.length) { return message; } return AUTH_MESSAGES[code - 1]; } return message; }</code><technical_language>Please, simplify this method Map<String, String> (code description)</technical_language>

Target:
static String from(final ServerError serverError) { final String message = serverError.getMessage(); return StringUtils.defaultString(AUTH_DICT.get(message), message); }
Source:
<code>protected boolean isWsAgentRequest(String url) { WorkspaceImpl currentWorkspace = appContext.getWorkspace(); if (currentWorkspace == null || !isWsAgentStarted(currentWorkspace)) { return false; } <START> final boolean contains = url.contains(nullToEmpty(appContext.getWsAgentServerApiEndpoint())); <END> return contains; }</code><technical_language>do need this variable</technical_language>

Target:
protected boolean isWsAgentRequest(String url) { WorkspaceImpl currentWorkspace = appContext.getWorkspace(); if (currentWorkspace == null || !isWsAgentStarted(currentWorkspace)) { return false; } return url.contains(nullToEmpty(appContext.getWsAgentServerApiEndpoint())); }
Source:
<code>private ThresholdingSession getSessionForAgent(CollectionAgent agent, RrdRepository repository) throws ThresholdInitializationException { if (thresholdingService == null) { isThresholdingEnabled = false; throw new ThresholdInitializationException("No ThresholdingService available. No future Threshholding will be done"); } int nodeId = agent.getNodeId(); String hostAddress = agent.getHostAddress(); String serviceName = adapterConfig.getName(); String sessionKey = getSessionKey(nodeId, hostAddress, serviceName); <START> ThresholdingSession session = agentThresholdingSessions.asMap().get(sessionKey); <END> if (session == null) { session = thresholdingService.createSession(nodeId, hostAddress, serviceName, repository, EMPTY_SERVICE_PARAMETERS); agentThresholdingSessions.put(sessionKey, session); } return session; }</code><technical_language>Do need call asMap() for cache lookup</technical_language>

Target:
private ThresholdingSession getSessionForAgent(CollectionAgent agent, RrdRepository repository) throws ThresholdInitializationException { if (thresholdingService == null) { isThresholdingEnabled.set(false); throw new ThresholdInitializationException("No ThresholdingService available. No future Threshholding will be done"); } int nodeId = agent.getNodeId(); String hostAddress = agent.getHostAddress(); String serviceName = adapterConfig.getName(); String sessionKey = getSessionKey(nodeId, hostAddress, serviceName); ThresholdingSession session = agentThresholdingSessions.getIfPresent(sessionKey); if (session == null) { session = thresholdingService.createSession(nodeId, hostAddress, serviceName, repository, EMPTY_SERVICE_PARAMETERS); agentThresholdingSessions.put(sessionKey, session); } return session; }
Source:
<code>private void setXsrfCookie(String cookieName) throws GerritLoginException { <START> Optional<Cookie> cookie = Arrays.stream(httpClient.getState().getCookies()) .filter(c -> cookieName.equals(c.getName())) .findFirst(); <END> cookie.ifPresent(this::setXsrfCookie); cookie.orElseThrow(() -> new GerritLoginException()); }</code><technical_language>this part similiar #validateAuthenticationState consider extracting common code a shared method</technical_language>

Target:
private void setXsrfCookie(String cookieName) throws GerritLoginException { Optional<Cookie> cookie = findCookieWithName(cookieName, httpClient); cookie.ifPresent(this::setXsrfCookie); cookie.orElseThrow(() -> new GerritLoginException()); }
Source:
<code>public IBlockState getStateFromMeta(int meta) { <START> return getDefaultState().withProperty(LIT, (meta >> 3) == 1); <END> }</code><technical_language>need for bitwise operations (>> 3) lit property is additional saved. this removed meta checked for equality 1. require removal of reverse operation in getMetaFromstate (just meta 1 0 based lit property is set to)</technical_language>

Target:
public IBlockState getStateFromMeta(int meta) { return getDefaultState().withProperty(LIT, (meta == 1)); }
Source:
<code>public boolean equals(Object obj) { if (obj == null) { return false; } if (this == obj) { return true; } if (!(obj instanceof CompactConfig)) { return false; } CompactConfig that = (CompactConfig) obj; <START> return mInputPartitionInfo.equals(that.mInputPartitionInfo) <END> && mInput.equals(that.mInput) && mOutput.equals(that.mOutput) && mMaxNumFiles == that.mMaxNumFiles && mMinFileSize == that.mMinFileSize; }</code><technical_language>this output partition too</technical_language>

Target:
public boolean equals(Object obj) { if (obj == null) { return false; } if (this == obj) { return true; } if (!(obj instanceof CompactConfig)) { return false; } CompactConfig that = (CompactConfig) obj; return mInputPartitionInfo.equals(that.mInputPartitionInfo) && mOutputPartitionInfo.equals(that.mOutputPartitionInfo) && mInput.equals(that.mInput) && mOutput.equals(that.mOutput) && mMaxNumFiles == that.mMaxNumFiles && mMinFileSize == that.mMinFileSize; }
Source:
<code>void release() { if (mSurface == null && mSurfaceTexture == null) { return; } Resource resource; synchronized (mLock) { resource = mResourceMap.get(mSurfaceTexture); } if (resource != null) { releaseResourceWhenDetached(resource); } mSurfaceTexture = null; mSurface = null; if <START> (!mSurfaceToReleaseList.isEmpty()) <END> { for (Surface surface : mSurfaceToReleaseList) { surface.release(); } mSurfaceToReleaseList.clear(); } }</code><technical_language>if-check for empty list removed. for-loop clear call work for empty list</technical_language>

Target:
void release() { if (mSurface == null && mSurfaceTexture == null) { return; } Resource resource; synchronized (mLock) { resource = mResourceMap.get(mSurfaceTexture); } if (resource != null) { releaseResourceWhenDetached(resource); } mSurfaceTexture = null; mSurface = null; for (Surface surface : mSurfaceToReleaseList) { surface.release(); } mSurfaceToReleaseList.clear(); }
Source:
<code>public Entry(@JsonProperty("message") String message, @JsonProperty("nanos") long nanos, @JsonProperty("threadName") String threadName) { <START> this.message = message; <END> this.nanos = nanos; this.threadName = threadName; }</code><technical_language>requireNonNull(message, "message is null");</technical_language>

Target:
public Entry(@JsonProperty("message") String message, @JsonProperty("nanos") long nanos, @JsonProperty("threadName") String threadName) { this.message = requireNonNull(message, "messsage is null"); this.nanos = nanos; this.threadName = threadName; }
Source:
<code>public List<CompletePaxosHistoryForNamespaceAndUseCase> getHistory() { <START> Map<NamespaceAndUseCase, SequenceBounds> lastVerifiedSequences = getNamespaceAndUseCaseToLastVerifiedSeqMap(); <END> PaxosHistoryOnSingleNode localPaxosHistory = localHistoryLoader.getLocalPaxosHistory(lastVerifiedSequences); List<HistoryQuery> historyQueries = getHistoryQueryListForRemoteServers(lastVerifiedSequences); List<PaxosHistoryOnRemote> rawHistoryFromAllRemotes = getHistoriesFromRemoteServers(historyQueries); List<ConsolidatedPaxosHistoryOnSingleNode> historyFromAllRemotes = buildHistoryFromRemoteResponses(rawHistoryFromAllRemotes); List<CompletePaxosHistoryForNamespaceAndUseCase> completeHistoryList = consolidateAndGetHistoriesAcrossAllNodes( lastVerifiedSequences, localPaxosHistory, historyFromAllRemotes); progressTracker.updateProgressState(lastVerifiedSequences); return completeHistoryList; }</code><technical_language>This variable name is misleading. bounds _not_ verified time this call is - candidates want verify. In previous model correct (because start query from)</technical_language>

Target:
public List<CompletePaxosHistoryForNamespaceAndUseCase> getHistory() { Map<NamespaceAndUseCase, HistoryQuerySequenceBounds> namespaceAndUseCaseWiseSequenceRangeToBeVerified = getNamespaceAndUseCaseToHistoryQuerySeqBoundsMap(); PaxosHistoryOnSingleNode localPaxosHistory = localHistoryLoader.getLocalPaxosHistory(namespaceAndUseCaseWiseSequenceRangeToBeVerified); List<HistoryQuery> historyQueries = getHistoryQueryListForRemoteServers(namespaceAndUseCaseWiseSequenceRangeToBeVerified); List<PaxosHistoryOnRemote> rawHistoryFromAllRemotes = getHistoriesFromRemoteServers(historyQueries); List<ConsolidatedPaxosHistoryOnSingleNode> historyFromAllRemotes = buildHistoryFromRemoteResponses(rawHistoryFromAllRemotes); List<CompletePaxosHistoryForNamespaceAndUseCase> completeHistoryList = consolidateAndGetHistoriesAcrossAllNodes( namespaceAndUseCaseWiseSequenceRangeToBeVerified, localPaxosHistory, historyFromAllRemotes); progressTracker.updateProgressState(namespaceAndUseCaseWiseSequenceRangeToBeVerified); return completeHistoryList; }
Source:
<code><START> LeaseCoordinator(ILeaseManager<T> leaseManager, <END> String workerIdentifier, long leaseDurationMillis, long epsilonMillis, int maxLeasesForWorker, int maxLeasesToStealAtOneTime, int maxLeaseRenewerThreadCount, IMetricsFactory metricsFactory) { this(leaseManager, getDefaultLeaseSelector(), workerIdentifier, leaseDurationMillis, epsilonMillis, maxLeasesForWorker, maxLeasesToStealAtOneTime, maxLeaseRenewerThreadCount, metricsFactory); }</code><technical_language>public removed. This class is a public class, this a breaking change</technical_language>

Target:
public LeaseCoordinator(ILeaseManager<T> leaseManager, String workerIdentifier, long leaseDurationMillis, long epsilonMillis, int maxLeasesForWorker, int maxLeasesToStealAtOneTime, int maxLeaseRenewerThreadCount, IMetricsFactory metricsFactory) { this(leaseManager, getDefaultLeaseSelector(), workerIdentifier, leaseDurationMillis, epsilonMillis, maxLeasesForWorker, maxLeasesToStealAtOneTime, maxLeaseRenewerThreadCount, metricsFactory); }
Source:
<code>public void addInformation(@Nonnull ItemStack stack, @Nonnull EntityPlayer playerIn, @Nonnull List<String> tooltip, boolean advanced) { super.addInformation(stack, playerIn, tooltip, advanced); if(!stack.hasTagCompound()) { return; } NBTTagCompound tag = stack.getTagCompound().getCompoundTag(TileTable.FEET_TAG); ItemStack legs = ItemStack.loadItemStackFromNBT(tag); if(legs != null && legs.getItem() != null) { tooltip.add(legs.getDisplayName()); } if(stack.getTagCompound().hasKey("inventory")) { NBTTagCompound inventory = stack.getTagCompound().getCompoundTag("inventory"); if (!inventory.hasKey("Items")) { return; } NBTTagList items = inventory.getTagList("Items", 10); if (BlockToolTable.TableTypes.fromMeta(stack.getItemDamage()) == BlockToolTable.TableTypes.PatternChest) { boolean holdsCasts = false; <START> for (int i = 0; i < items.tagCount(); ++i) { <END> Item item = ItemStack.loadItemStackFromNBT(items.getCompoundTagAt(i)).getItem(); if (item instanceof ICast || item instanceof IPattern) { holdsCasts = (item instanceof ICast); break; } } if (holdsCasts) { tooltip.addAll(LocUtils.getTooltips(Util.translateFormatted("tooltip.patternchest.holds_casts", items.tagCount()))); } else { tooltip.addAll(LocUtils.getTooltips(Util.translateFormatted("tooltip.patternchest.holds_patterns", items.tagCount()))); } } else { tooltip.addAll(LocUtils.getTooltips(Util.translateFormatted("tooltip.chest.has_items", items.tagCount()))); } } }</code><technical_language>chest hold casts patterns, need for a loop, item is enough</technical_language>

Target:
public void addInformation(@Nonnull ItemStack stack, @Nonnull EntityPlayer playerIn, @Nonnull List<String> tooltip, boolean advanced) { super.addInformation(stack, playerIn, tooltip, advanced); if(!stack.hasTagCompound()) { return; } NBTTagCompound tag = stack.getTagCompound().getCompoundTag(TileTable.FEET_TAG); ItemStack legs = ItemStack.loadItemStackFromNBT(tag); if(legs != null && legs.getItem() != null) { tooltip.add(legs.getDisplayName()); } if(stack.getTagCompound().hasKey("inventory")) { this.addInventoryInformation(stack, playerIn, tooltip, advanced); } }
Source:
<code>private String[] getItemStrings(List<TmfEventTableColumn> columns, ITmfEvent event) { if (event == null) { return EMPTY_STRING_ARRAY; } synchronized (columns) { Map<TmfEventTableColumn , String> itemStrings = new HashMap<>(); for (TableColumn viewColumn : fTable.getColumns()) { <START> TmfEventTableColumn column = columns.get((int) viewColumn.getData(Key.INDEX)); <END> ITmfEvent passedEvent = event; if (!(column instanceof TmfMarginColumn) && (event instanceof CachedEvent)) { passedEvent = ((CachedEvent) event).event; } if (passedEvent == null || (!viewColumn.getResizable() && viewColumn.getWidth() == 0)) { itemStrings.put(column ,EMPTY_STRING); } else { itemStrings.put(column ,column.getItemString(passedEvent)); } } String[] displayStrings = new String[columns.size()]; int i = 0; for (TmfEventTableColumn column : columns) { displayStrings[i] = itemStrings.get(column); i++; } return displayStrings; } }</code><technical_language>index is column creation order, 'columns' parameter in order</technical_language>

Target:
private String[] getItemStrings(List<TmfEventTableColumn> columns, ITmfEvent event) { if (event == null) { return EMPTY_STRING_ARRAY; } synchronized (columns) { Map<TmfEventTableColumn, String> itemStrings = new HashMap<>(); for (TableColumn viewColumn : fTable.getColumns()) { TmfEventTableColumn column = fColumns.get((int) viewColumn.getData(Key.INDEX)); ITmfEvent passedEvent = event; if (!(column instanceof TmfMarginColumn) && (event instanceof CachedEvent)) { passedEvent = ((CachedEvent) event).event; } if (passedEvent == null || (!viewColumn.getResizable() && viewColumn.getWidth() == 0)) { itemStrings.put(column, EMPTY_STRING); } else { itemStrings.put(column, column.getItemString(passedEvent)); } } String[] displayStrings = new String[columns.size()]; int i = 0; for (TmfEventTableColumn column : columns) { displayStrings[i] = itemStrings.get(column); i++; } return displayStrings; } }
Source:
<code>protected void initImportClonedTemplateDisks() { for (DiskImage image : getImages()) { if (Guid.isNullOrEmpty(image.getStoragePoolId())) { image.setStoragePoolId(getStoragePoolId()); } <START> List<StorageDomain> storageDomainList = storageDomainDao.getAllStorageDomainsByImageId(image.getImageId()); <END> getParameters().setSourceDomainId(storageDomainList.get(0).getId()); updateDiskSizeByQcowImageInfo(image); if (getParameters().isImportAsNewEntity()) { generateNewDiskId(image); updateManagedDeviceMap(image, getVmTemplate().getManagedDeviceMap()); } else { originalDiskIdMap.put(image.getId(), image.getId()); originalDiskImageIdMap.put(image.getId(), image.getImageId()); } } }</code><technical_language>do if getParameters().getSourceDomainId() is null empty</technical_language>

Target:
protected void initImportClonedTemplateDisks() { for (DiskImage image : getImages()) { if (Guid.isNullOrEmpty(image.getStoragePoolId())) { image.setStoragePoolId(getStoragePoolId()); } List<StorageDomain> storageDomainList = storageDomainDao.getAllStorageDomainsByImageId(image.getImageId()); if (!validateSourceStorageDomainPerImage(storageDomainList)) { getParameters().setSourceDomainId(storageDomainList.get(0).getId()); } updateDiskSizeByQcowImageInfo(image); if (getParameters().isImportAsNewEntity()) { generateNewDiskId(image); updateManagedDeviceMap(image, getVmTemplate().getManagedDeviceMap()); } else { originalDiskIdMap.put(image.getId(), image.getId()); originalDiskImageIdMap.put(image.getId(), image.getImageId()); } } }
Source:
<code>protected boolean mergeImpl() throws IOException { boolean implicitDirCache = false; if (dircache == null) { dircache = getRepository().lockDirCache(); implicitDirCache = true; } try { builder = dircache.builder(); DirCacheBuildIterator buildIt = new DirCacheBuildIterator(builder); tw = new NameConflictTreeWalk(db); tw.reset(); tw.addTree(mergeBase()); tw.addTree(sourceTrees[0]); tw.addTree(sourceTrees[1]); tw.addTree(buildIt); if (workingTreeIt != null) tw.addTree(workingTreeIt); while (tw.next()) { if (!processEntry( tw.getTree(T_BASE, CanonicalTreeParser.class), tw.getTree(T_OURS, CanonicalTreeParser.class), tw.getTree(T_THEIRS, CanonicalTreeParser.class), tw.getTree(T_INDEX, DirCacheBuildIterator.class), (workingTreeIt == null) ? null : tw.getTree(T_FILE, WorkingTreeIterator.class))) { <START> if (!inCore) <END> cleanUp(); return false; } if (tw.isSubtree() && enterSubtree) tw.enterSubtree(); } if (!inCore) { if (!builder.commit()) { cleanUp(); throw new IndexWriteException(); } builder = null; checkout(); } else { builder.finish(); builder = null; } if (getUnmergedPathes().isEmpty()) { resultTree = dircache.writeTree(oi); return true; } else { resultTree = null; return false; } } finally { if (implicitDirCache) dircache.unlock(); } }</code><technical_language>skip cleanUp() in case of inCore attribute modifiedFiles filled wrongly. incore-merge fails for reason clean modifiedFiles list. is modifiy cleanup() do in case of incore</technical_language>

Target:
protected boolean mergeImpl() throws IOException { boolean implicitDirCache = false; if (dircache == null) { dircache = getRepository().lockDirCache(); implicitDirCache = true; } try { builder = dircache.builder(); DirCacheBuildIterator buildIt = new DirCacheBuildIterator(builder); tw = new NameConflictTreeWalk(db); tw.reset(); tw.addTree(mergeBase()); tw.addTree(sourceTrees[0]); tw.addTree(sourceTrees[1]); tw.addTree(buildIt); if (workingTreeIt != null) tw.addTree(workingTreeIt); while (tw.next()) { if (!processEntry( tw.getTree(T_BASE, CanonicalTreeParser.class), tw.getTree(T_OURS, CanonicalTreeParser.class), tw.getTree(T_THEIRS, CanonicalTreeParser.class), tw.getTree(T_INDEX, DirCacheBuildIterator.class), (workingTreeIt == null) ? null : tw.getTree(T_FILE, WorkingTreeIterator.class))) { cleanUp(); return false; } if (tw.isSubtree() && enterSubtree) tw.enterSubtree(); } if (!inCore) { if (!builder.commit()) { cleanUp(); throw new IndexWriteException(); } builder = null; checkout(); } else { builder.finish(); builder = null; } if (getUnmergedPathes().isEmpty()) { resultTree = dircache.writeTree(oi); return true; } else { resultTree = null; return false; } } finally { if (implicitDirCache) dircache.unlock(); } }
Source:
<code>public static boolean isSupportedMimetype(String mimetype) { boolean supported = true; if ("audio/L24".equalsIgnoreCase(mimetype) || "video/vnd.dlna.mpeg-tts".equalsIgnoreCase(mimetype) || "video/mpeg2".equalsIgnoreCase(mimetype) <START> || "audio/vnd.dlna.adts".equals(mimetype) <END> ) supported = false; return supported; }</code><technical_language>equals</technical_language>

Target:
public static boolean isSupportedMimetype(String mimetype) { boolean supported = true; if ("audio/L24".equalsIgnoreCase(mimetype) || "video/vnd.dlna.mpeg-tts".equalsIgnoreCase(mimetype) || "video/mpeg2".equalsIgnoreCase(mimetype) || "audio/vnd.dlna.adts".equalsIgnoreCase(mimetype) ) supported = false; return supported; }
Source:
<code>public long consumeUntil(BufferedDataOutputStreamPlus writer, long len) throws IOException { long copied = 0; while (copied < len) { int position = buffer.position(); int remaining = buffer.remaining(); if (remaining == 0) { try { reBuffer(); } catch (EOFException e) { throw new EOFException("EOF after " + copied + " bytes out of " + len); } position = buffer.position(); remaining = buffer.remaining(); if (remaining == 0) return copied == 0 ? -1 : copied; } int toCopy = (int) Math.min(len - copied, remaining); <START> ByteBuffer dup = buffer.duplicate(); <END> if (toCopy < remaining) dup.limit(dup.position() + toCopy); int result = writer.applyToChannel(c -> c.write(dup)); buffer.position(position + result); copied += result; } return copied; }</code><technical_language>I store position stack of buffer opportunity get wrong direct buffer. remaining is stored stack store stack all? I hate bikeshedding this, I need dup manually update position? if (buffer.remaining() == 0) { try { reBuffer(); } catch (EOFException e) { throw new EOFException("EOF " + copied + " bytes out of " + len); } if (buffer.remaining() == 0) { return copied == 0 ? -1 : copied; } } int originalLimit = buffer.limit(); buffer.limit(Math.min(len - copied, remaining); int written = writer.applyToChannel(c -> c.write(buffer)); buffer.limit(originalLimit); copied += written;</technical_language>

Target:
public long consumeUntil(BufferedDataOutputStreamPlus writer, long len) throws IOException { long copied = 0; while (copied < len) { if (buffer.remaining() == 0) { try { reBuffer(); } catch (EOFException e) { throw new EOFException("EOF after " + copied + " bytes out of " + len); } if (buffer.remaining() == 0 && copied < len) throw new AssertionError("reBuffer() failed to return data"); } int originalLimit = buffer.limit(); int toCopy = (int) Math.min(len - copied, buffer.remaining()); buffer.limit(buffer.position() + toCopy); int written = writer.applyToChannel(c -> c.write(buffer)); buffer.limit(originalLimit); copied += written; } return copied; }
Source:
<code>public DslComponent(Scope scope, String componentId) { <START> this.componentId = componentId; <END> this.scope = scope; }</code><technical_language>= checkNotNull(componentId, "componentId") = checkNotNull(scope, "scope")</technical_language>

Target:
public DslComponent(Scope scope, String componentId) { Preconditions.checkNotNull(scope, "scope"); this.componentId = componentId; this.scope = scope; }
Source:
<code>private static Duration getFsTimestampResolution(Path file) { Path dir = Files.isDirectory(file) ? file : file.getParent(); if (!dir.toFile().canWrite()) { return FALLBACK_TIMESTAMP_RESOLUTION; } FileStore s; try { s = Files.getFileStore(dir); FileStoreAttributeCache c = attributeCache.get(s); if (c != null) { return c.getFsTimestampResolution(); } Lock lock = locks.computeIfAbsent(s, l -> new ReentrantLock()); if (lock.tryLock()) { try { CompletableFuture<FileStoreAttributeCache> f = CompletableFuture .supplyAsync(() -> new FileStoreAttributeCache( s, dir)); f.exceptionally(e -> { Throwable cause = e.getCause(); if (!(cause instanceof NoSuchFileException)) { LOG.error(e.getLocalizedMessage(), e); } return null; }); f.thenAccept(cache -> { if (cache != null) { attributeCache.put(s, cache); } }); if (background.get()) { if (LOG.isDebugEnabled()) { f.thenAccept( cache -> LOG.debug(cache.toString())); } } else { FileStoreAttributeCache cache = f.get(); if (LOG.isDebugEnabled()) { LOG.debug(cache.toString()); } return cache.getFsTimestampResolution(); } } finally { lock.unlock(); locks.remove(s); } <START> } <END> return FALLBACK_TIMESTAMP_RESOLUTION; } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); return FALLBACK_TIMESTAMP_RESOLUTION; } }</code><technical_language>I this works, I mistaken. I find this logic hard grok separate lock map. I in background case, lock get removed map CompletableFuture terminated way, get multiple futures for filestore. in non-background case I calling f.get() while lock is held. I part of difficulties is actual determination of time resolution is done in FileStoreAttributeCache constructor. I alternate approach call getFsTimestampResolution simpler me. I push Gerrit is acting up. bug 547837 cross-project-issues-dev</technical_language>

Target:
private static Duration getFsTimestampResolution(Path file) { Path dir = Files.isDirectory(file) ? file : file.getParent(); if (!dir.toFile().canWrite()) { return FALLBACK_TIMESTAMP_RESOLUTION; } try { FileStore s = Files.getFileStore(dir); FileStoreAttributeCache c = attributeCache.get(s); if (c != null) { return c.getFsTimestampResolution(); } Lock lock = locks.computeIfAbsent(s, l -> new ReentrantLock()); CompletableFuture<Optional<Duration>> f = CompletableFuture .supplyAsync(() -> { if (!lock.tryLock()) { return Optional.empty(); } Optional<Duration> resolution; try { resolution = measureTimestampResolution(s, dir); if (resolution.isPresent()) { FileStoreAttributeCache cache = new FileStoreAttributeCache( resolution.get()); attributeCache.put(s, cache); if (LOG.isDebugEnabled()) { LOG.debug(cache.toString()); } } } finally { lock.unlock(); } return resolution; }); if (!background.get()) { Optional<Duration> d = f.get(); if (d.isPresent()) { return d.get(); } } } catch (IOException | InterruptedException | ExecutionException e) { LOG.error(e.getMessage(), e); } return FALLBACK_TIMESTAMP_RESOLUTION; }
Source:
<code>private void addHeaderIfRequired(HttpServletResponse response) { Collection<String> cookies = response.getHeaders("Set-Cookie"); for( String cookie : cookies) { if(cookie.contains(DEFAULT_SESSION_ID_NAME)){ <START> response.addHeader("Cache-Control", "no-cache"); <END> return; } } }</code><technical_language>Filters processed in order of filter-mapping definitions. I gave this a try moved new filter-mapping one: HTTP/1.1 200 OK Date: Mon, 09 Sep 2019 17:23:30 GMT X-Frame-Options: SAMEORIGIN Content-Type: text/html;charset=utf-8 Set-Cookie: JSESSIONID=node0w4cziqnkjair1gkn4ojtsquwi78.node0;Path=/opennms Expires: Thu, 01 Jan 1970 00:00:00 GMT Cache-Control: no-cache Content-Length: 5519 Server: Jetty(9.4.18.v20190429)</technical_language>

Target:
private void addHeaderIfRequired(HttpServletResponse response) { boolean cacheControlHeaderNeeded = false; Collection<String> cookies = response.getHeaders("Set-Cookie"); for( String cookie : cookies) { if(cookie.contains(sessionIdName)){ cacheControlHeaderNeeded = true; break; } } String location = response.getHeader("Location"); if(location != null && location.contains(sessionIdName.toLowerCase())) { cacheControlHeaderNeeded = true; } if(cacheControlHeaderNeeded) { response.addHeader("Cache-Control", "no-cache"); } }
Source:
<code>private boolean isServerBlocked(TerracottaServer server) { try (Connection connection = tryDiagnosticConnection(server)) { try (Diagnostics diagnostics = fetchDiagnosticEntity(connection)) { <START> return Boolean.parseBoolean(diagnostics.invoke("ConsistencyManager", "isBlocked")); <END> } } catch (Exception e) { e.printStackTrace(); return false; } }</code><technical_language>new diagnostic layer is wired in this class (example end): try (DiagnosticService diagnosticService = DiagnosticServiceFactory.fetch( InetSocketAddress.createUnresolved(host, port), getClass().getSimpleName(), getConnectionTimeout(), getConnectionTimeout(), null, objectMapperFactory)) { return diagnosticService.isBlocked(); }</technical_language>

Target:
private boolean isServerBlocked(TerracottaServer server) { try (DiagnosticService diagnosticService = DiagnosticServiceFactory.fetch( InetSocketAddress.createUnresolved(server.getHostName(), server.getTsaPort()), getClass().getSimpleName(), getConnectionTimeout(), getConnectionTimeout(), null, objectMapperFactory)) { return diagnosticService.isBlocked(); } catch (Exception e) { return false; } }