auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public CompletableFuture<HRegionLocation> getRegionLocation(byte[] row, boolean reload){ try { this.regionsFuture = getRegionsAsync(reload); } catch (IOException e) { <START> e.getCause(); <END> } Futures.addCallback(this.regionsFuture, new FutureCallback<List<HRegionLocation>>() { @Override public void onSuccess(@Nullable List<HRegionLocation> result) { for(HRegionLocation region : result) { if (region.getRegion().containsRow(row)) { hRegionLocation = region; } } } @Override public void onFailure(Throwable t) { synchronized (BigtableAsyncTableRegionLocator.this) { regionsFuture = null; } } }); if(hRegionLocation == null) { LOG.info("Region not found for row: ", Bytes.toStringBinary(row)); } return CompletableFuture.completedFuture(hRegionLocation); }</code><technical_language>Please return FutureUtils.failedFuture(e) here. getRegionsAsync() some logic throw IOException. Or, better, getRegionsAsync() throw exception, do wrapping of execution a Futures.immediateFailFuture()</technical_language>

Target:
public CompletableFuture<HRegionLocation> getRegionLocation(byte[] row, boolean reload) { return FutureUtils.toCompletableFuture(getRegionsAsync(reload)) .thenApplyAsync(result -> { for (HRegionLocation region : result) { if (region.getRegion().containsRow(row)) { hRegionLocation = region; break; } } return hRegionLocation; }); }
Source:
<code><START> public SyntaxToken MEMBER_MODIFIER() { <END> return b.<SyntaxToken>nonterminal().is( b.firstOf( b.token(PHPKeyword.PUBLIC), b.token(PHPKeyword.PROTECTED), b.token(PHPKeyword.PRIVATE), b.token(PHPKeyword.STATIC), b.token(PHPKeyword.ABSTRACT), b.token(PHPKeyword.FINAL) )); }</code><technical_language>![MAJOR](<LINK_1> Rename this method name match regular expression '^[a-z][a-zA-Z0-9]*$'. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
public SyntaxToken MEMBER_MODIFIER() { return b.<SyntaxToken>nonterminal(PHPLexicalGrammar.MEMBER_MODIFIER).is( b.firstOf( b.token(PHPKeyword.PUBLIC), b.token(PHPKeyword.PROTECTED), b.token(PHPKeyword.PRIVATE), b.token(PHPKeyword.STATIC), b.token(PHPKeyword.ABSTRACT), b.token(PHPKeyword.FINAL))); }
Source:
<code>private static Collection<Geocache> importCachesFromGPXResponse(final HttpResponse response) { if (response == null) { return Collections.emptyList(); } Collection<Geocache> caches; try { <START> caches = new ECGPXParser(StoredList.TEMPORARY_LIST_ID).parse(response.getEntity().getContent(), null); <END> } catch (Exception e) { Log.e("Error importing gpx from extremcaching.com", e); return Collections.emptyList(); } return caches; }</code><technical_language>java try { return new ECGPXParser( ); }</technical_language>

Target:
private static Collection<Geocache> importCachesFromGPXResponse(final HttpResponse response) { if (response == null) { return Collections.emptyList(); } try { return new GPX10Parser(StoredList.TEMPORARY_LIST_ID).parse(response.getEntity().getContent(), null); } catch (Exception e) { Log.e("Error importing gpx from extremcaching.com", e); return Collections.emptyList(); } }
Source:
<code>public static Map<String, Object> getTypesMapFromAppMap(Map<String, Object> appMap) { Map<String, Object> typesMap; try { <START> if (log.isDebugEnabled()) { <END> log.debug("Opening TOSCA for obtaining types"); } typesMap = (Map<String, Object>) appMap.get(TOSCAkeywords.NODE_TYPES); } catch (NullPointerException E) { log.error("It was not found '" + TOSCAkeywords.NODE_TYPES + "' . Cannot be unveiled the types of modules"); return null; } return typesMap; }</code><technical_language>I if is useful log.isDebugEnabled() here. a [here](<LINK_0></technical_language>

Target:
public static Map<String, Object> getTypesMapFromAppMap(Map<String, Object> appMap) { Map<String, Object> typesMap; try { log.debug("Opening TOSCA for obtaining types"); typesMap = (Map<String, Object>) appMap.get(TOSCAkeywords.NODE_TYPES); } catch (NullPointerException E) { log.error("It was not found '" + TOSCAkeywords.NODE_TYPES + "' . Cannot be unveiled the types of modules"); return null; } return typesMap; }
Source:
<code>public App(AppConfig appConfig) { this.appConfig = appConfig; ExecutorService collectionThreadPool = appConfig.getThreadPoolSize() >= 1 ? Executors.newFixedThreadPool(appConfig.getThreadPoolSize()) : Executors.newCachedThreadPool(); <START> collectionProcessor = new TaskProcessor(collectionThreadPool, appConfig.getReporter(), LOGGER); <END> ExecutorService recoveryThreadPool = appConfig.getReconnectionThreadPoolSize() >= 1 ? Executors.newFixedThreadPool(appConfig.getReconnectionThreadPoolSize()) : Executors.newCachedThreadPool(); recoveryProcessor = new TaskProcessor(recoveryThreadPool, appConfig.getReporter(), LOGGER); if (appConfig.remoteEnabled()) { client = new HttpClient(appConfig.getIPCHost(), appConfig.getIPCPort(), false); } this.configs = getConfigs(appConfig); }</code><technical_language>TaskProcessor initiate logger</technical_language>

Target:
public App(AppConfig appConfig) { this.appConfig = appConfig; ExecutorService collectionThreadPool = appConfig.getThreadPoolSize() >= 1 ? Executors.newFixedThreadPool(appConfig.getThreadPoolSize()) : Executors.newCachedThreadPool(); collectionProcessor = new TaskProcessor(collectionThreadPool, appConfig.getReporter()); ExecutorService recoveryThreadPool = appConfig.getReconnectionThreadPoolSize() >= 1 ? Executors.newFixedThreadPool(appConfig.getReconnectionThreadPoolSize()) : Executors.newCachedThreadPool(); recoveryProcessor = new TaskProcessor(recoveryThreadPool, appConfig.getReporter()); if (appConfig.remoteEnabled()) { client = new HttpClient(appConfig.getIpcHost(), appConfig.getIpcPort(), false); } this.configs = getConfigs(appConfig); }
Source:
<code>public boolean persistNowSafely(boolean alreadyHasMutex) { Stopwatch timer = Stopwatch.createStarted(); try { persistNowInternal(alreadyHasMutex); metrics.noteSuccess(Duration.of(timer)); return true; } catch (RuntimeInterruptedException e) { LOG.debug("Interrupted persisting change-delta (rethrowing)", e); metrics.noteFailure(Duration.of(timer)); metrics.noteError(e.toString()); Thread.currentThread().interrupt(); return false; <START> } catch (Exception e) { <END> LOG.error("Problem persisting change-delta", e); metrics.noteFailure(Duration.of(timer)); metrics.noteError(e.toString()); return false; } catch (Throwable t) { LOG.warn("Problem persisting change-delta (rethrowing)", t); metrics.noteFailure(Duration.of(timer)); metrics.noteError(t.toString()); throw Exceptions.propagate(t); } }</code><technical_language>merge catch Exception catch Throwable, with: } catch (Throwable t) { // rethrow: behaviour of executionManager is a scheduledExecutorService, // if throw exception, task get executed LOG.error("Problem persisting change-delta", t); metrics.noteFailure(Duration.of(timer)); metrics.noteError(t.toString()); Exceptions.propagateIfFatal(t); return false; Downside is log message is error, include is "(rethrowing)"</technical_language>

Target:
private boolean persistNowSafely(boolean alreadyHasMutex) { Stopwatch timer = Stopwatch.createStarted(); try { persistNowInternal(alreadyHasMutex); metrics.noteSuccess(Duration.of(timer)); return true; } catch (RuntimeInterruptedException e) { LOG.debug("Interrupted persisting change-delta (rethrowing)", e); metrics.noteFailure(Duration.of(timer)); metrics.noteError(e.toString()); Thread.currentThread().interrupt(); return false; } catch (Exception e) { LOG.error("Problem persisting change-delta", e); metrics.noteFailure(Duration.of(timer)); metrics.noteError(e.toString()); return false; } catch (Throwable t) { LOG.warn("Problem persisting change-delta (rethrowing)", t); metrics.noteFailure(Duration.of(timer)); metrics.noteError(t.toString()); throw Exceptions.propagate(t); } }
Source:
<code>public AllKnownEEsResolutionHints() { additionalUnits = new LinkedHashMap<VersionedId, IInstallableUnit>(); for (String env : getAllKnownExecutionEnvironments()) { <START> StandardEEResolutionHints.addIUsFromEnvironment(env, additionalUnits); <END> } this.temporaryUnits = StandardEEResolutionHints.computeTemporaryAdditions(additionalUnits); }</code><technical_language>I add JRE units temporaryUnits. In this removed resolution results end in eclipse-repositories includeAllDependencies</technical_language>

Target:
public AllKnownEEsResolutionHints() { temporaryUnits = new LinkedHashMap<VersionedId, IInstallableUnit>(); for (String env : getAllKnownExecutionEnvironments()) { StandardEEResolutionHints.addIUsFromEnvironment(env, temporaryUnits); } }
Source:
<code>public boolean containsValue(Object value) { Objects.nonNull(value); <START> return values().stream().filter(value::equals).findFirst().isPresent(); <END> }</code><technical_language>values().stream().anyMatch(value::equals)</technical_language>

Target:
public boolean containsValue(Object value) { Objects.nonNull(value); return values().stream().anyMatch(StreamMarshalling.equalityPredicate(value)); }
Source:
<code>private void planDistribution(PlanRoot plan) { CloseableSplitSourceProvider splitSourceProvider = new CloseableSplitSourceProvider(splitManager::getSplits); stateMachine.addStateChangeListener(state -> { if (state.isDone()) { splitSourceProvider.close(); } }); if (stateMachine.isDone()) { return; } SubPlan outputStagePlan = plan.getRoot(); stateMachine.setColumns(((OutputNode) outputStagePlan.getFragment().getRoot()).getColumnNames(), outputStagePlan.getFragment().getTypes()); SplitSourceFactory splitSourceFactory = new SplitSourceFactory(splitSourceProvider); SqlQueryScheduler scheduler = createSqlQueryScheduler( locationFactory, executionPolicy, queryExecutor, schedulerStats, sectionStageExecutionFactory, remoteTaskFactory, splitSourceFactory, stateMachine.getSession(), stateMachine, outputStagePlan, plan.isSummarizeTaskInfos()); <START> queryScheduler.set(scheduler); <END> if (stateMachine.isDone()) { scheduler.abort(); queryScheduler.set(null); } }</code><technical_language>Totally unrelated this PR. createSqlQueryScheduler() is a factory method, passed stateMachine in, this kinda redundant</technical_language>

Target:
private void planDistribution(PlanRoot plan) { CloseableSplitSourceProvider splitSourceProvider = new CloseableSplitSourceProvider(splitManager::getSplits); stateMachine.addStateChangeListener(state -> { if (state.isDone()) { splitSourceProvider.close(); } }); if (stateMachine.isDone()) { return; } SubPlan outputStagePlan = plan.getRoot(); stateMachine.setColumns(((OutputNode) outputStagePlan.getFragment().getRoot()).getColumnNames(), outputStagePlan.getFragment().getTypes()); PartitioningHandle partitioningHandle = outputStagePlan.getFragment().getPartitioningScheme().getPartitioning().getHandle(); OutputBuffers rootOutputBuffers = createInitialEmptyOutputBuffers(partitioningHandle) .withBuffer(OUTPUT_BUFFER_ID, BROADCAST_PARTITION_ID) .withNoMoreBufferIds(); SplitSourceFactory splitSourceFactory = new SplitSourceFactory(splitSourceProvider); SqlQuerySchedulerInterface scheduler = isUseLegacyScheduler(getSession()) ? LegacySqlQueryScheduler.createSqlQueryScheduler( locationFactory, executionPolicy, queryExecutor, schedulerStats, sectionExecutionFactory, remoteTaskFactory, splitSourceFactory, stateMachine.getSession(), stateMachine, outputStagePlan, rootOutputBuffers, plan.isSummarizeTaskInfos()) : SqlQueryScheduler.createSqlQueryScheduler( locationFactory, executionPolicy, queryExecutor, schedulerStats, sectionExecutionFactory, remoteTaskFactory, splitSourceFactory, internalNodeManager, stateMachine.getSession(), stateMachine, outputStagePlan, plan.isSummarizeTaskInfos()); queryScheduler.set(scheduler); if (stateMachine.isDone()) { scheduler.abort(); queryScheduler.set(null); } }
Source:
<code>public ResponseEntity<List<String>> syncRepository(String repositoryUrl) { <START> boolean validRequest = repositoryUrl != null && !StringUtils.isEmpty(repositoryUrl); <END> if (validRequest) { String oldUrl = configurationService.getModelRepositoryUrl(); configurationService.setModelRepositoryUrl(repositoryUrl); try { sourceCodeManager.updateRepository(); List<String> versions = sourceCodeManager.getAvailableVersions(); if (!repositoryUrl.equals(oldUrl)) { configurationService.setModelRepositoryVersion(""); } return new ResponseEntity<List<String>>(versions, HttpStatus.OK); } catch (Exception e) { configurationService.setModelRepositoryUrl(oldUrl); } } return new ResponseEntity<List<String>>(HttpStatus.BAD_REQUEST); }</code><technical_language>remove "repositoryUrl != null &&"</technical_language>

Target:
public ResponseEntity<List<String>> syncRepository(String repositoryUrl) { boolean validRequest = !StringUtils.isEmpty(repositoryUrl); if (validRequest) { String oldUrl = configurationService.getModelRepositoryUrl(); configurationService.setModelRepositoryUrl(repositoryUrl); try { sourceCodeManager.updateRepository(); List<String> versions = sourceCodeManager.getAvailableVersions(); if (!repositoryUrl.equals(oldUrl)) { configurationService.setModelRepositoryVersion(""); } return new ResponseEntity<List<String>>(versions, HttpStatus.OK); } catch (Exception e) { configurationService.setModelRepositoryUrl(oldUrl); } } return new ResponseEntity<List<String>>(HttpStatus.BAD_REQUEST); }
Source:
<code>public void finish() throws IOException, SQLException { super.finish(); executorService.shutdown(); try { <START> executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); <END> } catch (InterruptedException e) { throw new RuntimeException(e); } logger.info("Loaded files.", fileCount); }</code><technical_language>I Long.MAX_VALUE is long. 1 hour</technical_language>

Target:
public void finish() throws IOException, SQLException { super.finish(); for (Future<Void> uploadAndCopyFuture : uploadAndCopyFutures) { try { uploadAndCopyFuture.get(); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { if (e.getCause() instanceof SQLException) { throw (SQLException)e.getCause(); } throw new RuntimeException(e); } } logger.info("Loaded files.", fileCount); }
Source:
<code>public void <START> test_BorderedEdgeAndContainer() <END> { createBorderedEdgeAndValidateAnchors("Container", "A", AbstractDiagramContainerEditPart.class, "B", AbstractDiagramContainerEditPart.class); }</code><technical_language>This test is OK fix. I test is relevant. change Sirius preference "Enable user specific default values" Rectilinear. I this is problem in test</technical_language>

Target:
public void test_BorderedEdgeAndContainer() { changeDiagramPreference(SiriusDiagramCorePreferences.PREF_ENABLE_OVERRIDE, true); changeDiagramPreference(SiriusDiagramCorePreferences.PREF_LINE_STYLE, EdgeRouting.MANHATTAN); createBorderedEdgeAndValidateAnchors("Container", "A", AbstractDiagramContainerEditPart.class, "B", AbstractDiagramContainerEditPart.class); resetDiagramPreference(SiriusDiagramCorePreferences.PREF_ENABLE_OVERRIDE); }
Source:
<code>protected boolean isBonitaGroovyBasedValidator(final Instance validator) { final String className = validator.get("validatorClass"); <START> final boolean isBonitaGroovyBasedValidator = className != null <END> && (className.contains("GroovyPageValidator") || className.contains("GroovyFieldValidator")); return isBonitaGroovyBasedValidator; }</code><technical_language>return className != null && (className.contains("GroovyPageValidator") || className.contains("GroovyFieldValidator"));</technical_language>

Target:
protected boolean isBonitaGroovyBasedValidator(final Instance validator) { final String className = validator.get("validatorClass"); return className != null && (className.contains("GroovyPageValidator") || className.contains("GroovyFieldValidator")); }
Source:
<code>public String toString() { switch (status) { case ADDED: return "(" + name + " " + type + " +" + current + ")"; case MATCHED: return "(" + name + " " + type + " " + current + " " + baseline + ")"; case DELETED: return "(" + name + " " + type + " -" + baseline + ")"; } <START> return "???"; <END> }</code><technical_language>common throw AssertionError() for cases, legitimately impossible</technical_language>

Target:
public String toString() { switch (status) { case ADDED: return "(" + name + " " + type + " +" + current + ")"; case MATCHED: return "(" + name + " " + type + " " + current + " " + baseline + ")"; case DELETED: return "(" + name + " " + type + " -" + baseline + ")"; default: throw new AssertionError("unsupported enum member"); } }
Source:
<code>void createTransactionAndRollbackMessagesTest(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, isSessionEnabled); <START> final String messageId = "createTransactionAndRollbackMessagesTest";UUID.randomUUID().toString(); <END> final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(OPERATION_TIMEOUT); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(receiver.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); final ServiceBusReceivedMessageContext receivedContext = receiver.receive().next().block(OPERATION_TIMEOUT); assertNotNull(receivedContext); final ServiceBusReceivedMessage receivedMessage = receivedContext.getMessage(); assertNotNull(receivedMessage); StepVerifier.create(receiver.complete(receivedMessage, transaction.get())) .verifyComplete(); StepVerifier.create(receiver.rollbackTransaction(transaction.get())) .verifyComplete(); }</code><technical_language>Clean messageIds</technical_language>

Target:
void createTransactionAndRollbackMessagesTest(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message).block(OPERATION_TIMEOUT); AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>(); StepVerifier.create(receiver.createTransaction()) .assertNext(txn -> { transaction.set(txn); assertNotNull(transaction); }) .verifyComplete(); final ServiceBusReceivedMessageContext receivedContext = receiver.receive().next().block(OPERATION_TIMEOUT); assertNotNull(receivedContext); final ServiceBusReceivedMessage receivedMessage = receivedContext.getMessage(); assertNotNull(receivedMessage); StepVerifier.create(receiver.complete(receivedMessage, transaction.get())) .verifyComplete(); StepVerifier.create(receiver.rollbackTransaction(transaction.get())) .verifyComplete(); }
Source:
<code>public void toStream(@NonNull JsonStream writer) throws IOException { writer.beginArray(); if (cachedThreads != null) { for (CachedThread thread : cachedThreads) { writer.value(thread); } } else { <START> for (Thread thread : threads) { <END> writer.beginObject(); writer.name("id").value(thread.getId()); writer.name("name").value(thread.getName()); writer.name("type").value(THREAD_TYPE); StackTraceElement[] stacktrace = stackTraces.get(thread); writer.name("stacktrace").value(new Stacktrace(config, stacktrace)); if (currentThreadId == thread.getId()) { writer.name("errorReportingThread").value(true); } writer.endObject(); } } writer.endArray(); }</code><technical_language>implementation of ThreadState simplified constructing a CachedThread instance for object in threads. field ThreadState need is a cachedThreads collection. follow a similar pattern mapping StackTraceElement StackTrace</technical_language>

Target:
public void toStream(@NonNull JsonStream writer) throws IOException { writer.beginArray(); for (CachedThread thread : cachedThreads) { writer.value(thread); } writer.endArray(); }
Source:
<code>public List<? extends Module> getJacksonModules() { return ImmutableList.<Module>of( new SimpleModule("SingleCached-LoadingOrPolling-Lookup-Module") { @Override public void setupModule(SetupContext context) { <START> context.setMixInAnnotations(LookupExtractorFactory.class, LookupExtractorFactoryMixIn.class); <END> } } ); }</code><technical_language>This is commonly in Druid, subtype registration prior? If want names class registration com.fasterxml.jackson.databind.jsontype.NamedType</technical_language>

Target:
public List<? extends Module> getJacksonModules() { return ImmutableList.<Module>of( new SimpleModule("SingleCached-LoadingOrPolling-Lookup-Module") { @Override public void setupModule(SetupContext context) { context.registerSubtypes(LoadingLookupFactory.class); context.registerSubtypes(PollingLookupFactory.class); context.registerSubtypes(new NamedType(PrefetchedLoadingLookupFactory.class, "prefetchLoadingLookup")); } } ); }
Source:
<code>public ShaderLayer setTextureBounds(double... bounds) { if(bounds==null) return this; <START> assert (bounds.length==4); <END> this.textureBounds = bounds; return this; }</code><technical_language>I prefer Preconditions.checkArgument asserts (at for cheap things), run catch issues crash point early in production (IIRC assert is disabled default)</technical_language>

Target:
public ShaderLayer setTextureBounds(double... bounds) { if(bounds==null) return this; Preconditions.checkArgument(bounds.length==4); this.textureBounds = bounds; return this; }
Source:
<code><START> private String getUrl() throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, MalformedURLException { <END> if (Strings.isNullOrEmpty(dingtalkConfiguration.getSecret())) { return dingtalkConfiguration.getWebhook(); } else { return getSignUrl(); } }</code><technical_language>MalformedURLException removed</technical_language>

Target:
private String getUrl() { if (Strings.isNullOrEmpty(dingtalkConfiguration.getSecret())) { return dingtalkConfiguration.getWebhook(); } else { return getSignUrl(); } }
Source:
<code>public void run() { <START> synchronized (scannerLock) { <END> if (status == Status.STOPPED) { return; } scanNow(); status = Status.RUNNING; } }</code><technical_language>Avoid scannerLock object synchronize KieRepositoryScannerImpl.this. I this clearer sync'ing lock of scanNow() method</technical_language>

Target:
public void run() { synchronized (KieRepositoryScannerImpl.this) { if (status == Status.STOPPED) { return; } scanNow(); status = Status.RUNNING; } }
Source:
<code>private void deleteInDb(NetworkInstance networkInstance, String vdc, String region) throws InvalidEntityException { log.info("Destroying network in DB" + networkInstance.getNetworkName()); try { networkInstance = load(networkInstance.getNetworkName(), vdc, region); Set<SubNetworkInstance> subNetAux = networkInstance.cloneSubNets(); log.info("Deleting the subnets " + subNetAux.size()); networkInstance.getSubNets().clear(); networkInstanceDao.update(networkInstance); for (SubNetworkInstance subNet : subNetAux) { log.info ("Delete subnet " + subNet.getName()); subNetworkInstanceManager.deleteInBD(subNet); } <START> log.info("Deleting the network"); <END> networkInstanceDao.remove(networkInstance); } catch (Exception e) { log.error("Error to remove the network in BD " + e.getMessage()); throw new InvalidEntityException(networkInstance); } }</code><technical_language>a view code is logs message "Deleting network", difficult trace origin of executed line if message is same</technical_language>

Target:
private void deleteInDb(NetworkInstance networkInstance, String vdc, String region) throws InvalidEntityException { log.info("Destroying network in DB" + networkInstance.getNetworkName()); try { networkInstance = load(networkInstance.getNetworkName(), vdc, region); Set<SubNetworkInstance> subNetAux = networkInstance.cloneSubNets(); networkInstance.getSubNets().clear(); networkInstanceDao.update(networkInstance); for (SubNetworkInstance subNet : subNetAux) { log.info ("Delete subnet in BD " + subNet.getName()); subNetworkInstanceManager.deleteInBD(subNet); } networkInstanceDao.remove(networkInstance); } catch (Exception e) { log.error("Error to remove the network in BD " + e.getMessage()); throw new InvalidEntityException(networkInstance); } }
Source:
<code>public void registerReferenceProviders(@NotNull PsiReferenceRegistrar registrar) { registerRecords(registrar, "erlang", "is_record", 2, 1); registerRecords(registrar, "erlang", "is_record", 3, 1); registrar.registerReferenceProvider(psiElement(ErlangQAtom.class).with( <START> new ErlangPsiImplUtil.ErlangSpecParameter<PsiElement>()), <END> getProvider(Kind.MODULE)); ErlangFunctionCallNamedParameter<PsiElement> funParameter = new ErlangFunctionCallNamedParameter<PsiElement>("Function", "Fun", "_Function"); registrar.registerReferenceProvider(psiElement(ErlangQAtom.class).with(funParameter), getProvider(Kind.FUNCTION)); }</code><technical_language>This is intuitive all. ErlangSpecParameter give idea match here</technical_language>

Target:
public void registerReferenceProviders(@NotNull PsiReferenceRegistrar registrar) { PsiElementPattern.Capture<ErlangQAtom> atom = psiElement(ErlangQAtom.class); PsiElementPattern.Capture<ErlangQAtom> atomArg = atom.withParents(ErlangMaxExpression.class, ErlangArgumentList.class, ErlangFunctionCallExpression.class); registrar.registerReferenceProvider(atomArg.with(isRecordArgument(2)), new RecordReferenceProvider()); registrar.registerReferenceProvider(atomArg.with(isRecordArgument(3)), new RecordReferenceProvider()); registrar.registerReferenceProvider(atom.with(new ErlangFunctionCallModuleArgument()), new ModuleReferenceProvider()); registrar.registerReferenceProvider(atom.with(new ErlangFunctionCallFunctionArgument()), new FunctionReferenceProvider()); }
Source:
<code>public void afterPropertiesSet() throws Exception { Assert.state(dataSource != null, "DataSource must be provided"); if (getJdbcTemplate() == null) { setJdbcTemplate(new JdbcTemplate(dataSource)); } setJobExecutionIncrementer(new AbstractDataFieldMaxValueIncrementer() { @Override protected long getNextKey() { return 0; } }); final String subQuery = getQuery( <START> "not exists (select * from %PREFIX%JOB_EXECUTION_PARAMS a where key_name = 'xd_parent_execution_id' and E.JOB_EXECUTION_ID=a.JOB_EXECUTION_ID)"); <END> allExecutionsPagingQueryProvider = getPagingQueryProvider(null, subQuery); final String childJobExecutionsSubQuery = getQuery( "exists (select * from %PREFIX%JOB_EXECUTION_PARAMS a where key_name = 'xd_parent_execution_id' and E.JOB_EXECUTION_ID=a.JOB_EXECUTION_ID and long_val=?)"); childJobExecutionsPagingQueryProvider = getPagingQueryProvider(null, childJobExecutionsSubQuery); super.afterPropertiesSet(); }</code><technical_language>move this string xd_parent_execution_id a constant originates</technical_language>

Target:
public void afterPropertiesSet() throws Exception { Assert.state(dataSource != null, "DataSource must be provided"); if (getJdbcTemplate() == null) { setJdbcTemplate(new JdbcTemplate(dataSource)); } setJobExecutionIncrementer(new AbstractDataFieldMaxValueIncrementer() { @Override protected long getNextKey() { return 0; } }); final String subQuery = getQuery( "not exists (select * from %PREFIX%JOB_EXECUTION_PARAMS a where key_name = '" + JobLaunchingTasklet.XD_PARENT_JOB_EXECUTION_ID + "' and E.JOB_EXECUTION_ID=a.JOB_EXECUTION_ID)"); allExecutionsPagingQueryProvider = getPagingQueryProvider(subQuery); final String childJobExecutionsSubQuery = getQuery( "exists (select * from %PREFIX%JOB_EXECUTION_PARAMS a where key_name = '" + JobLaunchingTasklet.XD_PARENT_JOB_EXECUTION_ID + "' and E.JOB_EXECUTION_ID=a.JOB_EXECUTION_ID and long_val=?)"); childJobExecutionsPagingQueryProvider = getPagingQueryProvider(childJobExecutionsSubQuery); super.afterPropertiesSet(); }
Source:
<code>public void awaitCompletion() throws InterruptedException { boolean performedWarning = false; lock.lock(); try { while (!isFlushed()) { flushedCondition.await(finishWaitMillis, TimeUnit.MILLISECONDS); long now = clock.nanoTime(); if (now >= noSuccessCheckDeadlineNanos) { lock.lock(); try { for (RetryHandler retryHandler : outstandingRetries.values()) { <START> retryHandler.performRetryIfStale(); <END> } if (isFlushed()) { break; } } finally { lock.unlock(); } logNoSuccessWarning(now); resetNoSuccessWarningDeadline(); performedWarning = true; } } if (performedWarning) { LOG.info("awaitCompletion() completed"); } } finally { lock.unlock(); } }</code><technical_language>I this PR addresses problem. extra lock lock acquired line 168 lock is reentrant I this anything. I problem is call stack happen (all while holding lock): RetryHandler#performRetryIfStale BulkMutation.Batch#setRetryComplete RpcThrottler#onRetryCompletion this point outstandingRetries.remove(id) is called, a ConcurrentModificationException next iteration this line. If true, a local copy of oustandingRetries.values() (because backed map: <LINK_0> iterate that</technical_language>

Target:
public void awaitCompletion() throws InterruptedException { boolean performedWarning = false; lock.lock(); try { while (!isFlushed()) { flushedCondition.await(finishWaitMillis, TimeUnit.MILLISECONDS); long now = clock.nanoTime(); if (now >= noSuccessCheckDeadlineNanos) { for (RetryHandler retryHandler : ImmutableList.copyOf(outstandingRetries.values())) { retryHandler.performRetryIfStale(); } if (isFlushed()) { break; } logNoSuccessWarning(now); resetNoSuccessWarningDeadline(); performedWarning = true; } } if (performedWarning) { LOG.info("awaitCompletion() completed"); } } finally { lock.unlock(); } }
Source:
<code>public int compareTo(Currency o) { if (attributes.equals(o.attributes)) return 0; <START> int comparison = attributes.commonCode.compareTo(o.attributes.commonCode); <END> if (comparison == 0) comparison = getDisplayName().compareTo(o.getDisplayName()); if (comparison == 0) comparison = hashCode() - o.hashCode(); return comparison; }</code><technical_language>null pointer exception incoming</technical_language>

Target:
public int compareTo(Currency o) { if (attributes.equals(o.attributes)) return 0; Comparator<String> nullSafeStringComparator = Comparator .nullsFirst(String::compareToIgnoreCase); Comparator<Integer> nullSafeIntComparator = Comparator .nullsFirst(Integer::compareTo); Comparator<Currency> currencyComparator; if (attributes.commonCode != null && o.attributes.commonCode != null) { currencyComparator= Comparator .comparing(Currency::getCommonCode, nullSafeStringComparator); } else { currencyComparator= Comparator .comparing(Currency::getCurrencyCode, nullSafeStringComparator); } return currencyComparator .thenComparing(Currency::getDisplayName, nullSafeStringComparator) .thenComparing(Currency::hashCode, nullSafeIntComparator) .compare(this, o); }
Source:
<code>public void testExportTableCase() throws IOException { if (! MiscUtils.isPro()) { return; } VoltProjectBuilder project = new VoltProjectBuilder(); <START> project.addSchema(TestVoltCompiler.class.getResource("ExportTester-ddl.sql")); <END> project.addStmtProcedure("Dummy", "insert into a values (?, ?, ?);", new ProcedurePartitionData("a", "a_id")); project.addExport(true, ServerExportEnum.CUSTOM, "org.voltdb.exportclient.NoOpExporter", new Properties(), "noop"); project.addExport(true ); try { assertTrue(project.compile("/tmp/exportsettingstest.jar")); String catalogContents = VoltCompilerUtils.readFileFromJarfile("/tmp/exportsettingstest.jar", "catalog.txt"); Catalog cat = new Catalog(); cat.execute(catalogContents); CatalogUtil.compileDeployment(cat, project.getPathToDeployment(), false); Connector connector = cat.getClusters().get("cluster").getDatabases(). get("database").getConnectors().get("noop"); assertTrue(connector.getEnabled()); assertNotNull(connector.getTableinfo().getIgnoreCase("a")); assertNotNull(connector.getTableinfo().getIgnoreCase("b")); assertNotNull(connector.getTableinfo().getIgnoreCase("c")); assertNotNull(connector.getTableinfo().getIgnoreCase("d")); assertNotNull(connector.getTableinfo().getIgnoreCase("e")); assertNull(connector.getTableinfo().getIgnoreCase("f")); } finally { File jar = new File("/tmp/exportsettingstest.jar"); jar.delete(); } }</code><technical_language>This test is disabled in community (see check beginning of test). Is want</technical_language>

Target:
public void testExportTableCase() throws IOException { if (! MiscUtils.isPro()) { return; } VoltProjectBuilder project = new VoltProjectBuilder(); project.addSchema(TestVoltCompiler.class.getResource("ExportTester-ddl.sql")); project.addStmtProcedure("Dummy", "insert into a values (?, ?, ?);", new ProcedurePartitionData("a", "a_id")); project.addExport(true, ServerExportEnum.CUSTOM, "org.voltdb.exportclient.NoOpExporter", new Properties(), "noop"); project.addExport(true ); try { assertTrue(project.compile("/tmp/exportsettingstest.jar")); String catalogContents = VoltCompilerUtils.readFileFromJarfile("/tmp/exportsettingstest.jar", "catalog.txt"); Catalog cat = new Catalog(); cat.execute(catalogContents); CatalogUtil.compileDeployment(cat, project.getPathToDeployment(), false); Connector connector = cat.getClusters().get("cluster").getDatabases(). get("database").getConnectors().get("noop"); assertTrue(connector.getEnabled()); assertNotNull(connector.getTableinfo().getIgnoreCase("a")); assertNotNull(connector.getTableinfo().getIgnoreCase("B")); assertNull(connector.getTableinfo().getIgnoreCase("c")); assertNull(connector.getTableinfo().getIgnoreCase("D")); assertNull(connector.getTableinfo().getIgnoreCase("e")); assertNotNull(connector.getTableinfo().getIgnoreCase("f")); } finally { File jar = new File("/tmp/exportsettingstest.jar"); jar.delete(); } }
Source:
<code>protected PatchScreen(final Patch.Key id, final int patchIndex, final PatchSetDetail detail, final PatchTable patchTable) { patchKey = id; patchSetDetail = detail; fileList = patchTable; <START> diffSideA = patchTable.getPatchSetIdToCompareWith(); <END> if (diffSideA == null) { historyOpen = null; } idSideA = diffSideA; idSideB = diffSideB != null ? diffSideB : id.getParentKey(); this.patchIndex = patchIndex; prefs = fileList != null ? fileList.getPreferences() : new ListenableAccountDiffPreference(); prefs.addValueChangeHandler( new ValueChangeHandler<AccountDiffPreference>() { @Override public void onValueChange(ValueChangeEvent<AccountDiffPreference> event) { update(event.getValue()); } }); settingsPanel = new PatchScriptSettingsPanel(prefs); settingsPanel.getReviewedCheckBox().addValueChangeHandler( new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { setReviewedByCurrentUser(event.getValue()); } }); }</code><technical_language>IIRC patchTable null if a user jumps this screen coming web UI. (Consider copying pasting URL of a side side page email clicking link open a new browser window.) need handle patchTable null assume diffSideA is null</technical_language>

Target:
protected PatchScreen(final Patch.Key id, final int patchIndex, final PatchSetDetail detail, final PatchTable patchTable) { patchKey = id; patchSetDetail = detail; fileList = patchTable; if (patchTable != null) { diffSideA = patchTable.getPatchSetIdToCompareWith(); } else { diffSideA = null; } if (diffSideA == null) { historyOpen = null; } idSideA = diffSideA; idSideB = diffSideB != null ? diffSideB : id.getParentKey(); this.patchIndex = patchIndex; prefs = fileList != null ? fileList.getPreferences() : new ListenableAccountDiffPreference(); prefs.addValueChangeHandler( new ValueChangeHandler<AccountDiffPreference>() { @Override public void onValueChange(ValueChangeEvent<AccountDiffPreference> event) { update(event.getValue()); } }); settingsPanel = new PatchScriptSettingsPanel(prefs); settingsPanel.getReviewedCheckBox().addValueChangeHandler( new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { setReviewedByCurrentUser(event.getValue()); } }); }
Source:
<code>private void sendMessages(List<BackupMessage> messages) { logger.info("Sending messages from backup storage.", messages.size()); <START> ExecutorService executor = Executors.newFixedThreadPool(16); <END> int sentCounter = 0; int discardedCounter = 0; for (BackupMessage backupMessage : messages) { Message message = new JsonMessage(backupMessage.getMessageId(), backupMessage.getData(), backupMessage.getTimestamp()); Optional<Topic> topic = loadTopic(fromQualifiedName(backupMessage.getQualifiedTopicName()), executor); if (sendMessageIfNeeded(message, topic, "sending")) { sentCounter++; } else { discardedCounter++; } } executor.shutdownNow(); try { executor.awaitTermination(1, TimeUnit.MINUTES); } catch (InterruptedException e) { logger.error("Termination of load topics executor service interrupted.", e); } logger.info("Loaded and sent messages and discarded messages from the backup storage.", sentCounter, discardedCounter); }</code><technical_language>16</technical_language>

Target:
private void sendMessages(List<BackupMessage> messages) { logger.info("Sending messages from backup storage.", messages.size()); ExecutorService executor = createExecutor(); try { int sentCounter = 0; int discardedCounter = 0; for (BackupMessage backupMessage : messages) { Message message = new JsonMessage(backupMessage.getMessageId(), backupMessage.getData(), backupMessage.getTimestamp()); Optional<Topic> topic = loadTopic(fromQualifiedName(backupMessage.getQualifiedTopicName()), executor); if (sendMessageIfNeeded(message, topic, "sending")) { sentCounter++; } else { discardedCounter++; } } logger.info("Loaded and sent messages and discarded messages from the backup storage.", sentCounter, discardedCounter); } finally { shutdownExecutor(executor); } }
Source:
<code>public <V> Future<V> schedule(BackgroundTask<V> task, long delay, TimeUnit unit) { <START> return scheduledExecutor.schedule(task::call, delay, unit); <END> }</code><technical_language>remove getJavaFX call</technical_language>

Target:
public <V> Future<V> schedule(BackgroundTask<V> task, long delay, TimeUnit unit) { return scheduledExecutor.schedule(() -> getJavaFXTask(task).get(), delay, unit); }
Source:
<code>public double kPercentileLatencyAsDouble(double percentile) { <START> if (m_latencyHistogram.getTotalCount() == 0) return 0.0; <END> percentile = Math.max(0.0, percentile); return m_latencyHistogram.getValueAtPercentile(percentile * 100.0) / 1000.0; }</code><technical_language>please apply correct type literals</technical_language>

Target:
public double kPercentileLatencyAsDouble(double percentile) { if (m_latencyHistogram.getTotalCount() == 0) return 0.0; percentile = Math.max(0.0D, percentile); return m_latencyHistogram.getValueAtPercentile(percentile * 100.0D) / 1000.0; }
Source:
<code>public void write(Persistable persistable) { if (persistable.getID() != -1) { update(persistable.getID(), persistable); return; } SQLiteDatabase db = getDbOrThrow(); try { db.beginTransaction(); long insertedId; ByteArrayOutputStream bos = writeExternalizableToStream(persistable); try { if (blobFitsInDb(bos)) { ContentValues contentValues = helper.getNonDataContentValues(persistable); contentValues.put(DatabaseHelper.DATA_COL, bos.toByteArray()); insertedId = db.insertOrThrow(table, DatabaseHelper.DATA_COL, contentValues); } else { File dataFile = HybridFileBackedSqlHelpers.newFileForEntry(dbDir); ContentValues contentValues = helper.getNonDataContentValues(persistable); contentValues.put(DatabaseHelper.FILE_COL, dataFile.getAbsolutePath()); byte[] key = generateKeyAndAdd(contentValues); insertedId = db.insertOrThrow(table, DatabaseHelper.FILE_COL, contentValues); writeStreamToFile(bos, dataFile.getAbsolutePath(), key); } } finally { bos.close(); } persistable.setID((int)insertedId); if (insertedId > Integer.MAX_VALUE) { throw new RuntimeException("Waaaaaaaaaay too many values"); } db.setTransactionSuccessful(); } catch (IOException e) { <START> e.printStackTrace(); <END> } finally { db.endTransaction(); } }</code><technical_language>? This absolutely throw this exception, it</technical_language>

Target:
public void write(Persistable persistable) { if (persistable.getID() != -1) { update(persistable.getID(), persistable); return; } SQLiteDatabase db = getDbOrThrow(); try { long insertedId; ByteArrayOutputStream bos = writeExternalizableToStream(persistable); String dataFilePath = null; try { if (blobFitsInDb(bos)) { db.beginTransaction(); ContentValues contentValues = helper.getNonDataContentValues(persistable); contentValues.put(DatabaseHelper.DATA_COL, bos.toByteArray()); insertedId = db.insertOrThrow(table, DatabaseHelper.DATA_COL, contentValues); } else { dataFilePath = HybridFileBackedSqlHelpers.newFileForEntry(dbDir).getAbsolutePath(); HybridFileBackedSqlHelpers.setFileAsOrphan(db, dataFilePath); db.beginTransaction(); ContentValues contentValues = helper.getNonDataContentValues(persistable); contentValues.put(DatabaseHelper.FILE_COL, dataFilePath); byte[] key = generateKeyAndAdd(contentValues); insertedId = db.insertOrThrow(table, DatabaseHelper.FILE_COL, contentValues); writeStreamToFile(bos, dataFilePath, key); } } finally { bos.close(); } persistable.setID((int)insertedId); if (insertedId > Integer.MAX_VALUE) { throw new RuntimeException("Waaaaaaaaaay too many values"); } if (dataFilePath != null) { HybridFileBackedSqlHelpers.unsetFileAsOrphan(db, dataFilePath); } db.setTransactionSuccessful(); } catch (IOException e) { throw new RuntimeException(e); } finally { db.endTransaction(); } }
Source:
<code>public void mouseScrollWithKey(final int xPosition, final int yPosition, final int keyCode, final int zoomIncrement) { if (canvas instanceof SWTBotSiriusFigureCanvas) { ((SWTBotSiriusFigureCanvas) canvas).mouseScrollWithKey(xPosition, yPosition, keyCode, zoomIncrement); } else { throw new UnsupportedOperationException("This method is supported only by SWTBotSiriusFigureCanvas <START> canva and <END> not by " + canvas.getClass().getSimpleName()); } }</code><technical_language>canvas</technical_language>

Target:
public void mouseScrollWithKey(final int xPosition, final int yPosition, final int keyCode, final int zoomIncrement) { if (canvas instanceof SWTBotSiriusFigureCanvas) { ((SWTBotSiriusFigureCanvas) canvas).mouseScrollWithKey(xPosition, yPosition, keyCode, zoomIncrement); } else { throw new UnsupportedOperationException("This method is supported only by SWTBotSiriusFigureCanvas canvas and not by " + canvas.getClass().getSimpleName()); } }
Source:
<code>public void getMuleBinTest() { <START> assertThat("Mule bin path is not the expected", controller.getMuleBin(), equalTo("/home/mule/bin/mule")); <END> }</code><technical_language>equalTo("/home/mule/bin/mule") -> equalTo(MUE_HOME +"/bin/mule")</technical_language>

Target:
public void getMuleBinTest() { assertThat("Mule bin path is not the expected", controller.getMuleBin(), equalTo(MULE_HOME + "/bin/mule")); }
Source:
<code>private static Multimap<Cell, Value> getVersions() { Multimap<Cell, Value> versions = ArrayListMultimap.create(); <START> LongStream.range(1, CELL_VERSIONS + 1).boxed() <END> .forEach(timestamp -> versions.put(cell, Value.create(value, timestamp))); return versions; }</code><technical_language>nit: LongStream.rangeClosed(1, CELL_VERSIONS) a bit clearer</technical_language>

Target:
private static Multimap<Cell, Value> getVersions() { Multimap<Cell, Value> versions = ArrayListMultimap.create(); LongStream.rangeClosed(1, CELL_VERSIONS).boxed() .forEach(timestamp -> versions.put(cell, Value.create(value, timestamp))); return versions; }
Source:
<code>protected String getValue() { <START> return this.width + "|" + <END> this.height + "|" + this.screenX + "|" + this.screenY + "|" + this.isMaximized; }</code><technical_language>String.format</technical_language>

Target:
protected String getValue() { return String.format("%d|%d|%d|%d|%s", this.width, this.height, this.screenX, this.screenY, this.isMaximized); }
Source:
<code>public int hashCode() { <START> return isBigInteger() ? biValue.hashCode() : (int) longValue; <END> }</code><technical_language>Integer.MAX_VALUE + 1 Integer.MIN_VALUE return hash</technical_language>

Target:
public int hashCode() { int hash = 0; if(isBigInteger()) { hash = biValue.hashCode(); } else { hash = (int)((longValue >>> 32) * 31 + longValue & 0xFFFFFFFF); } return hash; }
Source:
<code>private String getTargetPath(String location) { <START> return getClass().getResource(File.separatorChar + location).toString().substring(5); <END> }</code><technical_language>add a check resource string starts "file:/"? guarding strange (and unlikely) build system changes end putting resources a JAR else silly</technical_language>

Target:
private String getTargetPath(String location) { String targetPath = getClass().getResource(File.separatorChar + location).toString(); if (targetPath.startsWith("file:/")) { return targetPath.substring(5); } return targetPath; }
Source:
<code>private ResultWithToken getTimestampsByCell( DbReadTable table, Iterable<byte[]> rows, ColumnSelection columns, long timestamp, long batchSize, boolean isReverse, Token token) { try (ClosableIterator<AgnosticLightResultRow> iterator = table .getAllRows(rows, columns, timestamp, false, DbReadTable.Order.fromBoolean(isReverse))) { ResultWithToken result = ResultWithToken.create(iterator); <START> result.moveForward(token); <END> result.getBatchOfTimestamps(batchSize); result.checkNextEntryAndCreateToken(); return result; } }</code><technical_language>ResultWithToken in this (calling create, moveForward, getBatchOfTimestamps, checkNextEntryAndCreateToken, in order), object sense done. enforce this temporal dependency moving other methods create, iterator, previous token, batch size</technical_language>

Target:
private TimestampsByCellResultWithToken getTimestampsByCell( DbReadTable table, Iterable<byte[]> rows, ColumnSelection columns, long timestamp, long batchSize, boolean isReverse, Token token) { try (ClosableIterator<AgnosticLightResultRow> iterator = table .getAllRows(rows, columns, timestamp, false, DbReadTable.Order.fromBoolean(isReverse))) { return TimestampsByCellResultWithToken.create(iterator, token, batchSize); } }
Source:
<code>public Subscriber<? super T> call(final Subscriber<? super T> subscriber) { return new Subscriber<T>(subscriber) { private int counter = 0; @Override public void onNext(T args) { boolean isSelected; try { isSelected = predicate.call(args, counter++); } catch (Throwable e) { subscriber.onError(e); return; } if (isSelected) { subscriber.onNext(args); } else { <START> subscriber.onCompleted(); <END> } } @Override public void onCompleted() { subscriber.onCompleted(); } @Override public void onError(Throwable e) { subscriber.onError(e); } }; }</code><technical_language>need unsubscribe too. In addition, I add a done flag (similar Take) event delivery is strictly stopped this operator</technical_language>

Target:
public Subscriber<? super T> call(final Subscriber<? super T> subscriber) { return new Subscriber<T>(subscriber) { private int counter = 0; @Override public void onNext(T args) { boolean isSelected; try { isSelected = predicate.call(args, counter++); } catch (Throwable e) { subscriber.onError(e); unsubscribe(); return; } if (isSelected) { subscriber.onNext(args); } else { subscriber.onCompleted(); unsubscribe(); } } @Override public void onCompleted() { subscriber.onCompleted(); } @Override public void onError(Throwable e) { subscriber.onError(e); } }; }
Source:
<code>public final <T> T visit(Visitor<T> visitor) { return visitor.apply(hosts().stream().map(CqlCapableServer::thriftServer).collect(Collectors.toSet()), <START> Optional.of(hosts().stream().map(CqlCapableServer::thriftServer).collect(Collectors.toSet()))); <END> }</code><technical_language>Similarly, this read cqlServer()? I helpful inline for this :)</technical_language>

Target:
public final <T> T visit(Visitor<T> visitor) { return visitor.apply( hosts().stream() .map(host -> new InetSocketAddress(host, thriftPort())) .collect(Collectors.toSet()), Optional.of(hosts().stream() .map(host -> new InetSocketAddress(host, cqlPort())) .collect(Collectors.toSet()))); }