List of usage examples for java.lang Float MAX_VALUE
float MAX_VALUE
To view the source code for java.lang Float MAX_VALUE.
Click Source Link
From source file:it.uniroma2.sag.kelp.learningalgorithm.clustering.kernelbasedkmeans.KernelBasedKMeansEngine.java
@Override public ClusterList cluster(Dataset dataset, ExampleSelector seedSelector) { /*/*from w w w .j a va2 s . com*/ * Check consistency: the number of input examples MUST be greater or * equal to the target K */ if (dataset.getNumberOfExamples() < k) { System.err.println("Error: the number of instances (" + dataset.getNumberOfExamples() + ") must be higher than k (" + k + ")"); return null; } /* * Alphas Value are stored */ for (Example example : dataset.getExamples()) { alphas.put(example, 1.0f); } /* * Initialize seed and outputStructures */ ClusterList resClusters = new ClusterList(); List<Example> seedVector = seedSelector.select(dataset); for (int clusterId = 0; clusterId < k; clusterId++) { resClusters.add(new Cluster("cluster_" + clusterId)); if (clusterId < seedVector.size()) { KernelBasedKMeansExample kernelBasedKMeansExample = new KernelBasedKMeansExample( seedVector.get(clusterId), 0); resClusters.get(clusterId).add(kernelBasedKMeansExample); } } /* * Do Work */ // For each iteration for (int t = 0; t < maxIterations; t++) { int reassignment; logger.debug("\nITERATION:\t" + (t + 1)); TreeMap<Long, Integer> exampleIdToClusterMap = new TreeMap<Long, Integer>(); HashMap<Example, Float> minDistances = new HashMap<Example, Float>(); /* * Searching for the nearest cluster */ for (Example example : dataset.getExamples()) { float minValue = Float.MAX_VALUE; int targetCluster = -1; for (int clusterId = 0; clusterId < k; clusterId++) { float d = calculateDistance(example, resClusters.get(clusterId)); logger.debug("Distance of " + example.getId() + " from cluster " + clusterId + ":\t" + d); if (d < minValue) { minValue = d; targetCluster = clusterId; } } minDistances.put(example, minValue); exampleIdToClusterMap.put(example.getId(), targetCluster); } /* * Counting reassignments */ reassignment = countReassigment(exampleIdToClusterMap, resClusters); logger.debug("Reassigments:\t" + reassignment); /* * Updating */ for (int i = 0; i < resClusters.size(); i++) resClusters.get(i).clear(); this.thirdMemberEqBuffer.clear(); for (Example example : dataset.getExamples()) { logger.debug( "Re-assigning " + example.getId() + " to " + exampleIdToClusterMap.get(example.getId())); int assignedClusterId = exampleIdToClusterMap.get(example.getId()); float minDist = minDistances.get(example); KernelBasedKMeansExample kernelBasedKMeansExample = new KernelBasedKMeansExample(example, minDist); resClusters.get(assignedClusterId).add(kernelBasedKMeansExample); } if (t > 0 && reassignment == 0) { break; } } /* * Sort results by distance from the controid. */ for (Cluster c : resClusters) { c.sortAscendingOrder(); } return resClusters; }
From source file:com.choicemaker.cm.modelmaker.gui.panels.HoldVsAccuracyPlotPanel.java
private void display() { com.choicemaker.cm.modelmaker.stats.Statistics stats = parent.getModelMaker().getStatistics(); StatPoint ptb = new StatPoint(); ptb.humanReview = 0f;/*from www . ja va 2 s .c om*/ stats.computeStatPoint(ptb); float from = Math.max(0.001f, Math.min(0.1f, Float.isNaN(ptb.falseNegatives) || Float.isNaN(ptb.falsePositives) ? Float.MAX_VALUE : Math.max(ptb.falseNegatives, ptb.falsePositives))); int numPoints = 101; float step = from / (numPoints - 1); errorRates = new float[numPoints]; for (int i = 0; i < numPoints; ++i) { errorRates[i] = from - i * step; } dirty = false; if (parent.isEvaluated()) { reset(); float[][] res = stats.getHoldPercentageVsAccuracy(errorRates); final int len = res.length; float lastX = Float.NaN; for (int i = 0; i < len; ++i) { final float hr = 100 * res[i][1]; final float x = 100f - 100 * res[i][0]; if (!Float.isNaN(x) && x != lastX && !Float.isNaN(hr)) { data.add(x, hr); lastX = x; } } } accuracyData = stats.getHoldPercentageVsAccuracy(accErrs); accuracyTable.refresh(accuracyData); StatPoint pt = new StatPoint(); hrData = new float[hrs.length][4]; for (int i = 0; i < hrs.length; ++i) { pt.reset(); pt.humanReview = hrs[i]; stats.computeStatPoint(pt); hrData[i][0] = hrs[i]; hrData[i][1] = 1f - (pt.falseNegatives + pt.falsePositives) / 2; hrData[i][2] = pt.differThreshold; hrData[i][3] = pt.matchThreshold; } hrTable.refresh(hrData); accuracyTable.setEnabled(true); hrTable.setEnabled(true); }
From source file:org.jts.eclipse.conversion.cjsidl.ConversionUtil.java
/** * Used to fill a gap where a maximum value isn't specified in a range. * @param val - the current value, if there is one. * @param inputType - the input data type that the maximum should fit within * // w w w . j a va2 s .com * @return - the original value if it exists, or the maximum value allowed within * the inputType specified. */ public static String getCountMax(String val, String inputType) { String result = val; if (result == null || result.isEmpty()) { if (inputType.equals("byte") || inputType.equals("int8")) { result = Byte.toString(Byte.MAX_VALUE); } else if (inputType.equals("short integer") || inputType.equals("int16")) { result = Short.toString(Short.MAX_VALUE); } else if (inputType.equals("integer") || inputType.equals("int32")) { result = Integer.toString(Integer.MAX_VALUE); } else if (inputType.equals("long integer") || inputType.equals("int64")) { result = Long.toString(Long.MAX_VALUE); } else if (inputType.equals("unsigned byte") || inputType.equals("uint8")) { result = Short.toString((short) (Byte.MAX_VALUE * 2 + 1)); } else if (inputType.equals("unsigned short integer") || inputType.equals("uint16")) { result = Integer.toString((int) (Short.MAX_VALUE * 2 + 1)); } else if (inputType.equals("unsigned integer") || inputType.equals("uint32")) { result = Long.toString((long) (Integer.MAX_VALUE * 2 + 1)); } else if (inputType.equals("unsigned long integer") || inputType.equals("uint64")) { result = "18446744073709551615"; } else if (inputType.equals("float") || inputType.equals("float")) { result = Float.toString(Float.MAX_VALUE); } else if (inputType.equals("long float") || inputType.equals("double")) { result = Double.toString(Double.MAX_VALUE); } } return result; }
From source file:com.siemens.industrialbenchmark.dynamics.IndustrialBenchmarkDynamics.java
/** * initialize the industrial benchmark// w w w. ja v a 2s . com * @throws PropertiesException */ protected void init() throws PropertiesException { // configure convolution variables CRGS = PropertiesUtil.getFloat(mProperties, "CRGS", true); mEmConvWeights = getFloatArray(mProperties.getProperty("ConvArray")); markovStateAdditionalNames = new ArrayList<String>(); mOperationalCostsBuffer = new CircularFifoBuffer(mEmConvWeights.length); for (int i = 0; i < mEmConvWeights.length; i++) { mOperationalCostsBuffer.add(0.0d); // initialize all operationalcosts with zero markovStateAdditionalNames.add("OPERATIONALCOST_" + i); // add operationalcost_lag to list of convoluted markov variables } markovStateAdditionalNames.addAll(MarkovianStateDescription.getNonConvolutedInternalVariables()); // add variables from external driver List<String> extNames = new ArrayList<String>(); for (ExternalDriver d : this.externalDrivers) { for (String n : d.getState().getKeys()) { if (!extNames.contains(n)) { extNames.add(n); } } } markovStateAdditionalNames.addAll(extNames); //markovStateAdditionalNames.addAll(extDriver.getState().getKeys()); // instantiate markov state with additional convolution variable names markovState = new MarkovianState(markovStateAdditionalNames); mMin = new MarkovianState(markovStateAdditionalNames); // lower variable boundaries mMax = new MarkovianState(markovStateAdditionalNames); // upper variable boundaries // extract variable boundings + initial values from Properties for (String v : this.markovState.getKeys()) { float init = PropertiesUtil.getFloat(mProperties, v + "_INIT", 0); float max = PropertiesUtil.getFloat(mProperties, v + "_MAX", Float.MAX_VALUE); float min = PropertiesUtil.getFloat(mProperties, v + "_MIN", -Float.MAX_VALUE); Preconditions.checkArgument(max > min, "variable=%s: max=%s must be > than min=%s", v, max, min); Preconditions.checkArgument(init >= min && init <= max, "variable=%s: init=%s must be between min=%s and max=%s", v, init, min, max); mMax.setValue(v, max); mMin.setValue(v, min); markovState.setValue(v, init); } // seed all random number generators for allowing to re-conduct the experiment randomSeed = PropertiesUtil.getLong(mProperties, "SEED", System.currentTimeMillis()); //mLogger.debug("init seed: " + randomSeed); rda.reSeed(randomSeed); //extDriver.setSeed(rda.nextLong(0, Long.MAX_VALUE)); for (ExternalDriver d : this.externalDrivers) { d.setSeed(rda.nextLong(0, Long.MAX_VALUE)); d.filter(markovState); } this.gsEnvironment = new GoldstoneEnvironment(24, maxRequiredStep, maxRequiredStep / 2.0); // set all NaN values to 0.0 for (String key : markovState.getKeys()) { if (Double.isNaN(markovState.getValue(key))) { markovState.setValue(key, 0.0); } } //for (String key : markovState.getKeys()) { // mLogger.debug(key + "=" + markovState.getValue(key)); //} //System.exit(-1); //mRewardCore.setNormal(rda); }
From source file:org.opencms.ade.sitemap.CmsSitemapNavPosCalculator.java
/** * Creates a new sitemap navigation position calculator and performs the navigation position calculation for a given * insertion operation.<p>/*from w ww. j a va2s . c o m*/ * * @param navigation the existing navigation element list * @param movedElement the resource which should be inserted * @param insertPosition the insertion position in the list */ public CmsSitemapNavPosCalculator(List<CmsJspNavElement> navigation, CmsResource movedElement, int insertPosition) { List<CmsJspNavElement> workList = new ArrayList<CmsJspNavElement>(navigation); CmsJspNavElement dummyNavElement = new CmsJspNavElement(DUMMY_PATH, movedElement, new HashMap<String, String>()); // There may be another navigation element for the same resource in the navigation, so remove it for (int i = 0; i < workList.size(); i++) { CmsJspNavElement currentElement = workList.get(i); if ((i != insertPosition) && currentElement.getResource().getStructureId().equals(movedElement.getStructureId())) { workList.remove(i); break; } } if (insertPosition > workList.size()) { // could happen if the navigation was concurrently changed by another user insertPosition = workList.size(); } // First, insert the dummy element at the correct position in the list. workList.add(insertPosition, dummyNavElement); // now remove elements which aren't actually part of the navigation Iterator<CmsJspNavElement> it = workList.iterator(); while (it.hasNext()) { CmsJspNavElement nav = it.next(); if (!nav.isInNavigation() && (nav != dummyNavElement)) { it.remove(); } } insertPosition = workList.indexOf(dummyNavElement); m_insertPositionInResult = insertPosition; /* * Now calculate the "block" of the inserted element. * The block is the range of indices for which the navigation * positions need to be updated. This range only needs to contain * more than the inserted element if it was inserted either between two elements * with the same navigation position or after an element with Float.MAX_VALUE * navigation position. In either of those two cases, the block will contain * all elements with the same navigation position. */ int blockStart = insertPosition; int blockEnd = insertPosition + 1; PositionInfo before = getPositionInfo(workList, insertPosition - 1); PositionInfo after = getPositionInfo(workList, insertPosition + 1); boolean extendBlock = false; float blockValue = 0; if (before.isMax()) { blockValue = Float.MAX_VALUE; extendBlock = true; } else if (before.isNormal() && after.isNormal() && (before.getNavPos() == after.getNavPos())) { blockValue = before.getNavPos(); extendBlock = true; } if (extendBlock) { while ((blockStart > 0) && (workList.get(blockStart - 1).getNavPosition() == blockValue)) { blockStart -= 1; } while ((blockEnd < workList.size()) && ((blockEnd == (insertPosition + 1)) || (workList.get(blockEnd).getNavPosition() == blockValue))) { blockEnd += 1; } } /* * Now calculate the new navigation positions for the elements in the block using the information * from the elements directly before and after the block, and set the positions in the nav element * instances. */ PositionInfo beforeBlock = getPositionInfo(workList, blockStart - 1); PositionInfo afterBlock = getPositionInfo(workList, blockEnd); // now calculate the new navigation positions for the elements in the block ( List<Float> newNavPositions = interpolatePositions(beforeBlock, afterBlock, blockEnd - blockStart); for (int i = 0; i < (blockEnd - blockStart); i++) { workList.get(i + blockStart).setNavPosition(newNavPositions.get(i).floatValue()); } m_resultList = Collections.unmodifiableList(workList); }
From source file:au.org.ala.delta.intkey.WriteOnceIntkeyItemsFile.java
public void writeAttributeFloats(int charNumber, BitSet inapplicableBits, List<FloatRange> values, List<Float> keyStateBoundaries) { int record = updateCharacterIndex(charNumber); List<Integer> inapplicable = bitSetToInts(inapplicableBits, _header.getNItem()); record += writeToRecord(record, inapplicable); List<Float> floats = new ArrayList<Float>(); for (FloatRange range : values) { // Special cases, Float.MAX_VALUE indicates coded unknown. // -Float.MIN_VALUE indicates uncoded unknown if (range.getMinimumFloat() == Float.MAX_VALUE) { // These somewhat strange values are for CONFOR compatibility floats.add((float) CONFOR_INT_MAX); floats.add(-(float) CONFOR_INT_MAX); } else if (range.getMaximumFloat() == -Float.MAX_VALUE) { floats.add(1f);//www . jav a 2 s. c om floats.add(0f); } else { floats.add(range.getMinimumFloat()); floats.add(range.getMaximumFloat()); } } writeFloatsToRecord(record, floats); int recordNum = nextAvailableRecord(); writeToRecord(recordNum, keyStateBoundaries.size()); writeFloatsToRecord(recordNum + 1, keyStateBoundaries); if (_keyStateBoundariesIndex == null) { _keyStateBoundariesIndex = new int[_header.getNChar()]; Arrays.fill(_keyStateBoundariesIndex, 0); } _keyStateBoundariesIndex[charNumber - 1] = recordNum; _header.setLSbnd(_header.getLSbnd() + keyStateBoundaries.size()); _header.setLkstat(Math.max(_header.getLkstat(), keyStateBoundaries.size())); }
From source file:org.globus.examples.services.filebuy.broker.impl.FileBrokerService.java
public FindResponse find(Find params) throws RemoteException { /* Retrieve parameters */ String name = params.getName(); float maxPrice = params.getMaxPrice(); logger.debug("find invoked with name=" + name + ",maxPrice=" + maxPrice); /* Create response object */ FindResponse response = new FindResponse(); /*//from w ww. j av a 2 s .c om * QUERY INDEX SERVICE */ // Create index service EPR FileBrokerConfiguration conf = null; try { conf = FileBrokerConfiguration.getConfObject(); } catch (Exception e) { logger.error("ERROR: Unable to obtain FileBroker configuration object (JNDI)."); throw new RemoteException("ERROR: Unable to obtain FileBroker configuration object (JNDI).", e); } String indexURI = conf.getIndexURI(); EndpointReferenceType indexEPR = new EndpointReferenceType(); try { indexEPR.setAddress(new Address(indexURI)); } catch (Exception e) { logger.error("ERROR: Malformed index URI '" + indexURI + "'"); throw new RemoteException("ERROR: Malformed index URI '" + indexURI + "'", e); } // Get QueryResourceProperties portType WSResourcePropertiesServiceAddressingLocator queryLocator; queryLocator = new WSResourcePropertiesServiceAddressingLocator(); QueryResourceProperties_PortType query = null; try { query = queryLocator.getQueryResourcePropertiesPort(indexEPR); } catch (ServiceException e) { logger.error("ERROR: Unable to obtain query portType."); throw new RemoteException("ERROR: Unable to obtain query portType.", e); } // Setup security options ((Stub) query)._setProperty(Constants.GSI_TRANSPORT, Constants.SIGNATURE); ((Stub) query)._setProperty(Constants.AUTHORIZATION, NoAuthorization.getInstance()); // The following XPath query retrieves all the files with the specified // name String xpathQuery = "//*[local-name()='Entry'][./*/*/*[local-name()='Name']/text()='" + name + "']"; // Create request to QueryResourceProperties QueryExpressionType queryExpr = new QueryExpressionType(); try { queryExpr.setDialect(new URI(WSRFConstants.XPATH_1_DIALECT)); } catch (Exception e) { logger.error("ERROR: Malformed URI (WSRFConstants.XPATH_1_DIALECT)"); throw new RemoteException("ERROR: Malformed URI (WSRFConstants.XPATH_1_DIALECT)", e); } queryExpr.setValue(xpathQuery); QueryResourceProperties_Element queryRequest = new QueryResourceProperties_Element(queryExpr); // Invoke QueryResourceProperties QueryResourcePropertiesResponse queryResponse = null; try { queryResponse = query.queryResourceProperties(queryRequest); } catch (RemoteException e) { logger.error("ERROR: Unable to invoke QueryRP operation."); throw new RemoteException("ERROR: Unable to invoke QueryRP operation.", e); } // The response includes 0 or more entries from the index service. MessageElement[] entries = queryResponse.get_any(); /* * FIND THE CHEAPEST FILE */ // If the number of entries is 0, there are no files with that name. if (entries == null || entries.length == 0) { logger.debug("No file found with name " + name); // We return a null EPR to indicate that no file has // been found meeting the specified criteria. // Ideally, we should throw a custom exception. response.setFileOrderEPR(null); } else { // We know that there is at least one file with the specified name. // Now, we find the cheapest file, to then see if it meets the // price restriction float minPrice = Float.MAX_VALUE; EntryType cheapestEntry = null; for (int i = 0; i < entries.length; i++) { try { // Access information contained in the entry. First of all, // we need to deserialize the entry... EntryType entry = (EntryType) ObjectDeserializer.toObject(entries[i], EntryType.class); // ... access its content ... AggregatorContent content = (AggregatorContent) entry.getContent(); // ... then the data ... AggregatorData data = content.getAggregatorData(); /* * Now, because of how the registration is set up, we know * that the price is the second element. * * From registration.xml: * <agg:ResourcePropertyNames>ffs:Name * </agg:ResourcePropertyNames> * <agg:ResourcePropertyNames>ffs:Price * </agg:ResourcePropertyNames> */ String price_str = data.get_any()[1].getValue(); float price = Float.parseFloat(price_str); /* Is this the cheapest? */ if (price < minPrice) { minPrice = price; cheapestEntry = entry; } } catch (Exception e) { logger.error("Error when accessing index service entry."); throw new RemoteException("Error when accessing index service entry.", e); } } if (minPrice < maxPrice) { // A file matches the specified criteria! // Return values float price = minPrice; EndpointReferenceType fileOrderEPR = null; /* * CREATE A FILE ORDER RESOURCE, AND ADD THE CHEAPEST FILE TO * THE RESOURCE */ // Get EPR of File resource. It will be included in the // FileOrder resource we are going to create EndpointReferenceType fileEPR = cheapestEntry.getMemberServiceEPR(); ResourceContext ctx = null; FileOrderResourceHome home = null; ResourceKey key = null; try { /* Create new FileOrder resource */ ctx = ResourceContext.getResourceContext(); home = (FileOrderResourceHome) ctx.getResourceHome(); key = home.create(name, fileEPR); /* Create FileOrder EPR */ URL serviceURL = ctx.getServiceURL(); fileOrderEPR = AddressingUtils.createEndpointReference(serviceURL.toString(), key); } catch (Exception e) { logger.error("Error when creating FileOrder resource."); throw new RemoteException("Error when creating FileOrder resource.", e); } logger.debug("Found file with price=" + price); logger.info("Created new file order for file NAME=" + name + ", PRICE=" + price); logger.info( "FileOrder has been created for user '" + SecurityManager.getManager().getCaller() + "'"); /* Create response object */ response.setPrice(price); response.setFileOrderEPR(fileOrderEPR); } else { logger.debug("No file with name " + name + " is cheaper than " + maxPrice); // We return a null EPR to indicate that no file has // been found meeting the specified criteria. // Ideally, we should throw a custom exception. response.setFileOrderEPR(null); } } return response; }
From source file:com.nadmm.airports.wx.WxCursorAdapter.java
protected void showMetarInfo(View view, Cursor c, Metar metar) { ViewHolder holder = getViewHolder(view); if (metar != null && metar.isValid) { // We have METAR for this station double lat = c.getDouble(c.getColumnIndex(Wxs.STATION_LATITUDE_DEGREES)); double lon = c.getDouble(c.getColumnIndex(Wxs.STATION_LONGITUDE_DEGREES)); Location location = new Location(""); location.setLatitude(lat);/*from www . ja va 2s .c o m*/ location.setLongitude(lon); float declination = GeoUtils.getMagneticDeclination(location); WxUtils.setColorizedWxDrawable(holder.stationName, metar, declination); StringBuilder info = new StringBuilder(); info.append(metar.flightCategory); if (metar.visibilitySM < Float.MAX_VALUE) { info.append(", "); info.append(FormatUtils.formatStatuteMiles(metar.visibilitySM)); } if (metar.windSpeedKnots < Integer.MAX_VALUE) { info.append(", "); if (metar.windSpeedKnots == 0) { info.append("calm"); } else if (metar.windGustKnots < Integer.MAX_VALUE) { info.append(String.format("%dG%dKT", metar.windSpeedKnots, metar.windGustKnots)); } else { info.append(String.format("%dKT", metar.windSpeedKnots)); } if (metar.windSpeedKnots > 0 && metar.windDirDegrees >= 0 && metar.windDirDegrees < Integer.MAX_VALUE) { info.append("/"); info.append(FormatUtils.formatDegrees(metar.windDirDegrees)); } } if (metar.wxList.size() > 0) { for (WxSymbol wx : metar.wxList) { if (!wx.getSymbol().equals("NSW")) { info.append(", "); info.append(wx.toString().toLowerCase(Locale.US)); } } } holder.stationWx.setVisibility(View.VISIBLE); holder.stationWx.setText(info.toString()); info.setLength(0); SkyCondition sky = WxUtils.getCeiling(metar.skyConditions); int ceiling = sky.getCloudBaseAGL(); String skyCover = sky.getSkyCover(); if (skyCover.equals("OVX")) { info.append("Ceiling indefinite"); } else if (!skyCover.equals("NSC")) { info.append("Ceiling "); info.append(skyCover); info.append(" "); info.append(FormatUtils.formatFeet(ceiling)); } else { if (!metar.skyConditions.isEmpty()) { sky = metar.skyConditions.get(0); skyCover = sky.getSkyCover(); if (skyCover.equals("CLR") || skyCover.equals("SKC")) { info.append("Sky clear"); } else if (!skyCover.equals("SKM")) { info.append(skyCover); info.append(" "); info.append(FormatUtils.formatFeet(sky.getCloudBaseAGL())); } } } if (info.length() > 0) { info.append(", "); } // Do some basic sanity checks on values if (metar.tempCelsius < Float.MAX_VALUE && metar.dewpointCelsius < Float.MAX_VALUE) { info.append(FormatUtils.formatTemperatureF(metar.tempCelsius)); info.append("/"); info.append(FormatUtils.formatTemperatureF(metar.dewpointCelsius)); info.append(", "); } if (metar.altimeterHg < Float.MAX_VALUE) { info.append(FormatUtils.formatAltimeterHg(metar.altimeterHg)); } holder.stationWx2.setVisibility(View.VISIBLE); holder.stationWx2.setText(info.toString()); holder.reportAge.setVisibility(View.VISIBLE); holder.reportAge.setText(TimeUtils.formatElapsedTime(metar.observationTime)); } else { WxUtils.setColorizedWxDrawable(holder.stationName, metar, 0); if (metar != null) { holder.stationWx.setText("Unable to fetch Wx data"); } else { holder.stationWx.setText("Wx not fetched"); } holder.stationWx2.setVisibility(View.GONE); holder.reportAge.setVisibility(View.GONE); } }
From source file:it.geosolutions.jaiext.range.RangeTest.java
@BeforeClass public static void initialSetup() { arrayB = new byte[] { 0, 1, 5, 50, 100 }; arrayUS = new short[] { 0, 1, 5, 50, 100 }; arrayS = new short[] { -10, 0, 5, 50, 100 }; arrayI = new int[] { -10, 0, 5, 50, 100 }; arrayF = new float[] { -10, 0, 5, 50, 100 }; arrayD = new double[] { -10, 0, 5, 50, 100 }; arrayL = new long[] { -10, 0, 5, 50, 100 }; rangeB2bounds = RangeFactory.create((byte) 2, true, (byte) 60, true); rangeBpoint = RangeFactory.create(arrayB[2], true, arrayB[2], true); rangeU2bounds = RangeFactory.createU((short) 2, true, (short) 60, true); rangeUpoint = RangeFactory.createU(arrayUS[2], true, arrayUS[2], true); rangeS2bounds = RangeFactory.create((short) 1, true, (short) 60, true); rangeSpoint = RangeFactory.create(arrayS[2], true, arrayS[2], true); rangeI2bounds = RangeFactory.create(1, true, 60, true); rangeIpoint = RangeFactory.create(arrayI[2], true, arrayI[2], true); rangeF2bounds = RangeFactory.create(0.5f, true, 60.5f, true, false); rangeFpoint = RangeFactory.create(arrayF[2], true, arrayF[2], true, false); rangeD2bounds = RangeFactory.create(1.5d, true, 60.5d, true, false); rangeDpoint = RangeFactory.create(arrayD[2], true, arrayD[2], true, false); rangeL2bounds = RangeFactory.create(1L, true, 60L, true); rangeLpoint = RangeFactory.create(arrayL[2], true, arrayL[2], true); arrayBtest = new Byte[100]; arrayStest = new Short[100]; arrayItest = new Integer[100]; arrayFtest = new Float[100]; arrayDtest = new Double[100]; // Random value creation for the various Ranges for (int j = 0; j < 100; j++) { double randomValue = Math.random(); arrayBtest[j] = (byte) (randomValue * (Byte.MAX_VALUE - Byte.MIN_VALUE) + Byte.MIN_VALUE); arrayStest[j] = (short) (randomValue * (Short.MAX_VALUE - Short.MIN_VALUE) + Short.MIN_VALUE); arrayItest[j] = (int) (randomValue * (Integer.MAX_VALUE - Integer.MIN_VALUE) + Integer.MIN_VALUE); arrayFtest[j] = (float) (randomValue * (Float.MAX_VALUE - Float.MIN_VALUE) + Float.MIN_VALUE); arrayDtest[j] = (randomValue * (Double.MAX_VALUE - Double.MIN_VALUE) + Double.MIN_VALUE); }/*from www. j a v a2 s .c o m*/ // JAI tools Ranges rangeJTB = org.jaitools.numeric.Range.create((byte) 1, true, (byte) 60, true); rangeJTS = org.jaitools.numeric.Range.create((short) 1, true, (short) 60, true); rangeJTI = org.jaitools.numeric.Range.create(1, true, 60, true); rangeJTF = org.jaitools.numeric.Range.create(0.5f, true, 60.5f, true); rangeJTD = org.jaitools.numeric.Range.create(1.5d, true, 60.5d, true); // 1 point Ranges rangeJTBpoint = org.jaitools.numeric.Range.create((byte) 5, true, (byte) 5, true); rangeJTSpoint = org.jaitools.numeric.Range.create((short) 5, true, (short) 5, true); rangeJTIpoint = org.jaitools.numeric.Range.create(5, true, 5, true); rangeJTFpoint = org.jaitools.numeric.Range.create(5f, true, 5f, true); rangeJTDpoint = org.jaitools.numeric.Range.create(5d, true, 5d, true); // JAI Ranges rangeJAIB = new javax.media.jai.util.Range(Byte.class, (byte) 1, true, (byte) 60, true); rangeJAIS = new javax.media.jai.util.Range(Short.class, (short) 1, true, (short) 60, true); rangeJAII = new javax.media.jai.util.Range(Integer.class, 1, true, 60, true); rangeJAIF = new javax.media.jai.util.Range(Float.class, 0.5f, true, 60.5f, true); rangeJAID = new javax.media.jai.util.Range(Double.class, 1.5d, true, 60.5d, true); // 1 point Ranges rangeJAIBpoint = new javax.media.jai.util.Range(Byte.class, (byte) 5, true, (byte) 5, true); rangeJAISpoint = new javax.media.jai.util.Range(Short.class, (short) 5, true, (short) 5, true); rangeJAIIpoint = new javax.media.jai.util.Range(Integer.class, 5, true, 5, true); rangeJAIFpoint = new javax.media.jai.util.Range(Float.class, 5f, true, 5f, true); rangeJAIDpoint = new javax.media.jai.util.Range(Double.class, 5d, true, 5d, true); // Apache Common Ranges rangeCommonsB = new org.apache.commons.lang.math.IntRange((byte) 1, (byte) 60); rangeCommonsS = new org.apache.commons.lang.math.IntRange((short) 1, (short) 60); rangeCommonsI = new org.apache.commons.lang.math.IntRange(1, 60); rangeCommonsF = new org.apache.commons.lang.math.FloatRange(0.5f, 60.5f); rangeCommonsD = new org.apache.commons.lang.math.DoubleRange(1.5d, 60.5d); // 1 point Ranges rangeCommonsBpoint = new org.apache.commons.lang.math.IntRange(5); rangeCommonsSpoint = new org.apache.commons.lang.math.IntRange(5); rangeCommonsIpoint = new org.apache.commons.lang.math.IntRange(5); rangeCommonsFpoint = new org.apache.commons.lang.math.FloatRange(5f); rangeCommonsDpoint = new org.apache.commons.lang.math.DoubleRange(5d); // // GeoTools Ranges // rangeGeoToolsB = new org.geotools.util.NumberRange<Byte>(Byte.class, (byte) 1, (byte) 60); // rangeGeoToolsS = new org.geotools.util.NumberRange<Short>(Short.class, (short) 1, // (short) 60); // rangeGeoToolsI = new org.geotools.util.NumberRange<Integer>(Integer.class, 1, 60); // rangeGeoToolsF = new org.geotools.util.NumberRange<Float>(Float.class, 0.5f, 60.5f); // rangeGeoToolsD = new org.geotools.util.NumberRange<Double>(Double.class, 1.5d, 60.5d); // // 1 point Ranges // rangeGeoToolsBpoint = new org.geotools.util.NumberRange<Byte>(Byte.class, (byte) 5, // (byte) 5); // rangeGeoToolsSpoint = new org.geotools.util.NumberRange<Short>(Short.class, (short) 5, // (short) 5); // rangeGeoToolsIpoint = new org.geotools.util.NumberRange<Integer>(Integer.class, 5, 5); // rangeGeoToolsFpoint = new org.geotools.util.NumberRange<Float>(Float.class, 5f, 5f); // rangeGeoToolsDpoint = new org.geotools.util.NumberRange<Double>(Double.class, 5d, 5d); // // Guava Ranges // rangeGuavaB = com.google.common.collect.Range.closed((byte) 1, (byte) 60); // rangeGuavaS = com.google.common.collect.Range.closed((short) 1, (short) 60); // rangeGuavaI = com.google.common.collect.Range.closed(1, 60); // rangeGuavaF = com.google.common.collect.Range.closed(0.5f, 60.5f); // rangeGuavaD = com.google.common.collect.Range.closed(1.5d, 60.5d); // // 1 point Ranges // rangeGuavaBpoint = com.google.common.collect.Range.singleton((byte) 5); // rangeGuavaSpoint = com.google.common.collect.Range.singleton((short) 5); // rangeGuavaIpoint = com.google.common.collect.Range.singleton(5); // rangeGuavaFpoint = com.google.common.collect.Range.singleton(5f); // rangeGuavaDpoint = com.google.common.collect.Range.singleton(5d); }
From source file:mil.jpeojtrs.sca.util.tests.AnyUtilsTest.java
@Test public void test_convertAny() throws Exception { final Boolean result = (Boolean) AnyUtils.convertAny(this.any); Assert.assertTrue(result);/* w ww.j ava 2 s. c o m*/ Assert.assertNull(AnyUtils.convertAny(null)); String str = (String) AnyUtils.convertAny(AnyUtils.toAny("2", TCKind.tk_string)); Assert.assertEquals("2", str); str = (String) AnyUtils.convertAny(AnyUtils.toAny("3", TCKind.tk_wstring)); Assert.assertEquals("3", str); final short b = (Short) AnyUtils.convertAny(AnyUtils.toAny(Byte.MAX_VALUE, TCKind.tk_octet)); Assert.assertEquals(Byte.MAX_VALUE, b); char c = (Character) AnyUtils.convertAny(AnyUtils.toAny(Character.MAX_VALUE, TCKind.tk_char)); Assert.assertEquals(Character.MAX_VALUE, c); c = (Character) AnyUtils.convertAny(AnyUtils.toAny(new Character('2'), TCKind.tk_wchar)); Assert.assertEquals('2', c); final short s = (Short) AnyUtils.convertAny(AnyUtils.toAny(Short.MAX_VALUE, TCKind.tk_short)); Assert.assertEquals(Short.MAX_VALUE, s); final int i = (Integer) AnyUtils.convertAny(AnyUtils.toAny(Integer.MAX_VALUE, TCKind.tk_long)); Assert.assertEquals(Integer.MAX_VALUE, i); final long l = (Long) AnyUtils.convertAny(AnyUtils.toAny(Long.MAX_VALUE, TCKind.tk_longlong)); Assert.assertEquals(Long.MAX_VALUE, l); final float f = (Float) AnyUtils.convertAny(AnyUtils.toAny(Float.MAX_VALUE, TCKind.tk_float)); Assert.assertEquals(Float.MAX_VALUE, f, 0.00001); final double d = (Double) AnyUtils.convertAny(AnyUtils.toAny(Double.MAX_VALUE, TCKind.tk_double)); Assert.assertEquals(Double.MAX_VALUE, d, 0.00001); final int us = (Integer) AnyUtils.convertAny(AnyUtils.toAny(Short.MAX_VALUE, TCKind.tk_ushort)); Assert.assertEquals(Short.MAX_VALUE, us); final long ui = (Long) AnyUtils.convertAny(AnyUtils.toAny(Integer.MAX_VALUE, TCKind.tk_ulong)); Assert.assertEquals(Integer.MAX_VALUE, ui); final BigInteger ul = (BigInteger) AnyUtils.convertAny(AnyUtils.toAny(Long.MAX_VALUE, TCKind.tk_ulonglong)); Assert.assertEquals(Long.MAX_VALUE, ul.longValue()); /** TODO Big Decimal not supported final BigDecimal fix = (BigDecimal) AnyUtils.convertAny(AnyUtils.toAny(new BigDecimal(1.0), TCKind.tk_fixed)); Assert.assertEquals(1.0, fix.doubleValue(), 0.00001); */ Any tmpAny = (Any) AnyUtils.convertAny(AnyUtils.toAny(AnyUtils.toAny(1, TCKind.tk_long), TCKind.tk_any)); Assert.assertNotNull(tmpAny); Assert.assertEquals(1, tmpAny.extract_long()); /** TODO Why do these not work in Jacorb? **/ // tmpAny = (Any) AnyUtils.convertAny(AnyUtils.toAny(AnyUtils.toAny((short) 1, TCKind.tk_short), TCKind.tk_value)); // Assert.assertNotNull(tmpAny); // Assert.assertEquals((short) 1, tmpAny.extract_short()); // final TypeCode tmpType = (TypeCode) AnyUtils.convertAny(AnyUtils.toAny(tmpAny.type(), TCKind.tk_TypeCode)); // Assert.assertNotNull(tmpType); // Assert.assertEquals(TCKind._tk_short, tmpType.kind().value()); // final Object obj = AnyUtils.convertAny(null, tmpType); // Assert.assertNull(obj); }