auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public PasswordBasedEncryptionUtil build() throws GeneralSecurityException { if (picketBoxCompatibility && alphabet != Alphabet.PICKETBOX_COMPATIBILITY) { alphabet = Alphabet.PICKETBOX_COMPATIBILITY; usePadding = false; keyAlgorithm = DEFAULT_PICKETBOX_ALGORITHM; password = DEFAULT_PICKETBOX_INITIAL_KEY_MATERIAL.toCharArray(); } if (iteration <= -1) { throw log.iterationCountNotSpecified(); } if (salt == null) { throw log.saltNotSpecified(); } if (password == null || password.length == 0) { throw log.initialKeyNotSpecified(); } if (keyAlgorithm == null) { keyAlgorithm = DEFAULT_PBE_ALGORITHM; } if (transformation == null) { transformation = keyAlgorithm; } if (parametersAlgorithm == null) { parametersAlgorithm = keyAlgorithm; } if (cipherSalt == null) { cipherSalt = salt; } if (cipherIteration == -1) { cipherIteration = iteration; } if (ivSpec == null && encodedIV != null) { ByteIterator byteIterator = isBase64(alphabet) ? CodePointIterator.ofString(encodedIV).base64Decode(getAlphabet64(alphabet)) : CodePointIterator.ofString(encodedIV).base32Decode(getAlphabet32(alphabet)); ivSpec = new IvParameterSpec(byteIterator.drain()); } return new PasswordBasedEncryptionUtil(createAndInitCipher(deriveSecretKey()), algorithmParameters, alphabet, usePadding, picketBoxCompatibility); }

Target:
public PasswordBasedEncryptionUtil build() throws GeneralSecurityException { if (picketBoxCompatibility) { alphabet = Alphabet.PICKETBOX_COMPATIBILITY; usePadding = false; keyAlgorithm = DEFAULT_PICKETBOX_ALGORITHM; password = DEFAULT_PICKETBOX_INITIAL_KEY_MATERIAL.toCharArray(); } if (iteration <= -1) { throw log.iterationCountNotSpecified(); } if (salt == null) { throw log.saltNotSpecified(); } if (password == null || password.length == 0) { throw log.initialKeyNotSpecified(); } if (keyAlgorithm == null) { keyAlgorithm = DEFAULT_PBE_ALGORITHM; } if (transformation == null) { transformation = keyAlgorithm; } if (parametersAlgorithm == null) { parametersAlgorithm = keyAlgorithm; } if (cipherSalt == null) { cipherSalt = salt; } if (cipherIteration == -1) { cipherIteration = iteration; } if (ivSpec == null && encodedIV != null) { ByteIterator byteIterator = isBase64(alphabet) ? CodePointIterator.ofString(encodedIV).base64Decode(getAlphabet64(alphabet)) : CodePointIterator.ofString(encodedIV).base32Decode(getAlphabet32(alphabet)); ivSpec = new IvParameterSpec(byteIterator.drain()); } return new PasswordBasedEncryptionUtil(createAndInitCipher(deriveSecretKey()), algorithmParameters, alphabet, usePadding, picketBoxCompatibility); }
Source:
public GitHubSource(String organization, String project, HttpClient httpClient, GitHubLastUpdateCache gitHubLastUpdateCache) { this.httpClient = httpClient; this.projectUrl = String.format("<LINK_0>", organization, project); this.uniqueKey = organization + "@" + project; this.gson = new Gson(); this.cache = gitHubLastUpdateCache; }

Target:
public GitHubSource(String organization, String project, HttpClient httpClient, GitHubLastUpdateCache gitHubLastUpdateCache) { this.httpClient = httpClient; this.projectUrl = String.format("<LINK_0>", organization, project); this.uniqueKey = organization + "@" + project; this.cache = gitHubLastUpdateCache; }
Source:
private ILaunchConfiguration getRunningLaunchConfiguration( IProgressMonitor monitor) { final ILaunchConfiguration[] lc = new ILaunchConfiguration[1]; try { ModalContext.run(new IRunnableWithProgress() { public void run(IProgressMonitor m) throws InvocationTargetException, InterruptedException { Set<IProject> projects = new HashSet<IProject>(Arrays .asList(ProjectUtil.getProjects(repository))); ILaunchManager launchManager = DebugPlugin.getDefault() .getLaunchManager(); ILaunch[] launches = launchManager.getLaunches(); m.beginTask( UIText.BranchOperationUI_SearchLaunchConfiguration, launches.length); for (ILaunch launch : launches) { m.worked(1); if (launch.isTerminated()) continue; ISourceLocator locator = launch.getSourceLocator(); if (locator instanceof ISourceLookupDirector) { ISourceLookupDirector director = (ISourceLookupDirector) locator; ISourceContainer[] containers = director .getSourceContainers(); if (isAnyProjectInSourceContainers(containers, projects)) { lc[0] = launch.getLaunchConfiguration(); return; } } } } }, true, monitor, Display.getDefault()); } catch (@SuppressWarnings("unused") InvocationTargetException e) { } catch (@SuppressWarnings("unused") InterruptedException e) { } return lc[0]; }

Target:
private ILaunchConfiguration getRunningLaunchConfiguration( IProgressMonitor monitor) { final ILaunchConfiguration[] lc = new ILaunchConfiguration[1]; try { ModalContext.run(new IRunnableWithProgress() { public void run(IProgressMonitor m) throws InvocationTargetException, InterruptedException { Set<IProject> projects = new HashSet<IProject>(Arrays .asList(ProjectUtil.getProjects(repository))); ILaunchManager launchManager = DebugPlugin.getDefault() .getLaunchManager(); ILaunch[] launches = launchManager.getLaunches(); m.beginTask( UIText.BranchOperationUI_SearchLaunchConfiguration, launches.length); for (ILaunch launch : launches) { m.worked(1); if (launch.isTerminated()) continue; ISourceLocator locator = launch.getSourceLocator(); if (locator instanceof ISourceLookupDirector) { ISourceLookupDirector director = (ISourceLookupDirector) locator; ISourceContainer[] containers = director .getSourceContainers(); if (isAnyProjectInSourceContainers(containers, projects)) { lc[0] = launch.getLaunchConfiguration(); return; } } } } }, true, monitor, Display.getDefault()); } catch (InvocationTargetException e) { } catch (InterruptedException e) { } return lc[0]; }
Source:
private DateTimeFormatter getFormatter(){ switch (this){ case days: return DateTimeFormat.forPattern("yyyy-MM-dd"); case months: return DateTimeFormat.forPattern("yyyy/MM"); case weeks: return DateTimeFormat.forPattern("yyyy/ww"); case years: return DateTimeFormat.forPattern("yyyy"); case quarters: return DateTimeFormat.forPattern("yyyy"); case simpleSum: break; } return null; }

Target:
private DateTimeFormatter getFormatter(){ switch (this){ case days: return DateTimeFormat.forPattern("yyyy-MM-dd"); case months: return DateTimeFormat.forPattern("yyyy/MM"); case weeks: return DateTimeFormat.forPattern("yyyy/ww"); case years: return DateTimeFormat.forPattern("yyyy"); case quarters: return DateTimeFormat.forPattern("yyyy"); } return null; }
Source:
private boolean connectHostToPool() { setStoragePool(null); final Guid masterDomainIdFromDb = getMasterDomainIdFromDb(); final VDS vds = getVds(); final storage_pool storagePool = getStoragePool(); EventResult result = ((EventQueue) EjbUtils.findBean(BeanType.EVENTQUEUE_MANAGER, BeanProxyType.LOCAL)).submitEventSync(new Event(storagePool.getId(), masterDomainIdFromDb, vds.getId(), EventType.VDSCONNECTTOPOOL), new Callable<EventResult>() { @Override public EventResult call() { return runConnectHostToPoolEvent(masterDomainIdFromDb, vds, storagePool); } }); if (result != null) { return result.isSuccess(); } return false; }

Target:
private boolean connectHostToPool() { final VDS vds = getVds(); EventResult result = ((EventQueue) EjbUtils.findBean(BeanType.EVENTQUEUE_MANAGER, BeanProxyType.LOCAL)).submitEventSync(new Event(getStoragePool().getId(), null, vds.getId(), EventType.VDSCONNECTTOPOOL), new Callable<EventResult>() { @Override public EventResult call() { return runConnectHostToPoolEvent(getStoragePool().getId(), vds); } }); if (result != null) { return result.isSuccess(); } return false; }
Source:
private List<IBuildPlan> getPlans(Object parent, List<IBuildPlan> plans) { List<IBuildPlan> children = new ArrayList<IBuildPlan>(plans.size()); for (IBuildPlan plan : plans) { if (isSelectedOnly() && !plan.isSelected()) { continue; } if (isNestPlansEnabled() && plan.getParent() != null && plan.getParent() != parent) { continue; } plan.getChildren().forEach(child -> { IBuildPlan childParent = child.getParent(); child.setServer(childParent.getServer()); IBuild childParentBuild = childParent.getLastBuild(); if (childParentBuild != null) { child.setLastBuild(childParentBuild); } child.setSelected(child.getParent().isSelected()); }); children.add(plan); } return children; }

Target:
private List<IBuildPlan> getPlans(Object parent, List<IBuildPlan> plans) { List<IBuildPlan> children = new ArrayList<IBuildPlan>(plans.size()); for (IBuildPlan plan : plans) { if (isSelectedOnly() && !plan.isSelected()) { continue; } if (isNestPlansEnabled() && plan.getParent() != null && plan.getParent() != parent) { continue; } children.add(plan); } return children; }
Source:
public static Fragment get(final Type type, final Bundle data) { switch (type) { case ACCOUNT_PROFILE: return AccountProfileFragment.newInstance(data); case BATTLE_FEED: return BattleFeedFragment.newInstance(data); case PLATOON_PROFILE: return PlatoonProfileFragment.newInstance(data); case SOLDIER_OVERVIEW: return SoldierOverviewFragment.newInstance(data); case SOLDIER_STATS: return SoldierStatsFragment.newInstance(data); case WEAPON_STATS: return WeaponStatsFragment.newInstance(); case NEWS_LISTING: return NewsListingFragment.newInstance(data); case NEWS_ITEM: return NewsArticleFragment.newInstance(data); case BATTLE_FEED_POSTING: return BattleFeedPostingFragment.newInstance(data); case FORUM_LISTING: return ForumListingFragment.newInstance(data); case THREAD_LISTING: return ThreadListingFragment.newInstance(data); case THREAD_CREATING: return ThreadCreationFragment.newInstance(data); case POST_LISTING: return PostListingFragment.newInstance(data); case POST_CREATING: return PostCreationFragment.newInstance(data); case NOTIFICATION: return NotificationFragment.newInstance(data); case BATTLE_REPORT: return BattleReportFragment.newInstance(data); case BATTLE_REPORT_LISTING: return BattleReportListingFragment.newInstance(data); default: throw new TypeNotPresentException("" + type, null); } }

Target:
public static Fragment get(final Type type, final Bundle data) { switch (type) { case ACCOUNT_PROFILE: return AccountProfileFragment.newInstance(data); case BATTLE_FEED: return BattleFeedFragment.newInstance(data); case PLATOON_PROFILE: return PlatoonProfileFragment.newInstance(data); case SOLDIER_OVERVIEW: return SoldierOverviewFragment.newInstance(data); case SOLDIER_STATS: return SoldierStatsFragment.newInstance(data); case WEAPON_STATS: return WeaponStatsFragment.newInstance(data); case NEWS_LISTING: return NewsListingFragment.newInstance(data); case NEWS_ITEM: return NewsArticleFragment.newInstance(data); case BATTLE_FEED_POSTING: return BattleFeedPostingFragment.newInstance(data); case FORUM_LISTING: return ForumListingFragment.newInstance(data); case THREAD_LISTING: return ThreadListingFragment.newInstance(data); case THREAD_CREATING: return ThreadCreationFragment.newInstance(data); case POST_LISTING: return PostListingFragment.newInstance(data); case POST_CREATING: return PostCreationFragment.newInstance(data); case NOTIFICATION: return NotificationFragment.newInstance(data); case BATTLE_REPORT: return BattleReportFragment.newInstance(data); case BATTLE_REPORT_LISTING: return BattleReportListingFragment.newInstance(data); default: throw new TypeNotPresentException("" + type, null); } }
Source:
public static String extractDisplayNameFromGenerated(String generatedDisplayName) { if (generatedDisplayName.matches("^.*(" + ITERATIONS_SAMPLES + "|Latency, sec|" + SUCCESS_RATE + ").*")) { return removePattern(generatedDisplayName, " (Latency, sec|" + ITERATIONS_SAMPLES + "|" + SUCCESS_RATE + ") \\[.*\\]"); } return null; }

Target:
public static String extractDisplayNameFromGenerated(String generatedDisplayName) { if (generatedDisplayName.matches(DISPLAY_NAME_REGEXP)) { return removePattern(generatedDisplayName, " (" + LATENCY_SEC + "|" + ITERATIONS_SAMPLES + "|" + SUCCESS_RATE + ") \\[.*\\]"); } log.warn("Generated display name '{}' doesn't match regexp '{}'. Will return null.", generatedDisplayName, DISPLAY_NAME_REGEXP); return null; }
Source:
public void testGobbleStream() throws Exception { byte[] bytes = new byte[] {'a','b','c'}; InputStream stream = new ByteArrayInputStream(bytes); ByteArrayOutputStream out = new ByteArrayOutputStream(); StreamGobbler gobbler = new StreamGobbler(stream, out, null); gobbler.start(); try { gobbler.join(1000*1000); assertFalse(gobbler.isAlive()); assertEquals(new String(out.toByteArray()), "abc" + NL); } finally { gobbler.close(); gobbler.interrupt(); } }

Target:
public void testGobbleStream() throws Exception { byte[] bytes = new byte[] {'a','b','c'}; InputStream stream = new ByteArrayInputStream(bytes); ByteArrayOutputStream out = new ByteArrayOutputStream(); StreamGobbler gobbler = new StreamGobbler(stream, out, null); gobbler.start(); try { gobbler.join(10*1000); assertFalse(gobbler.isAlive()); assertEquals(new String(out.toByteArray()), "abc" + NL); } finally { gobbler.close(); gobbler.interrupt(); } }
Source:
public PlanWithProperties visitSort(SortNode node, Context context) { PlanWithProperties child = planChild(node, context.withPreferredProperties(PreferredProperties.undistributed())); if (child.getProperties().isSingleNode()) { List<LocalProperty<Symbol>> desiredProperties = new ArrayList<>(); for (Symbol symbol : node.getOrderingScheme().getOrderBy()) { desiredProperties.add(new SortingProperty<>(symbol, node.getOrderingScheme().getOrdering(symbol))); } if (LocalProperties.match(child.getProperties().getLocalProperties(), desiredProperties).stream() .noneMatch(Optional::isPresent)) { return child; } } if (isDistributedSortEnabled(session)) { PlanNode source = child.getNode(); if (isRedistributeSort(session)) { source = roundRobinExchange(idAllocator.getNextId(), REMOTE, source); } return withDerivedProperties( mergingExchange( idAllocator.getNextId(), REMOTE, new SortNode( idAllocator.getNextId(), source, node.getOrderingScheme()), node.getOrderingScheme()), child.getProperties()); } if (!child.getProperties().isSingleNode()) { child = withDerivedProperties( gatheringExchange(idAllocator.getNextId(), REMOTE, child.getNode()), child.getProperties()); } return rebaseAndDeriveProperties(node, child); }

Target:
public PlanWithProperties visitSort(SortNode node, Context context) { PlanWithProperties child = planChild(node, context.withPreferredProperties(PreferredProperties.undistributed())); if (child.getProperties().isSingleNode()) { List<LocalProperty<Symbol>> desiredProperties = new ArrayList<>(); for (Symbol symbol : node.getOrderingScheme().getOrderBy()) { desiredProperties.add(new SortingProperty<>(symbol, node.getOrderingScheme().getOrdering(symbol))); } if (LocalProperties.match(child.getProperties().getLocalProperties(), desiredProperties).stream() .noneMatch(Optional::isPresent)) { return child; } } if (isDistributedSortEnabled(session)) { child = planChild(node, context.withPreferredProperties(PreferredProperties.any())); PlanNode source = child.getNode(); if (isRedistributeSort(session)) { source = roundRobinExchange(idAllocator.getNextId(), REMOTE, source); } return withDerivedProperties( mergingExchange( idAllocator.getNextId(), REMOTE, new SortNode( idAllocator.getNextId(), source, node.getOrderingScheme()), node.getOrderingScheme()), child.getProperties()); } if (!child.getProperties().isSingleNode()) { child = withDerivedProperties( gatheringExchange(idAllocator.getNextId(), REMOTE, child.getNode()), child.getProperties()); } return rebaseAndDeriveProperties(node, child); }
Source:
public void setUp() throws Exception { URL resource = getClass().getResource("/projects/defaultSpringProjectWithDifferentTypeOfFiles"); blankWorkspace = testWorkspaceProvider.createWorkspace(defaultTestUser, 2, DEFAULT); javaWorkspace = testWorkspaceProvider.createWorkspace(defaultTestUser, 3, UBUNTU_JDK8); blankWorkspace.await(); javaWorkspace.await(); testProjectServiceClient.importProject( javaWorkspace.getId(), Paths.get(resource.toURI()), "web-java-spring", MAVEN_SPRING); expectedBlankItem = new Workspaces.WorkspaceListItem( defaultTestUser.getName(), blankWorkspace.getName(), BLANK_WS_MB, BLANK_WS_PROJECTS_COUNT); expectedJavaItem = new Workspaces.WorkspaceListItem( defaultTestUser.getName(), javaWorkspace.getName(), JAVA_WS_MB, JAVA_WS_PROJECTS_COUNT); expectedNewestWorkspaceItem = new Workspaces.WorkspaceListItem( defaultTestUser.getName(), NEWEST_CREATED_WORKSPACE_NAME, BLANK_WS_MB, BLANK_WS_PROJECTS_COUNT); dashboard.open(); }

Target:
public void setUp() throws Exception { URL resource = getClass().getResource("/projects/defaultSpringProjectWithDifferentTypeOfFiles"); testProjectServiceClient.importProject( javaWorkspace.getId(), Paths.get(resource.toURI()), "web-java-spring", MAVEN_SPRING); expectedBlankItem = new Workspaces.WorkspaceListItem( defaultTestUser.getName(), blankWorkspace.getName(), BLANK_WS_MB, BLANK_WS_PROJECTS_COUNT); expectedJavaItem = new Workspaces.WorkspaceListItem( defaultTestUser.getName(), javaWorkspace.getName(), JAVA_WS_MB, JAVA_WS_PROJECTS_COUNT); expectedNewestWorkspaceItem = new Workspaces.WorkspaceListItem( defaultTestUser.getName(), NEWEST_CREATED_WORKSPACE_NAME, BLANK_WS_MB, BLANK_WS_PROJECTS_COUNT); dashboard.open(); }
Source:
public Map<String, Serializable> getParameters(String key) { StorageEntry entry = getStorageEntry(key); if (entry == null) { return null; } Map<String, Serializable> res = new LinkedHashMap<>(entry.getParams()); if (log.isDebugEnabled()) { log.debug(String.format("Fetched parameters from StorageEntry stored at key %s: %s", key, res)); } return res; }

Target:
public Map<String, Serializable> getParameters(String key) { StorageEntry entry = getStorageEntry(key); if (entry == null) { return null; } Map<String, Serializable> res = new HashMap<>(entry.getParams()); if (log.isDebugEnabled()) { log.debug(String.format("Fetched parameters from StorageEntry stored at key %s: %s", key, res)); } return res; }
Source:
private StopReplicaRequest(StopReplicaRequestData data, short version) { super(ApiKeys.STOP_REPLICA, version, data.controllerId(), data.controllerEpoch(), data.brokerEpoch()); this.data = data; Stream<TopicPartition> partitionStream; if (version == 0) { partitionStream = data.partitionsV0().stream() .map(tp -> new TopicPartition(tp.topicName(), tp.partitionIndex())); } else { partitionStream = data.topics().stream().flatMap(topic -> topic.partitionIndexes().stream().map(partitionIndex -> new TopicPartition(topic.name(), partitionIndex)) ); } topicPartitions = Collections.unmodifiableList(partitionStream.collect(Collectors.toList())); }

Target:
private StopReplicaRequest(StopReplicaRequestData data, short version) { super(ApiKeys.STOP_REPLICA, version); this.data = data; }
Source:
public void handle(ResourcePackRequest resourcePackRequest) throws Exception { ResourcePackRequestEvent requestEvent = new ResourcePackRequestEvent( con, resourcePackRequest.getHash(), resourcePackRequest.getUrl() ); if ( con.getResourcePackHash() != null && resourcePackRequest.getHash().equals( con.getResourcePackHash() ) ) { requestEvent.setCancelled( true ); } if ( bungee.getPluginManager().callEvent( requestEvent ).isCancelled() ) { throw CancelSendSignal.INSTANCE; } else { con.setRequestedResourcePackHash( resourcePackRequest.getHash() ); } }

Target:
public void handle(ResourcePackRequest resourcePackRequest) throws Exception { ResourcePackRequestEvent requestEvent = new ResourcePackRequestEvent( con, con.getServer(), con, resourcePackRequest.getHash(), resourcePackRequest.getUrl() ); if ( con.getResourcePackHash() != null && resourcePackRequest.getHash().equals( con.getResourcePackHash() ) ) { requestEvent.setCancelled( true ); } if ( bungee.getPluginManager().callEvent( requestEvent ).isCancelled() ) { throw CancelSendSignal.INSTANCE; } con.setRequestedResourcePackHash( resourcePackRequest.getHash() ); }
Source:
public TableAsyncBatch createBatch(String partitionKey) { if (partitionKey == null || partitionKey.isEmpty()) { throw logger.logExceptionAsError( new IllegalArgumentException("The partition key must not be null or empty.")); } return new TableAsyncBatch(partitionKey, this); }

Target:
public TableAsyncBatch createBatch(String partitionKey) { if (CoreUtils.isNullOrEmpty(partitionKey)) { throw logger.logExceptionAsError( new IllegalArgumentException("The partition key must not be null or empty.")); } return new TableAsyncBatch(partitionKey, this); }
Source:
private CharSequence getDatabaseContents(Content source, AbstractReader reader) { try { Map<String, String> tables = reader.getTableSchemas(); Collection<String> databaseStorage = new LinkedList<>(); Integer charactersCopied = loadDatabaseIntoCollection(databaseStorage, tables, reader, source); return toCharSequence(databaseStorage, charactersCopied); } catch (AbstractReader.FileReaderException ex) { logger.log(Level.WARNING, String.format( "Error attempting to get tables from file: " + "[%s] (id=%d).", source.getName(), source.getId()), ex); } return EMPTY_CHARACTER_SEQUENCE; }

Target:
private CharSequence getDatabaseContents(Content source, AbstractReader reader) throws FileReaderException { Collection<String> databaseStorage = new LinkedList<>(); Integer charactersCopied = loadDatabaseIntoCollection(databaseStorage, reader, source); return toCharSequence(databaseStorage, charactersCopied); }
Source:
public BasicLabelStyleDescription createBasicLabelStyleDescription() { BasicLabelStyleDescriptionImpl basicLabelStyleDescription = new BasicLabelStyleDescriptionImpl(); return basicLabelStyleDescription; }

Target:
public BasicLabelStyleDescription createBasicLabelStyleDescription() { BasicLabelStyleDescriptionImpl basicLabelStyleDescription = new BasicLabelStyleDescriptionImpl(); new DefaultColorStyleDescription().setDefaultColors(basicLabelStyleDescription); return basicLabelStyleDescription; }
Source:
public void clearPartition(boolean onShutdown, boolean onStorageDestroy) { clearOtherResourcesThanStorage(onStorageDestroy); if (onShutdown) { if (hasPooledMemoryAllocator()) { destroyStorage(true, true); } else { clearAndDestroyStorage(true, true); } } else { if (onStorageDestroy) { clearAndDestroyStorage(false, false); } else { clearStorage(false); } } }

Target:
public void clearPartition(boolean onShutdown, boolean onStorageDestroy) { clearLockStore(); clearOtherDataThanStorage(onStorageDestroy); if (onShutdown) { if (hasPooledMemoryAllocator()) { destroyStorageImmediate(true, true); } else { destroyStorageAfterClear(true, true); } } else { if (onStorageDestroy) { destroyStorageAfterClear(false, false); } else { clearStorage(false); } } }
Source:
public void initializeUnityAds(Context context, String gameId, IUnityAdsInitializationListener initializationListener) { if (!UnityAds.isSupported()) { String errorMessage = "Unity Ads cannot be initialized: current device is not supported."; initializationListener.onInitializationFailed(UnityAds.UnityAdsInitializationError.INTERNAL_ERROR, errorMessage); } if (UnityAds.isInitialized()) { initializationListener.onInitializationComplete(); } MediationMetaData mediationMetaData = new MediationMetaData(context); mediationMetaData.setName("AdMob"); mediationMetaData.setVersion(BuildConfig.VERSION_NAME); mediationMetaData.set("adapter_version", UnityAds.getVersion()); mediationMetaData.commit(); UnityAds.initialize(context, gameId, false, true, initializationListener); }

Target:
public void initializeUnityAds(Context context, String gameId, IUnityAdsInitializationListener initializationListener) { if (UnityAds.isInitialized()) { initializationListener.onInitializationComplete(); return; } MediationMetaData mediationMetaData = new MediationMetaData(context); mediationMetaData.setName("AdMob"); mediationMetaData.setVersion(BuildConfig.VERSION_NAME); mediationMetaData.set("adapter_version", UnityAds.getVersion()); mediationMetaData.commit(); UnityAds.initialize(context, gameId, false, true, initializationListener); }
Source:
public Binder build(Annotation annotation) { return new Binder<BindMap, Object>() { @Override public void bind(SQLStatement q, BindMap bind, Object arg) { final String prefix; if (BindBean.BARE_BINDING.equals(bind.prefix())) { prefix = ""; } else { prefix = bind.prefix() + "."; } final Set<String> allowedKeys = new HashSet<String>(Arrays.asList(bind.value())); final Map<String, Object> map = (Map<String, Object>) arg; try { for (Entry e : map.entrySet()) { final Object keyObj = e.getKey(); final String key; if (bind.implicitKeyStringConversion() || (keyObj instanceof String)) { key = keyObj.toString(); } else { throw new IllegalArgumentException("Key " + keyObj + " (of " + keyObj.getClass() + ") must be a String"); } if (allowedKeys.isEmpty() || allowedKeys.remove(key)) { q.bind(prefix + key, e.getValue()); } } for (String key : allowedKeys) { final Object val = map.get(key); if (val != null) { throw new IllegalStateException("Internal error: map iteration missed key " + key); } q.bind(prefix + key, val); } } catch (Exception e) { throw new IllegalStateException("Unable to bind map properties", e); } } }; }

Target:
public Binder build(Annotation annotation) { return new Binder<BindMap, Object>() { @SuppressWarnings("unchecked") @Override public void bind(SQLStatement q, BindMap bind, Object arg) { final String prefix; if (BindBean.BARE_BINDING.equals(bind.prefix())) { prefix = ""; } else { prefix = bind.prefix() + "."; } final Set<String> allowedKeys = new HashSet<String>(Arrays.asList(bind.value())); final Map<String, Object> map = (Map<String, Object>) arg; for (Entry e : map.entrySet()) { final Object keyObj = e.getKey(); final String key; if (bind.implicitKeyStringConversion() || (keyObj instanceof String)) { key = keyObj.toString(); } else { throw new IllegalArgumentException("Key " + keyObj + " (of " + keyObj.getClass() + ") must be a String"); } if (allowedKeys.isEmpty() || allowedKeys.remove(key)) { q.bind(prefix + key, e.getValue()); } } for (String key : allowedKeys) { final Object val = map.get(key); if (val != null) { throw new IllegalStateException("Internal error: map iteration missed key " + key); } q.bind(prefix + key, (Object) null); } } }; }
Source:
public int getIconRes(Context context) { if (context instanceof MapActivity) { final OsmandApplication application = (OsmandApplication) (context).getApplicationContext(); final MapPoiTypes poiTypes = application.getPoiTypes(); final Map<String, PoiType> allTranslatedNames = poiTypes.getAllTranslatedNames(true); PoiCategory category = getCategory(allTranslatedNames); if (category != null) { category.getIconKeyName(); String res = category.getIconKeyName(); if (res instanceof String && RenderingIcons.containsBigIcon(res)) { return RenderingIcons.getBigIconResourceId(res); } else { return super.getIconRes(); } } } return super.getIconRes(); }

Target:
public int getIconRes(Context context) { PoiCategory category = getCategory(getAllTranslatedNames(context)); if (category != null) { category.getIconKeyName(); String res = category.getIconKeyName(); if (res != null && RenderingIcons.containsBigIcon(res)) { return RenderingIcons.getBigIconResourceId(res); } } return super.getIconRes(); }
Source:
protected WorkDefinitionMatch getWorkDefinitionForPeerToPeerReview(IAtsPeerToPeerReview review) throws OseeCoreException { Conditions.notNull(review); WorkDefinitionMatch match = getWorkDefinitionFromArtifactsAttributeValue(review); if (!match.isMatched()) { match = getDefaultPeerToPeerWorkflowDefinitionMatch(); } return match; }

Target:
protected WorkDefinitionMatch getWorkDefinitionForPeerToPeerReview(IAtsPeerToPeerReview review) throws OseeCoreException { Conditions.notNull(review, getClass().getSimpleName()); WorkDefinitionMatch match = getWorkDefinitionFromArtifactsAttributeValue(review); if (!match.isMatched()) { match = getDefaultPeerToPeerWorkflowDefinitionMatch(); } return match; }
Source:
public synchronized int read() throws IOException { if (ensureBytes(1)) { return buffer[index++] & 0xFF; } return -1; }

Target:
public int read() throws IOException { if (ensureBytes(1)) { return buffer[index++] & 0xFF; } return -1; }
Source:
private byte[] getFileAsByteArray (File tarFile, String fileName) { byte[] data = null; LOG.info("Getting file " + fileName + " from " + tarFile); try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(tarFile)); TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(bis)) { TarArchiveEntry tarArchiveEntry = tarArchiveInputStream.getNextTarEntry(); while (tarArchiveEntry != null) { if (tarArchiveEntry.getName().equals(fileName)) { data = IOUtils.toByteArray(tarArchiveInputStream); break; } tarArchiveEntry = tarArchiveInputStream.getNextTarEntry(); } } catch (IOException e) { LOG.warn("Exception occured while getting file: " + fileName + " from " + tarFile, e); } return data; }

Target:
private byte[] getFileAsByteArray (File tarFile, String fileName) { byte[] data = null; LOG.info("Getting file from {}", fileName, tarFile); try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(tarFile)); TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(bis)) { TarArchiveEntry tarArchiveEntry = tarArchiveInputStream.getNextTarEntry(); while (tarArchiveEntry != null) { if (tarArchiveEntry.getName().equals(fileName)) { data = IOUtils.toByteArray(tarArchiveInputStream); break; } tarArchiveEntry = tarArchiveInputStream.getNextTarEntry(); } } catch (IOException e) { LOG.warn("Exception occured while getting file: " + fileName + " from " + tarFile, e); } return data; }
Source:
public List<ServiceExtension> getServiceExtensions() { if (this.serviceExtensions == null) { this.serviceExtensions = new ArrayList<ServiceExtension>(); for (ServiceExtension serviceExtension : ServicesExtensionPoint.getDefault().getServiceExtensions()) { if (serviceExtension.getServiceTypeId().equals(this.id)) { this.serviceExtensions.add(serviceExtension); } } } Collections.sort(this.serviceExtensions, new Comparator<ServiceExtension>() { @Override public int compare(ServiceExtension o1, ServiceExtension o2) { return o2.getPriority() - o1.getPriority(); } }); return this.serviceExtensions; }

Target:
public List<ServiceExtension> getServiceExtensions() { if (this.serviceExtensions == null) { this.serviceExtensions = new ArrayList<ServiceExtension>(); for (ServiceExtension serviceExtension : ServicesExtensionPoint.getDefault().getServiceExtensions()) { if (serviceExtension.getServiceTypeId().equals(this.id)) { this.serviceExtensions.add(serviceExtension); } } } Collections.sort(this.serviceExtensions, new Comparator<ServiceExtension>() { @Override public int compare(ServiceExtension o1, ServiceExtension o2) { return Integer.compare(o2.getPriority(), o1.getPriority()); } }); return this.serviceExtensions; }
Source:
public void testCustomSignerOverride() throws AssertionError { LOG.debug("Inside createConfiguration..."); assertTrue(assertIsCustomSignerLoaded()); }

Target:
public void testCustomSignerOverride() throws AssertionError { assertIsCustomSignerLoaded(); }
Source:
public void shouldCreateVisitWithRequiredGivenParameters() { Patient patient = new Patient(); patient.setUuid("10"); DateTime startDateTime = new DateTime("2010-01-10T07:22:05Z"); DateTime endDateTime = new DateTime("2012-08-01T07:22:05Z"); Visit visit = new Visit(startDateTime.toDate(), endDateTime.toDate(), patient, new VisitType("testVisitType")); doReturn(patient).when(patientService).getPatientByUuid(eq(CONFIG_NAME), eq(patient.getUuid())); openMRSActionProxyService.createVisit(CONFIG_NAME, patient.getUuid(), new DateTime(visit.getStartDatetime()), new DateTime(visit.getEndDatetime()), visit.getVisitType().getDisplay(), null); verify(visitService).createVisit(eq(CONFIG_NAME), visitCaptor.capture()); assertEquals(visit, visitCaptor.getValue()); }

Target:
public void shouldCreateVisitWithRequiredGivenParameters() { Patient patient = new Patient(); patient.setUuid("10"); DateTime startDateTime = new DateTime("2010-01-10T07:22:05Z"); DateTime endDateTime = new DateTime("2012-08-01T07:22:05Z"); Visit visit = new Visit(startDateTime.toDate(), endDateTime.toDate(), patient, new VisitType("ee1b6117-e40b-4082-8880-96aca7ea1472")); doReturn(patient).when(patientService).getPatientByUuid(eq(CONFIG_NAME), eq(patient.getUuid())); openMRSActionProxyService.createVisit(CONFIG_NAME, patient.getUuid(), new DateTime(visit.getStartDatetime()), new DateTime(visit.getStopDatetime()), visit.getVisitType().getUuid(), null); verify(visitService).createVisit(eq(CONFIG_NAME), visitCaptor.capture()); assertEquals(visit, visitCaptor.getValue()); }
Source:
public void testNumConnectionsMetricHttp() throws Exception { String text = "hello"; ByteArrayOutputStream out = new ByteArrayOutputStream(); try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(out)) { gzipOutputStream.write(text.getBytes(Charset.defaultCharset())); } Request request = new Request(HttpMethod.POST, new URL("http://localhost:" + port + "/slow/hello")); request.setHeader("Content-Encoding", "gzip"); request.setContent(MediaType.TEXT_PLAIN, out.toByteArray()); JettyServerModule jsm = inj.getInstance(JettyServerModule.class); Assert.assertEquals(0, jsm.getActiveConnections()); ListenableFuture<InputStream> go = client.go( request, new InputStreamResponseHandler() ); Thread.sleep(100); Assert.assertEquals(1, jsm.getActiveConnections()); go.get(); Thread.sleep(1000); Assert.assertEquals(0, jsm.getActiveConnections()); }

Target:
public void testNumConnectionsMetricHttp() throws Exception { String text = "hello"; ByteArrayOutputStream out = new ByteArrayOutputStream(); try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(out)) { gzipOutputStream.write(text.getBytes(Charset.defaultCharset())); } Request request = new Request(HttpMethod.GET, new URL("http://localhost:" + port + "/latched/hello")); request.setHeader("Content-Encoding", "gzip"); request.setContent(MediaType.TEXT_PLAIN, out.toByteArray()); JettyServerModule jsm = injector.getInstance(JettyServerModule.class); latchedRequestState.reset(); Assert.assertEquals(0, jsm.getActiveConnections()); ListenableFuture<InputStream> go = client.go( request, new InputStreamResponseHandler() ); latchedRequestState.clientWaitForServerToStartRequest(); Assert.assertEquals(1, jsm.getActiveConnections()); latchedRequestState.clientReadyToFinishRequest(); go.get(); waitForJettyServerModuleActiveConnectionsZero(jsm); Assert.assertEquals(0, jsm.getActiveConnections()); }
Source:
public ImmutableRoaringBitmap getDocIds(long h3IndexId) { SoftReference<ImmutableRoaringBitmap>[] bitmapArrayReference = null; int dictId = _dictionary.indexOf(String.valueOf(h3IndexId)); if (dictId < 0) { return new MutableRoaringBitmap(); } if (_bitmaps != null) { bitmapArrayReference = _bitmaps.get(); if (bitmapArrayReference != null) { SoftReference<ImmutableRoaringBitmap> bitmapReference = bitmapArrayReference[dictId]; if (bitmapReference != null) { ImmutableRoaringBitmap value = bitmapReference.get(); if (value != null) { return value; } } } else { bitmapArrayReference = new SoftReference[_numBitmaps]; _bitmaps = new SoftReference<SoftReference<ImmutableRoaringBitmap>[]>(bitmapArrayReference); } } else { bitmapArrayReference = new SoftReference[_numBitmaps]; _bitmaps = new SoftReference<SoftReference<ImmutableRoaringBitmap>[]>(bitmapArrayReference); } synchronized (this) { ImmutableRoaringBitmap value; if (bitmapArrayReference[dictId] == null || bitmapArrayReference[dictId].get() == null) { value = buildRoaringBitmapForIndex(dictId); bitmapArrayReference[dictId] = new SoftReference<ImmutableRoaringBitmap>(value); } else { value = bitmapArrayReference[dictId].get(); } return value; } }

Target:
public ImmutableRoaringBitmap getDocIds(long h3IndexId) { SoftReference<ImmutableRoaringBitmap>[] bitmapArrayReference; int dictId = _dictionary.indexOf(String.valueOf(h3IndexId)); if (dictId < 0) { return new MutableRoaringBitmap(); } if (_bitmaps != null) { bitmapArrayReference = _bitmaps.get(); if (bitmapArrayReference != null) { SoftReference<ImmutableRoaringBitmap> bitmapReference = bitmapArrayReference[dictId]; if (bitmapReference != null) { ImmutableRoaringBitmap value = bitmapReference.get(); if (value != null) { return value; } } } else { bitmapArrayReference = new SoftReference[_numBitmaps]; _bitmaps = new SoftReference<>(bitmapArrayReference); } } else { bitmapArrayReference = new SoftReference[_numBitmaps]; _bitmaps = new SoftReference<>(bitmapArrayReference); } synchronized (this) { ImmutableRoaringBitmap value; if (bitmapArrayReference[dictId] == null || bitmapArrayReference[dictId].get() == null) { value = buildRoaringBitmapForIndex(dictId); bitmapArrayReference[dictId] = new SoftReference<>(value); } else { value = bitmapArrayReference[dictId].get(); } return value; } }
Source:
public String renderArticle(HttpServletRequest request, Model model, @SiteParam Site site, @RequestParam("id") String articleId) throws IOException, ParserConfigurationException, SAXException, XmlContentException { Map<?, ?> articleMetaData = addCommonModelAttributes(request, model, site, articleId); validateArticleVisibility(site, articleMetaData); requireNonemptyParameter(articleId); RenderContext renderContext = new RenderContext(site); renderContext.setArticleId(articleId); XmlContent xmlContent = getXmlContent(renderContext); model.addAttribute("references", xmlContent.references); model.addAttribute("article", articleMetaData); model.addAttribute("articleText", xmlContent.html); model.addAttribute("amendments", fillAmendments(site, articleMetaData)); return site + "/ftl/article/article"; }

Target:
public String renderArticle(HttpServletRequest request, Model model, @SiteParam Site site, @RequestParam("id") String articleId) throws IOException { Map<?, ?> articleMetaData = addCommonModelAttributes(request, model, site, articleId); validateArticleVisibility(site, articleMetaData); requireNonemptyParameter(articleId); RenderContext renderContext = new RenderContext(site); renderContext.setArticleId(articleId); XmlContent xmlContent = getXmlContent(renderContext); model.addAttribute("references", xmlContent.references); model.addAttribute("article", articleMetaData); model.addAttribute("articleText", xmlContent.html); model.addAttribute("amendments", fillAmendments(site, articleMetaData)); return site + "/ftl/article/article"; }
Source:
public DynamicArrayStore( File fileName, Config configuration, IdType idType, IdGeneratorFactory idGeneratorFactory, PageCache pageCache, LogProvider logProvider, int dataSizeFromConfiguration, RecordFormats recordFormats, OpenOption... openOptions ) { super( fileName, configuration, idType, idGeneratorFactory, pageCache, logProvider, TYPE_DESCRIPTOR, dataSizeFromConfiguration, recordFormats.dynamic(), recordFormats.storeVersion(), openOptions ); allowStorePointsAndTemporal = recordFormats.hasCapability( Capability.POINT_PROPERTIES ); }

Target:
public DynamicArrayStore( File fileName, Config configuration, IdType idType, IdGeneratorFactory idGeneratorFactory, PageCache pageCache, LogProvider logProvider, int dataSizeFromConfiguration, RecordFormats recordFormats, OpenOption... openOptions ) { super( fileName, configuration, idType, idGeneratorFactory, pageCache, logProvider, TYPE_DESCRIPTOR, dataSizeFromConfiguration, recordFormats.dynamic(), recordFormats.storeVersion(), openOptions ); allowStorePointsAndTemporal = recordFormats.hasCapability( Capability.POINT_PROPERTIES ) && recordFormats.hasCapability( Capability.TEMPORAL_PROPERTIES ); }
Source:
public boolean verifyEventIdentifier(AbstractPlaceEvent event) { boolean equals = Objects.equals(getEditorIdentifier(), event.getPlace().getIdentifier()); boolean equals1 = Objects.equals(editorPlaceRequest, event.getPlace()); return (equals && equals1); }

Target:
public boolean verifyEventIdentifier(AbstractPlaceEvent event) { return (Objects.equals(getEditorIdentifier(), event.getPlace().getIdentifier()) && Objects.equals(editorPlaceRequest, event.getPlace())); }
Source:
public int hashCode() { return fFieldName.hashCode(); }

Target:
public int hashCode() { return Objects.hash(fFieldName, fLabel); }
Source:
public void createOrUpdateObjectFromJson_primaryKey_isNull_updateFromJsonObject() throws JSONException { if (clazz.equals(PrimaryKeyAsString.class)) { realm.beginTransaction(); realm.createObject(clazz, null); realm.createOrUpdateObjectFromJson(clazz, new JSONObject(jsonString)); realm.commitTransaction(); RealmResults<PrimaryKeyAsString> results = realm.where(PrimaryKeyAsString.class).findAll(); assertEquals(1, results.size()); assertEquals(Long.valueOf(secondaryFieldValue).longValue(), results.first().getId()); assertEquals(null, results.first().getName()); } else { realm.beginTransaction(); realm.createObject(clazz, null); realm.createOrUpdateObjectFromJson(clazz, new JSONObject(jsonString)); realm.commitTransaction(); RealmResults results = realm.where(clazz).findAll(); assertEquals(1, results.size()); assertEquals(null, ((NullPrimaryKey)results.first()).getId()); assertEquals(secondaryFieldValue, ((NullPrimaryKey)results.first()).getName()); } }

Target:
public void createOrUpdateObjectFromJson_primaryKey_isNull_updateFromJsonObject() throws JSONException { realm.beginTransaction(); realm.createObject(clazz, null); realm.createOrUpdateObjectFromJson(clazz, new JSONObject(jsonString)); realm.commitTransaction(); if (clazz.equals(PrimaryKeyAsString.class)) { RealmResults<PrimaryKeyAsString> results = realm.where(PrimaryKeyAsString.class).findAll(); assertEquals(1, results.size()); assertEquals(Long.valueOf(secondaryFieldValue).longValue(), results.first().getId()); assertEquals(null, results.first().getName()); } else { RealmResults results = realm.where(clazz).findAll(); assertEquals(1, results.size()); assertEquals(null, ((NullPrimaryKey)results.first()).getId()); assertEquals(secondaryFieldValue, ((NullPrimaryKey)results.first()).getName()); } }
Source:
private List<String> getVdsIps(VDS vds) { List<String> vdsIps = new ArrayList<String>(); for (VdsNetworkInterface iface : getInterfaceDao().getAllInterfacesForVds(vds.getId())) { vdsIps.add(iface.getAddress()); } return vdsIps; }

Target:
private List<String> getVdsIps(VDS vds) { List<String> vdsIps = new ArrayList<String>(); for (VdsNetworkInterface iface : getInterfaceDao().getAllInterfacesForVds(vds.getId())) { if (iface.getAddress() != null) { vdsIps.add(iface.getAddress()); } } return vdsIps; }
Source:
public static Optional<Formatter> getFormatterForModifier(String modifier) { Objects.requireNonNull(modifier); switch (modifier) { case "lower": return Optional.of(new LowerCaseFormatter()); case "upper": return Optional.of(new UpperCaseFormatter()); case "capitalize": return Optional.of(new CapitalizeFormatter()); case "titlecase": return Optional.of(new TitleCaseFormatter()); case "sentencecase": return Optional.of(new SentenceCaseFormatter()); } if (modifier.startsWith(RegexFormatter.KEY)) { String regex = modifier.substring(RegexFormatter.KEY.length()); return Optional.of(new RegexFormatter(regex)); } else if (modifier.matches(TruncateFormatter.KEY + "\\d+")) { int truncateAfter = Integer.parseInt(modifier.substring(TruncateFormatter.KEY.length())); return Optional.of(new TruncateFormatter(truncateAfter)); } else { return getAll().stream().filter(f -> f.getKey().equals(modifier)).findAny(); } }

Target:
public static Optional<Formatter> getFormatterForModifier(String modifier) { Objects.requireNonNull(modifier); switch (modifier) { case "lower": return Optional.of(new LowerCaseFormatter()); case "upper": return Optional.of(new UpperCaseFormatter()); case "capitalize": return Optional.of(new CapitalizeFormatter()); case "titlecase": return Optional.of(new TitleCaseFormatter()); case "sentencecase": return Optional.of(new SentenceCaseFormatter()); } if (modifier.startsWith(RegexFormatter.KEY)) { String regex = modifier.substring(RegexFormatter.KEY.length()); return Optional.of(new RegexFormatter(regex)); } else if (TRUNCATE_PATTERN.matcher(modifier).matches()) { int truncateAfter = Integer.parseInt(modifier.substring(8)); return Optional.of(new TruncateFormatter(truncateAfter)); } else { return getAll().stream().filter(f -> f.getKey().equals(modifier)).findAny(); } }
Source:
@Test public void testCorrelateQuery() { final FrameworkConfig config = RelBuilderTest.config().build(); final RelBuilder builder = RelBuilder.create(config); final Holder<RexCorrelVariable> v = Holder.of(null); RelNode relNode = builder.scan("EMP") .variable(v) .scan("DEPT") .filter( builder.equals(builder.field(0), builder.field(v.get(), "DEPTNO"))) .correlate( JoinRelType.INNER, v.get().id, builder.field(2, 0, "DEPTNO")) .build(); RelJsonWriter jsonWriter = new RelJsonWriter(); relNode.explain(jsonWriter); final String relJson = jsonWriter.asString(); String s = deserializeAndDumpToTextFormat(getSchema(relNode), relJson, SqlExplainFormat.TEXT); final String expected = "" + "LogicalCorrelate(correlation=[$cor0], joinType=[inner], requiredColumns=[{7}])\n" + " LogicalTableScan(table=[[scott, EMP]])\n" + " LogicalFilter(condition=[=($0, $cor0.DEPTNO)])\n" + " LogicalTableScan(table=[[scott, DEPT]])\n"; assertThat(s, isLinux(expected)); }

Target:
@Test public void testCorrelateQuery() { final FrameworkConfig config = RelBuilderTest.config().build(); final RelBuilder builder = RelBuilder.create(config); final Holder<RexCorrelVariable> v = Holder.of(null); RelNode relNode = builder.scan("EMP") .variable(v) .scan("DEPT") .filter( builder.equals(builder.field(0), builder.field(v.get(), "DEPTNO"))) .correlate( JoinRelType.INNER, v.get().id, builder.field(2, 0, "DEPTNO")) .build(); RelJsonWriter jsonWriter = new RelJsonWriter(); relNode.explain(jsonWriter); final String relJson = jsonWriter.asString(); String s = deserializeAndDump(getSchema(relNode), relJson, SqlExplainFormat.TEXT); final String expected = "" + "LogicalCorrelate(correlation=[$cor0], joinType=[inner], requiredColumns=[{7}])\n" + " LogicalTableScan(table=[[scott, EMP]])\n" + " LogicalFilter(condition=[=($0, $cor0.DEPTNO)])\n" + " LogicalTableScan(table=[[scott, DEPT]])\n"; assertThat(s, isLinux(expected)); }
Source:
IndexTuningConfig computeTuningConfig(List<Pair<QueryableIndex, DataSegment>> queryableIndexAndSegments) { if (!hasPartitionConfig(tuningConfig)) { final double avgRowsPerByte = queryableIndexAndSegments .stream() .mapToDouble(queryableIndexAndDataSegment -> { final long numRows = queryableIndexAndDataSegment.lhs.getNumRows(); final long size = queryableIndexAndDataSegment.rhs.getSize(); return numRows / (double) size; }) .average() .orElseThrow(() -> new ISE("Cannot find targetPartitionSize because the input segment is empty")); final int targetPartitionSize = (int) Math.round(avgRowsPerByte * targetCompactionSizeBytes); Preconditions.checkState(targetPartitionSize > 0, "Negative targetPartitionSize[%s]", targetPartitionSize); log.info( "Estimated targetPartitionSize[%d] = avgRowsPerByte[%f] * targetCompactionSizeBytes[%d]", targetPartitionSize, avgRowsPerByte, targetCompactionSizeBytes ); return (tuningConfig == null ? IndexTuningConfig.createDefault() : tuningConfig) .withTargetPartitionSize(targetPartitionSize); } else { return tuningConfig; } }

Target:
IndexTuningConfig computeTuningConfig(List<Pair<QueryableIndex, DataSegment>> queryableIndexAndSegments) { if (!hasPartitionConfig(tuningConfig)) { final long nonNullTargetCompactionSizeBytes = Preconditions.checkNotNull( targetCompactionSizeBytes, "targetCompactionSizeBytes" ); final long totalNumRows = queryableIndexAndSegments .stream() .mapToLong(queryableIndexAndDataSegment -> queryableIndexAndDataSegment.lhs.getNumRows()) .sum(); final long totalSizeBytes = queryableIndexAndSegments .stream() .mapToLong(queryableIndexAndDataSegment -> queryableIndexAndDataSegment.rhs.getSize()) .sum(); if (totalSizeBytes == 0L) { throw new ISE("Total input segment size is 0 byte"); } final double avgRowsPerByte = totalNumRows / (double) totalSizeBytes; final int targetPartitionSize = Math.toIntExact(Math.round(avgRowsPerByte * nonNullTargetCompactionSizeBytes)); Preconditions.checkState(targetPartitionSize > 0, "Negative targetPartitionSize[%s]", targetPartitionSize); log.info( "Estimated targetPartitionSize[%d] = avgRowsPerByte[%f] * targetCompactionSizeBytes[%d]", targetPartitionSize, avgRowsPerByte, nonNullTargetCompactionSizeBytes ); return (tuningConfig == null ? IndexTuningConfig.createDefault() : tuningConfig) .withTargetPartitionSize(targetPartitionSize); } else { return tuningConfig; } }