auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void readEntityFromNBT(NBTTagCompound nbt) { super.readEntityFromNBT(nbt); if (nbt.hasKey("home")) { saveHome = true; int[] h = nbt.getIntArray("home"); home = new AxisAlignedBB(h[0], h[1], h[2], h[3], h[4], h[5]); if (nbt.hasKey("homeMovePrio")) { this.setMoveTowardsRestriction(nbt.getInteger("moveHomePrio"), true); } } if (nbt.hasKey("activeAction")) { entityActionHandler.resetAction(EntityActionManager.actionsByID.get(nbt.getInteger("activeAction"))); } }

Target:
public void readEntityFromNBT(NBTTagCompound nbt) { super.readEntityFromNBT(nbt); if (nbt.hasKey("home")) { saveHome = true; int[] h = nbt.getIntArray("home"); home = new AxisAlignedBB(h[0], h[1], h[2], h[3], h[4], h[5]); if (nbt.hasKey("homeMovePrio")) { this.setMoveTowardsRestriction(nbt.getInteger("moveHomePrio"), true); } } if (entityActionHandler != null) { entityActionHandler.readFromNBT(nbt); } }
Source:
public int hashCode() { if (isDisposed()) return 0; return this.getRed() ^ this.getBlue() ^ this.getGreen() ^ this.getAlpha(); }

Target:
public int hashCode() { if (isDisposed()) return 0; return (((alpha * 31) + this.getGreen()) * 31 + this.getBlue()) * 31 + this.getRed(); }
Source:
public static void deleteJobs() throws IOException { String projectID = "your-project-id"; String jobID = "your-job-id"; deleteJobs(projectID,jobID); }

Target:
public static void deleteJobs() throws IOException { String projectId = "your-project-id"; String jobId = "your-job-id"; deleteJobs(projectId,jobId); }
Source:
public int run(CommandLine cl) throws AlluxioException, IOException { mWorkingDirPath = getWorkingDirectory(cl); String confDirPath = mFsContext.getClusterConf().get(PropertyKey.CONF_DIR); File confDir = new File(confDirPath); List<File> allFiles = CommonUtils.recursiveListDir(confDir); for (File f : allFiles) { String relativePath = confDir.toURI().relativize(f.toURI()).getPath(); for (String prefix : EXCLUDED_FILES) { if (relativePath.startsWith(prefix)) { continue; } File targetFile = new File(mWorkingDirPath, relativePath); FileUtils.copyFile(f, targetFile, true); } } return 0; }

Target:
public int run(CommandLine cl) throws AlluxioException, IOException { mWorkingDirPath = getWorkingDirectory(cl); String confDirPath = mFsContext.getClusterConf().get(PropertyKey.CONF_DIR); File confDir = new File(confDirPath); List<File> allFiles = CommonUtils.recursiveListLocalDir(confDir); for (File f : allFiles) { String filename = f.getName(); String relativePath = confDir.toURI().relativize(f.toURI()).getPath(); if (EXCLUDED_FILE_PREFIXES.stream().anyMatch(filename::startsWith)) { continue; } File targetFile = new File(mWorkingDirPath, relativePath); FileUtils.copyFile(f, targetFile, true); } return 0; }
Source:
private void notifyListeners() { IndexDiffChangedListener[] tmpListeners; synchronized (listeners) { tmpListeners = listeners .toArray(new IndexDiffChangedListener[listeners.size()]); } for (int i = 0; i < tmpListeners.length; i++) { tmpListeners[i].indexDiffChanged(repository, indexDiffData); } }

Target:
private void notifyListeners() { IndexDiffChangedListener[] tmpListeners; synchronized (listeners) { tmpListeners = listeners .toArray(new IndexDiffChangedListener[listeners.size()]); } for (int i = 0; i < tmpListeners.length; i++) tmpListeners[i].indexDiffChanged(repository, indexDiffData); }
Source:
public void testDetectDeadlockOnUiThread() throws Exception { assertNotNull(Display.getCurrent()); TestSecureCredentialsStore store = createCredentialsStore(); store.put("key", "value", true); ILock lock = store.getLock(); assertNotNull(lock); try { assertTrue(lock.acquire(3000)); } catch (InterruptedException e) { fail("Interrupted trying to acquire SecurePreferencesRoot lock"); } try { try { store.get("key", null); fail("Expected exception"); } catch (RuntimeException e) { assertEquals("Possible deadlock detected accessing secure storage; aborting request", e.getMessage()); } try { store.put("key", "newValue", true); fail("Expected exception"); } catch (RuntimeException e) { assertEquals("Possible deadlock detected accessing secure storage; aborting request", e.getMessage()); } } finally { lock.release(); } assertEquals("value", store.get("key", null)); store.put("key", "newValue", true); assertEquals("newValue", store.get("key", null)); }

Target:
public void testDetectDeadlockOnUiThread() throws Exception { assertNotNull(Display.getCurrent()); TestSecureCredentialsStore store = createCredentialsStore(); store.put("key", "value", true); ILock lock = store.getLock(); assertNotNull(lock); try { assertTrue(lock.acquire(3000)); try { store.get("key", null); fail("Expected exception"); } catch (RuntimeException e) { assertEquals(DEADLOCK_ERROR_MESSAGE, e.getMessage()); } try { store.put("key", "newValue", true); fail("Expected exception"); } catch (RuntimeException e) { assertEquals(DEADLOCK_ERROR_MESSAGE, e.getMessage()); } } catch (InterruptedException e) { fail("Interrupted trying to acquire SecurePreferencesRoot lock"); } finally { lock.release(); } assertEquals("value", store.get("key", null)); store.put("key", "newValue", true); assertEquals("newValue", store.get("key", null)); }
Source:
CompactibleTimelineObjectHolderCursor( VersionedIntervalTimeline<String, DataSegment> timeline, List<Interval> totalIntervalsToSearch ) { this.holders = totalIntervalsToSearch .stream() .flatMap(interval -> timeline .lookup(interval) .stream() .filter(holder -> { final List<PartitionChunk<DataSegment>> chunks = Lists.newArrayList(holder.getObject().iterator()); final long partitionBytes = chunks.stream().mapToLong(chunk -> chunk.getObject().getSize()).sum(); return chunks.size() > 0 && partitionBytes > 0 && interval.contains(chunks.get(0).getObject().getInterval()); }) ) .collect(Collectors.toList()); }

Target:
CompactibleTimelineObjectHolderCursor( VersionedIntervalTimeline<String, DataSegment> timeline, List<Interval> totalIntervalsToSearch ) { this.holders = totalIntervalsToSearch .stream() .flatMap(interval -> timeline .lookup(interval) .stream() .filter(holder -> { final List<PartitionChunk<DataSegment>> chunks = Lists.newArrayList(holder.getObject().iterator()); final long partitionBytes = chunks.stream().mapToLong(chunk -> chunk.getObject().getSize()).sum(); return !chunks.isEmpty() && partitionBytes > 0 && interval.contains(chunks.get(0).getObject().getInterval()); }) ) .collect(Collectors.toList()); }
Source:
public String getTournament(Model model, HttpSession session) { if (session.getAttribute("member") == null) { return "redirect:denied"; } Member member = (Member) session.getAttribute("member"); if (member.getUserType() != Member.UserType.COORDINATOR) { return "redirect:denied"; } Set<Tournament> tournaments = member.getManagingTournament(); model.addAttribute("tournaments", tournaments); return "coordinator"; }

Target:
public String getTournament(Model model, HttpSession session) { if (session.getAttribute("member") == null) { return "redirect:/denied"; } Member member = (Member) session.getAttribute("member"); if (MemberUtils.atLeastCoordinator(member)) { return "redirect:/denied"; } Set<Tournament> tournaments = member.getManagingTournament(); model.addAttribute("tournaments", tournaments); return "coordinator"; }
Source:
private List<File> createDirs(String basePath, int numDirectories) { List<File> directories = new ArrayList<>(); for (int i = 0; i < numDirectories; i++) { String dirName = basePath + File.separator + pathFilterString + "_" + getRandomStringOfLen(5); File file = new File(dirName); file.mkdirs(); directories.add(file); } return directories; }

Target:
private List<File> createDirs(String basePath, int numDirectories) { List<File> directories = new ArrayList<>(); for (int i = 0; i < numDirectories; i++) { String dirName = basePath + File.separator + PATH_FILTER_MATCHED_PREFIX + "dir_" + i; File file = new File(dirName); file.mkdirs(); directories.add(file); } return directories; }
Source:
public boolean check() throws Exception { File fileCopy = File.createTempFile("modeshape-sequencer-epub", ".tmp"); IoUtil.write(in, new BufferedOutputStream(new FileOutputStream(fileCopy))); ZipInputStream zipStream = new ZipInputStream(new FileInputStream(fileCopy)); List<String> rootfiles = getRootfiles(zipStream); zipStream.close(); zipStream = new ZipInputStream(new FileInputStream(fileCopy)); if (!rootfiles.isEmpty()) { ZipEntry entry = null; while ((entry = zipStream.getNextEntry()) != null) { String entryName = entry.getName(); if (rootfiles.contains(entryName)) { checkRootfile(zipStream, entry); } } } else { throw new IllegalArgumentException("No rootfile package found in given EPUB file."); } zipStream.close(); boolean deleted = false; try { deleted = fileCopy.delete(); } catch (SecurityException e) { } if (!deleted) { fileCopy.deleteOnExit(); } return true; }

Target:
public boolean check() throws Exception { File fileCopy = File.createTempFile("modeshape-sequencer-epub", ".tmp"); IoUtil.write(in, new BufferedOutputStream(new FileOutputStream(fileCopy))); List<String> rootfiles = new ArrayList<>(); try (ZipInputStream zipStream = new ZipInputStream(new FileInputStream(fileCopy))) { rootfiles = getRootfiles(zipStream); } if (!rootfiles.isEmpty()) { try (ZipInputStream zipStream = new ZipInputStream(new FileInputStream(fileCopy))) { ZipEntry entry = null; while ((entry = zipStream.getNextEntry()) != null) { String entryName = entry.getName(); if (rootfiles.contains(entryName)) { checkRootfile(zipStream, entry); } } } } else { throw new IllegalArgumentException("No rootfile package found in given EPUB file."); } boolean deleted = false; try { deleted = fileCopy.delete(); } catch (SecurityException e) { } if (!deleted) { fileCopy.deleteOnExit(); } return true; }
Source:
public void onStartInstallClicked() { if (lastInstallMode != INSTALL_MODE_OFFLINE && isNetworkNotConnected()) { failWithNotification(AppInstallStatus.NoConnection); } else { ConnectionDiagnosticTask<CommCareSetupActivity> task = new ConnectionDiagnosticTask(getApplicationContext()); task.setListener(new ConnectionDiagnosticTask.ConnectionDiagnosticListener<CommCareSetupActivity>() { @Override public void connected(CommCareSetupActivity receiver) { CommCareApplication.notificationManager().clearNotifications(AIRPLANE_MODE_CATEGORY); receiver.startResourceInstall(); } @Override public void failed(CommCareSetupActivity receiver, String errorMessageId, MessageTag notificationTag, String analyticsMessage) { Toast.makeText(receiver, Localization.get(errorMessageId), Toast.LENGTH_LONG).show(); CommCareApplication.notificationManager().reportNotificationMessage( NotificationMessageFactory.message( notificationTag, AIRPLANE_MODE_CATEGORY)); FirebaseAnalyticsUtil.reportAppInstallFailure(getAnalyticsParamForInstallMethod(receiver.lastInstallMode), analyticsMessage); } }); task.connect(CommCareSetupActivity.this); task.executeParallel(); } }

Target:
public void onStartInstallClicked() { if (lastInstallMode != INSTALL_MODE_OFFLINE && isNetworkNotConnected()) { failWithNotification(AppInstallStatus.NoConnection); } else { startResourceInstall(); } }
Source:
private boolean canProcessDictionary(Page page) { boolean processDictionary = this.processDictionary && channels.length == 1 && page.getBlock(channels[0]) instanceof DictionaryBlock; if (processDictionary && inputHashChannel.isPresent()) { Block inputHashBlock = page.getBlock(inputHashChannel.get()); DictionaryBlock inputDataBlock = (DictionaryBlock) page.getBlock(channels[0]); if (!(inputHashBlock instanceof DictionaryBlock)) { processDictionary = false; } else if (!((DictionaryBlock) inputHashBlock).getDictionarySourceId().equals(inputDataBlock.getDictionarySourceId())) { processDictionary = false; } } return processDictionary; }

Target:
private boolean canProcessDictionary(Page page) { if (!this.processDictionary || channels.length > 1 || !(page.getBlock(channels[0]) instanceof DictionaryBlock)) { return false; } if (inputHashChannel.isPresent()) { Block inputHashBlock = page.getBlock(inputHashChannel.get()); DictionaryBlock inputDataBlock = (DictionaryBlock) page.getBlock(channels[0]); if (!(inputHashBlock instanceof DictionaryBlock)) { return false; } if (!((DictionaryBlock) inputHashBlock).getDictionarySourceId().equals(inputDataBlock.getDictionarySourceId())) { return false; } } return true; }
Source:
public byte[] encodeMessage(KM200Device device, String data) { byte[] encryptedDataB64 = null; try { byte[] bdata = data.getBytes(device.getCharSet()); final Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(device.getCryptKeyPriv(), "AES")); logger.debug("Create padding.."); int bsize = cipher.getBlockSize(); logger.debug("Add Padding and Encrypt AES.."); final byte[] encryptedData = cipher.doFinal(addZeroPadding(bdata, bsize, device.getCharSet())); logger.debug("Encrypt B64.."); try { encryptedDataB64 = Base64.getMimeEncoder().encode(encryptedData); } catch (IllegalArgumentException e) { logger.error("Base64encoding not possible:" + e.getMessage()); e.printStackTrace(); } return encryptedDataB64; } catch (BadPaddingException | IllegalBlockSizeException | UnsupportedEncodingException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) { logger.error("Exception on encoding:" + e.getMessage()); return null; } catch (final GeneralSecurityException e) { throw new IllegalStateException("Algorithms or unlimited crypto files not available", e); } }

Target:
public byte[] encodeMessage(KM200Device device, String data) { byte[] encryptedDataB64 = null; try { byte[] bdata = data.getBytes(device.getCharSet()); final Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(device.getCryptKeyPriv(), "AES")); logger.debug("Create padding.."); int bsize = cipher.getBlockSize(); logger.debug("Add Padding and Encrypt AES.."); final byte[] encryptedData = cipher.doFinal(addZeroPadding(bdata, bsize, device.getCharSet())); logger.debug("Encrypt B64.."); try { encryptedDataB64 = Base64.getMimeEncoder().encode(encryptedData); } catch (IllegalArgumentException e) { logger.error("Base64encoding not possible: {}", e); e.printStackTrace(); } return encryptedDataB64; } catch (BadPaddingException | IllegalBlockSizeException | UnsupportedEncodingException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) { logger.error("Exception on encoding: {}", e); return null; } catch (final GeneralSecurityException e) { throw new IllegalStateException("Algorithms or unlimited crypto files not available", e); } }
Source:
protected void ExecuteVdsBrokerCommand() { _result = null; if (getParameters().getStoragePoolId() != null) { VDS vds = DbFacade.getInstance().getVdsDao().get(getParameters().getVdsId()); if (FeatureSupported.saferGetAllTasksRequest(vds.getVdsGroupCompatibilityVersion())) { _result = getBroker().getAllTasksStatuses(getParameters().getStoragePoolId().toString()); } } if (_result == null) { _result = getBroker().getAllTasksStatuses(); } ProceedProxyReturnValue(); setReturnValue(ParseTaskStatusList(_result.TaskStatusList)); }

Target:
protected void ExecuteVdsBrokerCommand() { _result = null; if (getParameters().getStoragePoolId() != null) { if (FeatureSupported.saferGetAllTasksRequest(getVds().getVdsGroupCompatibilityVersion())) { _result = getBroker().getAllTasksStatuses(getParameters().getStoragePoolId().toString()); } } if (_result == null) { _result = getBroker().getAllTasksStatuses(); } ProceedProxyReturnValue(); setReturnValue(ParseTaskStatusList(_result.TaskStatusList)); }
Source:
public OsiamLdapAuthenticationProvider createLdapAuthProvider() { if (isLdapConfigured) { createLdapToScimAttributeMapping(); DefaultSpringSecurityContextSource contextSource = createLdapContextSource(); BindAuthenticator bindAuthenticator = new BindAuthenticator(contextSource); bindAuthenticator.setUserDnPatterns(dnPatterns); bindAuthenticator.setUserAttributes(attributes); OsiamLdapUserContextMapper mapper = new OsiamLdapUserContextMapper(scimLdapAttributes); OsiamLdapAuthenticationProvider provider = new OsiamLdapAuthenticationProvider(bindAuthenticator, new DefaultLdapAuthoritiesPopulator(contextSource, groupSearchBase), mapper); authenticationManager.getProviders().add(provider); return provider; } return null; }

Target:
public OsiamLdapAuthenticationProvider createLdapAuthProvider() { if (isLdapConfigured) { createLdapToScimAttributeMapping(); DefaultSpringSecurityContextSource contextSource = createLdapContextSource(); BindAuthenticator bindAuthenticator = new BindAuthenticator(contextSource); bindAuthenticator.setUserDnPatterns(dnPatterns); bindAuthenticator.setUserAttributes(attributes); OsiamLdapUserContextMapper mapper = new OsiamLdapUserContextMapper(scimLdapAttributes); DefaultLdapAuthoritiesPopulator authoritiesPopulator = new DefaultLdapAuthoritiesPopulator(contextSource, groupSearchBase); OsiamLdapAuthenticationProvider provider = new OsiamLdapAuthenticationProvider(bindAuthenticator, authoritiesPopulator, mapper); authenticationManager.getProviders().add(provider); return provider; } return null; }
Source:
public String getTaskUrl(String reviewUrlToFind) { for (Map.Entry<String, List<String>> mapping : taskReviewsMap.entrySet()) { int index = mapping.getValue().indexOf(reviewUrlToFind); if (index != -1) { return mapping.getKey(); } } return null; }

Target:
public String getTaskUrl(String reviewUrlToFind) { for (Entry<String, String> mapping : taskReviewsMap.entries()) { int index = mapping.getValue().indexOf(reviewUrlToFind); if (index != -1) { return mapping.getKey(); } } return null; }
Source:
private void completeTransaction(final TransactionInfo transactionInfo, CacheTopology cacheTopology) { final Collection<Address> affectedNodes = transactionInfo.getCommitNodes(cacheTopology); NotifyingNotifiableFuture<Map<Address, Response>> notifyingFuture = new NotifyingFutureImpl<>(); notifyingFuture.attachListener(new FutureListener<Map<Address, Response>>() { @Override public void futureDone(Future<Map<Address, Response>> future) { final GlobalTransaction globalTransaction = transactionInfo.getGlobalTransaction(); if (trace) { log.tracef("Future done for transaction %s", globalTransaction); } try { future.get(); } catch (Throwable e) { if (trace) { log.tracef(e, "Exception for transaction %s", globalTransaction); } return; } if (trace) { log.tracef("Performing cleanup for transaction %s", globalTransaction); } lockManager.unlock(transactionInfo.getLockedKeys(), globalTransaction); partialTransactions.remove(globalTransaction); TxCompletionNotificationCommand command = commandsFactory.buildTxCompletionNotificationCommand(null, globalTransaction); rpcManager.invokeRemotely(null, command, rpcManager.getDefaultRpcOptions(false)); } }); rpcManager.invokeRemotelyInFuture(notifyingFuture, affectedNodes, transactionInfo.buildCommand(commandsFactory, isVersioned), rpcManager.getDefaultRpcOptions(true)); }

Target:
private void completeTransaction(final TransactionInfo transactionInfo, CacheTopology cacheTopology) { rpcManager.invokeRemotelyAsync(transactionInfo.getCommitNodes(cacheTopology), transactionInfo.buildCommand(commandsFactory, isVersioned), rpcManager.getDefaultRpcOptions(true)) .whenComplete((responseMap, throwable) -> { final GlobalTransaction globalTransaction = transactionInfo.getGlobalTransaction(); if (trace) { log.tracef("Future done for transaction %s", globalTransaction); } if (throwable != null) { if (trace) { log.tracef(throwable, "Exception for transaction %s. Retry later.", globalTransaction); } return; } if (trace) { log.tracef("Future done for transaction %s. Response are %s", globalTransaction, responseMap); } for (Response response : responseMap.values()) { if (response == UnsureResponse.INSTANCE || response == CacheNotFoundResponse.INSTANCE) { if (trace) { log.tracef("Another partition or topology changed for transaction %s. Retry later.", globalTransaction); } return; } } if (trace) { log.tracef("Performing cleanup for transaction %s", globalTransaction); } lockManager.unlock(transactionInfo.getLockedKeys(), globalTransaction); partialTransactions.remove(globalTransaction); TxCompletionNotificationCommand command = commandsFactory.buildTxCompletionNotificationCommand(null, globalTransaction); rpcManager.invokeRemotely(null, command, rpcManager.getDefaultRpcOptions(false, DeliverOrder.NONE)); }); }
Source:
protected boolean reconstructMaster() { newMasterStorageDomainId = getNewMasterId(); proceedStorageDomainTreatmentByDomainType(getNewMaster(), false); if (getParameters().isInactive() && !getStorageDomain().getId().equals(getNewMasterId())) { executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { setStorageDomainStatus(StorageDomainStatus.Inactive, getCompensationContext()); calcStoragePoolStatusByDomainsStatus(); getCompensationContext().stateChanged(); return null; } }); } if (_isLastMaster) { return stopSpm(); } boolean commandSucceeded = stopSpm(); final List<String> disconnectPoolFormats = Config.<List<String>> getValue( ConfigValues.DisconnectPoolOnReconstruct); if (commandSucceeded && disconnectPoolFormats.contains(getNewMaster().getStorageFormat().getValue())) { commandSucceeded = runVdsCommand( VDSCommandType.DisconnectStoragePool, new DisconnectStoragePoolVDSCommandParameters(getVds().getId(), getStoragePool().getId(), getVds().getVdsSpmId()) ).getSucceeded(); } if (!commandSucceeded) { return false; } List<StoragePoolIsoMap> domains = getStoragePoolIsoMapDAO() .getAllForStoragePool(getStoragePool().getId()); setActionReturnValue(true); return runVdsCommand(VDSCommandType.ReconstructMaster, new ReconstructMasterVDSCommandParameters(getVds().getId(), getVds().getVdsSpmId(), getStoragePool().getId(), getStoragePool().getName(), getNewMasterId(), domains, getStoragePool().getMasterDomainVersion())).getSucceeded(); }

Target:
protected boolean reconstructMaster() { proceedStorageDomainTreatmentByDomainType(getNewMaster(), false); if (getParameters().isInactive() && !getStorageDomain().getId().equals(getNewMasterId())) { executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { setStorageDomainStatus(StorageDomainStatus.Inactive, getCompensationContext()); calcStoragePoolStatusByDomainsStatus(); getCompensationContext().stateChanged(); return null; } }); } if (_isLastMaster) { return stopSpm(); } boolean commandSucceeded = stopSpm(); final List<String> disconnectPoolFormats = Config.<List<String>> getValue( ConfigValues.DisconnectPoolOnReconstruct); if (commandSucceeded && disconnectPoolFormats.contains(getNewMaster().getStorageFormat().getValue())) { commandSucceeded = runVdsCommand( VDSCommandType.DisconnectStoragePool, new DisconnectStoragePoolVDSCommandParameters(getVds().getId(), getStoragePool().getId(), getVds().getVdsSpmId()) ).getSucceeded(); } if (!commandSucceeded) { return false; } List<StoragePoolIsoMap> domains = getStoragePoolIsoMapDAO() .getAllForStoragePool(getStoragePool().getId()); setActionReturnValue(true); return runVdsCommand(VDSCommandType.ReconstructMaster, new ReconstructMasterVDSCommandParameters(getVds().getId(), getVds().getVdsSpmId(), getStoragePool().getId(), getStoragePool().getName(), getNewMasterId(), domains, getStoragePool().getMasterDomainVersion())).getSucceeded(); }
Source:
public Object getMetaData(String fieldName) { if (fieldName.startsWith(ATTR_PREFIX)) { return root.getAttributeValue(null, getEntryFromCol(fieldName).substring(1)); } else if (fieldName.startsWith(ELEM_PREFIX)) { TreeElement child = root.getChild(getEntryFromCol(fieldName), 0); IAnswerData value = child.getValue(); if (value == null) { return ""; } else { return value.uncast().getString(); } } return null; }

Target:
public Object getMetaData(String fieldName) { if (fieldName.startsWith(ATTR_COL_PREFIX)) { return root.getAttributeValue(null, getElementOrAttributeFromSqlColumnName(fieldName).substring(ATTR_PREFIX_LENGTH)); } else if (fieldName.startsWith(ELEM_COL_PREFIX)) { TreeElement child = root.getChild(getElementOrAttributeFromSqlColumnName(fieldName), 0); if (child == null) { return null; } IAnswerData value = child.getValue(); if (value == null) { return null; } else { return value.uncast().getString(); } } throw new IllegalArgumentException("No metadata field " + fieldName + " in the indexed fixture storage table."); }
Source:
public void getClassloaderFromAllDependenciesComplexTest() { Path path = Paths.get(".").resolve("src/test/projects/dummy_deps_complex"); AFCompiler compiler = KieMavenCompilerFactory.getCompiler(KieDecorator.CLASSPATH_DEPS_AFTER_DECORATOR); WorkspaceCompilationInfo info = new WorkspaceCompilationInfo(path); CompilationRequest req = new DefaultCompilationRequest(mavenRepo.toAbsolutePath().toString(), info, new String[]{MavenCLIArgs.ALTERNATE_USER_SETTINGS + alternateSettingsAbsPath, MavenConfig.DEPS_IN_MEMORY_BUILD_CLASSPATH}, Boolean.FALSE); CompilationResponse res = compiler.compile(req); assertThat(res.isSuccessful()).isTrue(); assertThat(res.getDependencies().isEmpty()).isFalse(); assertThat(res.getDependencies().size()).isEqualTo(7); }

Target:
public void getClassloaderFromAllDependenciesComplexTest() { Path path = Paths.get(".").resolve("target/test-classes/dummy_deps_complex"); AFCompiler compiler = KieMavenCompilerFactory.getCompiler(KieDecorator.CLASSPATH_DEPS_AFTER_DECORATOR); WorkspaceCompilationInfo info = new WorkspaceCompilationInfo(path); CompilationRequest req = new DefaultCompilationRequest(mavenRepo.toAbsolutePath().toString(), info, new String[]{MavenCLIArgs.ALTERNATE_USER_SETTINGS + alternateSettingsAbsPath, MavenConfig.DEPS_IN_MEMORY_BUILD_CLASSPATH}, Boolean.FALSE); CompilationResponse res = compiler.compile(req); assertThat(res.isSuccessful()).isTrue(); assertThat(res.getDependencies()).isNotEmpty(); assertThat(res.getDependencies()).hasSize(7); }
Source:
public Optional<String> computeComment(final List<IBundle> presentBundles, IThrowable throwable) { if (packageAdmin == null) { return Optional.absent(); } List<String> problematicPackages = extractProblematicPackage(throwable); if (problematicPackages.isEmpty()) { return Optional.absent(); } Set<String> presentBundlesSymbolicNames = Sets.newHashSet(); for (IBundle presentBundle : presentBundles) { presentBundlesSymbolicNames.add(presentBundle.getName()); } StringBuilder comment = new StringBuilder(); for (String problematicPackage : problematicPackages) { comment.append(Formats.format(Messages.COMMENT_PROBLEMATIC_PACKAGE_ORIGIN_EXPORTS, problematicPackage)); ExportedPackage[] exportedPackages = packageAdmin.getExportedPackages(problematicPackage); if (ArrayUtils.isEmpty(exportedPackages)) { continue; } Multimap<org.osgi.framework.Bundle, org.osgi.framework.Bundle> exportersToImporters = HashMultimap.create(); for (ExportedPackage exportedPackage : exportedPackages) { org.osgi.framework.Bundle exportingBundle = exportedPackage.getExportingBundle(); if (!isPresent(exportingBundle)) { continue; } for (org.osgi.framework.Bundle importingBundle : exportedPackage.getImportingBundles()) { if (!isPresent(importingBundle)) { continue; } if (presentBundlesSymbolicNames.contains(importingBundle.getSymbolicName())) { exportersToImporters.put(exportingBundle, importingBundle); } } } if (exportersToImporters.isEmpty()) { continue; } for (Entry<org.osgi.framework.Bundle, Collection<org.osgi.framework.Bundle>> entry : exportersToImporters.asMap().entrySet()) { org.osgi.framework.Bundle exporter = entry.getKey(); Collection<org.osgi.framework.Bundle> importers = entry.getValue(); comment.append( Formats.format(Messages.COMMENT_PROBLEMATIC_PACKAGE_IMPORTS, exporter.getSymbolicName(), exporter.getVersion())); for (org.osgi.framework.Bundle importer : importers) { comment.append( Formats.format(Messages.COMMENT_PROBLEMATIC_PACKAGE_IMPORT, importer.getSymbolicName(), importer.getVersion())); } } } return Optional.of(comment.toString()); }

Target:
public Optional<String> computeComment(final List<IBundle> presentBundles, IThrowable throwable) { if (packageAdmin == null) { return Optional.absent(); } List<String> problematicPackages = extractProblematicPackage(throwable); if (problematicPackages.isEmpty()) { return Optional.absent(); } Set<String> presentBundlesSymbolicNames = presentBundles.stream().map(bundle -> bundle.getName()).collect(Collectors.toSet()); StringBuilder commentBuilder = new StringBuilder(); for (String problematicPackage : problematicPackages) { Multimap<org.osgi.framework.Bundle, org.osgi.framework.Bundle> exportersToImporters = mapExportingToImportingBundles( presentBundlesSymbolicNames, problematicPackage); if (!exportersToImporters.isEmpty()) { appendProblematicPackageComment(problematicPackage, exportersToImporters, commentBuilder); } } String comment = commentBuilder.toString(); if (StringUtils.isEmpty(comment)) { return Optional.absent(); } else { return Optional.of(comment); } }
Source:
private BundleNotFoundException unpackBundleNotFoundException(Throwable caught) { if (caught instanceof RuntimeException) { String message = caught.getMessage(); int patternStart = message.indexOf(BUNDLE_NOT_FOUND_EXCEPTION_PATTERN_START); if (patternStart > 0) { int patternEnd = message.indexOf(BUNDLE_NOT_FOUND_EXCEPTION_PATTERN_END, patternStart + BUNDLE_NOT_FOUND_EXCEPTION_PATTERN_START.length()); if (patternEnd > 0) { return new BundleNotFoundException( message.substring( patternStart + BUNDLE_NOT_FOUND_EXCEPTION_PATTERN_START.length(), patternEnd)); } } } return null; }

Target:
private BundleNotFoundException unpackBundleNotFoundException(Throwable caught) { if (caught instanceof RuntimeException) { String message = caught.getMessage(); int patternStart = message.indexOf(BUNDLE_NOT_FOUND_EXCEPTION_PATTERN_START); if (patternStart > -1) { int patternEnd = message.indexOf(BUNDLE_NOT_FOUND_EXCEPTION_PATTERN_END, patternStart + BUNDLE_NOT_FOUND_EXCEPTION_PATTERN_START.length()); if (patternEnd > -1) { return new BundleNotFoundException( message.substring( patternStart + BUNDLE_NOT_FOUND_EXCEPTION_PATTERN_START.length(), patternEnd)); } } } return null; }
Source:
private void validate(Scanner scanner, String[] expectedValues) { for (String expectedValue : expectedValues) { assertThat(scanner.hasNext(), is(true)); assertThat(scanner.next(), is(expectedValue)); } }

Target:
private void validate(Scanner scanner, String[] expectedValues) { for (String expectedValue : expectedValues) { assertThat( "Expected next value to be " + expectedValue + " but scanner.hasNext() returned false", scanner.hasNext(), is(true)); assertThat(scanner.next(), is(expectedValue)); } }
Source:
private Set<byte[]> getKnownPayloadHashes() { Set<byte[]> excludedKeys; if (seedNodeRepository != null && seedNodeRepository.isSeedNode(networkNode.getNodeAddress())) excludedKeys = this.appendOnlyDataStoreService.getMap().keySet().stream() .map(e -> e.bytes) .collect(Collectors.toSet()); else excludedKeys = this.appendOnlyDataStoreService.getMap("since " + Version.VERSION).keySet().stream() .map(e -> e.bytes) .collect(Collectors.toSet()); Set<byte[]> excludedKeysFromPersistedEntryMap = this.map.keySet() .stream() .map(e -> e.bytes) .collect(Collectors.toSet()); excludedKeys.addAll(excludedKeysFromPersistedEntryMap); excludedKeys.add(getSpecialKey()); return excludedKeys; }

Target:
private Set<byte[]> getKnownPayloadHashes() { Set<byte[]> excludedKeys; boolean weAreASeedNode = seedNodeRepository != null && seedNodeRepository.isSeedNode(networkNode.getNodeAddress()); if (weAreASeedNode) { excludedKeys = getKeySetInBytes(this.appendOnlyDataStoreService.getMap()); } else { excludedKeys = getKeySetInBytes(this.appendOnlyDataStoreService.getMap("since " + Version.VERSION)); } Set<byte[]> excludedKeysFromPersistedEntryMap = getKeySetInBytes(this.map); excludedKeys.addAll(excludedKeysFromPersistedEntryMap); excludedKeys.add(getSpecialKey()); return excludedKeys; }
Source:
public Collection<Partition<T>> updateBandwidth(Collection<Partition<T>> newpartitions, long currentBandwidth) { LOG.info("Updating bandwidth of partitions."); long newBandwidth = currentBandwidth / newpartitions.size(); for (Partition<T> partition : newpartitions) { partition.getPartitionedInstance().getBandwidthManager().setBandwidth(newBandwidth); } return newpartitions; }

Target:
public Collection<Partition<T>> updateBandwidth(Collection<Partition<T>> newpartitions, long currentBandwidth) { long newBandwidth = currentBandwidth / newpartitions.size(); for (Partition<T> partition : newpartitions) { partition.getPartitionedInstance().getBandwidthManager().setBandwidth(newBandwidth); } LOG.info("Updating bandwidth of partitions to value: " + newBandwidth); return newpartitions; }
Source:
public void addMembers(PerunSession sess, Group group, List<Member> members) throws InternalErrorException, MemberNotExistsException, PrivilegeException, AlreadyMemberException, GroupNotExistsException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException, AttributeNotExistsException, ExternallyManagedException { Utils.checkPerunSession(sess); getGroupsManagerBl().checkGroupExists(sess, group); for (Member member : members) { getPerunBl().getMembersManagerBl().checkMemberExists(sess, member); if (member.getVoId() != (group.getVoId())) { throw new MembershipMismatchException("Member and group are form the different VO"); } } if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, group) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, group)) { throw new PrivilegeException(sess, "addMember"); } Attribute attrSynchronizeEnabled = getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GROUPSYNCHROENABLED_ATTRNAME); if ("true".equals(attrSynchronizeEnabled.getValue()) || getGroupsManagerBl().isGroupInStructureSynchronizationTree(sess, group)) { throw new ExternallyManagedException("Adding of member is not allowed. Group is externally managed."); } getGroupsManagerBl().addMembers(sess, group, members); }

Target:
public void addMembers(PerunSession sess, Group group, List<Member> members) throws InternalErrorException, MemberNotExistsException, PrivilegeException, AlreadyMemberException, GroupNotExistsException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException, AttributeNotExistsException, ExternallyManagedException { Utils.checkPerunSession(sess); getGroupsManagerBl().checkGroupExists(sess, group); for (Member member : members) { getPerunBl().getMembersManagerBl().checkMemberExists(sess, member); if (member.getVoId() != (group.getVoId())) { throw new MembershipMismatchException("Member and group are form the different VO"); } } if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, group) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, group)) { throw new PrivilegeException(sess, "addMembers"); } Attribute attrSynchronizeEnabled = getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GROUPSYNCHROENABLED_ATTRNAME); if ("true".equals(attrSynchronizeEnabled.getValue()) || getGroupsManagerBl().isGroupInStructureSynchronizationTree(sess, group)) { throw new ExternallyManagedException("Adding of member is not allowed. Group is externally managed."); } getGroupsManagerBl().addMembers(sess, group, members); }
Source:
public void checkSymbolExistence(SensorContextTester context, int line, int column, boolean mustExist) { Collection<TextRange> foundReferences = context.referencesForSymbolAt(componentKey, line, column); if (mustExist) { String message = "a symbol is expected to exist at line " + line + " and column " + column; assertThat(foundReferences).as(message).isEmpty(); } else { String message = "no symbol is expected to exist at line " + line + " and column " + column; assertThat(foundReferences).as(message).isEmpty(); } }

Target:
public void checkSymbolExistence(SensorContextTester context, int line, int column, boolean mustExist) { Collection<TextRange> foundReferences = context.referencesForSymbolAt(componentKey, line, column); if (mustExist) { String message = "a symbol is expected to exist at line " + line + " and column " + column; assertThat(foundReferences).as(message).isNotNull(); } else { String message = "no symbol is expected to exist at line " + line + " and column " + column; assertThat(foundReferences).as(message).isEmpty(); } }
Source:
public void testTypeParameterTree() { Class c = Class.clas(Option.none().getClass()); Collection<Type> coll = c.classParameters().toCollection(); for (Type t: coll) { Class.typeParameterTree(t); } }

Target:
public void testTypeParameterTree() { Class c = Class.clas(Option.none().getClass()); Collection<Type> coll = c.classParameters().toCollection(); for (Type t: coll) { assertThat(Class.typeParameterTree(t).toString(), is("Tree(class fj.data.Option$None)")); } }
Source:
public void dump(PrintWriter pw) { mLog.dump(null, pw, null); ConnectivityModuleConnector.getInstance().dump(pw); pw.println(); }

Target:
public void dump(PrintWriter pw) { mLog.dump(null, pw, null); pw.println(); }
Source:
public boolean delete() { List<Lock> locks = new ArrayList<Lock>(); lockRecursively(locks); try { List<ResourceNotification.Event> events = SimpleResourceWatcher.createEvents(this, ResourceNotification.Kind.ENTRY_DELETE); if (entry.delete()) { resourceWatcher.changed(new ResourceNotification(path(), ResourceNotification.Kind.ENTRY_DELETE, System.currentTimeMillis(), events)); return true; } else { return false; } } finally { for (Lock lock : locks) { lock.release(); } } }

Target:
public boolean delete() { List<Lock> locks = new ArrayList<Lock>(); lockRecursively(locks); try { List<ResourceNotification.Event> events = SimpleResourceNotificationDispatcher.createEvents(this, ResourceNotification.Kind.ENTRY_DELETE); if (entry.delete()) { resourceWatcher.changed(new ResourceNotification(path(), ResourceNotification.Kind.ENTRY_DELETE, System.currentTimeMillis(), events)); return true; } else { return false; } } finally { for (Lock lock : locks) { lock.release(); } } }
Source:
private boolean hasIpv6Gateway(VdsNetworkInterface iface) { return iface!= null && !IpAddressPredicate.isUnspecifiedIpv6(iface.getIpv6Gateway()); }

Target:
private boolean hasIpv6Gateway(VdsNetworkInterface iface) { return iface!= null && Ipv6UnspecifiedPredicate.INSTANCE.negate().test(iface.getIpv6Gateway()); }
Source:
public void onItemClick(BoxItem item) { BoxBrowseFragment browseFrag = getTopBrowseFragment(); if (browseFrag != null) { browseFrag.onItemClick(item); } if (item instanceof BoxFolder) { handleBoxFolderClicked((BoxFolder) item); } }

Target:
public void onItemClick(BoxItem item) { if (item instanceof BoxFolder) { mCurrentBoxFolder = (BoxFolder) item; handleBoxFolderClicked(mCurrentBoxFolder); } }
Source:
public void addNewField() { Field field = newFieldToAddProperty.getValue(); FieldViewModel model = new FieldViewModel(field, true, FieldPriority.IMPORTANT, selectedEntryTypesProperty.getValue()); typesWithFields.computeIfAbsent(selectedEntryTypesProperty.getValue(), key -> new ArrayList<>()).add(model); fieldsForType.add(model); }

Target:
public void addNewField() { Field field = newFieldToAdd.getValue(); FieldViewModel model = new FieldViewModel(field, true, FieldPriority.IMPORTANT, selectedEntryTypes.getValue()); typesWithFields.computeIfAbsent(selectedEntryTypes.getValue(), key -> new ArrayList<>()).add(model); allFieldsForType.add(model); newFieldToAddProperty().setValue(null); }
Source:
public ProjectAccess call() throws NoSuchProjectException, IOException, ConfigInvalidException { pc = open(); ProjectConfig config; MetaDataUpdate md = metaDataUpdateFactory.create(projectName); try { config = ProjectConfig.read(md); if (config.updateGroupNames(groupCache)) { md.setMessage("Update group names\n"); if (config.commit(md)) { projectCache.evict(config.getProject()); pc = open(); } } else if (config.getRevision() != null && !config.getRevision().equals( pc.getProjectState().getConfig().getRevision())) { projectCache.evict(config.getProject()); pc = open(); } } finally { md.close(); } List<AccessSection> local = new ArrayList<AccessSection>(); for (AccessSection section : config.getAccessSections()) { RefControl rc = pc.controlForRef(section.getRefPattern()); if (rc.isVisible() || rc.isOwner()) { local.add(section); } } final ProjectAccess detail = new ProjectAccess(); detail.setRevision(config.getRevision().name()); detail.setLocal(local); detail.setOwnerOf(getOwnedRefs()); if (projectName.equals(wildProject)) { detail.setInheritsFrom(null); } else if (config.getProject().getParent() != null) { detail.setInheritsFrom(config.getProject().getParent()); } else { detail.setInheritsFrom(wildProject); } return detail; }

Target:
public ProjectAccess call() throws NoSuchProjectException, IOException, ConfigInvalidException { pc = open(); ProjectConfig config; MetaDataUpdate md = metaDataUpdateFactory.create(projectName); try { config = ProjectConfig.read(md); if (config.updateGroupNames(groupCache)) { md.setMessage("Update group names\n"); if (config.commit(md)) { projectCache.evict(config.getProject()); pc = open(); } } else if (config.getRevision() != null && !config.getRevision().equals( pc.getProjectState().getConfig().getRevision())) { projectCache.evict(config.getProject()); pc = open(); } } finally { md.close(); } List<AccessSection> local = new ArrayList<AccessSection>(); Set<String> ownerOf = new HashSet<String>(); for (AccessSection section : config.getAccessSections()) { RefControl rc = pc.controlForRef(section.getRefPattern()); if (rc.isOwner()) { local.add(section); ownerOf.add(section.getRefPattern()); } else if (rc.isVisible()) { local.add(section); } } if (ownerOf.isEmpty() && pc.isOwnerAnyRef()) { ownerOf.add(AccessSection.ALL); } final ProjectAccess detail = new ProjectAccess(); detail.setRevision(config.getRevision().name()); detail.setLocal(local); detail.setOwnerOf(ownerOf); if (projectName.equals(wildProject)) { detail.setInheritsFrom(null); } else if (config.getProject().getParent() != null) { detail.setInheritsFrom(config.getProject().getParent()); } else { detail.setInheritsFrom(wildProject); } return detail; }
Source:
public Response saveAttachment(InputStream in, String name, String contentType, String docId, String docRev) { assertNotEmpty(in, "in"); assertNotEmpty(name, "name"); assertNotEmpty(contentType, "ContentType"); if (docId == null) { docId = generateUUID(); } final URI uri = new DatabaseURIHelper(dbUri).attachmentUri(docId, docRev, name); return couchDbClient.put(uri, in, contentType); }

Target:
public Response saveAttachment(InputStream in, String name, String contentType, String docId, String docRev) { assertNotEmpty(in, "in"); assertNotEmpty(name, "name"); assertNotEmpty(contentType, "ContentType"); if (docId == null) { docId = generateUUID(); assertNull(docRev, "docRev"); } else { assertNotEmpty(docId, "docId"); if (docRev != null) { assertNotEmpty(docRev, "docRev"); } } final URI uri = new DatabaseURIHelper(dbUri).attachmentUri(docId, docRev, name); return couchDbClient.put(uri, in, contentType); }
Source:
public void testExportWithStorageDomainName() throws Exception { setUpEntityQueryExpectations(VdcQueryType.GetAllStorageDomains, VdcQueryParametersBase.class, new String[] {}, new Object[] {}, Collections.singletonList(getStorageDomain(2))); StorageDomain storageDomain = new StorageDomain(); storageDomain.setName(NAMES[2]); doTestExport(storageDomain, false); }

Target:
public void testExportWithStorageDomainName() throws Exception { setUpGetEntityExpectations("Storage: name=" + NAMES[2], SearchType.StorageDomain, getStorageDomain(2)); StorageDomain storageDomain = new StorageDomain(); storageDomain.setName(NAMES[2]); doTestExport(storageDomain, false); }
Source:
public void onParagraphRemove(Paragraph p) { try { getJobManagerService().getNoteJobInfoByUnixTime(System.currentTimeMillis() - 5000, null, new JobManagerServiceCallback()); } catch (IOException ioe) { LOG.warn("can not broadcast for job manager {}", ioe.getMessage()); } }

Target:
public void onParagraphRemove(Paragraph p) { try { getJobManagerService().getNoteJobInfoByUnixTime(System.currentTimeMillis() - 5000, null, new JobManagerServiceCallback()); } catch (IOException e) { LOG.warn("can not broadcast for job manager: " + e.getMessage(), e); } }
Source:
private void generateUpdateMethod(Method method) { Parameter mainParameter = method.getParameters().stream() .filter(x -> x.getType() instanceof StructType) .findFirst() .orElse(null); if (mainParameter == null) { System.err.println("Method \"" + method + "\" doesn't have any struct parameter"); return; } Type mainType = mainParameter.getType(); JavaTypeReference mainTypeReference = schemaNames.getXjcTypeReference(mainType); javaBuffer.addImport(Consumes.class); javaBuffer.addImport(PUT.class); javaBuffer.addImports(mainTypeReference.getImports()); generateDoc(method); javaBuffer.addLine("@PUT"); javaBuffer.addLine("@Consumes({ %s })", generateMediaTypes()); javaBuffer.addLine(generateMethodSignature(mainTypeReference.getText(), "update(%s %s)", mainTypeReference.getText(), javaNames.getJavaMemberStyleName(mainParameter.getName())) ); javaBuffer.addLine(); }

Target:
private void generateUpdateMethod(Method method) { Parameter mainParameter = method.getParameters().stream() .filter(x -> x.getType() instanceof StructType) .findFirst() .orElse(null); if (mainParameter == null) { System.err.println("Method \"" + method + "\" doesn't have any struct parameter"); return; } Type mainType = mainParameter.getType(); JavaTypeReference mainTypeReference = schemaNames.getXjcTypeReference(mainType); javaBuffer.addImport(Consumes.class); javaBuffer.addImport(PUT.class); javaBuffer.addImports(mainTypeReference.getImports()); generateDoc(method); javaBuffer.addLine("@PUT"); javaBuffer.addLine("@Consumes({ %s })", generateMediaTypes()); generateMethod(mainTypeReference.getText(), "update(%s %s)", mainTypeReference.getText(), javaNames.getJavaMemberStyleName(mainParameter.getName())); javaBuffer.addLine(); }
Source:
public Avg(String fieldName, Schema fieldSchema) { this.fieldName = fieldName; boolean isNullable = fieldSchema.isNullable(); Schema.Type fieldType = isNullable ? fieldSchema.getNonNullable().getType() : fieldSchema.getType(); if (!(fieldType == Schema.Type.INT || fieldType == Schema.Type.LONG || fieldType == Schema.Type.FLOAT || fieldType == Schema.Type.DOUBLE)) { throw new IllegalArgumentException(String.format( "Cannot compute avg on field %s because its type %s is not numeric", fieldName, fieldSchema)); } outputSchema = isNullable ? Schema.nullableOf(Schema.of(Schema.Type.DOUBLE)) : Schema.of(Schema.Type.DOUBLE); }

Target:
public Avg(String fieldName, Schema fieldSchema) { this.fieldName = fieldName; boolean isNullable = fieldSchema.isNullable(); Schema.Type fieldType = isNullable ? fieldSchema.getNonNullable().getType() : fieldSchema.getType(); if (!(fieldType == Schema.Type.INT || fieldType == Schema.Type.LONG || fieldType == Schema.Type.FLOAT || fieldType == Schema.Type.DOUBLE)) { throw new IllegalArgumentException(String.format( "Cannot compute avg on field %s because its type %s is not numeric", fieldName, fieldType)); } outputSchema = isNullable ? Schema.nullableOf(Schema.of(Schema.Type.DOUBLE)) : Schema.of(Schema.Type.DOUBLE); }
Source:
static String getFontSize(int theSize, boolean isSizeTag) { loadFontMap(); String theReturn = MEDIUM_FONT; if (isSizeTag) { Object[] theSizes = FONT_MAP.values().toArray(); if (theSize <= theSizes.length) { theReturn = (String) theSizes[theSize - 1]; } } else { Iterator<Integer> iter = FONT_MAP.keySet().iterator(); Iterator<String> value = FONT_MAP.values().iterator(); while (iter.hasNext()) { Integer theInt = iter.next(); String theString = value.next(); if (theSize <= theInt.intValue()) { theReturn = theString; break; } } } return theReturn; }

Target:
private String getFontSize(int theSize, boolean isSizeTag) { String theReturn = MEDIUM_FONT; if (isSizeTag) { Object[] theSizes = FONT_MAP.values().toArray(); if (theSize <= theSizes.length) { theReturn = (String) theSizes[theSize - 1]; } } else { theReturn = FONT_MAP.ceilingEntry(theSize).getValue(); } return theReturn; }