List of usage examples for com.google.common.math IntMath divide
@SuppressWarnings("fallthrough") public static int divide(int p, int q, RoundingMode mode)
From source file:joachimeichborn.geotag.refinetracks.ReplacePositionsByAccuracyComparisonTask.java
/** * Check for every position, if it could be replaced with a better (more * accurate) adjacent positions. This is repeated until no positions are * replaced any more. <br>/*from w w w . ja v a2 s . c om*/ * Position adjacency is meant in a timely matter, a position can only be * replaced with the previous or next position. If a position is replaced, * the new position has the time stamp of the one that is replaced but the * coordinates and accuracy of the position that is the template for the * replacement. */ @Override void process(final List<PositionData> aPositions) { logger.fine("Position replacement by location accuracy activated"); int chunks = Runtime.getRuntime().availableProcessors(); logger.fine("Splitting positions in " + chunks + " chunks for replacement by location accuracy"); final ExecutorService threadPool = Executors.newCachedThreadPool(); boolean replacementOccured = true; int replacementCount = 0; final int chunkSize = IntMath.divide(aPositions.size(), chunks, RoundingMode.CEILING); while (replacementOccured) { replacementOccured = false; final List<Future<Integer>> futures = new LinkedList<>(); for (int i = 0; i < chunks; i++) { final int startIndex = i * chunkSize; final int endIndex = Math.min(startIndex + chunkSize, aPositions.size() - 1); futures.add(threadPool.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { logger.fine("Computing replacements for indices " + startIndex + " to " + endIndex); int replacementCount = 0; for (int i = startIndex; i < endIndex; i++) { if (replaceIfBetter(i, i + 1, aPositions) || replaceIfBetter(i + 1, i, aPositions)) { replacementCount++; } } return replacementCount; } })); } for (final Future<Integer> future : futures) { int newReplacementCount = 0; try { newReplacementCount = future.get(); } catch (InterruptedException | ExecutionException e) { logger.log(Level.WARNING, "An error occured while computing the improved track", e); aPositions.clear(); } if (newReplacementCount > 0) replacementOccured = true; replacementCount += newReplacementCount; } } logger.info("Replaced " + replacementCount + " positions by location accuracy"); }
From source file:org.terasology.rendering.nui.layers.mainMenu.preview.FacetLayerPreview.java
private static Rect2i worldToTileArea(Rect2i area) { int chunkMinX = IntMath.divide(area.minX(), TILE_SIZE_X, RoundingMode.FLOOR); int chunkMinZ = IntMath.divide(area.minY(), TILE_SIZE_Y, RoundingMode.FLOOR); int chunkMaxX = IntMath.divide(area.maxX(), TILE_SIZE_X, RoundingMode.CEILING); int chunkMaxZ = IntMath.divide(area.maxY(), TILE_SIZE_Y, RoundingMode.CEILING); return Rect2i.createFromMinAndMax(chunkMinX, chunkMinZ, chunkMaxX, chunkMaxZ); }
From source file:com.github.emabrey.rtmp4j.testing.amf.data.simple.AMF0StringDataProviders.java
/** * Creates a {@code String} filled with the given character that is the * minimum sized {@code String} needed to overflow the AMF0 String type. The * minimum {@code String} size needed to exceed the AMF0 String type differs * based upon the character provided, as the UTF-8 standard has variable * length character encodings. Calculating the optimum size uses memory more * efficiently, and also ensures that no subtle bugs are introduced by using * an arbitrarily large {@code String} simply assumed to be oversized * instead of calculated as such.//from www . j a v a2s. c o m * * @param chosenCharacter Any valid UTF-8 character that can be expressed * with the {@code char} type. * * @return A String composed by repeating the {@code chosenCharacter} the * minimum number of times required to create a String too large for * encoding as an AMF0 String. */ private static String generateOversizedString(final char chosenCharacter) { //Calculate the number of bytes needed to represent the chosen char with UTF-8 encoding final int encodedCharLengthInBytes = String.valueOf(chosenCharacter) .getBytes(StandardCharsets.UTF_8).length; /* UShort.MAX_VALUE / encodedCharLengthInBytes = number of chars that is at least UShort.MAX_VALUE bytes long when encoded as UTF-8. Adding one to that number of characters always gives us a String length of the given character that exceeds the maximum length of valid AMF0 String encodings. */ final int minimumSizeOfOversizedStringComposedOfChosenCharacter = IntMath.divide(UShort.MAX_VALUE, encodedCharLengthInBytes, RoundingMode.UP) + 1; //Create a new String of the calculated size, and replace the null characters with the chosen character //The String being returned is always going to be too large for AMF0 encoding return new String(new char[minimumSizeOfOversizedStringComposedOfChosenCharacter]).replace('\0', chosenCharacter); }
From source file:net.tridentsdk.world.RegionFile.java
/** * Pass in a chunk to save its data to the file *///from w w w . java 2s . c om public void saveChunkData(TridentChunk chunk) throws IOException, NBTException { /* Gets the ChunkData in a byte array form */ ByteArrayOutputStream nbtStream = new ByteArrayOutputStream(); new NBTEncoder(new DataOutputStream(new ByteArrayOutputStream())).encode(chunk.toNbt()); byte[] uncompressed = nbtStream.toByteArray(); /* Gonna only use Zlib compression by default */ Deflater deflater = new Deflater(); deflater.setInput(uncompressed); byte[] compressed = new byte[(int) deflater.getBytesRead()]; deflater.deflate(compressed); /* Compare and sector lengths*/ //The extra byte is for compression type (always saved as 1 for now) int actualLength = compressed.length + 1; //Sector length is rounded up to the nearest sector int sectorLength = IntMath.divide(actualLength, SectorStorage.SECTOR_LENGTH, RoundingMode.CEILING); //Checks if offsets need to change int oldSectorLength = this.sectors.getDataSectors(chunk); //If the length is smaller, we can free up a sector if (sectorLength < oldSectorLength) { this.sectors.setDataSectors(chunk, sectorLength); //Clears up all the now-free sectors this.sectors.freeSectors(this.sectors.getSectorOffset(chunk) + sectorLength - 1, oldSectorLength - sectorLength); } //If the length is bigger, we need to find a new location! else if (sectorLength > oldSectorLength) { this.sectors.setDataSectors(chunk, sectorLength); //Clears up all the space previously used by this chunk (we need to find a new space! this.sectors.freeSectors(this.sectors.getSectorOffset(chunk), oldSectorLength); //Finds a new free location this.sectors.setSectorOffset(chunk, this.sectors.findFreeSectors(sectorLength)); } //Update what sectors are being used this.sectors.addSectors(this.sectors.getSectorOffset(chunk), this.sectors.getDataSectors(chunk)); synchronized (this.readWriteLock) { /* Write the actual chunk data */ //Initialize access to the file RandomAccessFile access = new RandomAccessFile(this.path.toFile(), "rw"); access.seek((long) this.sectors.getDataLocation(chunk)); access.write(actualLength); //We only use compression type 1 (zlib) access.write((int) (byte) 1); access.write(compressed); //Now we pad to the end of the sector... just in-case int paddingNeeded = actualLength % SectorStorage.SECTOR_LENGTH; if (paddingNeeded != 0) { byte[] padding = new byte[paddingNeeded]; access.write(padding); } //Write the new offset data to the header access.seek((long) (4 * this.sectors.getOffsetLoc(chunk))); access.write(this.sectors.getRawOffset(chunk)); //Pack the file as in the specifications this.packFile(access); //Finished writing the chunk access.close(); } }
From source file:org.terasology.awt.world.renderer.BlockTileWorldRenderer.java
public void renderBlockTileWorld(Camera camera, Vector3i centerBlockPosition) { AwtDisplayDevice displayDevice = (AwtDisplayDevice) CoreRegistry.get(DisplayDevice.class); Graphics g1 = displayDevice.getDrawGraphics(); Graphics2D g = (Graphics2D) g1; int width = displayDevice.getWidth(); int height = displayDevice.getHeight(); InputSystem inputSystem = CoreRegistry.get(InputSystem.class); Vector2i mousePosition = inputSystem.getMouseDevice().getPosition(); g.setColor(Color.BLACK);//from w w w. j a va 2 s.co m g.fillRect(0, 0, width, height); int blockTileSize = getBlockTileSize(); int blocksWide = IntMath.divide(width, blockTileSize, RoundingMode.CEILING); int blocksHigh = IntMath.divide(height, blockTileSize, RoundingMode.CEILING); // update chunk production to cover the entire screen ChunkProvider chunkProvider = getChunkProvider(); int chunksWide = blocksWide / ChunkConstants.SIZE_X; int chunksHigh = blocksHigh / ChunkConstants.SIZE_Z; int chunkDist = Math.max(chunksWide, chunksHigh); EntityRef entity = localPlayer.getClientEntity(); chunkProvider.updateRelevanceEntity(entity, chunkDist); RenderMode renderMode; if (blockTileSize == 1) { renderMode = RenderMode.POINT; } else if (blockTileSize <= 4) { renderMode = RenderMode.SQUARE; } else { renderMode = RenderMode.IMAGE; } mapCenterX = (int) ((blocksWide + 0.5f) / 2f); mapCenterY = (int) ((blocksHigh + 0.5f) / 2f); Vector3i behindLocationChange; switch (displayAxisType) { case XZ_AXIS: behindLocationChange = new Vector3i(0, -1, 0); break; case YZ_AXIS: behindLocationChange = new Vector3i(1, 0, 0); break; case XY_AXIS: behindLocationChange = new Vector3i(0, 0, 1); break; default: throw new RuntimeException("illegal displayAxisType " + displayAxisType); } // TODO: If we base what block side we see on viewpoint, this probably needs to go inside the loop BlockPart blockPart; Map<Block, Color> cachedColor; Map<Block, BufferedImage> cachedImages; switch (displayAxisType) { case XZ_AXIS: // top down view blockPart = BlockPart.TOP; cachedColor = cachedColorTop; cachedImages = cachedImagesTop; break; case YZ_AXIS: blockPart = BlockPart.LEFT; // todo: front/left/right/back needs to be picked base on viewpoint cachedColor = cachedColorLeft; cachedImages = cachedImagesLeft; break; case XY_AXIS: blockPart = BlockPart.FRONT; // todo: front/left/right/back needs to be picked base on viewpoint cachedColor = cachedColorFront; cachedImages = cachedImagesFront; break; default: throw new IllegalStateException("displayAxisType is invalid"); } // cachedImages.clear(); // cachedColor.clear(); WorldProvider worldProvider = CoreRegistry.get(WorldProvider.class); WorldAtlas worldAtlas = CoreRegistry.get(WorldAtlas.class); float tileSize = worldAtlas.getRelativeTileSize(); float prevAlpha = -1; for (int i = 0; i < blocksWide; i++) { for (int j = 0; j < blocksHigh; j++) { int dx1 = i * blockTileSize; int dy1 = j * blockTileSize; Vector2i relativeCellLocation = new Vector2i((j - mapCenterY), (i - mapCenterX)); Vector3i relativeLocation; switch (displayAxisType) { case XZ_AXIS: // top down view relativeLocation = new Vector3i(-relativeCellLocation.x, 0, relativeCellLocation.y); break; case YZ_AXIS: relativeLocation = new Vector3i(0, -relativeCellLocation.x, relativeCellLocation.y); break; case XY_AXIS: relativeLocation = new Vector3i(-relativeCellLocation.y, -relativeCellLocation.x, 0); break; default: throw new RuntimeException("displayAxisType containts invalid value"); } relativeLocation.add(centerBlockPosition); Block block = getBlockAtWorldPosition(worldProvider, relativeLocation); if (null != block) { int alphaChangeCounter = 0; float alpha = 1f; while (BlockManager.getAir().equals(block) && (alphaChangeCounter < (depthsOfTransparency - 1))) { alphaChangeCounter++; alpha = darken[alphaChangeCounter]; relativeLocation.add(behindLocationChange); block = getBlockAtWorldPosition(worldProvider, relativeLocation); } // let it remain black if nothing is there if (block != null && !BlockManager.getAir().equals(block)) { Color blockColor = null; BufferedImage blockImage = null; if (renderMode == RenderMode.POINT || renderMode == RenderMode.SQUARE) { blockColor = cachedColor.get(block); } if (renderMode == RenderMode.IMAGE || blockColor == null) { blockImage = cachedImages.get(block); if (null == blockImage) { BlockAppearance primaryAppearance = block.getPrimaryAppearance(); Vector2f textureAtlasPos = primaryAppearance.getTextureAtlasPos(blockPart); Vector2f size = new Vector2f(tileSize, tileSize); TextureRegion textureRegion = new BasicTextureRegion(textureAtlas, textureAtlasPos, size); Rect2i pixelRegion = textureRegion.getPixelRegion(); int sx1 = pixelRegion.minX(); int sy1 = pixelRegion.minY(); int sx2 = sx1 + pixelRegion.width(); // Surprisingly, maxX() is not minX + width() int sy2 = sy1 + pixelRegion.height(); Texture texture = textureRegion.getTexture(); AwtTexture awtTexture = (AwtTexture) texture; BufferedImage fullImage = awtTexture.getBufferedImage(texture.getWidth(), texture.getHeight(), 1f, WHITE); GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment() .getDefaultScreenDevice().getDefaultConfiguration(); int w = pixelRegion.width(); int h = pixelRegion.height(); blockImage = gc.createCompatibleImage(w, h, Transparency.TRANSLUCENT); BufferedImage tiny = gc.createCompatibleImage(1, 1, Transparency.TRANSLUCENT); ImageObserver observer = null; Graphics2D bg = (Graphics2D) blockImage.getGraphics(); bg.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); bg.drawImage(fullImage, 0, 0, w, h, sx1, sy1, sx2, sy2, observer); bg.dispose(); cachedImages.put(block, blockImage); Graphics2D tg = (Graphics2D) tiny.getGraphics(); tg.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); tg.drawImage(fullImage, 0, 0, 1, 1, sx1, sy1, sx2, sy2, observer); tg.dispose(); // I think this is correct, but the color appears to be darker than the average color of the original image blockColor = new Color(tiny.getRGB(0, 0)); cachedColor.put(block, blockColor); } } if (alpha != prevAlpha) { g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha)); } if (renderMode == RenderMode.POINT || renderMode == RenderMode.SQUARE) { int red = (int) (blockColor.getRed() * alpha); int green = (int) (blockColor.getGreen() * alpha); int blue = (int) (blockColor.getBlue() * alpha); blockColor = new Color(red, green, blue); g.setColor(blockColor); if (renderMode == RenderMode.SQUARE) { g.fillRect(dx1, dy1, blockTileSize, blockTileSize); } else { g.drawLine(dx1, dy1, dx1, dy1); } } else { ImageObserver observer = null; g.drawImage(blockImage, dx1, dy1, blockTileSize, blockTileSize, observer); } prevAlpha = alpha; } } if (relativeCellLocation.x == 0 && relativeCellLocation.y == 0) { g.setColor(Color.WHITE); g.setStroke(new BasicStroke(2)); g.drawRect(dx1, dy1, blockTileSize, blockTileSize); } } } g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)); drawCharacterEntities(g, blockTileSize, centerBlockPosition); drawBlockSelection(g, mousePosition); }
From source file:com.meltmedia.dropwizard.etcd.cluster.ClusterAssignmentService.java
public void startNodeAssignmentTask() { logger.info("starting assignment task for {}", thisNode.getId()); assignmentFuture = executor.scheduleWithFixedDelay(() -> { assignmentTask.mark();//from w w w.j av a 2 s . co m try { ProcessorState processorState = this.processorState.getState(); AssignmentState assignmentState = this.assignmentState.get(); State clusterState = stateTracker.getState(); long lastSeenIndex = Math.max(assignmentState.etcdIndex, clusterState.lastModifiedIndex()); if (lastAssignmentIndex > lastSeenIndex) return; boolean active = clusterState.hasMember(thisNode.getId()) && processorState.hasProcessor(this.getId()); int localProcesses = assignmentState.nodeProcessCount(); int unassigned = assignmentState.unassignedProcessCount(); int processorNodes = processorState.processorCount(); int totalProcesses = assignmentState.totalProcessCount(); int maxProcessCount = !active || totalProcesses == 0 || processorNodes == 0 ? 0 : IntMath.divide(assignmentState.totalProcessCount(), processorNodes, RoundingMode.CEILING); boolean giveProcess = localProcesses > maxProcessCount && unassigned == 0; boolean takeProcess = active && localProcesses < maxProcessCount && unassigned > 0; boolean abandonProcess = processorNodes == 0 && localProcesses > 0; boolean terminate = !active && localProcesses == 0; if (terminate) { shutdown.signalAll(); return; } else if (takeProcess) { for (String toAssign : assignmentState.unassigned) { try { lastAssignmentIndex = processDao.update(toAssign, p -> p.getAssignedTo() == null, p -> p.withAssignedTo(thisNode.getId())); return; } catch (IndexOutOfBoundsException | EtcdDirectoryException e) { assignmentFailures.mark(); logger.debug("could not assign process {}", e.getMessage()); } } } else if (giveProcess || abandonProcess) { for (String toUnassign : assignmentState.processes.get(thisNode.getId())) { try { lastAssignmentIndex = processDao.update(toUnassign, p -> thisNode.getId().equals(p.getAssignedTo()), p -> p.withAssignedTo(null)); return; } catch (IndexOutOfBoundsException | EtcdDirectoryException e) { unassignmentFailures.mark(); logger.warn("could not unassign process {}", e.getMessage()); } } } } catch (Exception e) { exceptions.mark(); logger.error("exception thrown in assignment process", e); } }, 100L, 100L, TimeUnit.MILLISECONDS); }
From source file:edu.washington.cs.cupid.views.InspectorView.java
private Row[] generateArrayRows(final Row parent, final String rootName, final Object array, final int offset, final int length) { List<Row> result = Lists.newArrayList(); if (length <= COLLECTION_PARTITION_SIZE) { for (int i = 0; i < length; i++) { result.add(new ClassRow(parent, rootName + "[" + (i + offset) + "]", Array.get(array, offset + i))); }/*ww w. jav a 2s . co m*/ } else { int depth = IntMath.log10(length - 1, RoundingMode.FLOOR); int size = IntMath.pow(COLLECTION_PARTITION_SIZE, depth); int cnt = IntMath.divide(length, size, RoundingMode.CEILING); for (int i = 0; i < cnt; i++) { int start = i * size; int end = Math.min(length - 1, start + size - 1); result.add(new ArrayRow(parent, rootName, array, offset + start, end - start + 1)); } } return result.toArray(new Row[] {}); }
From source file:edu.washington.cs.cupid.views.InspectorView.java
private Row[] generateListRows(final Row parent, final String rootName, final List<?> value, final int offset, final int length) { List<Row> result = Lists.newArrayList(); if (length <= COLLECTION_PARTITION_SIZE) { for (int i = 0; i < length; i++) { result.add(new ClassRow(parent, rootName + "[" + (i + offset) + "]", value.get(i + offset))); }// w w w. jav a 2s. co m } else { int depth = IntMath.log10(length - 1, RoundingMode.FLOOR); int size = IntMath.pow(COLLECTION_PARTITION_SIZE, depth); int cnt = IntMath.divide(length, size, RoundingMode.CEILING); for (int i = 0; i < cnt; i++) { int start = i * size; int end = Math.min(length - 1, start + size - 1); result.add(new ListRow(parent, rootName, value, offset + start, end - start + 1)); } } return result.toArray(new Row[] {}); }
From source file:com.google.gerrit.httpd.restapi.RestApiServlet.java
private static BinaryResult base64(BinaryResult bin) throws IOException { int max = 4 * IntMath.divide((int) bin.getContentLength(), 3, CEILING); TemporaryBuffer.Heap buf = heap(max); OutputStream encoded = BaseEncoding.base64() .encodingStream(new OutputStreamWriter(buf, Charsets.ISO_8859_1)); bin.writeTo(encoded);//from w w w. j a va 2s .co m encoded.close(); return asBinaryResult(buf); }