auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void run() { try { <START> assert(m_registeredStateMachineInstances == ByteBuffer.wrap(m_zk.getData(m_stateMachineRoot, false, null)).getInt()); <END> new ZKAsyncCreateHandler(m_stateMachineMemberPath, null, CreateMode.PERSISTENT) { @Override public void run() { if (checkForCommonKeeperExceptions(m_resultCode)) { addMemberIdIfMissing(); } } }; } catch (InterruptedException e) { m_done.set(true); m_initComplete.set(false); } catch (Exception e) { org.voltdb.VoltDB.crashLocalVoltDB( "Unexpected failure in initializeInstances.", true, e); m_done.set(true); m_initComplete.set(false); } }</code><technical_language>This returns true if code is success of errors. I caller expect error returned if error code success for case node exists</technical_language>

Target:
public void run() { try { assert(m_registeredStateMachineInstances == ByteBuffer.wrap(m_zk.getData(m_stateMachineRoot, false, null)).getInt()); new ZKAsyncCreateHandler(m_stateMachineMemberPath, null, CreateMode.PERSISTENT) { @Override public void run() { if (noCommonKeeperExceptions(m_resultCode)) { addMemberIdIfMissing(); } } }; } catch (InterruptedException e) { initializationFailed(); } catch (Exception e) { org.voltdb.VoltDB.crashLocalVoltDB( "Unexpected failure in initializeInstances.", true, e); } }
Source:
<code>protected MessageType getProjectedSchema(FieldProjectionFilter fieldProjectionFilter) { ThriftType.StructType thriftStruct = new ScroogeStructConverter().convert(thriftClass); <START> return getProjectedSchema(null, fieldProjectionFilter); <END> }</code><technical_language>pass empty config a null object</technical_language>

Target:
protected MessageType getProjectedSchema(FieldProjectionFilter fieldProjectionFilter) { return getProjectedSchema(new Configuration(), fieldProjectionFilter); }
Source:
<code>public AuthConfigurations getAuthConfigurations() { File dockerCfgFile = new File(getDockerConfig() + File.separator + DOCKER_CFG); <START> if (dockerCfgFile.exists()) { <END> AuthConfigFile authConfigFile; try { authConfigFile = AuthConfigFile.loadConfig(dockerCfgFile); } catch (IOException e) { throw new DockerClientException("Failed to parse dockerCfgFile", e); } return authConfigFile.getAuthConfigurations(); } return new AuthConfigurations(); }</code><technical_language>&& isFile() afair more exact check</technical_language>

Target:
public AuthConfigurations getAuthConfigurations() { File dockerCfgFile = new File(getDockerConfig() + File.separator + DOCKER_CFG); if (dockerCfgFile.exists() && dockerCfgFile.isFile()) { AuthConfigFile authConfigFile; try { authConfigFile = AuthConfigFile.loadConfig(dockerCfgFile); } catch (IOException e) { throw new DockerClientException("Failed to parse dockerCfgFile", e); } return authConfigFile.getAuthConfigurations(); } return new AuthConfigurations(); }
Source:
<code>private PrivateKeyEntry getPrivateKeyEntry(String alias) throws CertificateManagerException { LOG.debug("SamlCallbackHandler.getDefaultPrivKeyCert() -- Begin"); <START> KeyStore.PrivateKeyEntry pkEntry = null; <END> final String clientkeyAlias = StringUtils.isNotBlank(alias) ? alias : StoreUtil.getInstance().getPrivateKeyAlias(); LOG.debug("debug--getPrivateKeyEntry-clientkeyAlias:{}", clientkeyAlias); if (clientkeyAlias != null) { final String password = getKeyStoreSystemProperties().get(KEY_STORE_PASSWORD_KEY); if (password != null) { try { pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(clientkeyAlias, new KeyStore.PasswordProtection(password.toCharArray())); } catch (final NoSuchAlgorithmException | KeyStoreException | UnrecoverableEntryException ex) { LOG.error("Error initializing Private Key: {}", ex.getLocalizedMessage(), ex); throw new CertificateManagerException(ex.getLocalizedMessage(), ex); } } else { LOG.error("{} is not a defined system property.", KEY_STORE_PASSWORD_KEY); } } else { LOG.error("{} is not a defined system property.", NhincConstants.CLIENT_KEY_ALIAS); } LOG.debug("SamlCallbackHandler.getDefaultPrivKeyCert() -- End"); return pkEntry; }</code><technical_language>Optional: wrong PrivateKeyEntry instead of KeyStore.PrivateKeyEntry</technical_language>

Target:
private PrivateKeyEntry getPrivateKeyEntry(String alias) throws CertificateManagerException { LOG.debug("SamlCallbackHandler.getDefaultPrivKeyCert() -- Begin"); PrivateKeyEntry pkEntry = null; final String clientkeyAlias = StringUtils.isNotBlank(alias) ? alias : StoreUtil.getInstance().getPrivateKeyAlias(); LOG.debug("getPrivateKeyEntry-clientkeyAlias:{}", clientkeyAlias); final String password = getKeyStoreSystemProperties().get(KEY_STORE_PASSWORD_KEY); if (password != null) { try { pkEntry = (PrivateKeyEntry) keyStore.getEntry(clientkeyAlias, new KeyStore.PasswordProtection(password.toCharArray())); } catch (final NoSuchAlgorithmException | KeyStoreException | UnrecoverableEntryException ex) { throw new CertificateManagerException(ex.getLocalizedMessage(), ex); } } else { LOG.error("{} is not a defined system property.", KEY_STORE_PASSWORD_KEY); } LOG.debug("SamlCallbackHandler.getDefaultPrivKeyCert() -- End"); return pkEntry; }
Source:
<code>public void testLenientFromJson() { <START> String json = gson.fromJson("\"Hello\"", String.class); <END> assertEquals("Hello", json); }</code><technical_language>Wanna another example? support top-level primitives</technical_language>

Target:
public void testLenientFromJson() { List<String> json = gson.fromJson("" + "[ # One!\n" + " 'Hi' #Element!\n" + "] # Array!", new TypeToken<List<String>>() {}.getType()); assertEquals(singletonList("Hi"), json); }
Source:
<code>public void testNowWithComplexPeriod() throws Exception { Collection<CompoundVariable> params = makeParams("YYYY-MM-dd'T'HH:mm:ss", "", "+1M+1d-1H-5m5s", ""); function.setParameters(params); value = function.execute(result, null); LocalDateTime futureDate = LocalDateTime.now().plusMonths(1).plusDays(1).plusHours(-1).plusMinutes(-5).plusSeconds(5); <START> LocalDateTime futureDateFromFunction = LocalDateTime.parse(value); <END> assertThat(futureDateFromFunction, within(1, ChronoUnit.SECONDS, futureDate)); }</code><technical_language>format added LocalDateTime.parse</technical_language>

Target:
public void testNowWithComplexPeriod() throws Exception { Collection<CompoundVariable> params = makeParams("YYYY-MM-dd'T'HH:mm:ss", "", "P10DT-1H-5M5S", ""); function.setParameters(params); value = function.execute(result, null); LocalDateTime futureDate = LocalDateTime.now().plusDays(10).plusHours(-1).plusMinutes(-5).plusSeconds(5); LocalDateTime futureDateFromFunction = LocalDateTime.parse(value); assertThat(futureDateFromFunction, within(1, ChronoUnit.SECONDS, futureDate)); }
Source:
<code>protected Assertion parseResponseFromServer(final String response) throws TicketValidationException { try { final TicketValidationJsonResponse json = new JsonValidationResponseParser().parse(response); return json.getAssertion(getProxyGrantingTicketStorage(), getProxyRetriever()); <START> } catch (final Exception e) { <END> logger.warn("Unable parse the JSON response", e); return super.parseResponseFromServer(response); } }</code><technical_language>I idea of falling XML parsing JSON parse errors, switching Exception broad. Consider com.fasterxml.jackson.core.JsonProcessingException, appears cover low-level parse errors (JsonParseException ) JSON content map TicketValidationJsonResponse model (JsonMappingException)</technical_language>

Target:
protected Assertion parseResponseFromServer(final String response) throws TicketValidationException { try { final TicketValidationJsonResponse json = new JsonValidationResponseParser().parse(response); return json.getAssertion(getProxyGrantingTicketStorage(), getProxyRetriever()); } catch (final JsonProcessingException e) { logger.warn("Unable parse the JSON response. Falling back to XML", e); return super.parseResponseFromServer(response); } catch (final IOException e) { throw new TicketValidationException(e.getMessage(), e); } }
Source:
<code>private synchronized void handleFinishedServerContext(final String contextId) { serverContexts.remove(contextId); final String jobState = jobStateMachine.getCurrentState(); switch (jobState) { case RUNNING: <START> LOG.log(Level.WARNING, "Server context {0} is closed when the job is not in shutdown phase", contextId); <END> break; case CLOSING_WORKERS: LOG.log(Level.WARNING, "Server context {0} is closed after starting close of root contexts", contextId); break; case CLOSING_SERVERS: if (serverContexts.isEmpty()) { jobStateMachine.setState(CLOSING_ROOTS); LOG.info("Start closing root contexts"); for (final ActiveContext rootContext : rootContexts.values()) { rootContext.close(); } } break; case CLOSING_ROOTS: LOG.log(Level.WARNING, "Server context {0} is closed after starting close of root contexts", contextId); break; default: throw new RuntimeException("Unexpected state"); } }</code><technical_language>elaborate in case this type of action occurs? For example, this happen Context is closed EM.delete() for Server</technical_language>

Target:
private synchronized void handleFinishedServerContext(final String contextId) { contextIdToServerContexts.remove(contextId); final String jobState = jobStateMachine.getCurrentState(); switch (jobState) { case STATE_RUNNING: LOG.log(Level.WARNING, "Server context {0} is closed when the job is not in shutdown phase", contextId); break; case STATE_CLOSING_WORKERS: LOG.log(Level.WARNING, "Server context {0} is closed before starting close of servers", contextId); break; case STATE_CLOSING_SERVERS: if (contextIdToServerContexts.isEmpty()) { jobStateMachine.setState(STATE_CLOSING_ROOT_CONTEXTS); LOG.info("Start closing root contexts"); for (final ActiveContext rootContext : contextIdToRootContexts.values()) { rootContext.close(); } } break; case STATE_CLOSING_ROOT_CONTEXTS: LOG.log(Level.WARNING, "Server context {0} is closed after starting close of root contexts", contextId); break; default: throw new RuntimeException("Unexpected state"); } }
Source:
<code>private ServerSocket connectToPort() throws Exception { int port = findAvailablePort(); LOG.info("acquired port on "+port+" for test "+JavaClassNames.niceClassAndMethod()); <START> return new ServerSocket(port); <END> }</code><technical_language>port 0 avoid else stealing port</technical_language>

Target:
private ServerSocket connectToPort() throws Exception { ServerSocket result = new ServerSocket(0); LOG.info("Acquired port "+result+" for test "+JavaClassNames.niceClassAndMethod()); return result; }
Source:
<code>public void createsTree() throws Exception { final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple( HttpURLConnection.HTTP_CREATED, "{\"sha\":\"0abcd89jcabitest\",\"url\":\"http://localhost/1\"}" ) ).start(); final Trees trees = new RtTrees( new ApacheRequest(container.home()), repo() ); final JsonObject tree = Json.createObjectBuilder() .add("path", "/path").add("mode", "100644 ") .add("type", "blob").add("sha", "sha1") .add("content", "content1").build(); final JsonObject input = Json.createObjectBuilder() .add("tree", tree).add("base_tree", "SHA1") .build(); try { MatcherAssert.assertThat( trees.create(input), <START> Matchers.instanceOf(Tree.class) <END> ); MatcherAssert.assertThat( container.take().method(), Matchers.equalTo(Request.POST) ); } finally { container.stop(); } }</code><technical_language>check for sha</technical_language>

Target:
public void createsTree() throws Exception { final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple( HttpURLConnection.HTTP_CREATED, "{\"sha\":\"0abcd89jcabitest\",\"url\":\"http://localhost/1\"}" ) ).start(); final Trees trees = new RtTrees( new ApacheRequest(container.home()), repo() ); final JsonObject tree = Json.createObjectBuilder() .add("path", "/path").add("mode", "100644 ") .add("type", "blob").add("sha", "sha1") .add("content", "content1").build(); final JsonObject input = Json.createObjectBuilder() .add("tree", tree).add("base_tree", "SHA1") .build(); try { final Tree tri = trees.create(input); MatcherAssert.assertThat( tri, Matchers.instanceOf(Tree.class) ); MatcherAssert.assertThat( trees.get(tri.sha()), Matchers.equalTo(tri) ); MatcherAssert.assertThat( container.take().method(), Matchers.equalTo(Request.POST) ); } finally { container.stop(); } }
Source:
<code>public int getImageselector () { return imageSelectorIndex; <START> } <END></code><technical_language>is this method required? in code</technical_language>

Target:
int getImageselector () { return imageSelectorIndex; }
Source:
<code>public RepositoryConfigurationSourceSupport(Environment environment, ClassLoader classLoader) { <START> Assert.notNull(environment, "Environment must not be null!"); <END> this.environment = environment; this.beanNameGenerator = new RepositoryBeanNameGenerator(classLoader); }</code><technical_language>put a blank line assert remove group assignments</technical_language>

Target:
public RepositoryConfigurationSourceSupport(Environment environment, ClassLoader classLoader) { Assert.notNull(environment, "Environment must not be null!"); Assert.notNull(classLoader, "ClassLoader must not be null!"); this.environment = environment; this.beanNameGenerator = new RepositoryBeanNameGenerator(classLoader); }
Source:
<code>public boolean onTouchEvent(MotionEvent event) { <START> if (mScrollDirectionListener != null) { <END> mDetector.onTouchEvent(event); } return super.onTouchEvent(event); }</code><technical_language>want double check null check is correct: if (mScrollDirectionListener != null) { mDetector.onTouchEvent(event); } I yes, mDetector is null, fires updates mScrollDirectionListener</technical_language>

Target:
public boolean onTouchEvent(MotionEvent event) { if (mScrollDirectionListener != null && event.getActionMasked() == MotionEvent.ACTION_MOVE && event.getHistorySize() > 0) { float initialY = event.getHistoricalY(event.getHistorySize() - 1); float distanceY = initialY - event.getY(); if (distanceY < 0) { mScrollDirectionListener.onScrollUp(distanceY); startScrollCheck(); } else if (distanceY > 0) { mScrollDirectionListener.onScrollDown(distanceY); startScrollCheck(); } } return super.onTouchEvent(event); }
Source:
<code>public static Set<String> planTags() { <START> List<Map<String, Object>> blogs = WordPress.wpDB.getBlogsBy("dotcomFlag=1",new String[]{"plan_product_id"}); <END> Set<String> tags = new HashSet<String>(); for (Map<String, Object> blog : blogs) { Integer planId = MapUtils.getMapInt(blog, "plan_product_id"); if (planId == null) { continue; } String tag = String.format("plan:%d", planId); tags.add(tag); } return tags; }</code><technical_language>This is super minor (coding style): add a single space character , new. perform this automatically selecting line (better select this single line only) "Code -> Reformat Code" AndroidStudio's menu. Thanks</technical_language>

Target:
public static Set<String> planTags() { String[] extraFields = {"plan_product_id"}; List<Map<String, Object>> blogs = WordPress.wpDB.getBlogsBy("dotcomFlag=1", extraFields); Set<String> tags = new HashSet<>(); for (Map<String, Object> blog : blogs) { int planId = MapUtils.getMapInt(blog, "plan_product_id"); if (planId == 0) { continue; } String tag = String.format("plan:%d", planId); tags.add(tag); } return tags; }
Source:
<code>public List<OAuth2ServiceProvider> getProviders() { List<DocumentModel> providers = queryProviders(Collections.emptyMap(), 0); <START> return providers.stream().map(provider -> buildProvider(provider)).collect(Collectors.toList()); <END> }</code><technical_language>provider -> buildProvider(provider) -> this::buildProvider</technical_language>

Target:
public List<OAuth2ServiceProvider> getProviders() { List<DocumentModel> providers = queryProviders(Collections.emptyMap(), 0); return providers.stream().map(this::buildProvider).collect(Collectors.toList()); }
Source:
<code>public List<Notification> notifications() throws IOException { final List<Notification> notifs = new LinkedList<Notification>(); final JsonResponse resp = this.github().entry().uri() .path("notifications") .back() .fetch() .as(JsonResponse.class); final JsonArray jsnnotifs = resp.json().readArray(); <START> for (final JsonValue jsnnotif : jsnnotifs) { <END> final JsonObject notifobj = (JsonObject) jsnnotif; final Notification notif = this.createNotification(notifobj); notifs.add(notif); } return notifs; }</code><technical_language>variables in this method strange names. so? list, array value? Read this <LINK_0></technical_language>

Target:
public List<Notification> notifications() throws IOException { final List<Notification> list = new LinkedList<Notification>(); final JsonResponse resp = this.github().entry().uri() .path("notifications") .back() .fetch() .as(JsonResponse.class); final JsonArray array = resp.json().readArray(); for (final JsonValue value : array) { final JsonObject notif = (JsonObject) value; list.add(this.createNotification(notif)); } return list; }
Source:
<code>public void validate() { if (enabled && getBuilder().transaction().transactionMode != null && getBuilder().transaction().transactionMode.equals(NON_TRANSACTIONAL)) throw log.invocationBatchingNeedsTransactionalCache(); if (enabled && getBuilder().transaction().recovery().enabled) <START> throw log.invocationBatchingCannotBeRecovable(); <END> }</code><technical_language>typo: Recovable => Recoverable</technical_language>

Target:
public void validate() { if (enabled && getBuilder().transaction().transactionMode != null && getBuilder().transaction().transactionMode.equals(NON_TRANSACTIONAL)) throw log.invocationBatchingNeedsTransactionalCache(); if (enabled && getBuilder().transaction().recovery().enabled && !getBuilder().transaction().useSynchronization()) throw log.invocationBatchingCannotBeRecoverable(); }
Source:
<code>public void onPreMerge(Repository repo, CodeReviewCommit commit, ProjectState destProject, NameKey destBranch, Id patchSetId) throws MergeValidationException { PatchSetApproval psa = approvalsUtil.getSubmitter(reviewDb.get(), commit.notes(), patchSetId); if (psa == null) { throw new MergeValidationException( <START> CommitMergeStatus.SETTING_PARENT_PROJECT_ONLY_ALLOWED_BY_ADMIN); <END> } final IdentifiedUser submitter = identifiedUserFactory.create(psa.getAccountId()); if (!submitter.getCapabilities().canAdministrateServer()) { throw new MergeValidationException(CommitMergeStatus.MISSING_DEPENDENCY); } }</code><technical_language>are...interesting message choices. fine in terms of committing this status message support, not</technical_language>

Target:
public void onPreMerge(Repository repo, CodeReviewCommit commit, ProjectState destProject, NameKey destBranch, Id patchSetId) throws MergeValidationException { PatchSetApproval psa = approvalsUtil.getSubmitter(reviewDb.get(), commit.notes(), patchSetId); if (psa == null) { throw new MergeValidationException( CommitMergeStatus.NO_PATCH_SET); } final IdentifiedUser submitter = identifiedUserFactory.create(psa.getAccountId()); if (!submitter.getCapabilities().canAdministrateServer()) { throw new MergeValidationException(CommitMergeStatus.MISSING_DEPENDENCY); } }
Source:
<code>private BulkActionView findBulkActionByQuery(final String luceneQuery, final User user) throws DotDataException, DotSecurityException { final String cleanedUpQuery = QueryUtil.removeQueryPrefix(luceneQuery); <START> final String query = "{\n" <END> + " \"query\" : { \n" + " \"query_string\" : {\n" + " \"query\" : \"" + cleanedUpQuery + "\"\n" + " } \n" + "\n" + " },\n" + " \"aggs\" : {\n" + " \"tag\" : {\n" + " \"terms\" : {\n" + " \"field\" : \"wfstep\",\n" + " \"size\" : 1000 \n" + " }\n" + " }\n" + " },\n" + "\t\"size\":0 \n" + "}"; final ESSearchResults results = this.contentletAPI.esSearch(query, false, user, false); Logger.debug(getClass(),"luceneQuery: "+ cleanedUpQuery); Logger.debug(getClass(),"esSearch: "+ query); return this.buildBulkActionView(results, user); }</code><technical_language>this a constant interpolation, {0} ... {1}</technical_language>

Target:
private BulkActionView findBulkActionByQuery(final String luceneQuery, final User user) throws DotDataException, DotSecurityException { final String cleanedUpQuery = QueryUtil.removeQueryPrefix(luceneQuery); final String query = "{\n" + " \"query\" : { \n" + " \"query_string\" : {\n" + " \"query\" : \"%s\"\n" + " } \n" + "\n" + " },\n" + " \"aggs\" : {\n" + " \"tag\" : {\n" + " \"terms\" : {\n" + " \"field\" : \"wfstep\",\n" + " \"size\" : 1000 \n" + " }\n" + " }\n" + " },\n" + "\t\"size\":0 \n" + "}"; final String preparedQuery = String.format(query,cleanedUpQuery); final ESSearchResults results = this.contentletAPI.esSearch(preparedQuery, false, user, false); Logger.debug(getClass(),()-> "luceneQuery: "+ cleanedUpQuery); Logger.debug(getClass(),()-> "esSearch: "+ query); return this.buildBulkActionView(results, user); }
Source:
<code>public void deleteAllFromRealm_outsideTransaction() { try { list.deleteAllFromRealm(); fail("deleteAllFromRealm should be called in a transaction."); } catch (IllegalStateException e) { <START> assertThat(e.getMessage(), containsString("Must be in a write transaction ")); <END> } }</code><technical_language>thrown.expecteMessage(). minor thing, i fine this</technical_language>

Target:
public void deleteAllFromRealm_outsideTransaction() { thrown.expect(IllegalStateException.class); thrown.expectMessage("Must be in a write transaction "); list.deleteAllFromRealm(); }
Source:
<code>public Map<File, IndexProcessingResults> processIndex(Set<File> replicaDirs, Set<StoreKey> filterSet, int parallelism, boolean detectDuplicatesAcrossKeys) { if (detectDuplicatesAcrossKeys && parallelism != 1) { throw new IllegalArgumentException("Parallelism cannot be > 1 because StoreKeyConverter is not thread safe"); } if (replicaDirs == null || replicaDirs.size() == 0) { return Collections.emptyMap(); } long currentTimeMs = time.milliseconds(); ConcurrentMap<File, IndexProcessingResults> resultsByReplica = new ConcurrentHashMap<>(); ExecutorService executorService = Executors.newFixedThreadPool(Math.min(parallelism, replicaDirs.size())); for (File replicaDir : replicaDirs) { <START> executorService.submit(() -> { <END> logger.info("Processing segment files for replica ", replicaDir); IndexProcessingResults results = null; try { results = processIndex(replicaDir, filterSet, currentTimeMs, detectDuplicatesAcrossKeys); } catch (Throwable e) { results = new IndexProcessingResults(e); } finally { resultsByReplica.put(replicaDir, results); } }); } return resultsByReplica; }</code><technical_language>I wondering determine submitted tasks completed return resultsByReplica. Is blocking tasks get done exiting this method</technical_language>

Target:
public Map<File, IndexProcessingResults> processIndex(Set<File> replicaDirs, Set<StoreKey> filterSet, int parallelism, boolean detectDuplicatesAcrossKeys) { if (detectDuplicatesAcrossKeys && parallelism != 1) { throw new IllegalArgumentException("Parallelism cannot be > 1 because StoreKeyConverter is not thread safe"); } if (replicaDirs == null || replicaDirs.size() == 0) { return Collections.emptyMap(); } long currentTimeMs = time.milliseconds(); ConcurrentMap<File, IndexProcessingResults> resultsByReplica = new ConcurrentHashMap<>(); ExecutorService executorService = Executors.newFixedThreadPool(Math.min(parallelism, replicaDirs.size())); List<Future<?>> taskFutures = new ArrayList<>(replicaDirs.size()); for (File replicaDir : replicaDirs) { Future<?> taskFuture = executorService.submit(() -> { logger.info("Processing segment files for replica ", replicaDir); IndexProcessingResults results = null; try { results = processIndex(replicaDir, filterSet, currentTimeMs, detectDuplicatesAcrossKeys); } catch (Throwable e) { results = new IndexProcessingResults(e); } finally { resultsByReplica.put(replicaDir, results); } }); taskFutures.add(taskFuture); } for (Future<?> taskFuture : taskFutures) { try { taskFuture.get(); } catch (Exception e) { throw new IllegalStateException("Future encountered error while waiting", e); } } return resultsByReplica; }
Source:
<code>public void execute(Context context) throws SQLException { Map<String, PropertyRow> rows = context .prepareSelect("select id, prop_key, resource_id, text_value, created_at from properties") .list(row -> new PropertyRow( row.getLong(1), row.getString(2), row.getLong(3), row.getString(4), row.getLong(5))) .stream() <START> .filter(row -> row.key().startsWith("sonar.webhooks")) <END> .collect(toMap(PropertyRow::key, Function.identity())); if (!rows.isEmpty()) { final List<Long> toBeDeleted = new ArrayList<>(); toBeDeleted.addAll(migrateGlobalWebhooks(context, rows)); toBeDeleted.addAll(migrateProjectsWebhooks(context, rows, getProjectsUuids(context))); deleteFromProperties(context, toBeDeleted); } }</code><technical_language>filter moved SQL load table in memory: select ... properties prop_key 'sonar.webhooks%'</technical_language>

Target:
public void execute(Context context) throws SQLException { Map<String, PropertyRow> rows = context .prepareSelect("select id, prop_key, resource_id, text_value, created_at from properties where prop_key like 'sonar.webhooks%'") .list(row -> new PropertyRow( row.getLong(1), row.getString(2), row.getLong(3), row.getString(4), row.getLong(5))) .stream() .collect(toMap(PropertyRow::key, Function.identity())); if (!rows.isEmpty()) { migrateGlobalWebhooks(context, rows); migrateProjectsWebhooks(context, rows); context .prepareUpsert("delete from properties where prop_key like 'sonar.webhooks.global%' or prop_key like 'sonar.webhooks.project%'") .execute() .commit(); } }
Source:
<code><START> private List<Object> scan(Collection<ByteArrayWrapper> list, Pattern matchPattern, <END> int count, BigInteger cursor) { List<Object> returnList = new ArrayList<>(); int size = list.size(); BigInteger beforeCursor = new BigInteger("0"); int numElements = 0; int i = -1; for (ByteArrayWrapper key : list) { i++; if (beforeCursor.compareTo(cursor) < 0) { beforeCursor = beforeCursor.add(new BigInteger("1")); continue; } if (matchPattern != null) { if (matchPattern.matcher(key.toString()).matches()) { returnList.add(key); numElements++; } } else { returnList.add(key); numElements++; } if (numElements == count) { break; } } if (i >= size - 1) { returnList.add(0, String.valueOf(0)); } else { returnList.add(0, String.valueOf(i + 1)); } return returnList; }</code><technical_language>I this return a Pair<BigInteger, List<Object>> - hiding fact zero-th element is special</technical_language>

Target:
private Pair<BigInteger, List<Object>> scan(Collection<ByteArrayWrapper> list, Pattern matchPattern, int count, BigInteger cursor) { List<Object> returnList = new ArrayList<>(); int size = list.size(); BigInteger beforeCursor = new BigInteger("0"); int numElements = 0; int i = -1; for (ByteArrayWrapper key : list) { i++; if (beforeCursor.compareTo(cursor) < 0) { beforeCursor = beforeCursor.add(new BigInteger("1")); continue; } if (matchPattern != null) { if (matchPattern.matcher(key.toString()).matches()) { returnList.add(key); numElements++; } } else { returnList.add(key); numElements++; } if (numElements == count) { break; } } Pair<BigInteger, List<Object>> scanResult; if (i >= size - 1) { scanResult = new ImmutablePair<>(new BigInteger("0"), returnList); } else { scanResult = new ImmutablePair<>(new BigInteger(String.valueOf(i + 1)), returnList); } return scanResult; }
Source:
<code>public String toString() { StringBuilder sb = new StringBuilder(); sb.append("DimensionSelectorHavingSpec"); sb.append("{dimension='").append(dimension).append('\''); sb.append(", value='").append(value); <START> if (getExtractionFn() != null) { <END> sb.append("', extractionFunction='").append(getExtractionFn()); } sb.append("'}"); return sb.toString(); }</code><technical_language>extractionfn is null</technical_language>

Target:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("DimensionSelectorHavingSpec"); sb.append("{dimension='").append(dimension).append('\''); sb.append(", value='").append(value); sb.append("', extractionFunction='").append(getExtractionFn()); sb.append("'}"); return sb.toString(); }
Source:
<code>protected synchronized void handleMessageInternal(Message<?> message) throws Exception { String payloadString = message.getPayload().toString(); <START> Class<?> type = (payloadString.contains("\"composite\":true")) ? CompositeModuleDeploymentRequest.class <END> : ModuleDeploymentRequest.class; Object deserialized = this.mapper.readValue(payloadString, type); if (deserialized instanceof CompositeModuleDeploymentRequest) { handleCompositeModuleDeployment((CompositeModuleDeploymentRequest) deserialized, message); } else { handleDeploymentRequest((ModuleDeploymentRequest) deserialized, message); } }</code><technical_language>I guess this is laundry list, right ;)</technical_language>

Target:
protected synchronized void handleMessageInternal(Message<?> message) throws Exception { String payloadString = message.getPayload().toString(); ModuleDeploymentRequest deserialized = this.mapper.readValue(payloadString, ModuleDeploymentRequest.class); if (deserialized instanceof CompositeModuleDeploymentRequest) { handleCompositeModuleDeployment((CompositeModuleDeploymentRequest) deserialized, message); } else { handleDeploymentRequest(deserialized, message); } }
Source:
<code>private void share() { lumberYard.save() <START> .doOnError(new Action1<Throwable>() { <END> @Override public void call(Throwable throwable) { Toast.makeText(getContext(), "Couldn't save the logs for sharing.", Toast.LENGTH_SHORT).show(); } }) .subscribe(new Action1<File>() { @Override public void call(File file) { Intent sendIntent = new Intent(Intent.ACTION_SEND); sendIntent.setType("text/plain"); sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); Intents.maybeStartActivity(getContext(), sendIntent); } }); }</code><technical_language>Need java .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) this</technical_language>

Target:
private void share() { lumberYard.save() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<File>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { Toast.makeText(getContext(), "Couldn't save the logs for sharing.", Toast.LENGTH_SHORT) .show(); } @Override public void onNext(File file) { Intent sendIntent = new Intent(Intent.ACTION_SEND); sendIntent.setType("text/plain"); sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); Intents.maybeStartActivity(getContext(), sendIntent); } }); }
Source:
<code>public boolean clearContainerBlockContents(BlockVector3 position) { checkNotNull(position); BlockEntity tile = getWorld().getBlockEntity(FabricAdapter.toBlockPos(position)); if ((tile instanceof Inventory)) { Inventory inv = (Inventory) tile; int size = inv.getInvSize(); for (int i = 0; i < size; i++) { inv.setInvStack(i, ItemStack.EMPTY); } return true; } return false; <START> } <END></code><technical_language>I realized this while MCUtils, IClearable (MCP name - unsure of yarn name) interface a clear method handles campfires, jukeboxes, lecterns traditional Inventorys ~~(Forge too...)~~ done</technical_language>

Target:
public boolean clearContainerBlockContents(BlockVector3 position) { checkNotNull(position); BlockEntity tile = getWorld().getBlockEntity(FabricAdapter.toBlockPos(position)); if ((tile instanceof Clearable)) { ((Clearable) tile).clear(); return true; } return false; }
Source:
<code>public void setStandby(final boolean onOrOff, final String... deviceNames) { <START> neoHubConnector.sendMessage("{\"FROST_" + (onOrOff ? "ON" : "OFF") <END> + "\":[\"" + StringUtils.join(deviceNames, "\",\"") + "\"]}", null); }</code><technical_language>i prefer String.format() in order write message placeholders (%s) refactor commands static constants</technical_language>

Target:
public void setStandby(final boolean onOrOff, final String... deviceNames) { neoHubConnector.sendMessage( String.format("{\"FROST_%s\":[\"%s\"]}", onOrOff ? "ON" : "OFF", StringUtils.join(deviceNames, "\",\"")), null); }
Source:
<code>public boolean shouldPull(ImageData image) { <START> log.trace("Should pull image with tags: {}", Arrays.asList(image.getRepoTags())); <END> return true; }</code><technical_language>suggestion log.trace("Unconditionally pulling image tags: {}", Arrays.asList(image.getRepoTags()));</technical_language>

Target:
public boolean shouldPull(ImageData image) { log.trace("Unconditionally pulling an image with tags: {}", Arrays.asList(image.getRepoTags())); return true; }
Source:
<code>public void run(String[] args) throws Exception { try { options = parser.parse(args); } catch (OptionException e) { exitWithError(LOGGER, e.getMessage() + ". Use --help to get overview of the help options."); return; } if (options.has(helpSpec)) { parser.printHelpOn(System.out); System.exit(0); } provisioner.props.init(getPropertiesFile()); if (options.has(gitSpec)) { String git = options.valueOf(gitSpec); provisioner.props.forceGit(git); } provisioner.init(); if (options.has(restartSpec)) { boolean enterpriseEnabled = options.valueOf(enterpriseEnabledSpec); provisioner.restart(enterpriseEnabled); provisioner.startAgents(); } else if (options.has(killSpec)) { provisioner.killAgents(); } else if (options.has(downloadSpec)) { String dir = options.valueOf(downloadSpec); provisioner.download(dir); } else if (options.has(cleanSpec)) { provisioner.clean(); } else if (options.has(terminateSpec)) { provisioner.terminate(); } else if (options.has(scaleSpec)) { int size = options.valueOf(scaleSpec); boolean enterpriseEnabled = options.valueOf(enterpriseEnabledSpec); provisioner.scale(size, enterpriseEnabled); } else if (options.has(listAgentsSpec)) { provisioner.listAgents(); } else { parser.printHelpOn(System.out); } <START> provisioner.shutdown(); <END> }</code><technical_language>this in a try/finally block</technical_language>

Target:
public void run(String[] args) throws Exception { try { options = parser.parse(args); } catch (OptionException e) { exitWithError(LOGGER, e.getMessage() + ". Use --help to get overview of the help options."); return; } if (options.has(helpSpec)) { parser.printHelpOn(System.out); System.exit(0); } provisioner.props.init(getPropertiesFile()); if (options.has(gitSpec)) { String git = options.valueOf(gitSpec); provisioner.props.forceGit(git); } try { provisioner.init(); if (options.has(restartSpec)) { boolean enterpriseEnabled = options.valueOf(enterpriseEnabledSpec); provisioner.restart(enterpriseEnabled); provisioner.startAgents(); } else if (options.has(killSpec)) { provisioner.killAgents(); } else if (options.has(downloadSpec)) { String dir = options.valueOf(downloadSpec); provisioner.download(dir); } else if (options.has(cleanSpec)) { provisioner.clean(); } else if (options.has(terminateSpec)) { provisioner.terminate(); } else if (options.has(scaleSpec)) { int size = options.valueOf(scaleSpec); boolean enterpriseEnabled = options.valueOf(enterpriseEnabledSpec); provisioner.scale(size, enterpriseEnabled); } else if (options.has(listAgentsSpec)) { provisioner.listAgents(); } else { parser.printHelpOn(System.out); } } finally { provisioner.shutdown(); } }
Source:
<code>private boolean isSessionScopeMetric(MetricNameDto metricNameDto) { return (metricNameDto.getOrigin().equals(MetricNameDto.Origin.SESSION_SCOPE_TG) || metricNameDto.getOrigin().equals(MetricNameDto.Origin.SESSION_SCOPE_MONITORING)); <START> } <END></code><technical_language>in general: is necessary review Origins in code. IMHO SESSION_SCOPE_MONITORING in code this commit</technical_language>

Target:
private boolean isSessionScopeMetric(MetricNameDto metricNameDto) { return metricNameDto.getOrigin() == MetricNameDto.Origin.SESSION_SCOPE_TG; }
Source:
<code>private List<StatementGroup> getStatementGroups(JSONArray jsonStatements, EntityIdValue entityIdValue) throws JSONException { List<StatementGroup> result; List<Statement> statementsFromJson = new ArrayList<Statement>( jsonStatements.length()); for (int i = 0; i < jsonStatements.length(); i++) { JSONObject statementJson = jsonStatements.getJSONObject(i); try { Statement statement = this.getStatement(statementJson, entityIdValue); statementsFromJson.add(statement); <START> } catch( Exception e){ <END> logger.debug("Encountered an exception during statement parsing:\n" + e.getMessage() + "\nIn statement\n" + statementJson.toString(2)); } } result = this.statementGroupBuilder .buildFromStatementList(statementsFromJson); return result; }</code><technical_language>Is list "acceptable" exceptions (e.g. NumberFormatException) in try/catch? "catch Exception" catch exceptions show problems in code (e.g. NullPointerException) stop execution</technical_language>

Target:
private List<StatementGroup> getStatementGroups(JSONArray jsonStatements, EntityIdValue entityIdValue) throws JSONException { List<StatementGroup> result; List<Statement> statementsFromJson = new ArrayList<Statement>( jsonStatements.length()); for (int i = 0; i < jsonStatements.length(); i++) { JSONObject statementJson = jsonStatements.getJSONObject(i); try { Statement statement = this.getStatement(statementJson, entityIdValue); statementsFromJson.add(statement); } catch( IllegalArgumentException | JSONException e){ logger.debug("Encountered an exception during statement parsing:\n" + e.getMessage() + "\nIn statement\n" + statementJson.toString(2)); } } result = this.statementGroupBuilder .buildFromStatementList(statementsFromJson); return result; }
Source:
<code>public static String getStatsAssetsByChunkName(VaadinService service) throws IOException { DeploymentConfiguration config = service.getDeploymentConfiguration(); if (!config.isProductionMode() && config.enableDevServer()) { <START> return streamToString(getStatsFromWebpack()); <END> } InputStream resourceAsStream; if (config.isStatsExternal()) { resourceAsStream = getStatsFromExternalUrl( config.getExternalStatsUrl(), service.getContext()); } else { resourceAsStream = getStatsFromClassPath(service); } if (resourceAsStream == null) { return null; } try (Scanner scan = new Scanner(resourceAsStream, StandardCharsets.UTF_8.name())) { StringBuilder assets = new StringBuilder(); assets.append("{"); scanToAssetChunkStart(scan, assets); while (scan.hasNextLine()) { String line = scan.nextLine().trim(); if ("}".equals(line) || "},".equals(line)) { return assets.append("}").toString(); } else if (line.endsWith("}") || line.endsWith("},")) { return assets .append(line.substring(0, line.indexOf('}')).trim()) .append("}").toString(); } else if (line.contains("{")) { break; } assets.append(line); } getLogger() .error("Could not parse assetsByChunkName from stats.json"); } return null; }</code><technical_language>want stats.json form webpack want asset chunks. This reverted 4-8 lines of text 4-18 megabytes of text. returned content is is expected method</technical_language>

Target:
public static String getStatsAssetsByChunkName(VaadinService service) throws IOException { DeploymentConfiguration config = service.getDeploymentConfiguration(); if (!config.isProductionMode() && config.enableDevServer()) { return streamToString(getResourceFromWebpack("/assetsByChunkName", "getting assets by chunk name.")); } InputStream resourceAsStream; if (config.isStatsExternal()) { resourceAsStream = getStatsFromExternalUrl( config.getExternalStatsUrl(), service.getContext()); } else { resourceAsStream = getStatsFromClassPath(service); } if (resourceAsStream == null) { return null; } try (Scanner scan = new Scanner(resourceAsStream, StandardCharsets.UTF_8.name())) { StringBuilder assets = new StringBuilder(); assets.append("{"); scanToAssetChunkStart(scan, assets); while (scan.hasNextLine()) { String line = scan.nextLine().trim(); if ("}".equals(line) || "},".equals(line)) { return assets.append("}").toString(); } else if (line.endsWith("}") || line.endsWith("},")) { return assets .append(line.substring(0, line.indexOf('}')).trim()) .append("}").toString(); } else if (line.contains("{")) { break; } assets.append(line); } getLogger() .error("Could not parse assetsByChunkName from stats.json"); } return null; }
Source:
<code>public ListVersionView history(@PathParam("primaryKey") String key, @PathParam("primaryKeyValue") String value) throws Exception { String registerPrimaryKey = requestContext.getRegisterPrimaryKey(); if (key.equals(registerPrimaryKey)) { <START> return new ListVersionView(requestContext, publicBodiesConfiguration, queryDAO.findAllByKeyValue(key, value).stream().map(r -> new Version(r.getSerialNumber(), r.getContent().getHash())).collect(Collectors.toList())); <END> } throw new NotFoundException(); }</code><technical_language>move ListVersionView object construction in ViewFactory? this replace publicBodiesConfiguration dependency ViewFactory consistent other resources</technical_language>

Target:
public ListVersionView history(@PathParam("primaryKey") String key, @PathParam("primaryKeyValue") String value) throws Exception { String registerPrimaryKey = requestContext.getRegisterPrimaryKey(); if (key.equals(registerPrimaryKey)) { return viewFactory.listVersionView(queryDAO.findAllByKeyValue(key, value).stream().map(r -> new Version(r.getSerialNumber(), r.getContent().getHash())).collect(Collectors.toList())); } throw new NotFoundException(); }
Source:
<code>static void processAnnotatedType(@Observes ProcessAnnotatedType<?> pat) { <START> pat.veto(); <END> }</code><technical_language>Please remove this invocation. Right now, test pass ExtensionBeanDeployer modification. If remove invocation, test fail modification. good now</technical_language>

Target:
static void processAnnotatedType(@Observes ProcessAnnotatedType<?> pat) { }
Source:
<code>protected void assertOriginalEqualsToUnmarshalled(ClusterDataSetListResponseBody expected, ClusterDataSetListResponseBody actual) { final List<ClusterDataSetEntry> expectedDataSets = expected.getDataSets(); final List<ClusterDataSetEntry> actualDataSets = actual.getDataSets(); <START> assertEquals(expectedDataSets.size(), actualDataSets.size()); <END> assertThat(actualDataSets, hasSize(expectedDataSets.size())); for (int i = 0; i < expectedDataSets.size(); i++) { ClusterDataSetEntry expectedDataSet = expectedDataSets.get(i); ClusterDataSetEntry actualDataSet = actualDataSets.get(i); assertThat(actualDataSet.getDataSetId(), is(expectedDataSet.getDataSetId())); assertThat(actualDataSet.isComplete(), is(expectedDataSet.isComplete())); } }</code><technical_language>this next line</technical_language>

Target:
protected void assertOriginalEqualsToUnmarshalled(ClusterDataSetListResponseBody expected, ClusterDataSetListResponseBody actual) { final List<ClusterDataSetEntry> expectedDataSets = expected.getDataSets(); final List<ClusterDataSetEntry> actualDataSets = actual.getDataSets(); assertThat(actualDataSets, hasSize(expectedDataSets.size())); for (int i = 0; i < expectedDataSets.size(); i++) { ClusterDataSetEntry expectedDataSet = expectedDataSets.get(i); ClusterDataSetEntry actualDataSet = actualDataSets.get(i); assertThat(actualDataSet.getDataSetId(), is(expectedDataSet.getDataSetId())); assertThat(actualDataSet.isComplete(), is(expectedDataSet.isComplete())); } }
Source:
<code>public String executeAndGetResult() throws ProcessExecutionException { try { Map<String, String> env = processBuilder.environment(); if (env==null) <START> System.out.println("[executeAndGetResult] environment null"); <END> else { for (String key : environmentVariables.stringPropertyNames()) env.put(key, environmentVariables.getProperty(key)); } final Process process = processBuilder.start(); final String result = readString(process.getInputStream()); final String error = readString(process.getInputStream()); final int exitValue = process.waitFor(); if(exitValue == 0){ return result; } else { throw new ProcessExecutionException(result+" "+error); } } catch (IOException e) { throw new ProcessExecutionException(e); } catch (InterruptedException e) { throw new ProcessExecutionException(e); } }</code><technical_language>System.out.println ?! Is this option ? some logging library instead</technical_language>

Target:
public String executeAndGetResult() throws ProcessExecutionException { try { Map<String, String> env = processBuilder.environment(); if (env!=null) { for (String key : environmentVariables.stringPropertyNames()) env.put(key, environmentVariables.getProperty(key)); } final Process process = processBuilder.start(); final String result = readString(process.getInputStream()); final String error = readString(process.getInputStream()); final int exitValue = process.waitFor(); if(exitValue == 0){ return result; } else { throw new ProcessExecutionException(result+" "+error); } } catch (IOException e) { throw new ProcessExecutionException(e); } catch (InterruptedException e) { throw new ProcessExecutionException(e); } }
Source:
<code>public void bindTo(MeterRegistry registry) { <START> Gauge.builder("k8s_client_invocation_total", countedClientFactory::getClientInvocationsCount) <END> .register(registry); }</code><technical_language>k8s.client.invocation.total</technical_language>

Target:
public void bindTo(MeterRegistry registry) { Gauge.builder("k8s.client.invocation.total", countedClientFactory::getClientInvocationsCount) .register(registry); }
Source:
<code><START> public void getTypeFromIdShouldReturnProperEnumValue() throws JAXBException { <END> FormMappingModel formMappingModel = new FormMappingModel(); formMappingModel.addFormMapping(new FormMappingDefinition("lala", null, null)); StringWriter result = new StringWriter(); JAXBContext jaxbContext = JAXBContext.newInstance(FormMappingModel.class); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.marshal(formMappingModel, result); String result2 = result.toString(); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Object formMappingResult = unmarshaller.unmarshal(new StringReader(result2)); assertThat(formMappingModel).isEqualTo(formMappingResult); }</code><technical_language>I understand modified this test</technical_language>

Target:
public void getTypeFromIdShouldReturnProperEnumValue() { assertThat(FormMappingType.getTypeFromId(1)).isEqualTo(FormMappingType.PROCESS_START); assertThat(FormMappingType.getTypeFromId(2)).isEqualTo(FormMappingType.PROCESS_OVERVIEW); assertThat(FormMappingType.getTypeFromId(3)).isEqualTo(FormMappingType.TASK); }
Source:
<code>public void updateMediaDirection(MediaType type, String direction) { switch (direction) { case "sendrecv": case "sendonly": case "recvonly": case "inactive": { for (ChannelShim channelShim : channelShims) { <START> if (Objects.equals(channelShim.getMediaType(), type)) { <END> channelShim.setDirection(direction); } } break; } default: throw new IllegalArgumentException("Media direction unknown: " + direction); } }</code><technical_language>I a normal == works fine here</technical_language>

Target:
public void updateMediaDirection(MediaType type, String direction) { switch (direction) { case "sendrecv": case "sendonly": case "recvonly": case "inactive": { for (ChannelShim channelShim : channelShims) { if (channelShim.getMediaType() == type) { channelShim.setDirection(direction); } } break; } default: throw new IllegalArgumentException("Media direction unknown: " + direction); } }