List of usage examples for java.lang Math max
@HotSpotIntrinsicCandidate public static double max(double a, double b)
From source file:Main.java
/** * Applies the given style to a range of the input CharSequence. * @param style The style to apply (see the style constants in {@link Typeface}). * @param input The CharSequence to style. * @param start Starting index of the range to style (will be clamped to be a minimum of 0). * @param end Ending index of the range to style (will be clamped to a maximum of the input * length).//from w ww .j av a 2 s .c om * @param flags Bitmask for configuring behavior of the span. See {@link android.text.Spanned}. * @return The styled CharSequence. */ public static CharSequence applyStyleToSpan(int style, CharSequence input, int start, int end, int flags) { // Enforce bounds of the char sequence. start = Math.max(0, start); end = Math.min(input.length(), end); SpannableString text = new SpannableString(input); text.setSpan(new StyleSpan(style), start, end, flags); return text; }
From source file:Main.java
/** * Returns a collection that simulates concurrent modification by * having its size method return incorrect values. This is useful * for testing methods that must treat the return value from size() * as a hint only.//from www . j a va 2s. c om * * @param delta the difference between the true size of the * collection and the values returned by the size method */ public static <T> Collection<T> misleadingSizeCollection(final int delta) { // It would be nice to be able to return a real concurrent // collection like ConcurrentLinkedQueue, so that e.g. concurrent // iteration would work, but that would not be GWT-compatible. return new ArrayList<T>() { @Override public int size() { return Math.max(0, super.size() + delta); } }; }
From source file:Main.java
/** * Adjusts the widths and heights of the cells of the supplied table to fit their contents. *//*from www. ja v a2s . c om*/ public static void sizeToContents(JTable table) { TableModel model = table.getModel(); TableColumn column = null; Component comp = null; int ccount = table.getColumnModel().getColumnCount(), rcount = model.getRowCount(), cellHeight = 0; for (int cc = 0; cc < ccount; cc++) { int headerWidth = 0, cellWidth = 0; column = table.getColumnModel().getColumn(cc); try { comp = column.getHeaderRenderer().getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0); headerWidth = comp.getPreferredSize().width; } catch (NullPointerException e) { // getHeaderRenderer() this doesn't work in 1.3 } for (int rr = 0; rr < rcount; rr++) { Object cellValue = model.getValueAt(rr, cc); comp = table.getDefaultRenderer(model.getColumnClass(cc)).getTableCellRendererComponent(table, cellValue, false, false, 0, cc); Dimension psize = comp.getPreferredSize(); cellWidth = Math.max(psize.width, cellWidth); cellHeight = Math.max(psize.height, cellHeight); } column.setPreferredWidth(Math.max(headerWidth, cellWidth)); } if (cellHeight > 0) { table.setRowHeight(cellHeight); } }
From source file:fr.inria.atlanmod.dag.instantiator.Launcher.java
public static void main(String[] args) throws GenerationException, IOException { ResourceSetImpl resourceSet = new ResourceSetImpl(); { // initializing the registry resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(EcorePackage.eNS_PREFIX, new EcoreResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap() .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoEMFURI.NEOEMF_HBASE_SCHEME, NeoEMFResourceFactory.eINSTANCE); }/*from ww w.jav a 2 s . com*/ Options options = new Options(); configureOptions(options); CommandLineParser parser = new GnuParser(); try { CommandLine commandLine = parser.parse(options, args); // String epackage_class = commandLine.getOptionValue(E_PACKAGE_CLASS); // // LOGGER.info("Start loading the package"); // Class<?> inClazz = Launcher.class.getClassLoader().loadClass(epackage_class); // EPackage _package = (EPackage) inClazz.getMethod("init").invoke(null); // // Resource metamodelResource = new XMIResourceImpl(URI.createFileURI("dummy")); // metamodelResource.getContents().add(_package); // LOGGER.info("Finish loading the package"); int size = Launcher.DEFAULT_AVERAGE_MODEL_SIZE; if (commandLine.hasOption(SIZE)) { Number number = (Number) commandLine.getParsedOptionValue(SIZE); size = (int) Math.min(Integer.MAX_VALUE, number.longValue()); } float variation = Launcher.DEFAULT_DEVIATION; if (commandLine.hasOption(VARIATION)) { Number number = (Number) commandLine.getParsedOptionValue(VARIATION); if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) { throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}", VARIATION, number.floatValue())); } variation = number.floatValue(); } float propVariation = Launcher.DEFAULT_DEVIATION; if (commandLine.hasOption(PROP_VARIATION)) { Number number = (Number) commandLine.getParsedOptionValue(PROP_VARIATION); if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) { throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}", PROP_VARIATION, number.floatValue())); } propVariation = number.floatValue(); } long seed = System.currentTimeMillis(); if (commandLine.hasOption(SEED)) { seed = ((Number) commandLine.getParsedOptionValue(SEED)).longValue(); } Range<Integer> range = Range.between(Math.round(size * (1 - variation)), Math.round(size * (1 + variation))); ISpecimenConfiguration config = new DagMetamodelConfig(range, seed); IGenerator generator = new DagGenerator(config, config.getSeed()); GenericMetamodelGenerator modelGen = new GenericMetamodelGenerator(generator); if (commandLine.hasOption(OUTPUT_PATH)) { String outDir = commandLine.getOptionValue(OUTPUT_PATH); //java.net.URI intermediateURI = java.net.URI.create(outDir); modelGen.setSamplesPath(outDir); } int numberOfModels = 1; if (commandLine.hasOption(N_MODELS)) { numberOfModels = ((Number) commandLine.getParsedOptionValue(N_MODELS)).intValue(); } int valuesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_VALUES_LENGTH; if (commandLine.hasOption(VALUES_SIZE)) { Number number = (Number) commandLine.getParsedOptionValue(VALUES_SIZE); valuesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue()); } int referencesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_REFERENCES_SIZE; if (commandLine.hasOption(DEGREE)) { Number number = (Number) commandLine.getParsedOptionValue(DEGREE); referencesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue()); } config.setValuesRange(Math.round(valuesSize * (1 - propVariation)), Math.round(valuesSize * (1 + propVariation))); config.setReferencesRange(Math.round(referencesSize * (1 - propVariation)), Math.round(referencesSize * (1 + propVariation))); config.setPropertiesRange(Math.round(referencesSize * (1 - propVariation)), Math.round(referencesSize * (1 + propVariation))); long start = System.currentTimeMillis(); modelGen.runGeneration(resourceSet, numberOfModels, size, variation); long end = System.currentTimeMillis(); LOGGER.info( MessageFormat.format("Generation finished after {0} s", Long.toString((end - start) / 1000))); // for (Resource rsc : resourceSet.getResources()) { // if (rsc.getContents().get(0) instanceof DAG) { // // } // // } if (commandLine.hasOption(DIAGNOSE)) { for (Resource resource : resourceSet.getResources()) { LOGGER.info( MessageFormat.format("Requested validation for resource ''{0}''", resource.getURI())); BasicDiagnostic diagnosticChain = diagnoseResource(resource); if (!isFailed(diagnosticChain)) { LOGGER.info(MessageFormat.format("Result of the diagnosis of resurce ''{0}'' is ''OK''", resource.getURI())); } else { LOGGER.severe(MessageFormat.format("Found ''{0}'' error(s) in the resource ''{1}''", diagnosticChain.getChildren().size(), resource.getURI())); for (Diagnostic diagnostic : diagnosticChain.getChildren()) { LOGGER.fine(diagnostic.getMessage()); } } } LOGGER.info("Validation finished"); } } catch (ParseException e) { System.err.println(e.getLocalizedMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.setOptionComparator(new OptionComarator<Option>()); try { formatter.setWidth(Math.max(Terminal.getTerminal().getTerminalWidth(), 80)); } catch (Throwable t) { LOGGER.warning("Unable to get console information"); } ; formatter.printHelp("java -jar <this-file.jar>", options, true); System.exit(ERROR); } catch (Throwable t) { System.err.println("ERROR: " + t.getLocalizedMessage()); StringWriter stringWriter = new StringWriter(); t.printStackTrace(new PrintWriter(stringWriter)); System.err.println(t); LOGGER.severe(stringWriter.toString()); System.exit(ERROR); } }
From source file:Main.java
/** * Given a uri that represents a qualified name, tries to * determine the index of the split point between the namespace * and the local name. Returns the last index of #, /, or :, * checking for each. If the string contains no :, it doesn't count * as a uri and nothing is returned./* w w w. j ava2 s. co m*/ * @param uri the uri * @return the split point, or -1 if not found */ public static int getQNameSplitPoint(String uri) { int col = uri.indexOf(":"); if (col < 0) { return -1; } else { int hash = uri.indexOf("#"); if (hash < 0) { int slash = Math.max(uri.lastIndexOf("/"), uri.lastIndexOf("\\")); if (slash > 0) { return slash; } else { return col; } } else { return hash; } } }
From source file:lu.lippmann.cdb.ext.hydviga.ui.GapsUIUtil.java
public static ChartPanel buildGapChartPanel(final Instances dataSet, final int dateIdx, final Attribute attr, final int gapsize, final int position) throws Exception { Instances filteredDs = WekaDataProcessingUtil.buildFilteredByAttributesDataSet(dataSet, new int[] { attr.index(), dateIdx }); filteredDs = WekaDataProcessingUtil.buildFilteredDataSet(filteredDs, 0, filteredDs.numAttributes() - 1, Math.max(0, position - GapsUtil.VALUES_BEFORE_AND_AFTER_RATIO * gapsize), Math.min(position + gapsize + GapsUtil.VALUES_BEFORE_AND_AFTER_RATIO * gapsize, filteredDs.numInstances() - 1)); final ChartPanel cp = TimeSeriesChartUtil.buildChartPanelForAllAttributes(filteredDs, false, WekaDataStatsUtil.getFirstDateAttributeIdx(filteredDs), null); final XYPlot xyp = (XYPlot) cp.getChart().getPlot(); xyp.getDomainAxis().setLabel(""); xyp.getRangeAxis().setLabel(""); final Marker gapBeginMarker = new ValueMarker(dataSet.instance(Math.max(0, position - 1)).value(dateIdx)); gapBeginMarker.setPaint(Color.RED); gapBeginMarker.setLabel("Gap begin"); gapBeginMarker.setLabelAnchor(RectangleAnchor.TOP_LEFT); gapBeginMarker.setLabelTextAnchor(TextAnchor.TOP_RIGHT); cp.getChart().getXYPlot().addDomainMarker(gapBeginMarker); final Marker gapEndMarker = new ValueMarker( dataSet.instance(Math.min(dataSet.numInstances() - 1, position + gapsize)).value(dateIdx)); gapEndMarker.setPaint(Color.RED); gapEndMarker.setLabel("Gap end"); gapEndMarker.setLabelAnchor(RectangleAnchor.TOP_RIGHT); gapEndMarker.setLabelTextAnchor(TextAnchor.TOP_LEFT); cp.getChart().getXYPlot().addDomainMarker(gapEndMarker); addExportPopupMenu(filteredDs, cp);/*w w w.j ava 2s . c o m*/ return cp; }
From source file:Main.java
/** * Transform source Bitmap to targeted width and height. *///from w w w . j ava 2s.c o m private static Bitmap transform(Matrix scaler, Bitmap source, int targetWidth, int targetHeight, int options) { boolean scaleUp = (options & OPTIONS_SCALE_UP) != 0; boolean recycle = (options & OPTIONS_RECYCLE_INPUT) != 0; int deltaX = source.getWidth() - targetWidth; int deltaY = source.getHeight() - targetHeight; if (!scaleUp && (deltaX < 0 || deltaY < 0)) { /* * In this case the bitmap is smaller, at least in one dimension, * than the target. Transform it by placing as much of the image * as possible into the target and leaving the top/bottom or * left/right (or both) black. */ Bitmap b2 = Bitmap.createBitmap(targetWidth, targetHeight, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(b2); int deltaXHalf = Math.max(0, deltaX / 2); int deltaYHalf = Math.max(0, deltaY / 2); Rect src = new Rect(deltaXHalf, deltaYHalf, deltaXHalf + Math.min(targetWidth, source.getWidth()), deltaYHalf + Math.min(targetHeight, source.getHeight())); int dstX = (targetWidth - src.width()) / 2; int dstY = (targetHeight - src.height()) / 2; Rect dst = new Rect(dstX, dstY, targetWidth - dstX, targetHeight - dstY); c.drawBitmap(source, src, dst, null); if (recycle) { source.recycle(); } c.setBitmap(null); return b2; } float bitmapWidthF = source.getWidth(); float bitmapHeightF = source.getHeight(); float bitmapAspect = bitmapWidthF / bitmapHeightF; float viewAspect = (float) targetWidth / targetHeight; if (bitmapAspect > viewAspect) { float scale = targetHeight / bitmapHeightF; if (scale < .9F || scale > 1F) { scaler.setScale(scale, scale); } else { scaler = null; } } else { float scale = targetWidth / bitmapWidthF; if (scale < .9F || scale > 1F) { scaler.setScale(scale, scale); } else { scaler = null; } } Bitmap b1; if (scaler != null) { // this is used for minithumb and crop, so we want to filter here. b1 = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), scaler, true); } else { b1 = source; } if (recycle && b1 != source) { source.recycle(); } int dx1 = Math.max(0, b1.getWidth() - targetWidth); int dy1 = Math.max(0, b1.getHeight() - targetHeight); Bitmap b2 = Bitmap.createBitmap(b1, dx1 / 2, 0, targetWidth, targetHeight); if (b2 != b1) { if (recycle || b1 != source) { b1.recycle(); } } return b2; }
From source file:Main.java
/** * This method determines if the direction of a substring is right-to-left. * If the string is empty that determination is based on the default system language * Locale.getDefault().//from w w w . ja v a 2s.co m * The method can handle invalid substring definitions (start > end etc.), in which case the * method returns False. * * @return True if the text direction is right-to-left, false otherwise. */ public static boolean isRTL(CharSequence s, int start, int end) { if (s == null || s.length() == 0) { // empty string --> determine the direction from the default language return isRTL(Locale.getDefault()); } if (start == end) { // if no character is selected we need to expand the selection start = Math.max(0, --start); if (start == end) { end = Math.min(s.length(), ++end); } } try { Bidi bidi = new Bidi(s.subSequence(start, end).toString(), Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT); return !bidi.baseIsLeftToRight(); } catch (IndexOutOfBoundsException e) { return false; } }
From source file:Main.java
/** * Transform source Bitmap to targeted width and height. *//*from w ww. java 2s .c o m*/ private static Bitmap transform(Matrix scaler, Bitmap source, int targetWidth, int targetHeight, int options) { boolean scaleUp = (options & OPTIONS_SCALE_UP) != 0; boolean recycle = (options & OPTIONS_RECYCLE_INPUT) != 0; int deltaX = source.getWidth() - targetWidth; int deltaY = source.getHeight() - targetHeight; if (!scaleUp && (deltaX < 0 || deltaY < 0)) { /* * In this case the bitmap is smaller, at least in one dimension, * than the target. Transform it by placing as much of the image as * possible into the target and leaving the top/bottom or left/right * (or both) black. */ Bitmap b2 = Bitmap.createBitmap(targetWidth, targetHeight, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(b2); int deltaXHalf = Math.max(0, deltaX / 2); int deltaYHalf = Math.max(0, deltaY / 2); Rect src = new Rect(deltaXHalf, deltaYHalf, deltaXHalf + Math.min(targetWidth, source.getWidth()), deltaYHalf + Math.min(targetHeight, source.getHeight())); int dstX = (targetWidth - src.width()) / 2; int dstY = (targetHeight - src.height()) / 2; Rect dst = new Rect(dstX, dstY, targetWidth - dstX, targetHeight - dstY); c.drawBitmap(source, src, dst, null); if (recycle) { source.recycle(); } c.setBitmap(null); return b2; } float bitmapWidthF = source.getWidth(); float bitmapHeightF = source.getHeight(); float bitmapAspect = bitmapWidthF / bitmapHeightF; float viewAspect = (float) targetWidth / targetHeight; if (bitmapAspect > viewAspect) { float scale = targetHeight / bitmapHeightF; if (scale < .9F || scale > 1F) { scaler.setScale(scale, scale); } else { scaler = null; } } else { float scale = targetWidth / bitmapWidthF; if (scale < .9F || scale > 1F) { scaler.setScale(scale, scale); } else { scaler = null; } } Bitmap b1; if (scaler != null) { // this is used for minithumb and crop, so we want to filter here. b1 = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), scaler, true); } else { b1 = source; } if (recycle && b1 != source) { source.recycle(); } int dx1 = Math.max(0, b1.getWidth() - targetWidth); int dy1 = Math.max(0, b1.getHeight() - targetHeight); Bitmap b2 = Bitmap.createBitmap(b1, dx1 / 2, dy1 / 2, targetWidth, targetHeight); if (b2 != b1) { if (recycle || b1 != source) { b1.recycle(); } } return b2; }
From source file:Main.java
public static void setBestExposure(Camera.Parameters parameters, boolean lightOn) { int minExposure = parameters.getMinExposureCompensation(); int maxExposure = parameters.getMaxExposureCompensation(); float step = parameters.getExposureCompensationStep(); if ((minExposure != 0 || maxExposure != 0) && step > 0.0f) { // Set low when light is on float targetCompensation = lightOn ? MIN_EXPOSURE_COMPENSATION : MAX_EXPOSURE_COMPENSATION; int compensationSteps = Math.round(targetCompensation / step); // float actualCompensation = step * compensationSteps; // Clamp value: compensationSteps = Math.max(Math.min(compensationSteps, maxExposure), minExposure); if (parameters.getExposureCompensation() != compensationSteps) { // Log.i(TAG, "Exposure compensation already set to " + compensationSteps + " / " + actualCompensation); // } else { // Log.i(TAG, "Setting exposure compensation to " + compensationSteps + " / " + actualCompensation); parameters.setExposureCompensation(compensationSteps); }//w w w.ja v a2s .co m // } else { // Log.i(TAG, "Camera does not support exposure compensation"); } }