auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testLockUseAfterPartitionWithMajority() throws Throwable { ClusteredLockManager clm0 = EmbeddedClusteredLockManagerFactory.from(getCacheManagers().get(0)); ClusteredLockManager clm1 = EmbeddedClusteredLockManagerFactory.from(getCacheManagers().get(1)); ClusteredLockManager clm2 = EmbeddedClusteredLockManagerFactory.from(getCacheManagers().get(2)); ClusteredLockManager clm3 = EmbeddedClusteredLockManagerFactory.from(getCacheManagers().get(3)); ClusteredLockManager clm4 = EmbeddedClusteredLockManagerFactory.from(getCacheManagers().get(4)); ClusteredLockManager clm5 = EmbeddedClusteredLockManagerFactory.from(getCacheManagers().get(5)); assertTrue(clm0.defineLock(LOCK_NAME)); assertFalse(clm1.defineLock(LOCK_NAME)); assertFalse(clm2.defineLock(LOCK_NAME)); assertFalse(clm3.defineLock(LOCK_NAME)); assertFalse(clm4.defineLock(LOCK_NAME)); assertFalse(clm5.defineLock(LOCK_NAME)); ClusteredLock lock0 = clm0.get(LOCK_NAME); ClusteredLock lock1 = clm1.get(LOCK_NAME); ClusteredLock lock2 = clm2.get(LOCK_NAME); ClusteredLock lock3 = clm3.get(LOCK_NAME); ClusteredLock lock4 = clm4.get(LOCK_NAME); ClusteredLock lock5 = clm5.get(LOCK_NAME); splitCluster(new int[]{0, 1, 2, 3}, new int[]{4, 5}); asList(lock0, lock1, lock2, lock3).forEach(lock -> { <START> assertTrue("Lock acquisition should be true " + lock, await(lock.tryLock(29, TimeUnit.SECONDS) <END> .thenApply(tryLockRequest -> { if (tryLockRequest) { await(lock.unlock()); } return tryLockRequest; }).exceptionally(ex -> { fail("Should not be failing from majority partition " + lock + " " + ex.getMessage()); return null; }))); }); assertFailureFromMinorityPartition(lock4); assertFailureFromMinorityPartition(lock5); }</code><technical_language>29 seconds is a fun number :)</technical_language>

Target:
public void testLockUseAfterPartitionWithMajority() throws Throwable { ClusteredLockManager clm0 = EmbeddedClusteredLockManagerFactory.from(getCacheManagers().get(0)); ClusteredLockManager clm1 = EmbeddedClusteredLockManagerFactory.from(getCacheManagers().get(1)); ClusteredLockManager clm2 = EmbeddedClusteredLockManagerFactory.from(getCacheManagers().get(2)); ClusteredLockManager clm3 = EmbeddedClusteredLockManagerFactory.from(getCacheManagers().get(3)); ClusteredLockManager clm4 = EmbeddedClusteredLockManagerFactory.from(getCacheManagers().get(4)); ClusteredLockManager clm5 = EmbeddedClusteredLockManagerFactory.from(getCacheManagers().get(5)); assertTrue(clm0.defineLock(LOCK_NAME)); assertFalse(clm1.defineLock(LOCK_NAME)); assertFalse(clm2.defineLock(LOCK_NAME)); assertFalse(clm3.defineLock(LOCK_NAME)); assertFalse(clm4.defineLock(LOCK_NAME)); assertFalse(clm5.defineLock(LOCK_NAME)); ClusteredLock lock0 = clm0.get(LOCK_NAME); ClusteredLock lock1 = clm1.get(LOCK_NAME); ClusteredLock lock2 = clm2.get(LOCK_NAME); ClusteredLock lock3 = clm3.get(LOCK_NAME); ClusteredLock lock4 = clm4.get(LOCK_NAME); ClusteredLock lock5 = clm5.get(LOCK_NAME); splitCluster(new int[]{0, 1, 2, 3}, new int[]{4, 5}); asList(lock0, lock1, lock2, lock3).forEach(lock -> { assertTryLock(lock); }); assertFailureFromMinorityPartition(lock4); assertFailureFromMinorityPartition(lock5); }
Source:
<code>public void changeToAdvancedConfiguration() { isAdvanced.setDefaultValue(true); isAdvanceChangedHandler(); <START> <END> }</code><technical_language>I remote this jump next line</technical_language>

Target:
public void changeToAdvancedConfiguration() { isAdvanced.setValue(true); isAdvanceChangedHandler(); }
Source:
<code><START> private void handleIntent(Intent intent) { <END> if (intent == null) return; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } if (Objects.equals(intent.getAction(), Intent.ACTION_VIEW)) { Uri uri = intent.getData(); if (uri != null) { handleDeeplink(uri); } } }</code><technical_language>a function named handleNavIntent. functions combined? do pretty similar things</technical_language>

Target:
private void handleIntent(Intent intent) { if (intent == null) { return; } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } if (Objects.equals(intent.getAction(), Intent.ACTION_VIEW)) { Uri uri = intent.getData(); if (uri != null) { handleDeeplink(uri); } } }
Source:
<code>public Cluster getCluster(Guid clusterId) { <START> return DbFacade.getInstance().getClusterDao().get(clusterId); <END> }</code><technical_language>change getClusterDao()</technical_language>

Target:
public Cluster getCluster(Guid clusterId) { return getClusterDao().get(clusterId); }
Source:
<code>public GraphQuery queryGraph(Graph graph, String queryString, Authorizations authorizations) { return new ElasticSearchSearchGraphQuery( getClient(), getConfig().getIndicesToQuery(), graph, queryString, getAllPropertyDefinitions(), getConfig().getScoringStrategy(), <START> getConfig().getNameSubstitutionStrategy(), <END> authorizations); }</code><technical_language>this a field create time</technical_language>

Target:
public GraphQuery queryGraph(Graph graph, String queryString, Authorizations authorizations) { return new ElasticSearchSearchGraphQuery( getClient(), getConfig().getIndicesToQuery(), graph, queryString, getAllPropertyDefinitions(), getConfig().getScoringStrategy(), this.nameSubstitutionStrategy, authorizations); }
Source:
<code>private static Expr.ObjectBinding createBindings(ColumnSelectorFactory columnSelectorFactory, Expr expression) { final Map<String, Supplier<Number>> suppliers = Maps.newHashMap(); for (String columnName : Parser.findRequiredBindings(expression)) { final ColumnCapabilities columnCapabilities = columnSelectorFactory.getColumnCapabilities(columnName); final ValueType nativeType = columnCapabilities != null ? columnCapabilities.getType() : null; final Supplier<Number> supplier; if (nativeType == ValueType.FLOAT) { final FloatColumnSelector selector = columnSelectorFactory.makeFloatColumnSelector(columnName); supplier = new Supplier<Number>() { @Override public Number get() { return selector.get(); } }; } else if (nativeType == ValueType.LONG) { final LongColumnSelector selector = columnSelectorFactory.makeLongColumnSelector(columnName); supplier = new Supplier<Number>() { @Override public Number get() { return selector.get(); } }; } else if (nativeType == null) { final ObjectColumnSelector selector = columnSelectorFactory.makeObjectColumnSelector(columnName); final Class clazz = selector == null ? null : selector.classOfObject(); <START> if (selector == null || (clazz != Object.class && Number.class.isAssignableFrom(clazz))) { <END> supplier = null; } else { supplier = new Supplier<Number>() { @Override public Number get() { return tryParse(selector.get()); } }; } } else { supplier = null; } if (supplier != null) { suppliers.put(columnName, supplier); } } return Parser.withSuppliers(suppliers); }</code><technical_language>!Number.class.isAssignableFrom(clazz)</technical_language>

Target:
private static Expr.ObjectBinding createBindings(ColumnSelectorFactory columnSelectorFactory, Expr expression) { final Map<String, Supplier<Number>> suppliers = Maps.newHashMap(); for (String columnName : Parser.findRequiredBindings(expression)) { final ColumnCapabilities columnCapabilities = columnSelectorFactory.getColumnCapabilities(columnName); final ValueType nativeType = columnCapabilities != null ? columnCapabilities.getType() : null; final Supplier<Number> supplier; if (nativeType == ValueType.FLOAT) { supplier = supplierFromFloatSelector(columnSelectorFactory.makeFloatColumnSelector(columnName)); } else if (nativeType == ValueType.LONG) { supplier = supplierFromLongSelector(columnSelectorFactory.makeLongColumnSelector(columnName)); } else if (nativeType == null) { supplier = supplierFromObjectSelector(columnSelectorFactory.makeObjectColumnSelector(columnName)); } else { supplier = null; } if (supplier != null) { suppliers.put(columnName, supplier); } } return Parser.withSuppliers(suppliers); }
Source:
<code>public Binding getObject() throws Exception { String destination; DestinationType destinationType; if (destinationQueue != null) { destination = destinationQueue.getName(); destinationType = DestinationType.QUEUE; } else { destination = destinationExchange.getName(); destinationType = DestinationType.EXCHANGE; } <START> Binding binding = new Binding(destination, destinationType, exchange, routingKey != null ? routingKey : destination, arguments); <END> if (this.shouldDeclare != null) { binding.setShouldDeclare(this.shouldDeclare); } if (this.adminsThatShouldDeclare != null) { binding.setAdminsThatShouldDeclare(this.adminsThatShouldDeclare); } return binding; }</code><technical_language>do this for direct exchanges. Rabbit forgiving if set a routing key for, say, a fanout exchange, tighten in future. Unfortunately, though, factory bean currently exchange type</technical_language>

Target:
public Binding getObject() throws Exception { String destination; DestinationType destinationType; if (destinationQueue != null) { destination = destinationQueue.getName(); destinationType = DestinationType.QUEUE; } else { destination = destinationExchange.getName(); destinationType = DestinationType.EXCHANGE; } Binding binding = new Binding(destination, destinationType, exchange, routingKey, arguments); if (this.shouldDeclare != null) { binding.setShouldDeclare(this.shouldDeclare); } if (this.adminsThatShouldDeclare != null) { binding.setAdminsThatShouldDeclare(this.adminsThatShouldDeclare); } return binding; }
Source:
<code>static Notification success(Context context) { return AutoForegroundNotification.success(context, <START> NotificationsUtils.GENERAL_NORMAL_CHANNEL_ID, <END> R.string.notification_site_creation_title_success, R.string.notification_site_creation_created, R.drawable.ic_my_sites_24dp, R.color.blue_wordpress); }</code><technical_language>wondering GENERAL_IMPORTANT_CHANNEL_ID for site creation success failure</technical_language>

Target:
static Notification success(Context context) { return AutoForegroundNotification.success(context, context.getString(R.string.notification_channel_normal_id), R.string.notification_site_creation_title_success, R.string.notification_site_creation_created, R.drawable.ic_my_sites_24dp, R.color.blue_wordpress); }
Source:
<code>public static void init(final EventBus eventBus) { commonModel = CommonModel.newInstance(); ModelInitializedEvent.fire(eventBus); commonModel.getSelectedItemChangedEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { MainModelSelectionChangeEvent.fire(eventBus, commonModel.getSelectedItem()); } }); <START> commonModel.getSignedOutEvent().addListener(new IEventListener() { <END> @Override public void eventRaised(Event ev, Object sender, EventArgs args) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { commonModel = null; } }); } }); }</code><technical_language>IIRC, CommonModel#signOut removed, this listener called, remove it</technical_language>

Target:
public static void init(final EventBus eventBus) { commonModel = CommonModel.newInstance(); commonModel.getSelectedItemChangedEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { MainModelSelectionChangeEvent.fire(eventBus, commonModel.getSelectedItem()); } }); }
Source:
<code>private void setTitle(String fileName, Metacard metacard) { <START> if (metacard.getAttribute(Metacard.TITLE) == null) { <END> metacard.setAttribute(new AttributeImpl(Metacard.TITLE, fileName)); } }</code><technical_language>Core.TITLE</technical_language>

Target:
private void setTitle(String fileName, Metacard metacard) { if (metacard.getAttribute(Core.TITLE) == null) { metacard.setAttribute(new AttributeImpl(Core.TITLE, fileName)); } }
Source:
<code>public BigInteger getMinValue() { <START> if (!signed) <END> return BigInteger.ZERO; BigInteger capacity = BigInteger.ONE.shiftLeft(length); return capacity.divide(BigInteger.valueOf(2)).negate(); }</code><technical_language>H-How this happen?? project setting's Save Actions supposed add brackets 'if' clauses automatically..</technical_language>

Target:
public BigInteger getMinValue() { if (!signed) { return BigInteger.ZERO; } BigInteger capacity = BigInteger.ONE.shiftLeft(length); return capacity.divide(BigInteger.valueOf(2)).negate(); }
Source:
<code>public static SerializerEncoding fromHeaders(HttpHeaders headers) { final String mimeContentType = headers.getValue(CONTENT_TYPE); if (mimeContentType == null) { LOGGER.warning("'{}' not found. Returning default encoding: {}", CONTENT_TYPE, JSON); <START> return JSON; <END> } final String[] parts = mimeContentType.split(";"); final String mimeType = parts[0].toLowerCase(Locale.ROOT); final String[] mimeTypeParts = mimeType.split("/"); if (mimeTypeParts.length != 2) { LOGGER.warning("Content-Type '{}' does not match mime-type formatting 'type/'subtype'. " + "Returning default: {}", mimeType, DEFAULT_ENCODING); return DEFAULT_ENCODING; } for (SerializerEncodingMimeTypes serializerEncodingMimeTypes : SUPPORTED_MIME_TYPES) { if (serializerEncodingMimeTypes.matches(mimeTypeParts[0], mimeTypeParts[1])) { return serializerEncodingMimeTypes.getEncoding(); } } LOGGER.warning("Content-Type '{}' does not match any supported one. Returning default: {}", mimeType, DEFAULT_ENCODING); return DEFAULT_ENCODING; }</code><technical_language>I guess mean: java return DEFAULT_ENCODING;</technical_language>

Target:
public static SerializerEncoding fromHeaders(HttpHeaders headers) { final String mimeContentType = headers.getValue(CONTENT_TYPE); if (mimeContentType == null || mimeContentType.isEmpty()) { LOGGER.warning("'{}' not found. Returning default encoding: {}", CONTENT_TYPE, DEFAULT_ENCODING); return DEFAULT_ENCODING; } final SerializerEncoding encoding = SUPPORTED_MIME_TYPES.get(mimeContentType); if (encoding != null) { return encoding; } final String[] parts = mimeContentType.split(";"); final String[] mimeTypeParts = parts[0].split("/"); if (mimeTypeParts.length != 2) { LOGGER.warning("Content-Type '{}' does not match mime-type formatting 'type'/'subtype'. " + "Returning default: {}", parts[0], DEFAULT_ENCODING); return DEFAULT_ENCODING; } final String subtype = mimeTypeParts[1]; final int lastIndex = subtype.lastIndexOf("+"); if (lastIndex == -1) { return DEFAULT_ENCODING; } final String mimeTypeSuffix = subtype.substring(lastIndex + 1); final SerializerEncoding serializerEncoding = SUPPORTED_SUFFIXES.get(mimeTypeSuffix); if (serializerEncoding != null) { return serializerEncoding; } LOGGER.warning("Content-Type '{}' does not match any supported one. Returning default: {}", mimeContentType, DEFAULT_ENCODING); return DEFAULT_ENCODING; }
Source:
<code>public RemoveWatchesType remove(Watcher watcher) { <START> this.watcher = watcher == null ? null : client.getNamespaceWatcherMap().getNamespaceWatcher(watcher); <END> return this; }</code><technical_language><code> client.getNamespaceWatcherMap().getNamespaceWatcher(watcher)</code> add a namespace watcher record if exist. right for removal. A new method in NamespaceWatcherMap is needed</technical_language>

Target:
public RemoveWatchesType remove(Watcher watcher) { if(watcher == null) { this.watcher = null; } else { this.watcher = client.getNamespaceWatcherMap().get(watcher); if(this.watcher == null) { this.watcher = watcher; } } return this; }
Source:
<code>public void lock() { this.delegate.lock(); while (true) { try { while (!doLock()) { Thread.sleep(100); } break; } <START> catch (CannotSerializeTransactionException | TransactionTimedOutException | QueryTimeoutException | <END> DeadlockLoserDataAccessException e) { } catch (InterruptedException e) { } catch (Exception e) { this.delegate.unlock(); rethrowAsLockException(e); } } }</code><technical_language>CannotSerializeTransactionException DeadlockLoserDataAccessException inheritors of PessimisticLockingFailureException, for super class</technical_language>

Target:
public void lock() { this.delegate.lock(); while (true) { try { while (!doLock()) { Thread.sleep(100); } break; } catch (TransientDataAccessException e) { } catch (InterruptedException e) { } catch (Exception e) { this.delegate.unlock(); rethrowAsLockException(e); } } }
Source:
<code>public void testTokenFetch() { boolean authManagerEnabled = WikipediaApp.getInstance().isAuthManagerEnabled(); <START> long millis = System.currentTimeMillis(); <END> Site testWiki = new Site("test.wikipedia.org"); String username = "someusername" + millis; String password = "somepassword" + millis; String repeat = password; CompatCreateAccountResult result; if (authManagerEnabled) { AMSubject subject = new AMSubject(username, password, repeat, null); subject.execute(); result = subject.await(); } else { Subject subject = new Subject(username, password, null); subject.execute(); result = subject.await(); } if ((authManagerEnabled && result.getAuthManagerCreateAccountResult() instanceof AMCreateAccountSuccessResult) || (!authManagerEnabled && result.getLegacyCreateAccountResult() instanceof CreateAccountSuccessResult)) { return; } assertThat(result, authManagerEnabled ? instanceOf(AMCreateAccountCaptchaResult.class) : instanceOf(CreateAccountCaptchaResult.class)); CaptchaResult captchaResult = authManagerEnabled ? ((AMCreateAccountCaptchaResult) result.getAuthManagerCreateAccountResult()).getCaptchaResult() : ((CreateAccountCaptchaResult) result.getLegacyCreateAccountResult()).getCaptchaResult(); assertThat(captchaResult, notNullValue()); assertThat(captchaResult.getCaptchaId(), not(isEmptyOrNullString())); String expectedCaptchaUrlPrefix = WikipediaApp.getInstance().getSite().scheme() + "://test.wikipedia.org/w/index.php?title=Special:Captcha/image"; assertThat(captchaResult.getCaptchaUrl(testWiki), startsWith(expectedCaptchaUrlPrefix)); }</code><technical_language>+1, I generally prefer this style occurrences match</technical_language>

Target:
public void testTokenFetch() { long millis = System.currentTimeMillis(); final String username = "someusername" + millis; final String password = "somepassword" + millis; final String repeat = password; CompatCreateAccountResult createAccountResult; new AMLoginInfoTask() { @Override public void onCatch(Throwable caught) { L.e("AMLoginInfoTask failed: " + caught.getMessage()); } @Override public void onFinish(AMLoginInfoResult result) { if (result.getEnabled()) { L.i("Logging in with AuthManager"); AMSubject subject = new AMSubject(username, password, repeat, null); subject.execute(); handleCreateAccountResult(subject.await()); } else { L.i("Logging in with legacy login"); Subject subject = new Subject(username, password, null); subject.execute(); handleCreateAccountResult(subject.await()); } } }.execute(); }
Source:
<code>public void connect() throws IOException { logger.debug("Entering connect. is in transaction: {}", inTransaction); try { String queueName = getQueueName(getAppId(), getOperatorId()); logger.debug("Base is null: {}", getBase() == null); if (getBase() != null) { logger.debug("Session is null: {}", getBase().getSession() == null); } Queue queue = getBase().getSession().createQueue(queueName); <START> QueueBrowser browser = getBase().getSession().createBrowser(queue,"operatorId=" + String.valueOf(getOperatorId())); <END> boolean hasStore; try { Enumeration enumeration = browser.getEnumeration(); hasStore = enumeration.hasMoreElements(); } catch (JMSException ex) { throw new RuntimeException(ex); } producer = getBase().getSession().createProducer(queue); consumer = getBase().getSession().createConsumer(queue, "operatorId=" + String.valueOf(getOperatorId())); connected = true; logger.debug("Connected. is in transaction: {}", inTransaction); if (!hasStore) { beginTransaction(); BytesMessage message = getBase().getSession().createBytesMessage(); message.setIntProperty(OPERATOR_ID, getOperatorId()); message.writeLong(-1L); producer.send(message); commitTransaction(); } } catch (JMSException ex) { throw new RuntimeException(ex); } logger.debug("Exiting connect. is in transaction: {}", inTransaction); }</code><technical_language>String.valueOf is unnecessary. suffice: "operatorId=" + getOperatorId()</technical_language>

Target:
public void connect() throws IOException { logger.debug("Entering connect. is in transaction: {}", inTransaction); try { logger.debug("Base is null: {}", getBase() == null); if (getBase() != null) { logger.debug("Session is null: {}", getBase().getSession() == null); } metaQueueName = getBase().getSubject() + ".metadata"; String appOperatorId = getAppId() + "_" + getOperatorId(); Queue queue = getBase().getSession().createQueue(metaQueueName); QueueBrowser browser = getBase().getSession().createBrowser(queue, APP_OPERATOR_ID + " = '" + appOperatorId + "'"); boolean hasStore; try { Enumeration enumeration = browser.getEnumeration(); hasStore = enumeration.hasMoreElements(); } catch (JMSException ex) { throw new RuntimeException(ex); } producer = getBase().getSession().createProducer(queue); consumer = getBase().getSession().createConsumer(queue, APP_OPERATOR_ID + " = '" + appOperatorId + "'"); connected = true; logger.debug("Connected. is in transaction: {}", inTransaction); if (!hasStore) { beginTransaction(); BytesMessage message = getBase().getSession().createBytesMessage(); message.setStringProperty(APP_OPERATOR_ID, appOperatorId); message.writeLong(-1L); producer.send(message); commitTransaction(); } } catch (JMSException ex) { throw new RuntimeException(ex); } logger.debug("Exiting connect. is in transaction: {}", inTransaction); }
Source:
<code><START> public String getFeedbackUrl(String siteId) { <END> return ServerConfigurationService.getPortalUrl() + "/site/" + siteId + "/page/" + SkinnableCharonPortal.CONTACT_US_URL_SUFFIX; }</code><technical_language>This a private method, need docs</technical_language>

Target:
private String getFeedbackUrl(String siteId) { return ServerConfigurationService.getPortalUrl() + "/site/" + siteId + "/page/" + SkinnableCharonPortal.CONTACT_US_URL_SUFFIX; }
Source:
<code>public void addInput(Page page) { checkState(needsInput(), "Operator is already finishing"); requireNonNull(page, "page is null"); long memorySize = 0; for (Aggregator aggregate : aggregates) { aggregate.processPage(page); memorySize += aggregate.getEstimatedSize(); } <START> if (partial || useSystemMemoryPool) { <END> systemMemoryContext.setBytes(memorySize); } else { userMemoryContext.setBytes(memorySize); } }</code><technical_language>partial field is do system allocations. introduce useSystemMemoryPool, is partial needed</technical_language>

Target:
public void addInput(Page page) { checkState(needsInput(), "Operator is already finishing"); requireNonNull(page, "page is null"); long memorySize = 0; for (Aggregator aggregate : aggregates) { aggregate.processPage(page); memorySize += aggregate.getEstimatedSize(); } if (useSystemMemory) { systemMemoryContext.setBytes(memorySize); } else { userMemoryContext.setBytes(memorySize); } }
Source:
<code>public void work() { openSystemSession(); for (String string : docIds) { DocumentModel doc = null; try { doc = session.getDocument(new IdRef(string)); } catch (DocumentNotFoundException e) { log.warn("Document impacted by retention no longer exists {}", string); continue; } Record record = doc.getAdapter(Record.class); if (record == null) { log.warn("Document should be impacted by retention but is no longer a Record: {}", string); continue; } Framework.getService(RetentionManager.class) <START> .evalExpressionEventBasedRules(record, docsToCheckAndEvents.get(string), session); <END> } }</code><technical_language>Framework.getService(RetentionManager.class) extract outer for loop</technical_language>

Target:
public void work() { openSystemSession(); RetentionManager retentionManager = Framework.getService(RetentionManager.class); for (String string : docIds) { DocumentModel doc; try { doc = session.getDocument(new IdRef(string)); } catch (DocumentNotFoundException e) { log.warn("Document impacted by retention no longer exists {}", string); continue; } Record record = doc.getAdapter(Record.class); if (record == null) { log.warn("Document should be impacted by retention but is no longer a Record: {}", string); continue; } retentionManager.evalExpressionEventBasedRules(record, docsToCheckAndEvents.get(string), session); } }
Source:
<code>public YouViewResult delete(String elementId) { final String queryUrl = buildDeleteQuery(elementId); <START> log.trace(String.format("Sending Delete request: %s", queryUrl)); <END> Retryer<HttpResponse> retryer = getHttpRequestRetryer(); Callable<HttpResponse> deleteCall = new Callable<HttpResponse>() { @Override public HttpResponse call() throws Exception { deleteRetryCount++; log.trace(String.format("YouView delete retry count - %s.", deleteRetryCount)); return httpClient.delete(queryUrl); } }; try { HttpResponse response = retryer.call(deleteCall); deleteRetryCount = 0; if (response.statusCode() == HttpServletResponse.SC_ACCEPTED) { String transactionUrl = parseIdFrom(response.header("Location")); log.trace("Delete successful. Transaction url: " + transactionUrl); return success(transactionUrl, clock.now(), response.statusCode()); } else { return failure(response.body(), clock.now(), response.statusCode()); } } catch (ExecutionException e) { throw new YouViewClientException("Error deleting id " + elementId, e); } catch (RetryException e) { throw new YouViewClientException("Error deleting id " + elementId, e); } }</code><technical_language>do string formatting yourself, done logging framework, i.e., change this log.trace("Sending delete request: {}", queryUrl)</technical_language>

Target:
public YouViewResult delete(String elementId) { final String queryUrl = buildDeleteQuery(elementId); log.trace("Sending Delete request: {}", queryUrl); Retryer<HttpResponse> retryer = getHttpRequestRetryer(); Callable<HttpResponse> deleteCall = new Callable<HttpResponse>() { @Override public HttpResponse call() throws Exception { deleteRetryCount++; if (deleteRetryCount > 1) { log.warn("YouView delete retry count - {}", deleteRetryCount); } return httpClient.delete(queryUrl); } }; try { HttpResponse response = retryer.call(deleteCall); deleteRetryCount = 0; if (response.statusCode() == HttpServletResponse.SC_ACCEPTED) { String transactionUrl = parseIdFrom(response.header("Location")); log.trace("Delete successful. Transaction url: " + transactionUrl); return success(transactionUrl, clock.now(), response.statusCode()); } else { return failure(response.body(), clock.now(), response.statusCode()); } } catch (ExecutionException e) { throw new YouViewClientException("Error deleting id " + elementId, e); } catch (RetryException e) { throw new YouViewClientException("Error deleting id " + elementId, e); } }
Source:
<code>static ReftableConfig <START> configureReftable(ReftableConfig <END> cfg, DfsOutputStream out) { cfg = new ReftableConfig(cfg); if (out.blockSize() >= 256) { cfg.setRefBlockSize(out.blockSize()); } else { int sz = DfsBlockCache.getInstance().getBlockSize(); if (cfg.getRefBlockSize() < sz) { cfg.setRefBlockSize(sz); } } return cfg; }</code><technical_language>renamed reflect sets blockSize</technical_language>

Target:
static ReftableConfig configureReftable(ReftableConfig cfg, DfsOutputStream out) { int bs = out.blockSize(); if (bs > 0) { cfg = new ReftableConfig(cfg); cfg.setRefBlockSize(bs); cfg.setAlignBlocks(true); } return cfg; }
Source:
<code><START> public void loadFunctionNamespaceManager( <END> String functionNamespaceManagerName, String functionNamespaceManagerId, List<String> catalogSchemaPrefixes, Map<String, String> properties) { FunctionNamespaceManagerFactory factory = functionNamespaceManagerFactories.get(functionNamespaceManagerName); checkState(factory != null, "No factory for function namespace manager %s", functionNamespaceManagerName); FunctionNamespaceManager<?> functionNamespaceManager = factory.create(properties); transactionManager.registerFunctionNamespaceManager(functionNamespaceManagerId, functionNamespaceManager); if (functionNamespaceManagers.putIfAbsent(functionNamespaceManagerId, functionNamespaceManager) != null) { throw new IllegalArgumentException(format("Function namespace manager [%s] is already registered", functionNamespaceManagerId)); } for (String catalogSchemaPrefix : catalogSchemaPrefixes) { if (functionNamespaces.putIfAbsent(CatalogSchemaPrefix.of(catalogSchemaPrefix), functionNamespaceManagerId) != null) { throw new IllegalArgumentException(format("Function namespace [%s] is already registered to function namespace manager [%s]", catalogSchemaPrefix, functionNamespaceManagerId)); } } }</code><technical_language>want this? Do change connectorName though, a copy-paste error</technical_language>

Target:
public void loadFunctionNamespaceManager( String functionNamespaceManagerName, String functionNamespaceManagerId, List<String> catalogSchemaPrefixes, Map<String, String> properties) { requireNonNull(functionNamespaceManagerName, "functionNamespaceManagerName is null"); FunctionNamespaceManagerFactory factory = functionNamespaceManagerFactories.get(functionNamespaceManagerName); checkState(factory != null, "No factory for function namespace manager %s", functionNamespaceManagerName); FunctionNamespaceManager<?> functionNamespaceManager = factory.create(properties); transactionManager.registerFunctionNamespaceManager(functionNamespaceManagerId, functionNamespaceManager); if (functionNamespaceManagers.putIfAbsent(functionNamespaceManagerId, functionNamespaceManager) != null) { throw new IllegalArgumentException(format("Function namespace manager [%s] is already registered", functionNamespaceManagerId)); } for (String catalogSchemaPrefix : catalogSchemaPrefixes) { if (functionNamespaces.putIfAbsent(CatalogSchemaPrefix.of(catalogSchemaPrefix), functionNamespaceManagerId) != null) { throw new IllegalArgumentException(format("Function namespace [%s] is already registered to function namespace manager [%s]", catalogSchemaPrefix, functionNamespaceManagerId)); } } }
Source:
<code>protected BatchItem run() throws Exception { try { final ProducerRecord<String, String> kafkaRecord = new ProducerRecord<>( topicId, KafkaCursor.toKafkaPartition(batchItem.getPartition()), batchItem.getPartition(), batchItem.getEvent().toString()); final Producer<String, String> producer = kafkaFactory.takeProducer(); try { final NakadiCallback callback = new NakadiCallback(); producer.send(kafkaRecord, callback); final Exception exception = callback.result.get(timeout, TimeUnit.MILLISECONDS); if (exception != null) { if (isExceptionShouldLeadToReset(exception)) { LOG.warn("Terminating producer while publishing to topic {}", topicId, exception); kafkaFactory.terminateProducer(producer); } if (hasKafkaConnectionException(exception)) { LOG.error("Kafka timeout: on broker {}", topicId, batchItem.getBrokerId(), exception); batchItem.updateStatusAndDetail(EventPublishingStatus.FAILED, "timed out"); <START> throw new Exception("Kafka timeout exception"); <END> } } } finally { kafkaFactory.releaseProducer(producer); } } catch (final ExecutionException | RuntimeException ex) { batchItem.updateStatusAndDetail(EventPublishingStatus.FAILED, "internal error"); LOG.error("Error publishing message to kafka", ex); } catch (final InterruptedException ex) { Thread.currentThread().interrupt(); batchItem.updateStatusAndDetail(EventPublishingStatus.FAILED, "interrupted"); LOG.error("Error publishing message to kafka", ex); } catch (final java.util.concurrent.TimeoutException ex) { batchItem.updateStatusAndDetail(EventPublishingStatus.FAILED, "timed out"); LOG.error("Kafka timeout: on broker {}", topicId, batchItem.getBrokerId(), ex); throw new Exception("Kafka timeout exception"); } return batchItem; }</code><technical_language>throw plain Exception</technical_language>

Target:
protected NakadiCallback run() { final ProducerRecord<String, String> kafkaRecord = new ProducerRecord<>( batchItem.getTopic(), KafkaCursor.toKafkaPartition(batchItem.getPartition()), batchItem.getPartition(), batchItem.getEvent().toString()); final NakadiCallback callback = new NakadiCallback(batchItem); try { producer.send(kafkaRecord, callback); LOG.debug("Sent command to Kafka"); return callback; } catch (final RuntimeException ex) { LOG.error("Error publishing message to kafka", ex); batchItem.updateStatusAndDetail(EventPublishingStatus.FAILED, "internal error"); } return null; }
Source:
<code>public void doStop() { if (this.reader != null) { <START> this.stoppedDueToThrottling.set(false); END> this.reader.stop(); } }</code><technical_language>move this of if block set false stopping transport</technical_language>

Target:
public void doStop() { this.stoppedDueToThrottling.set(false); if (this.reader != null) { this.reader.stop(); } }
Source:
<code>public void createApplicationContextFrom_validBuilderContext_containingTwoSameExtraComponent_shouldCreateAnApplicationContext() { <START> String name1 = "workers1"; <END> ExecutorService workers1 = Executors.newFixedThreadPool(2); String name2 = "workers2"; ExecutorService workers2 = Executors.newFixedThreadPool(2); Map<Platform.ExtraComponentKey, Object> extraComponents = Maps.newHashMap(); extraComponents.put(new Platform.ExtraComponentKey(name1, ExecutorService.class), workers1); extraComponents.put(new Platform.ExtraComponentKey(name2, ExecutorService.class), workers2); KasperPlatformConfiguration platformConfiguration = new KasperPlatformConfiguration(); final Platform.BuilderContext builderContext = new Platform.BuilderContext( platformConfiguration.configuration(), platformConfiguration.eventBus(), platformConfiguration.commandGateway(), platformConfiguration.queryGateway(), platformConfiguration.metricRegistry(), extraComponents ); ApplicationContext applicationContext = BuilderContextHelper.createApplicationContextFrom(builderContext); assertNotNull(applicationContext); assertEquals(workers1, applicationContext.getBean(name1)); assertEquals(workers2, applicationContext.getBean(name2)); }</code><technical_language>name1 final</technical_language>

Target:
public void createApplicationContextFrom_validBuilderContext_containingTwoSameExtraComponent_shouldCreateAnApplicationContext() { final String name1 = "workers1"; final ExecutorService workers1 = Executors.newFixedThreadPool(2); final String name2 = "workers2"; final ExecutorService workers2 = Executors.newFixedThreadPool(2); final Map<Platform.ExtraComponentKey, Object> extraComponents = Maps.newHashMap(); extraComponents.put(new Platform.ExtraComponentKey(name1, ExecutorService.class), workers1); extraComponents.put(new Platform.ExtraComponentKey(name2, ExecutorService.class), workers2); final KasperPlatformConfiguration platformConfiguration = new KasperPlatformConfiguration(); final Platform.BuilderContext builderContext = new Platform.BuilderContext( platformConfiguration.configuration(), platformConfiguration.eventBus(), platformConfiguration.commandGateway(), platformConfiguration.queryGateway(), platformConfiguration.metricRegistry(), extraComponents ); ApplicationContext applicationContext = BuilderContextHelper.createApplicationContextFrom(builderContext); assertNotNull(applicationContext); assertEquals(workers1, applicationContext.getBean(name1)); assertEquals(workers2, applicationContext.getBean(name2)); }
Source:
<code>@Override public Connection createConnection(String userName, String password) throws JMSException { Connection connection; <START> if (userName == null || password == null) { <END> connection = super.createConnection(); } else { connection = super.createConnection(userName, password); } if (this.cacheLevel >= JMSConstants.CACHE_CONNECTION) { cachedConnection = connection; } return connection; }</code><technical_language>I method overloading is a approach checking for nulls. WDYT</technical_language>

Target:
public Connection createConnection(String userName, String password) throws JMSException { Connection connection; if (userName == null || password == null) { connection = super.createConnection(); } else { connection = super.createConnection(userName, password); } if (this.cacheLevel >= JMSConstants.CACHE_CONNECTION) { cachedConnection = connection; } return connection; }
Source:
<code>public void close() throws IOException { if (closed) { return; } closed = true; rowGroupPosition = 0; rowGroupRowCount = 0; currentChunkRowCount = 0; try (Closer closer = Closer.create()) { closer.register(input); closer.register(decompressor::destroy); } if (writeChecksumBuilder.isPresent()) { <START> WriteChecksum actualChecksum = writeChecksumBuilder.get().build(); <END> validateWrite(validation -> validation.getChecksum().getTotalRowCount() == actualChecksum.getTotalRowCount(), "Invalid row count"); List<Long> columnHashes = actualChecksum.getColumnHashes(); for (int i = 0; i < columnHashes.size(); i++) { int columnIndex = i; validateWrite(validation -> validation.getChecksum().getColumnHashes().get(columnIndex).equals(columnHashes.get(columnIndex)), "Invalid checksum for column %s", columnIndex); } validateWrite(validation -> validation.getChecksum().getRowGroupHash() == actualChecksum.getRowGroupHash(), "Invalid row group checksum"); } }</code><technical_language>Lets do this a traditional try/finally is more obvious is on. If more in this code (e.g., loops, conditional code, etc), closer sense: java try { input.close(); } finally { if (decompressor != null) { decompressor.destroy(); } }</technical_language>

Target:
public void close() throws IOException { if (closed) { return; } closed = true; rowGroupPosition = 0; rowGroupRowCount = 0; currentChunkRowCount = 0; try { input.close(); } finally { if (decompressor != null) { decompressor.destroy(); } } if (writeChecksumBuilder.isPresent()) { WriteChecksum actualChecksum = writeChecksumBuilder.get().build(); validateWrite(validation -> validation.getChecksum().getTotalRowCount() == actualChecksum.getTotalRowCount(), "Invalid row count"); List<Long> columnHashes = actualChecksum.getColumnHashes(); for (int i = 0; i < columnHashes.size(); i++) { int columnIndex = i; validateWrite(validation -> validation.getChecksum().getColumnHashes().get(columnIndex).equals(columnHashes.get(columnIndex)), "Invalid checksum for column %s", columnIndex); } validateWrite(validation -> validation.getChecksum().getRowGroupHash() == actualChecksum.getRowGroupHash(), "Invalid row group checksum"); } }
Source:
<code>private void recordDailyLast(int env, int day, int field, Object value, String table) { if (env == -1) { Logger.warn(LOG_TAG, "Refusing to record with environment = -1."); return; } final SQLiteDatabase db = this.helper.getWritableDatabase(); final String envString = Integer.toString(env); final String fieldIDString = Integer.toString(field, 10); final String dayString = Integer.toString(day, 10); final ContentValues v = new ContentValues(); putValue(v, value); final int updated = db.update(table, v, WHERE_DATE_AND_ENV_AND_FIELD, new String[] {dayString, envString, fieldIDString}); if (0 == updated) { v.put("env", env); v.put("field", field); v.put("date", day); try { db.insertOrThrow(table, null, v); } catch (SQLiteConstraintException e) { throw new IllegalStateException("Event did not reference existing an environment or field.", e); } catch (Exception e) { <START> Logger.error(LOG_TAG, "Unknown exception thrown while recording daily last value.", e); <END> } } }</code><technical_language>original exception propagate logged; drop this catch clause</technical_language>

Target:
private void recordDailyLast(int env, int day, int field, Object value, String table) { if (env == -1) { Logger.warn(LOG_TAG, "Refusing to record with environment = -1."); return; } final SQLiteDatabase db = this.helper.getWritableDatabase(); final String envString = Integer.toString(env); final String fieldIDString = Integer.toString(field, 10); final String dayString = Integer.toString(day, 10); final ContentValues v = new ContentValues(); putValue(v, value); final int updated = db.update(table, v, WHERE_DATE_AND_ENV_AND_FIELD, new String[] {dayString, envString, fieldIDString}); if (0 == updated) { v.put("env", env); v.put("field", field); v.put("date", day); try { db.insertOrThrow(table, null, v); } catch (SQLiteConstraintException e) { throw new IllegalStateException("Event did not reference existing an environment or field.", e); } } }
Source:
<code>public SanitizedText convert(String value, Class<? extends SanitizedText> type) { <START> return notSanitized(sanitizer.sanitize(value)); <END> }</code><technical_language>funny read return notSanitized(...) method return a SanitizedText instance. rename this factoryMethod? classe name improve readability: java return SanitizedText.fromPlainText(...) sanitizer.sanitize return a SanitizedText instead of String..</technical_language>

Target:
public SanitizedText convert(String value, Class<? extends SanitizedText> type) { return sanitizer.sanitize(value); }
Source:
<code>public void stopBlobStoreSuccessTest() throws InterruptedException, IOException { List<? extends PartitionId> partitionIds = clusterMap.getAllPartitionIds(); assertTrue("This test needs more than one partition to work", partitionIds.size() > 1); PartitionId id = partitionIds.get(0); List<? extends ReplicaId> replicaIds = id.getReplicaIds(); assertTrue("This test needs more than one replica for the first partition to work", replicaIds.size() > 1); int correlationId = TestUtils.RANDOM.nextInt(); String clientId = UtilsTest.getRandomString(10); long acceptableLagInBytes = 0; short numReplicasCaughtUpPerPartition = 3; replicationManager.reset(); replicationManager.controlReplicationReturnVal = true; generateLagOverrides(0, acceptableLagInBytes); AdminRequest adminRequest = new AdminRequest(AdminRequestOrResponseType.StopBlobStore, id, correlationId, clientId); StopBlobStoreAdminRequest stopBlobStoreAdminRequest = new StopBlobStoreAdminRequest(numReplicasCaughtUpPerPartition, adminRequest); Response response = sendRequestGetResponse(stopBlobStoreAdminRequest, ServerErrorCode.No_Error); <START> assertTrue("Response not of type AdminResponse", response instanceof AdminResponse); <END> }</code><technical_language>apis called</technical_language>

Target:
public void stopBlobStoreSuccessTest() throws InterruptedException, IOException { List<? extends PartitionId> partitionIds = clusterMap.getAllPartitionIds(); PartitionId id = partitionIds.get(0); List<? extends ReplicaId> replicaIds = id.getReplicaIds(); assertTrue("This test needs more than one replica for the first partition to work", replicaIds.size() > 1); int correlationId = TestUtils.RANDOM.nextInt(); String clientId = UtilsTest.getRandomString(10); long acceptableLagInBytes = 0; short numReplicasCaughtUpPerPartition = 3; replicationManager.reset(); replicationManager.controlReplicationReturnVal = true; generateLagOverrides(0, acceptableLagInBytes); AdminRequest adminRequest = new AdminRequest(AdminRequestOrResponseType.BlobStoreControl, id, correlationId, clientId); BlobStoreControlAdminRequest stopBlobStoreAdminRequest = new BlobStoreControlAdminRequest(numReplicasCaughtUpPerPartition, false, adminRequest); Response response = sendRequestGetResponse(stopBlobStoreAdminRequest, ServerErrorCode.No_Error); assertTrue("Response not of type AdminResponse", response instanceof AdminResponse); assertEquals("Partition disabled for compaction not as expected", id, storageManager.compactionDisabledPartitionId); assertEquals("Origins list should be empty", true, replicationManager.originsVal.isEmpty()); assertEquals("Replication on given BlobStore should be disabled", false, replicationManager.enableVal); assertEquals("Partition shutdown not as expected", id, storageManager.shutdownPartitionId); }
Source:
<code>private SplashDialog(URL welcomeTxtURL, boolean quitOnClose) { super("Welcome to Observing Tool [Version: " + Version.current + "]"); final SplashPanel splashPanel = new SplashPanel(welcomeTxtURL, quitOnClose); getContentPane().add(splashPanel, BorderLayout.CENTER); final Dimension dim = splashPanel.getPreferredSize(); splashPanel.setPreferredSize(dim); final Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); setLocation(screen.width / 2 - dim.width / 2, screen.height / 2 - dim.height / 2); int op = quitOnClose ? WindowConstants.EXIT_ON_CLOSE : WindowConstants.DISPOSE_ON_CLOSE; setDefaultCloseOperation(op); if (quitOnClose) { final JFrame dialog = this; ViewerService.instance().get().registerView(dialog); addWindowListener(new WindowAdapter() { public void windowClosed(WindowEvent e) { ViewerService.instance().get().unregisterView(dialog); } }); } if (Platform.get() != Platform.osx) { Resources.setOTFrameIcon(this); <START> } <END> pack(); setVisible(true); toFront(); }</code><technical_language>check for platform in other places this is used</technical_language>

Target:
private SplashDialog(URL welcomeTxtURL, boolean quitOnClose) { super("Welcome to Observing Tool [Version: " + Version.current + "]"); final SplashPanel splashPanel = new SplashPanel(welcomeTxtURL, quitOnClose); getContentPane().add(splashPanel, BorderLayout.CENTER); final Dimension dim = splashPanel.getPreferredSize(); splashPanel.setPreferredSize(dim); final Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); setLocation(screen.width / 2 - dim.width / 2, screen.height / 2 - dim.height / 2); int op = quitOnClose ? WindowConstants.EXIT_ON_CLOSE : WindowConstants.DISPOSE_ON_CLOSE; setDefaultCloseOperation(op); if (quitOnClose) { final JFrame dialog = this; ViewerService.instance().get().registerView(dialog); addWindowListener(new WindowAdapter() { public void windowClosed(WindowEvent e) { ViewerService.instance().get().unregisterView(dialog); } }); } Resources.setOTFrameIcon(this); pack(); setVisible(true); toFront(); }
Source:
<code>public static Map<String, Long> getAllVersions(final ZephyrRestClient restClient, final Long projectID) { final Map<String, Long> versions = new HashMap<>(); final String url = String.format(URL_GET_VERSIONS, restClient.getUrl(), projectID); <START> final HttpResponse response = restClient.get(url); <END> final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { final HttpEntity entity = response.getEntity(); String string = null; try { string = EntityUtils.toString(entity); } catch (ParseException | IOException e) { ZephyrPlugin.log(e); } final JsonArray projArray = new JsonParser().parse(string).getAsJsonArray(); for (int i = 0; i < projArray.size(); i++) { final Long id = projArray.get(i).getAsJsonObject().get("id").getAsLong(); final String projName = projArray.get(i).getAsJsonObject().get("name").getAsString(); versions.put(projName, id); } } else { ZephyrPlugin.log("Unexpected response status: " + statusCode); } return versions; }</code><technical_language>Response is closed</technical_language>

Target:
public static Map<String, Long> getAllVersions(final ZephyrRestClient restClient, final Long projectID) { final Map<String, Long> versions = new HashMap<>(); final String url = String.format(URL_GET_VERSIONS, restClient.getUrl(), projectID); try (final CloseableHttpResponse response = restClient.get(url)) { final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { final HttpEntity entity = response.getEntity(); String string = null; try { string = EntityUtils.toString(entity); } catch (ParseException | IOException e) { throw new IllegalArgumentException( String.format("Bad response entity upon receipt of versions <%s>", url), e); } final JsonArray projArray = new JsonParser().parse(string).getAsJsonArray(); for (int i = 0; i < projArray.size(); i++) { final Long id = projArray.get(i).getAsJsonObject().get("id").getAsLong(); final String projName = projArray.get(i).getAsJsonObject().get("name").getAsString(); versions.put(projName, id); } } else { throw new IllegalArgumentException(String .format("Unexpected response status <%s> upon receipt of versions <%s>", statusCode, url)); } } catch (IOException e) { throw new IllegalArgumentException(e); } return versions; }