List of usage examples for java.lang Math ceil
public static double ceil(double a)
From source file:com.sketchy.utils.image.SketchyImage.java
public static void save(SketchyImage sketchyImage, File file) throws Exception { if (!file.getParentFile().canWrite()) { throw new Exception("Can not write to File: " + file.getPath() + "!"); }//from ww w.j a v a 2s . c om if (!StringUtils.endsWithIgnoreCase(file.getName(), ".png")) { throw new Exception("Can not save SketchyImage! Must be a .png file!"); } Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByFormatName("png"); ImageWriter imageWriter = null; if (imageWriters.hasNext()) { // Just get first one imageWriter = imageWriters.next(); } if (imageWriter == null) { // this should never happen!! if so.. we got problems throw new Exception("Can not find ImageReader for .png Files!"); } ImageOutputStream os = null; try { os = ImageIO.createImageOutputStream(file); imageWriter.setOutput(os); ImageWriteParam imageWriterParam = imageWriter.getDefaultWriteParam(); IIOMetadata metadata = imageWriter.getDefaultImageMetadata( ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_BYTE_BINARY), imageWriterParam); String metaDataFormatName = metadata.getNativeMetadataFormatName(); IIOMetadataNode metaDataNode = (IIOMetadataNode) metadata.getAsTree(metaDataFormatName); NodeList childNodes = metaDataNode.getElementsByTagName("pHYs"); IIOMetadataNode physNode = null; if (childNodes.getLength() == 0) { physNode = new IIOMetadataNode("pHYs"); physNode.setAttribute("pixelsPerUnitXAxis", Integer.toString((int) Math.ceil(sketchyImage.dotsPerMillimeterWidth * 1000))); physNode.setAttribute("pixelsPerUnitYAxis", Integer.toString((int) Math.ceil(sketchyImage.dotsPerMillimeterHeight * 1000))); physNode.setAttribute("unitSpecifier", "meter"); // always meter metaDataNode.appendChild(physNode); } else { for (int nodeIdx = 0; nodeIdx < childNodes.getLength(); nodeIdx++) { physNode = (IIOMetadataNode) childNodes.item(nodeIdx); physNode.setAttribute("pixelsPerUnitXAxis", Integer.toString((int) Math.ceil(sketchyImage.dotsPerMillimeterWidth * 1000))); physNode.setAttribute("pixelsPerUnitYAxis", Integer.toString((int) Math.ceil(sketchyImage.dotsPerMillimeterHeight * 1000))); physNode.setAttribute("unitSpecifier", "meter"); // always meter metaDataNode.appendChild(physNode); } } metadata.setFromTree(metaDataFormatName, metaDataNode); imageWriter.write(new IIOImage(sketchyImage.image, null, metadata)); os.flush(); } catch (Exception e) { throw new Exception("Error Saving SketchyImage File: " + file.getPath() + "! " + e.getMessage()); } finally { IOUtils.closeQuietly(os); } }
From source file:de.christianseipl.utilities.maputils.MapMath.java
/** * Fhrt die {@link Math#ceil(double)} Operation auf jedem Element der Map * durch//from w ww . j ava 2s. c o m * * @param <K> ein beliebiger Objekttyp * * @param _map * Die Ursprungsmap * @return Eine neue Map, deren Wert das Ergebnis von * {@link Math#ceil(double)} darstellen. */ public static <K> Map<K, Double> ceil(Map<? extends K, ? extends Number> _map) { return operateOnMap(_map, new NumberTransformer<K, Double>() { @Override public Double transform(K _key, Number _number) { return Math.ceil(_number.doubleValue()); } }); }
From source file:com.wms.opensource.images3android.activity.ImageListFragmentActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.image_pages); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setIcon(R.drawable.ic_launcher); getSupportActionBar().setTitle(getString(R.string.imageListActivityTitle)); maxPageCount = getResources().getInteger(R.integer.MAX_PAGE_COUNT); imagePlantId = getString(R.string.imagePlantId); loadImagePlantHandler = new LoadImagePlantHandler(); String imagePlantFilePath = ""; imagePlantFilePath = StorageUtil.getTempDirectoryPath(this) + "/" + PersistFileNameUtil.getImagePlantPersistFileName(imagePlantId); boolean imagePlantFileExists = FileUtil.fileExist(imagePlantFilePath); if (imagePlantFileExists) { shouldAutoRunOverallInfoLoadingTask = true; // The app has loaded image plant before, so we directly get images count String imagePlantStr = ""; imagePlantStr = FileUtil.getStringFromFileInCache(StorageUtil.getTempDirectory(this), PersistFileNameUtil.getImagePlantPersistFileName(imagePlantId), getString(R.string.charSetName)); try {// w ww .j a v a 2s . c o m imagePlant = (ImagePlant) JsonUtil.deserialize(imagePlantStr, "", ImagePlant.class); savedImagesCount = imagePlant.getNumberOfImages(); pageCount = (int) Math.ceil(savedImagesCount * 1.0 / ImageS3Service.NUMBER_OF_IMAGES_PER_PAGE); MessageUtil.sendHandlerMessage(loadImagePlantHandler, HandlerMessage.IMAGES_COUNT_LOADED); } catch (JsonParseException e) { } catch (JsonMappingException e) { } catch (IOException e) { } } else { // The app never loaded image plant before, so we should load it loadImagePlant(false, savedImagesCount); } // Do not show the soft keyboard this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); }
From source file:amie.keys.CombinationsExplorationNew.java
/** * Parses the command line arguments and the returns an object that maps * each argument to its value./*from w w w. j a v a 2 s .c om*/ * * @param args * @return * @throws IOException */ public static CommandLine parseArguments(String[] args) throws IOException { HelpFormatter formatter = new HelpFormatter(); // create the command line parser CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); CommandLine cli = null; Option supportOpt = OptionBuilder.withArgName("min-support").hasArg() .withDescription( "Minimum support. Default: 5 positive examples. If the option percentage is enabled, " + "the value is considered as the percentage of entities covered " + "by the a conditional key.") .create("mins"); Option ratioOpt = OptionBuilder.withArgName("percentage") .withDescription("Interpret the support as a percentage " + "Default: false").create("p"); Option nonKeysOpt = OptionBuilder.withArgName("non-keys").withDescription("Path the to the non-keys file.") .hasArg().isRequired().create("nk"); options.addOption(supportOpt); options.addOption(ratioOpt); options.addOption(nonKeysOpt); try { cli = parser.parse(options, args); } catch (ParseException e) { System.out.println("Unexpected exception: " + e.getMessage()); formatter.printHelp("CombinationsExploration [OPTIONS] <TSV FILES>", options); System.exit(1); } String[] fileNameArgs = cli.getArgs(); // Use kb = amie.data.U.loadFiles(args, 1) to ignore the first // argument. This first argument could be the list of non-keys kb = amie.data.U.loadFiles(fileNameArgs); if (cli.hasOption("mins")) { try { support = Integer.parseInt(cli.getOptionValue("mins")); } catch (NumberFormatException e) { System.out.println("Unexpected exception: " + e.getMessage()); formatter.printHelp("CombinationsExploration [OPTIONS] <TSV FILES>", options); System.exit(1); } } if (cli.hasOption("p")) { System.out.println("Support interpreted as a " + support + "% of the number of entities."); long numberOfInstances = kb.size(Column.Subject); System.out.println(numberOfInstances + " instances found as subjects in the KB."); support = (int) Math.ceil(numberOfInstances * support / 100.0); } System.out.println("Using minimum support " + support); return cli; }
From source file:playground.johannes.snowball.Histogram.java
private void fillBins() { if (modified) { double min, max, width; int size; if (bounds != null) { min = bounds[0];/*from ww w.ja v a 2s. c o m*/ max = bounds[1]; } else { double minmax[] = getMinMax(); min = minmax[0]; max = minmax[1]; } if (binWidth > 0) { size = (int) Math.ceil((max - min) / (double) binWidth); width = binWidth; } else { size = bincount; width = (max - min) / (double) bincount; } bins = new DoubleArrayList(); bins.setSize(size + 1); for (int i = 0; i < values.size(); i++) { double value = values.get(i); if (value >= min && value <= max) { int idx = (int) Math.floor((values.get(i) - min) / width); bins.set(idx, bins.get(idx) + weights.get(i)); } } modified = false; } }
From source file:web.EventLogController.java
/** * Main method for paginating the list of events * @param pageid/*from www . ja v a2 s . c o m*/ * @param request * @return */ @RequestMapping("/eventlog/vieweventlog/{pageid}") public ModelAndView showEventLogPager(@PathVariable int pageid, HttpServletRequest request) { int total = 25; int start = 1; //displays page if user isn't on first page if (pageid != 1) { start = (pageid - 1) + total + 1; } //totals up results of pagination method in DAO to provide page numbers List<EventLog> eventLogs = dao.getEventsByPage(start, total); HashMap<String, Object> context = new HashMap<String, Object>(); context.put("eventlog", eventLogs); int count = dao.getEventsCount(); context.put("pages", Math.ceil((float) count / (float) total)); context.put("page", pageid); Messages msg = (Messages) request.getSession().getAttribute("message"); if (msg != null) { context.put("message", msg); request.getSession().removeAttribute("message"); } logger.info(eventLogs.toString()); return new ModelAndView("vieweventlog", context); }
From source file:com.gwac.action.OtObserveRecordAction.java
/** * @param records total number of records for the query. e.g. select count(*) * from table//from w w w. j av a 2 s. c om */ public void setRecords(Integer records) { this.records = records; if (this.records > 0 && this.rows > 0) { this.total = (int) Math.ceil((double) this.records / (double) this.rows); } else { this.total = 0; } }
From source file:com.inmobi.conduit.distcp.tools.mapred.lib.DynamicInputFormat.java
private List<DynamicInputChunk> splitCopyListingIntoChunksWithShuffle(JobContext context) throws IOException { final Configuration configuration = HadoopCompat.getConfiguration(context); int numRecords = getNumberOfRecords(configuration); int numMaps = getNumMapTasks(configuration); // Number of chunks each map will process, on average. int splitRatio = getListingSplitRatio(configuration, numMaps, numRecords); validateNumChunksUsing(splitRatio, numMaps); int numEntriesPerChunk = (int) Math.ceil((float) numRecords / (splitRatio * numMaps)); DistCpUtils.publish(HadoopCompat.getConfiguration(context), CONF_LABEL_NUM_ENTRIES_PER_CHUNK, numEntriesPerChunk);/*w w w .j av a 2 s.c o m*/ final int nChunksTotal = (int) Math.ceil((float) numRecords / numEntriesPerChunk); int nChunksOpenAtOnce = Math.min(N_CHUNKS_OPEN_AT_ONCE_DEFAULT, nChunksTotal); Path listingPath = getListingFilePath(configuration); SequenceFile.Reader reader = new SequenceFile.Reader(listingPath.getFileSystem(configuration), listingPath, configuration); List<DynamicInputChunk> openChunks = new ArrayList<DynamicInputChunk>(); List<DynamicInputChunk> chunksFinal = new ArrayList<DynamicInputChunk>(); FileStatus fileStatus = new FileStatus(); Text relPath = new Text(); int recordCounter = 0; int chunkCount = 0; DynamicInputChunkSet chunkSet = new DynamicInputChunkSet(configuration); try { while (reader.next(relPath, fileStatus)) { if (recordCounter % (nChunksOpenAtOnce * numEntriesPerChunk) == 0) { // All chunks full. Create new chunk-set. closeAll(openChunks); chunksFinal.addAll(openChunks); openChunks = createChunks(chunkSet, chunkCount, nChunksTotal, nChunksOpenAtOnce); chunkCount += openChunks.size(); nChunksOpenAtOnce = openChunks.size(); recordCounter = 0; } // Shuffle into open chunks. openChunks.get(recordCounter % nChunksOpenAtOnce).write(relPath, fileStatus); ++recordCounter; } } finally { closeAll(openChunks); chunksFinal.addAll(openChunks); IOUtils.closeStream(reader); } LOG.info("Number of dynamic-chunk-files created: " + chunksFinal.size()); return chunksFinal; }
From source file:es.ucm.fdi.dalgs.degree.repository.DegreeRepository.java
public Integer numberOfPages(Boolean showAll) { Query query = null;/* www. ja v a2 s . com*/ if (showAll) query = em.createNativeQuery("select count(*) from degree"); else query = em.createNativeQuery("select count(*) from degree where isDeleted='false'"); logger.info(query.getSingleResult().toString()); double dou = Double.parseDouble(query.getSingleResult().toString()) / ((double) noOfRecords); return (int) Math.ceil(dou); }
From source file:com.codelanx.codelanxlib.util.auth.UUIDFetcher.java
/** * Makes a request to mojang's servers of a sublist of at most 100 player's * names. Additionally can provide progress outputs * //from w ww. jav a 2s. c o m * @since 0.0.1 * @version 0.1.0 * * @param output Whether or not to print output * @param log The {@link Logger} to print to * @param doOutput A {@link Predicate} representing when to output a number * @return A {@link Map} of player names to their {@link UUID}s * @throws IOException If there's a problem sending or receiving the request * @throws ParseException If the request response cannot be read * @throws InterruptedException If the thread is interrupted while sleeping */ public Map<String, UUID> callWithProgessOutput(boolean output, Logger log, Predicate<? super Integer> doOutput) throws IOException, ParseException, InterruptedException { //Method start Map<String, UUID> uuidMap = new HashMap<>(); int totalNames = this.names.size(); int completed = 0; int failed = 0; int requests = (int) Math.ceil(this.names.size() / UUIDFetcher.PROFILES_PER_REQUEST); for (int i = 0; i < requests; i++) { List<String> request = names.subList(i * 100, Math.min((i + 1) * 100, this.names.size())); String body = JSONArray.toJSONString(request); HttpURLConnection connection = UUIDFetcher.createConnection(); UUIDFetcher.writeBody(connection, body); if (connection.getResponseCode() == 429 && this.rateLimiting) { log.warning("[UUIDFetcher] Rate limit hit! Waiting 10 minutes until continuing conversion..."); Thread.sleep(TimeUnit.MINUTES.toMillis(10)); connection = UUIDFetcher.createConnection(); UUIDFetcher.writeBody(connection, body); } JSONArray array = (JSONArray) this.jsonParser.parse(new InputStreamReader(connection.getInputStream())); completed += array.size(); failed += request.size() - array.size(); for (Object profile : array) { JSONObject jsonProfile = (JSONObject) profile; UUID uuid = UUIDFetcher.getUUID((String) jsonProfile.get("id")); uuidMap.put((String) jsonProfile.get("name"), uuid); } if (output) { int processed = completed + failed; if (doOutput.test(processed) || processed == totalNames) { log.info(String.format("[UUIDFetcher] Progress: %d/%d, %.2f%%, Failed names: %d", processed, totalNames, ((double) processed / totalNames) * 100D, failed)); } } } return uuidMap; }