auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public final String[] getRoleListOfUserFromDatabase(String username, String filter) throws UserStoreException { if (!isSecureCall.get()) { Class argTypes[] = new Class[]{String.class, String.class}; Object object = callSecure("getRoleListOfUserFromDatabase", new Object[]{username, filter}, argTypes); return (String[]) object; } if (isUniqueUserIdEnabledInUserStore(getUserStore(username))) { String userID = getUserIDFromUserName(username); if (userID == null) { return new String[]{realmConfig.getEveryOneRoleName()}; } return getUserRolesWithID(userID, "*").toArray(new String[0]); } else { <START> return getUserRoles(username, "*"); <END> } }</code><technical_language>filter instead of *</technical_language>

Target:
public final String[] getRoleListOfUserFromDatabase(String username, String filter) throws UserStoreException { if (!isSecureCall.get()) { Class argTypes[] = new Class[]{String.class, String.class}; Object object = callSecure("getRoleListOfUserFromDatabase", new Object[]{username, filter}, argTypes); return (String[]) object; } if (isUniqueUserIdEnabledInUserStore(getUserStore(username))) { String userID = getUserIDFromUserName(username); if (userID == null) { return new String[]{realmConfig.getEveryOneRoleName()}; } return getUserRolesWithID(userID, filter).toArray(new String[0]); } else { return getUserRoles(username, filter); } }
Source:
<code>public void addFailedAttempts() { <START> if (isLoginEnabled()) { <END> failedLoginAttempts++; if (failedLoginAttempts >= NUMBER_ATTEMPTS) { enableLoginTime = new Date().getTime() + DISABLE_TIME; failedLoginAttempts = 0; } } }</code><technical_language>@manuelplazaspalacio a domain protect invariants throw exception action is allowed current status. if login is disabled addFailedAttempts is invoked throw a domain exception, for example: new ActionNotAllowed("Add failed attempts is allowed login is disabled")</technical_language>

Target:
public void addFailedAttempts() throws ActionNotAllowed { if (isLoginEnabled()) { failedLoginAttempts++; if (failedLoginAttempts >= NUMBER_ATTEMPTS) { enableLoginTime = new Date().getTime() + disableTime; failedLoginAttempts = 0; } } else { throw new ActionNotAllowed("Add new attempt if login is disable is not allowed."); } }
Source:
<code>public void example() { collector.checkSucceeds(new Callable<Object>() { public Object call() throws Exception { throw new RuntimeException("first!"); } }); <START> collector.checkSucceeds(new Callable<Integer>() { <END> public Integer call() throws Exception { throw new RuntimeException("second!"); } }); }</code><technical_language>example throw exception a Callable<something>' (where "something" 'Object') verify return is passed-in value</technical_language>

Target:
public void example() { collector.checkSucceeds(new Callable<Object>() { public Object call() throws Exception { throw new RuntimeException("first!"); } }); collector.checkSucceeds(new Callable<Integer>() { public Integer call() throws Exception { throw new RuntimeException("second!"); } }); Integer result = collector.checkSucceeds(new Callable<Integer>() { public Integer call() throws Exception { return 1; } }); assertEquals(Integer.valueOf(1), result); }
Source:
<code>private TimeLockServices createNewClient(String namespace) { Preconditions.checkArgument(!namespace.equals(PaxosTimeLockConstants.LEADER_ELECTION_NAMESPACE), "The client name '%s' is reserved for the leader election service, and may not be " + "used.", PaxosTimeLockConstants.LEADER_ELECTION_NAMESPACE); if (servicesByNamespace.size() >= maxNumberOfNamespaces.get()) { log.error( "Unable to create timelock services for client {}, as it would exceed the maximum number of " + "allowed clients ({}). If this is intentional, the maximum number of clients can be " + "increased via the maximum-number-of-clients runtime config property.", SafeArg.of("client", namespace), <START> SafeArg.of("maxNumberOfNamespaces", maxNumberOfNamespaces)); <END> throw new IllegalStateException("Maximum number of clients exceeded"); } return clientServicesFactory.apply(namespace); }</code><technical_language>This a awkward I suggest leaving this client, match user-facing wording</technical_language>

Target:
private TimeLockServices createNewClient(String namespace) { Preconditions.checkArgument(!namespace.equals(PaxosTimeLockConstants.LEADER_ELECTION_NAMESPACE), "The client name '%s' is reserved for the leader election service, and may not be " + "used.", PaxosTimeLockConstants.LEADER_ELECTION_NAMESPACE); if (servicesByNamespace.size() >= maxNumberOfClients.get()) { log.error( "Unable to create timelock services for client {}, as it would exceed the maximum number of " + "allowed clients ({}). If this is intentional, the maximum number of clients can be " + "increased via the maximum-number-of-clients runtime config property.", SafeArg.of("client", namespace), SafeArg.of("maxNumberOfClients", maxNumberOfClients)); throw new IllegalStateException("Maximum number of clients exceeded"); } return clientServicesFactory.apply(namespace); }
Source:
<code>public String filePath() { <START> return String.format("%s", fileName); <END> }</code><technical_language>String.format("%s", s) is s, filePath() return fileName, is obsolete, consider renaming fileName filePath</technical_language>

Target:
public String filePath() { return fileName; }
Source:
<code>public TopNNumericResultBuilder addEntry( String dimName, Object dimValIndex, Object[] metricVals ) { <START> final Map<String, Object> metricValues = Maps.newLinkedHashMap(); <END> metricValues.put(dimSpec.getOutputName(), dimName); Iterator<AggregatorFactory> aggFactoryIter = aggFactories.iterator(); for (Object metricVal : metricVals) { metricValues.put(aggFactoryIter.next().getName(), metricVal); } for (PostAggregator postAgg : postAggs) { metricValues.put(postAgg.getName(), postAgg.compute(metricValues)); } Object topNMetricVal = metricValues.get(metricName); if (shouldAdd(topNMetricVal)) { DimValHolder dimValHolder = new DimValHolder.Builder() .withTopNMetricVal(topNMetricVal) .withDirName(dimName) .withDimValIndex(dimValIndex) .withMetricValues(metricValues) .build(); pQueue.add(dimValHolder); } if (this.pQueue.size() > this.threshold) { pQueue.poll(); } return this; }</code><technical_language>initialCapacity for metricValues</technical_language>

Target:
public TopNNumericResultBuilder addEntry( String dimName, Object dimValIndex, Object[] metricVals ) { final Map<String, Object> metricValues = new LinkedHashMap<>(metricVals.length + postAggs.size()); metricValues.put(dimSpec.getOutputName(), dimName); Iterator<AggregatorFactory> aggFactoryIter = aggFactories.iterator(); for (Object metricVal : metricVals) { metricValues.put(aggFactoryIter.next().getName(), metricVal); } for (PostAggregator postAgg : postAggs) { metricValues.put(postAgg.getName(), postAgg.compute(metricValues)); } Object topNMetricVal = metricValues.get(metricName); if (shouldAdd(topNMetricVal)) { DimValHolder dimValHolder = new DimValHolder.Builder() .withTopNMetricVal(topNMetricVal) .withDirName(dimName) .withDimValIndex(dimValIndex) .withMetricValues(metricValues) .build(); pQueue.add(dimValHolder); } if (this.pQueue.size() > this.threshold) { pQueue.poll(); } return this; }
Source:
<code>public Date created() throws IOException { return DateUtils.cloneDate( <START> (Date) this.ocket.meta().getRawMetadata().get("Date") <END> ); }</code><technical_language>@dmzaytsev getRawMetadataValue(Headers.DATE)</technical_language>

Target:
public Date created() throws IOException { return DateUtils.cloneDate( (Date) this.meta.getRawMetadataValue(Headers.DATE) ); }
Source:
<code>protected void markModuleRequiresRestart(IPath deployPath, IModule[] moduleTree, IJBossServerPublishMethod method, IPublishCopyCallbackHandler handler) throws CoreException { boolean useAS7Behavior = DeploymentMarkerUtils.supportsJBoss7MarkerDeployment(server.getServer()); <START> System.out.println("Mark " + deployPath + " for restart"); END> if( !useAS7Behavior) { JSTPublisherXMLToucher.getInstance().touch(deployPath, moduleTree[moduleTree.length-1], handler); } else { doDeployRequired(method, this.server, moduleTree, new NullProgressMonitor()); } }</code><technical_language>System.out please</technical_language>

Target:
protected void markModuleRequiresRestart(IPath deployPath, IModule[] moduleTree, IJBossServerPublishMethod method, IPublishCopyCallbackHandler handler) throws CoreException { boolean useAS7Behavior = DeploymentMarkerUtils.supportsJBoss7MarkerDeployment(server.getServer()); if( !useAS7Behavior) { JSTPublisherXMLToucher.getInstance().touch(deployPath, moduleTree[moduleTree.length-1], handler); } else { doDeployRequired(method, this.server, moduleTree, new NullProgressMonitor()); } }
Source:
<code>public void setUpdatedAt(final Timestamp value) { <START> this._updatedAt = value; <END> }</code><technical_language>Please remove "this."</technical_language>

Target:
public void setUpdatedAt(final Timestamp value) { _updatedAt = value; }
Source:
<code>public void deleteAll() { Cursor cursor = null; ContentProviderClient db = clientProvider.get(); try { cursor = db.query( RecentSearchesContentProvider.BASE_URI, Table.ALL_FIELDS, null, new String[]{}, Table.COLUMN_LAST_USED + " DESC"); while (cursor != null && cursor.moveToNext() ) { try { RecentSearch recentSearch = find(fromCursor(cursor).getQuery()); if (recentSearch.getContentUri() == null) { throw new RuntimeException("tried to delete item with no content URI"); } else { Timber.d("QUERY_NAME %s - delete tried", recentSearch.getContentUri()); db.delete(recentSearch.getContentUri(), null, null); Timber.d("QUERY_NAME %s - query deleted", recentSearch.getQuery()); } } catch (RemoteException e) { Timber.e(e, "query deleted"); throw new RuntimeException(e); } finally { db.release(); } } } catch (RemoteException e) { throw new RuntimeException(e); } finally { <START> cursor.close(); <END> } }</code><technical_language>Need do a null check avoid NPE i.e. if (cursor != null) {</technical_language>

Target:
public void deleteAll() { Cursor cursor = null; ContentProviderClient db = clientProvider.get(); try { cursor = db.query( RecentSearchesContentProvider.BASE_URI, Table.ALL_FIELDS, null, new String[]{}, Table.COLUMN_LAST_USED + " DESC" ); while (cursor != null && cursor.moveToNext()) { try { RecentSearch recentSearch = find(fromCursor(cursor).getQuery()); if (recentSearch.getContentUri() == null) { throw new RuntimeException("tried to delete item with no content URI"); } else { Timber.d("QUERY_NAME %s - delete tried", recentSearch.getContentUri()); db.delete(recentSearch.getContentUri(), null, null); Timber.d("QUERY_NAME %s - query deleted", recentSearch.getQuery()); } } catch (RemoteException e) { Timber.e(e, "query deleted"); throw new RuntimeException(e); } finally { db.release(); } } } catch (RemoteException e) { throw new RuntimeException(e); } finally { if (cursor != null) { cursor.close(); } } }
Source:
<code>public void batchInsertRollback() throws DatabaseEngineException { final CountDownLatch latch = new CountDownLatch(1); final DbEntity entity = dbEntity() .name("TEST") .addColumn("COL1", INT) .build(); new MockUp<AbstractDatabaseEngine>() { @Mock public synchronized void flush(final Invocation invocation) throws DatabaseEngineException { if (latch.getCount() == 1) { throw new DatabaseEngineException(""); } invocation.proceed(); } }; DatabaseEngineException expectedException = null; engine.addEntity(entity); engine.beginTransaction(); try { final EntityEntry entry = entry().set("COL1", 1).build(); engine.addBatch("TEST", entry); engine.flush(); } catch (final DatabaseEngineException e) { expectedException = e; } finally { if (engine.isTransactionActive()) { engine.rollback(); } } assertNotNull("DB returned exception when flushing", expectedException); latch.countDown(); engine.beginTransaction(); engine.flush(); engine.commit(); final List<Map<String, ResultColumn>> query = engine.query(select(all()).from(table("TEST")).orderby(column("COL1").asc())); <START> assertEquals("There is no rows on table TEST", query.size(), 0); <END> }</code><technical_language>"There _are_ rows..." in assertEquals, "expected" parameter is "actual"</technical_language>

Target:
public void batchInsertRollback() throws DatabaseEngineException { final CountDownLatch latch = new CountDownLatch(1); final DbEntity entity = dbEntity() .name("TEST") .addColumn("COL1", INT) .build(); new MockUp<AbstractDatabaseEngine>() { @Mock public synchronized void flush(final Invocation invocation) throws DatabaseEngineException { if (latch.getCount() == 1) { throw new DatabaseEngineException(""); } invocation.proceed(); } }; DatabaseEngineException expectedException = null; engine.addEntity(entity); engine.beginTransaction(); try { final EntityEntry entry = entry().set("COL1", 1).build(); engine.addBatch("TEST", entry); engine.flush(); fail("Was expecting the flush operation to fail"); } catch (final DatabaseEngineException e) { expectedException = e; } finally { if (engine.isTransactionActive()) { engine.rollback(); } } assertNotNull("DB returned exception when flushing", expectedException); latch.countDown(); engine.beginTransaction(); engine.flush(); engine.commit(); final List<Map<String, ResultColumn>> query = engine.query(select(all()) .from(table("TEST")) .orderby(column("COL1").asc())); assertEquals("There are no rows on table TEST", 0, query.size()); }
Source:
<code>public void visitExpressionStatement(ExpressionStatementTree tree) { slingQueries.putIfAbsent(tree.firstToken().text(), slingQueryStates.NOTUSED); <START> slingQueryName = tree.firstToken().text(); <END> super.visitExpressionStatement(tree); if (findWasUsedOnSlingQuery()) { context.reportIssue(this, tree, RULE_MESSAGE); slingQueries.put(slingQueryName, slingQueryStates.ISSUERETURNED); } }</code><technical_language>Duplicated code please introduce variable</technical_language>

Target:
public void visitExpressionStatement(ExpressionStatementTree tree) { currentSlingQueryVariableName = tree.firstToken().text(); if (isThisANewSlingQuery()) { slingQueries.putIfAbsent(currentSlingQueryVariableName, SlingQueryStates.NOT_USED); } super.visitExpressionStatement(tree); reportIssueIfStrategyNotUsed(tree, currentSlingQueryVariableName); }
Source:
<code>@Test public void detachMutlipleRequests() throws Exception { Action action = mockAction(URI_KEY_1, URI_1, mockImageViewTarget()); Action action2 = mockAction(URI_KEY_1, URI_1, mockImageViewTarget()); BitmapHunter hunter = new TestableBitmapHunter(picasso, dispatcher, cache, stats, action); hunter.attach(action2); hunter.detach(action2); assertThat(hunter.action).isNotNull(); assertThat(hunter.actions).isNotNull(); <START> assertThat(hunter.actions).isEmpty(); <END> hunter.detach(action); assertThat(hunter.action).isNull(); }</code><technical_language>nit: chained previous line's assertion</technical_language>

Target:
@Test public void detachMutlipleRequests() throws Exception { Action action = mockAction(URI_KEY_1, URI_1, mockImageViewTarget()); Action action2 = mockAction(URI_KEY_1, URI_1, mockImageViewTarget()); BitmapHunter hunter = new TestableBitmapHunter(picasso, dispatcher, cache, stats, action); hunter.attach(action2); hunter.detach(action2); assertThat(hunter.action).isNotNull(); assertThat(hunter.actions).isNotNull().isEmpty(); hunter.detach(action); assertThat(hunter.action).isNull(); }
Source:
<code>public void doNotSalvageUnit(int i) { <START> getLeftoverSalvage().add(getPotentialSalvage().get(i)); <END> }</code><technical_language>public include a check i</technical_language>

Target:
public void doNotSalvageUnit(int i) { if (i < getPotentialSalvage().size()) { getLeftoverSalvage().add(getPotentialSalvage().get(i)); } }
Source:
<code><START> public double getProcessCpuLoad() throws MalformedObjectNameException, ReflectionException, InstanceNotFoundException { <END> if (attrList == null || attrList.isEmpty()) { return Double.NaN; } Attribute att = (Attribute)attrList.get(0); Double value = (Double)att.getValue(); if (value == -1.0) { return Double.NaN; } return ((int)(value * 1000) / 10.0); }</code><technical_language>thrown anymore</technical_language>

Target:
public double getProcessCpuLoad() { if (attr == null) { return Double.NaN; } Double value = (Double)attr.getValue(); if (value == null || value == -1.0) { return Double.NaN; } return ((int)(value * 1000) / 10.0); }
Source:
<code>private Events executeTests(Class<? extends ClassOrderer> classOrderer) { return EngineTestKit .engine("junit-jupiter") .configurationParameter(CLASS_ORDERING_STRATEGY_PROPERTY_NAME, "custom") .configurationParameter(CUSTOM_CLASS_ORDERER_PROPERTY_NAME, classOrderer.getName()) <START> .configurationParameter(DEFAULT_TEST_METHOD_ORDER_PROPERTY_NAME, MethodOrderer.MethodName.class.getName()) <END> .selectors(selectClass(A_TestCase.class), selectClass(B_TestCase.class), selectClass(C_TestCase.class)) .execute() .testEvents(); }</code><technical_language>I need order methods here, do we</technical_language>

Target:
private Events executeTests(Class<? extends ClassOrderer> classOrderer) { return EngineTestKit .engine("junit-jupiter") .configurationParameter(DEFAULT_TEST_CLASS_ORDER_PROPERTY_NAME, classOrderer.getName()) .selectors(selectClass(A_TestCase.class), selectClass(B_TestCase.class), selectClass(C_TestCase.class)) .execute() .testEvents(); }
Source:
<code>public Properties loadStoreProperties(String configPath) { File configFile = new File(configPath); if (!configFile.exists() || !configFile.isFile()) { throw new ConfigurationException( <START> "Target store configuration file does not exist" + configPath); <END> } Properties properties = new Properties(); try (InputStream is = new FileInputStream(configFile)) { properties.load(is); } catch (IOException e) { throw new ConfigurationException( "Could not load the store configuration from " + configPath, e); } try { final DataStore dataStore = getDataStore(properties); if (dataStore == null) { throw new ConfigurationException( "No datastore could be loaded with the given properties, make sure you have all the required jars for it in the classpath. Tried to use " + configPath); } dataStore.dispose(); } catch (Exception e) { throw new ConfigurationException( "Failed to load data store from configuration at " + configPath + ": " + e.getMessage(), e); } return properties; }</code><technical_language>I add empty space "exist" word read configPath</technical_language>

Target:
public Properties loadStoreProperties(String configPath) { File configFile = new File(configPath); if (!configFile.exists() || !configFile.isFile()) { throw new ConfigurationException( "Target store configuration file does not exist: " + configPath); } Properties properties = new Properties(); try (InputStream is = new FileInputStream(configFile)) { properties.load(is); } catch (IOException e) { throw new ConfigurationException( "Could not load the store configuration from: " + configPath, e); } try { final DataStore dataStore = getDataStore(properties); if (dataStore == null) { throw new ConfigurationException( "No datastore could be loaded with the given properties, make sure you have all the required jars for it in the classpath. Tried to use: " + configPath); } dataStore.dispose(); } catch (Exception e) { throw new ConfigurationException( "Failed to load data store from configuration at " + configPath + ": " + e.getMessage(), e); } return properties; }
Source:
<code>public static final List<List<DeviceData>> splitDeviceDataByDay(List<DeviceData> data) { <START> List<List<DeviceData>> res = new ArrayList<>(); <END> int beg = 0; for (int i = 0; i < data.size(); i++) { if (i > 0 && !sameDay(data.get(i), data.get(i-1))) { res.add(data.subList(beg, i)); beg = i; } } return res; }</code><technical_language>final, Lists.newArrayList(),</technical_language>

Target:
public static final List<List<DeviceData>> splitDeviceDataByDay(List<DeviceData> data) { final List<List<DeviceData>> res = Lists.newArrayList(); int beg = 0; for (int i = 1; i < data.size(); i++) { if (!sameDay(data.get(i), data.get(i-1))) { res.add(data.subList(beg, i)); beg = i; } else if (i == data.size() - 1) { res.add(data.subList(beg, data.size())); } } LOGGER.debug("Split deviceData and got days", res.size()); return res; }
Source:
<code>public void startAndWait() { Preconditions.checkState(!server.isPresent()); Preconditions.checkState( s3Configuration.getS3AccessKey().isPresent(), "s3AccessKey not set!" ); Preconditions.checkState( s3Configuration.getS3SecretKey().isPresent(), "s3SecretKey not set!" ); Preconditions.checkState( s3Configuration.getLocalDownloadHttpPort().isPresent() || s3Configuration.getLocalDownloadSocket().isPresent(), "Must specify either unix socket (localDownloadSocket) or port (localDownloadHttpPort)" ); Server server = new Server(); if (s3Configuration.getLocalDownloadHttpPort().isPresent()) { ServerConnector http = new ServerConnector(server); http.setHost("localhost"); http.setPort(s3Configuration.getLocalDownloadHttpPort().get()); http.setIdleTimeout(configuration.getHttpServerTimeout()); server.addConnector(http); } if (s3Configuration.getLocalDownloadSocket().isPresent()) { UnixSocketConnector unix = new UnixSocketConnector(server); <START> unix.setAcceptQueueSize(128); <END> unix.setUnixSocket(s3Configuration.getLocalDownloadSocket().get()); server.addConnector(unix); } server.setHandler(handler); try { LOG.info( "Starting server on (configuration: {})", s3Configuration.getLocalDownloadHttpPort(), configuration ); server.start(); this.server = Optional.of(server); server.join(); } catch (Throwable t) { throw new RuntimeException(t); } }</code><technical_language>if want read this /proc/sys/net/core/somaxconn provide a override this</technical_language>

Target:
public void startAndWait() { Preconditions.checkState(!server.isPresent()); Preconditions.checkState( s3Configuration.getS3AccessKey().isPresent(), "s3AccessKey not set!" ); Preconditions.checkState( s3Configuration.getS3SecretKey().isPresent(), "s3SecretKey not set!" ); Preconditions.checkState( s3Configuration.getLocalDownloadHttpPort().isPresent() || s3Configuration.getLocalDownloadSocket().isPresent(), "Must specify either unix socket (localDownloadSocket) or port (localDownloadHttpPort)" ); Server server = new Server(); if (s3Configuration.getLocalDownloadHttpPort().isPresent()) { ServerConnector http = new ServerConnector(server); http.setHost("localhost"); http.setPort(s3Configuration.getLocalDownloadHttpPort().get()); http.setIdleTimeout(configuration.getHttpServerTimeout()); server.addConnector(http); } if (s3Configuration.getLocalDownloadSocket().isPresent()) { UnixSocketConnector unix = new UnixSocketConnector(server); unix.setAcceptQueueSize(configuration.getUnixAcceptQueueSize()); unix.setUnixSocket(s3Configuration.getLocalDownloadSocket().get()); server.addConnector(unix); } server.setHandler(handler); try { LOG.info( "Starting server on (configuration: {})", s3Configuration.getLocalDownloadHttpPort(), configuration ); server.start(); this.server = Optional.of(server); server.join(); } catch (Throwable t) { throw new RuntimeException(t); } }
Source:
<code>private Object process0(long cntr, CacheContinuousQueryEntry entry, boolean backup) { assert cntr >= 0 : cntr; Batch batch; Object res = null; for (;;) { batch = initBatch(entry.topologyVersion(), backup); if (batch == null || cntr < batch.startCntr) { if (backup) { backupQ.add(entry); return null; } return entry; } if (cntr <= batch.endCntr) { res = batch.processEntry0(null, cntr, entry, backup); if (res == RETRY) continue; } else { if (batch.endCntr < ackedUpdCntr) batch.tryRollOver(entry.topologyVersion()); if (pendingSize.get() > MAX_PENDING_BUFF_SIZE) { LT.warn(log, "Buffer for pending events reached max of its size " + "[cacheId=" + entry.cacheId() + ", maxSize=" + MAX_PENDING_BUFF_SIZE + ", partId=" + entry.partition() + ']'); int keysToRemove = BUF_SIZE; Iterator<Map.Entry<Long, CacheContinuousQueryEntry>> iter = pending.entrySet().iterator(); res = new ArrayList<>(); while (iter.hasNext() && keysToRemove > 0) { res = addResult(res, iter.next().getValue(), false); iter.remove(); pendingSize.decrementAndGet(); keysToRemove--; } } pendingSize.incrementAndGet(); pending.put(cntr, entry); } break; } Batch batch0 = curBatch.get(); <START> if (batch0 != batch) { <END> do { batch = batch0; res = processPending(res, batch, backup); batch0 = curBatch.get(); } while (batch != batch0); } return res; }</code><technical_language>simplified while, if</technical_language>

Target:
private Object process0(long cntr, CacheContinuousQueryEntry entry, boolean backup) { assert cntr >= 0 : cntr; Batch batch; Object res = null; for (;;) { batch = initBatch(entry.topologyVersion(), backup); if (batch == null || cntr < batch.startCntr) { if (backup) { backupQ.add(entry); return null; } return entry; } if (cntr <= batch.endCntr) { res = batch.processEntry0(null, cntr, entry, backup); if (res == RETRY) continue; } else { if (batch.endCntr < ackedUpdCntr.get() && batch.tryRollOver(entry.topologyVersion()) == RETRY) continue; pendingCurrSize.incrementAndGet(); pending.put(cntr, entry); if (pendingCurrSize.get() > MAX_PENDING_BUFF_SIZE) { synchronized (pending) { if (pendingCurrSize.get() <= MAX_PENDING_BUFF_SIZE) break; LT.warn(log, "Buffer for pending events reached max of its size " + "[cacheId=" + entry.cacheId() + ", maxSize=" + MAX_PENDING_BUFF_SIZE + ", partId=" + entry.partition() + ']'); int keysToRemove = BUF_SIZE; Iterator<Map.Entry<Long, CacheContinuousQueryEntry>> iter = pending.entrySet().iterator(); while (iter.hasNext() && keysToRemove > 0) { CacheContinuousQueryEntry entry0 = iter.next().getValue(); if (!backup) res = addResult(res, entry0.copyWithDataReset(), backup); iter.remove(); pendingCurrSize.decrementAndGet(); keysToRemove--; } } } } break; } Batch batch0 = curBatch.get(); if (batch0 != batch) { do { batch = batch0; res = processPending(res, batch, backup); batch0 = curBatch.get(); } while (batch != batch0); } return res; }
Source:
<code>public void postStartup() { <START> CliParser.getInstance().handleLateOptions(); <END> }</code><technical_language>If run this in a Display.getDefault().asyncExec() trace of --open opened editor active. This is due Trace Compass opens traces (switching UI thread)</technical_language>

Target:
public void postStartup() { Display.getDefault().asyncExec(() -> CliParser.getInstance().handleLateOptions()); }
Source:
<code>public void testTwoWaySSLv2HelloNotEnabled() throws Exception { List<Protocol> list = new ArrayList<>(); list.add(Protocol.forName("TLSv1")); list.add(Protocol.forName("TLSv1.1")); SSLContext serverContext = new SSLContextBuilder() .setSecurityDomain(securityDomain) .setKeyManager(getKeyManager("/ca/jks/scarab.keystore")) .setTrustManager(getCATrustManager()) .setNeedClientAuth(true) <START> .setProtocolSelector(ProtocolSelector.empty().add(EnumSet.copyOf(list))) <END> .build().create(); String[] enabledProtocols = new String[]{"TLSv1", "TLSv1.1"}; SecurityIdentity identity = performConnectionTest(serverContext, "protocol://two-way-no-sslv2hello.org", "wildfly-ssl-test-config-v1_6.xml", enabledProtocols, "TLSv1.1"); assertNotNull(identity); assertEquals("Principal Name", "ladybird", identity.getPrincipal().getName()); }</code><technical_language>I good server client of default protocols in this test, i.e., set protocol selector explicitly configure protocols client side. verify default protocols enabled server side client side</technical_language>

Target:
public void testTwoWaySSLv2HelloNotEnabled() throws Exception { SSLContext serverContext = new SSLContextBuilder() .setSecurityDomain(securityDomain) .setKeyManager(getKeyManager("/ca/jks/scarab.keystore")) .setTrustManager(getCATrustManager()) .setNeedClientAuth(true) .build().create(); String[] enabledProtocols = IS_IBM ? new String[]{"TLSv1", "TLSv1.1", "TLSv1.2"} : new String[]{"TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3"}; SecurityIdentity identity = performConnectionTest(serverContext, "protocol://two-way-no-sslv2hello.org", "wildfly-ssl-test-config-v1_6.xml", enabledProtocols, "TLSv1.2"); assertNotNull(identity); assertEquals("Principal Name", "ladybird", identity.getPrincipal().getName()); }
Source:
<code>public boolean addRoute(@NonNull RouteInfo route) { String routeIface = route.getInterface(); if (routeIface != null && !routeIface.equals(mIfaceName)) { throw new IllegalArgumentException( "Route added with non-matching interface: " + routeIface + " vs. " + mIfaceName); } route = routeWithInterface(route); <START> if (!mRoutes.contains(route)) <END> { mRoutes.add(route); return true; } return false; }</code><technical_language>This instead need check is route destination. addLinkAddress for example</technical_language>

Target:
public boolean addRoute(@NonNull RouteInfo route) { String routeIface = route.getInterface(); if (routeIface != null && !routeIface.equals(mIfaceName)) { throw new IllegalArgumentException( "Route added with non-matching interface: " + routeIface + " vs. " + mIfaceName); } route = routeWithInterface(route); int i = findRouteIndexByDestination(route); if (i < 0) { mRoutes.add(route); return true; } else if (mRoutes.get(i).equals(route)) { return false; } else { mRoutes.set(i, route); return true; } }
Source:
<code>public boolean needsUpdate(Diff diff, Object newValue, MergeViewerSide side) { <START> if (canUpdate(diff, side)) { <END> final IEqualityHelper equalityHelper = diff.getMatch().getComparison().getEqualityHelper(); final EObject eObject = MergeViewerUtil.getEObject(diff.getMatch(), side); final EAttribute eAttribute = ((AttributeChange)diff).getAttribute(); final Object oldValue = getStringValue(eObject, eAttribute); return !equalityHelper.matchingAttributeValues(newValue, oldValue); } return false; }</code><technical_language>test canUpdate here? necesasrily linked, is it</technical_language>

Target:
private boolean needsUpdate(Diff diff, Object newValue, MergeViewerSide side) { final IEqualityHelper equalityHelper = diff.getMatch().getComparison().getEqualityHelper(); final EObject eObject = getTargetObject(diff, side); final EAttribute eAttribute = ((AttributeChange)diff).getAttribute(); final Object oldValue = getStringValue(eObject, eAttribute); return !equalityHelper.matchingAttributeValues(newValue, oldValue); }
Source:
<code>public final Response post(@Context final HttpServletRequest request, @Context final HttpServletResponse response, @Context UriInfo uriInfo, @PathParam("folder") final String folderName, @PathParam("path") final String pathParams, final Map<String, String> properties) { final InitDataObject initDataObject = this.webResource.init (pathParams, false, request, false, null); try { final FileAsset vtlFile = getVTLFile(HTTPMethod.POST, request, folderName, initDataObject.getUser()); final Map<String, Object> contextParams = CollectionsUtils.map( "urlParams", initDataObject.getParamsMap(), "queryParams", uriInfo.getQueryParameters(), "postParams", properties, "user", initDataObject.getUser()); return evalVTLFile(request, response, vtlFile, contextParams, initDataObject.getUser(), getCacheStrategy(HTTPMethod.POST)); } catch(DotContentletStateException e) { <START> final String errorMessage = "Unable to find velocity file '" + HTTPMethod.POST.fileName + FILE_EXTENSION <END> + "' under path '" + VTL_PATH + StringPool.SLASH + folderName + StringPool.SLASH + "'"; Logger.error(this, errorMessage, e); return ResponseUtil.mapExceptionResponse(new DotDataException(errorMessage)); } catch(Exception e) { Logger.error(this,"Exception on VTL endpoint. POST method: " + e.getMessage(), e); return ResponseUtil.mapExceptionResponse(e); } }</code><technical_language>a StringBuilder instead</technical_language>

Target:
public final Response post(@Context final HttpServletRequest request, @Context final HttpServletResponse response, @Context UriInfo uriInfo, @PathParam("folder") final String folderName, @PathParam("path") final String pathParams, final Map<String, String> properties) { final InitDataObject initDataObject = this.webResource.init (pathParams, false, request, false, null); try { final FileAsset vtlFile = getVTLFile(HTTPMethod.POST, request, folderName, initDataObject.getUser()); final Map<String, Object> contextParams = CollectionsUtils.map( "urlParams", initDataObject.getParamsMap(), "queryParams", uriInfo.getQueryParameters(), "postParams", properties, "user", initDataObject.getUser()); return evalVTLFile(request, response, vtlFile, contextParams, initDataObject.getUser(), getCacheStrategy(HTTPMethod.POST)); } catch(DotContentletStateException e) { final String errorMessage = "Unable to find velocity file '" + HTTPMethod.POST.fileName() + FILE_EXTENSION + "' under path '" + VTL_PATH + StringPool.SLASH + folderName + StringPool.SLASH + "'"; Logger.warn(this, errorMessage, e); return ResponseUtil.mapExceptionResponse(new DotDataException(errorMessage)); } catch(Exception e) { Logger.error(this,"Exception on VTL endpoint. POST method: " + e.getMessage(), e); return ResponseUtil.mapExceptionResponse(e); } }
Source:
<code>protected Map<String, GroupInfo> createGroupInfos() { HashMap<String, GroupInfo> groupInfos = new HashMap<>(); <START> groupInfos.put("aggregate_report_max", END> createMaxGroupInfo()); groupInfos.put("aggregate_rpt_pct2", createPercentileGroupInfo("aggregate_rpt_pct2", 95, String.format( PERCENTILE_FORMAT, Integer.valueOf(95)))); return groupInfos; }</code><technical_language>Is regular max pct</technical_language>

Target:
protected Map<String, GroupInfo> createGroupInfos() { HashMap<String, GroupInfo> groupInfos = new HashMap<>(); groupInfos.put("aggregate_report_max", createMaxGroupInfo()); LatencyValueSelector valueSelector = new LatencyValueSelector(false); StaticSeriesSelector seriesSelector = new StaticSeriesSelector(); String seriesName = String.format(PERCENTILE_FORMAT, Integer.valueOf(95)); seriesSelector.setSeriesName(seriesName); groupInfos.put(PERCENTILE_PROPERTY, createPercentileGroupInfo(PERCENTILE_PROPERTY, 95, seriesName,valueSelector,seriesSelector)); return groupInfos; }
Source:
<code>private boolean isViolatingMaxNumberOfSessionPerIpPerUser(final Session session) { if (this.maxNumberOfSessionsPerIpPerUser.isPresent()) { final Set<Session> sessionsWithSameIP = this.findSessionsByIP(session.getIp()); int duplicateSessionCount = 0; <START> for (final Session sessionByIP : sessionsWithSameIP) { <END> if (sessionByIP.getUser().equals(session.getUser())) { duplicateSessionCount++; if (duplicateSessionCount >= this.maxNumberOfSessionsPerIpPerUser.get()) { return true; } } } } return false; }</code><technical_language>Talked offline encapsulating this logic in a new method findSessionsByIPByUser similar name</technical_language>

Target:
private boolean isViolatingMaxNumberOfSessionPerIpPerUser(final Session session) { if (this.maxNumberOfSessionsPerIpPerUser.isPresent()) { final int duplicateSessionCount = this.getSessionCountByUserByIP(session.getUser(), session.getIp()); return duplicateSessionCount >= this.maxNumberOfSessionsPerIpPerUser.get(); } return false; }
Source:
<code>public static Optional<Path> getConventionsTestsPath(String child) { try { String conventionTestsDir = System.getProperty(CONVENTION_TESTS_DIR_KEY); if (new File(conventionTestsDir).exists()) { <START> return Optional.of(Paths.get(conventionTestsDir)); <END> } Enumeration<URL> productTestUrls = getSystemResources(conventionTestsDir + "/" + child); Set<URI> productTestUris = new HashSet<>(); while (productTestUrls.hasMoreElements()) { URL url = productTestUrls.nextElement(); productTestUris.add(url.toURI()); } LOGGER.debug("discovered following convention tests uris: {}", productTestUris); if (!productTestUris.isEmpty()) { return Optional.of(copyTestsToTemporaryDirectory(productTestUris, child)); } else { return Optional.empty(); } } catch (IOException e) { throw new RuntimeException(e); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } }</code><technical_language>copy is needed run scripts in copied path</technical_language>

Target:
public static Optional<Path> getConventionsTestsPath(String child) { try { ensureTemporaryTestsRootPathExists(); String childLocation = System.getProperty(CONVENTION_TESTS_DIR_KEY) + "/" + child; Path childPath = Paths.get(childLocation); if (Files.exists(childPath)) { Path temporaryChildPath = temporaryTestsRootPath.get().resolve(child); copyRecursive(childPath, temporaryChildPath); return Optional.of(temporaryChildPath); } Enumeration<URL> productTestUrls = getSystemResources(childLocation); Set<URI> productTestUris = new HashSet<>(); while (productTestUrls.hasMoreElements()) { URL url = productTestUrls.nextElement(); productTestUris.add(url.toURI()); } LOGGER.debug("discovered following convention tests uris: {}", productTestUris); if (!productTestUris.isEmpty()) { return Optional.of(copyTestsToTemporaryDirectory(productTestUris, child)); } else { return Optional.empty(); } } catch (IOException e) { throw new RuntimeException(e); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } }
Source:
<code>private static int calcLength(int num) { <START> return (num + 7) / Byte.SIZE; <END> }</code><technical_language>Consider overflow check here. @Nashatyrev proposed a good simple solution for cases <LINK_0></technical_language>

Target:
private int calcLength(int num) { return num == 0 ? 0 : (num - 1) / Byte.SIZE + 1; }
Source:
<code>public void setDeviceLifecycleStatus(final String organisationIdentification, final String deviceIdentification, final String correlationUid, final DeviceLifecycleStatus deviceLifecycleStatus) throws FunctionalException { LOGGER.debug("SetDeviceLifecycleStatus called with organisation and device {}", organisationIdentification, deviceIdentification); this.findOrganisation(organisationIdentification); <START> final Device device = this.findDevice(deviceIdentification); <END> device.setDeviceLifecycleStatus(deviceLifecycleStatus); this.deviceDomainService.saveDevice(device); final ResponseMessageResultType result = ResponseMessageResultType.OK; this.webServiceResponseMessageSender.send( new ResponseMessage(correlationUid, organisationIdentification, deviceIdentification, result, null)); }</code><technical_language>call call deviceDomainService.searchDevice</technical_language>

Target:
public void setDeviceLifecycleStatus(final String organisationIdentification, final String deviceIdentification, final String correlationUid, final DeviceLifecycleStatus deviceLifecycleStatus) throws FunctionalException { LOGGER.debug( "SetDeviceLifecycleStatus called with organisation {}, deviceLifecycleStatus and deviceIdentification {}", organisationIdentification, deviceLifecycleStatus.name(), deviceIdentification); this.findOrganisation(organisationIdentification); final Device device = this.deviceDomainService.searchDevice(deviceIdentification); device.setDeviceLifecycleStatus(deviceLifecycleStatus); this.deviceDomainService.saveDevice(device); final ResponseMessageResultType result = ResponseMessageResultType.OK; this.webServiceResponseMessageSender.send( new ResponseMessage(correlationUid, organisationIdentification, deviceIdentification, result, null)); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_landing); <START> Button createAccountButton = (Button) findViewById(R.id.create_account_button); <END> createAccountButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { openChromeCustomTab(true); } }); Button signInButton = (Button) findViewById(R.id.sign_in_button); signInButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { openChromeCustomTab(false); } }); setUpSkipDialog(); }</code><technical_language>extracting this block of code a private method? Ideally, public methods pseudocode (no conditionals, fors, etc.)</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean("TOKEN_SAVED", false)) { setContentView(R.layout.activity_landing); getSupportActionBar().hide(); setUpSkipDialog(); setUpButtons(); } else { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } }
Source:
<code>public void waitForInitialRemoteData_mainThreadThrows() { final SyncUser user = loginUser(); SyncConfiguration config = new SyncConfiguration.Builder(user, Constants.USER_REALM) <START> .waitForInitialRemoteData(false) <END> .build(); Realm realm = null; try { realm = Realm.getInstance(config); fail(); } catch (IllegalStateException ignored) { } finally { if (realm != null) { realm.close(); } } }</code><technical_language>I admit false carries information. a constant READ_ONLY in name increase readability</technical_language>

Target:
public void waitForInitialRemoteData_mainThreadThrows() { final SyncUser user = loginUser(); SyncConfiguration config = new SyncConfiguration.Builder(user, Constants.USER_REALM) .waitForInitialRemoteData() .build(); Realm realm = null; try { realm = Realm.getInstance(config); fail(); } catch (IllegalStateException ignored) { } finally { if (realm != null) { realm.close(); } } }
Source:
<code>public void onMediaChanged(MediaStore.OnMediaChanged event) { <START> if (isAdded() && !event.isError() && getPostListAdapter() != null) { <END> if (event.mediaList != null && event.mediaList.size() > 0) { MediaModel mediaModel = event.mediaList.get(0); getPostListAdapter().mediaChanged(mediaModel); } } }</code><technical_language>Calling getPostListAdapter() create adapter if exist, instead mPostsListAdapter != null here</technical_language>

Target:
public void onMediaChanged(MediaStore.OnMediaChanged event) { if (isAdded() && !event.isError() && mPostsListAdapter != null) { if (event.mediaList != null && event.mediaList.size() > 0) { MediaModel mediaModel = event.mediaList.get(0); mPostsListAdapter.mediaChanged(mediaModel); } } }
Source:
<code><START> public String getExtractedToolbarGroupConfiguration() { <END> String toolbarGroupConfiguration = getToolbarGroupConfiguration().trim(); if( !toolbarGroupConfiguration.startsWith( CKEDITOR_CONFIG_TOOLBAR_GROUPS ) || !toolbarGroupConfiguration.endsWith( ";" ) ) { throw new RuntimeException( "Invalid CKEditor toolbarGroups configuration" ); } int equalSignIndex = toolbarGroupConfiguration.indexOf( '=' ); int lastSemicolonIndex = toolbarGroupConfiguration.lastIndexOf( ';' ); return toolbarGroupConfiguration.substring( equalSignIndex + 1, lastSemicolonIndex ).trim(); }</code><technical_language>This method API exist in SWT Nebula RichTextEditor. public method is toString</technical_language>

Target:
private String getExtractedToolbarGroupConfiguration() { String toolbarGroupConfiguration = getToolbarGroupConfiguration().trim(); if( !toolbarGroupConfiguration.startsWith( CKEDITOR_CONFIG_TOOLBAR_GROUPS ) || !toolbarGroupConfiguration.endsWith( ";" ) ) { throw new RuntimeException( "Invalid CKEditor toolbarGroups configuration" ); } int equalSignIndex = toolbarGroupConfiguration.indexOf( '=' ); int lastSemicolonIndex = toolbarGroupConfiguration.lastIndexOf( ';' ); return toolbarGroupConfiguration.substring( equalSignIndex + 1, lastSemicolonIndex ).trim(); }
Source:
<code>public void onException(final RxDocumentServiceRequest request, Throwable exception) { checkNotNull(request, "expect non-null request"); checkNotNull(exception, "expect non-null exception"); if (exception instanceof GoneException) { final Throwable cause = exception.getCause(); if (cause != null) { if (cause instanceof IOException) { final Class<?> type = cause.getClass(); <START> if (type == ClosedChannelException.class) { <END> this.onConnectionEvent(RntbdConnectionEvent.READ_EOF, request, exception); } else { if (logger.isDebugEnabled()) { logger.debug("Will not raise the connection state change event for error {}", cause); } } } } } }</code><technical_language>reason this is preferred instance of ClosedChannelException</technical_language>

Target:
public void onException(final RxDocumentServiceRequest request, Throwable exception) { checkNotNull(request, "expect non-null request"); checkNotNull(exception, "expect non-null exception"); if (exception instanceof GoneException) { final Throwable cause = exception.getCause(); if (cause != null) { if (cause instanceof IOException) { if (cause instanceof ClosedChannelException) { this.onConnectionEvent(RntbdConnectionEvent.READ_EOF, request, exception); } else { if (logger.isDebugEnabled()) { logger.debug("Will not raise the connection state change event for error {}", cause); } } } } } }
Source:
<code>public Map<StoreKey, ArtifactStore> getArtifactStoresByKey() { Map<StoreKey, ArtifactStore> ret = new HashMap<>(); <START> stores.getCache().forEach( ( k, v ) -> { <END> ArtifactStore store = readValueByJson( v, StoreKey.fromString( k ) ); if ( store != null ) { ret.put( store.getKey(), store ); } } ); return ret; }</code><technical_language>nitpick again. :)</technical_language>

Target:
public Map<StoreKey, ArtifactStore> getArtifactStoresByKey() { return stores.executeCache( c -> { Map<StoreKey, ArtifactStore> ret = new HashMap<>(); c.forEach( ( k, v ) -> { ArtifactStore store = readValueByJson( v, k ); if ( store != null ) { ret.put( store.getKey(), store ); } } ); return ret; } ); }
Source:
<code>public void suggestTime(@NonNull TimeSignal timeSignal) { enforceSetTimePermission(); Objects.requireNonNull(timeSignal); <START> mHandler.post(() -> mTimeDetectorStrategy.suggestTime(timeSignal)); <END> }</code><technical_language>chat in meeting, move do direct blocking calls, synchronize a new Object mLock field</technical_language>

Target:
public void suggestTime(@NonNull TimeSignal timeSignal) { enforceSetTimePermission(); Objects.requireNonNull(timeSignal); long idToken = Binder.clearCallingIdentity(); try { synchronized (mStrategyLock) { mTimeDetectorStrategy.suggestTime(timeSignal); } } finally { Binder.restoreCallingIdentity(idToken); } }
Source:
<code>private void pruneDeadThumbnailFiles() { HashSet<String> existingFiles = new HashSet<String>(); String directory = "/sdcard/DCIM/.thumbnails"; String files = (new File(directory)).list(); if (files == null) files = new String[0]; for (int i = 0; i < files.length; i++) { String fullPathString = directory + "/" + files[i]; existingFiles.add(fullPathString); } try { Cursor c = mMediaProvider.query( mThumbsUri, new String { "_data" }, null, null, null); Log.v(TAG, "pruneDeadThumbnailFiles... " + c); if (c != null && c.moveToFirst()) { do { String fullPathString = c.getString(0); existingFiles.remove(fullPathString); } while (c.moveToNext()); } for (String fileToDelete : existingFiles) { if (Config.LOGV) Log.v(TAG, "fileToDelete is " + fileToDelete); try { <START> if (!fileToDelete.contains(".thumbdata")) { <END> (new File(fileToDelete)).delete(); } } catch (SecurityException ex) { } } Log.v(TAG, "/pruneDeadThumbnailFiles... " + c); if (c != null) { c.close(); } } catch (RemoteException e) { } }</code><technical_language>filter out non-thumbnail files in File.list(new Jpegfilter...) accidentally delete wrong files</technical_language>

Target:
private void pruneDeadThumbnailFiles() { HashSet<String> existingFiles = new HashSet<String>(); String directory = "/sdcard/DCIM/.thumbnails"; String[] files = (new File(directory)).list(new FilenameFilter() { public boolean accept(File dir, String filename) { return filename.toLowerCase().endsWith(".jpg") || filename.toLowerCase().endsWith(".jpeg"); } }); if (files == null) files = new String[0]; for (int i = 0; i < files.length; i++) { String fullPathString = directory + "/" + files[i]; existingFiles.add(fullPathString); } try { Cursor c = mMediaProvider.query( mThumbsUri, new String { "_data" }, null, null, null); Log.v(TAG, "pruneDeadThumbnailFiles... " + c); if (c != null && c.moveToFirst()) { do { String fullPathString = c.getString(0); existingFiles.remove(fullPathString); } while (c.moveToNext()); } for (String fileToDelete : existingFiles) { if (Config.LOGV) Log.v(TAG, "fileToDelete is " + fileToDelete); try { (new File(fileToDelete)).delete(); } catch (SecurityException ex) { } } Log.v(TAG, "/pruneDeadThumbnailFiles... " + c); if (c != null) { c.close(); } } catch (RemoteException e) { } }