Example usage for java.lang Float compare

List of usage examples for java.lang Float compare

Introduction

In this page you can find the example usage for java.lang Float compare.

Prototype

public static int compare(float f1, float f2) 

Source Link

Document

Compares the two specified float values.

Usage

From source file:org.tinymediamanager.ui.movies.MovieExtendedComparator.java

@Override
public int compare(Movie movie1, Movie movie2) {
    int sortOrder = 0;

    try {//from  w  w  w  .  j a  v a2  s.  c o m
        // try to sort the chosen column
        switch (sortColumn) {
        case TITLE:
            sortOrder = stringCollator.compare(movie1.getTitleSortable().toLowerCase(Locale.ROOT),
                    movie2.getTitleSortable().toLowerCase(Locale.ROOT));
            break;

        case SORT_TITLE:
            String title1 = StringUtils.isNotBlank(movie1.getSortTitle()) ? movie1.getSortTitle()
                    : movie1.getTitleSortable();
            String title2 = StringUtils.isNotBlank(movie2.getSortTitle()) ? movie2.getSortTitle()
                    : movie2.getTitleSortable();
            sortOrder = stringCollator.compare(title1.toLowerCase(Locale.ROOT),
                    title2.toLowerCase(Locale.ROOT));
            break;

        case YEAR:
            sortOrder = stringCollator.compare(movie1.getYear(), movie2.getYear());
            break;

        case DATE_ADDED:
            sortOrder = movie1.getDateAdded().compareTo(movie2.getDateAdded());
            break;

        case WATCHED:
            Boolean watched1 = movie1.isWatched();
            Boolean watched2 = movie2.isWatched();
            sortOrder = watched1.compareTo(watched2);
            break;

        case RATING:
            sortOrder = Float.compare(movie1.getRating(), movie2.getRating());
            break;

        case RUNTIME:
            Integer runtime1 = movie1.getRuntime();
            Integer runtime2 = movie2.getRuntime();
            sortOrder = runtime1.compareTo(runtime2);
            break;

        case VIDEO_BITRATE:
            Integer videoBitrate1 = movie1.getMediaInfoVideoBitrate();
            Integer videoBitrate2 = movie2.getMediaInfoVideoBitrate();
            sortOrder = videoBitrate1.compareTo(videoBitrate2);
            break;
        }
    } catch (NullPointerException e) {
        // do nothing here. there could be
    } catch (Exception e) {
        LOGGER.warn(e.getMessage());
    }

    // sort ascending or descending
    if (sortAscending) {
        return sortOrder;
    } else {
        return sortOrder * -1;
    }
}

From source file:Main.java

/**
 * Finds the first occurrence of value in <code>float</code> array.
 *///w  w  w .  j  ava  2s. c o  m
public static int indexOf(float[] array, float value) {
    for (int i = 0; i < array.length; i++) {
        if (Float.compare(array[i], value) == 0) {
            return i;
        }
    }
    return -1;
}

From source file:ml.shifu.shifu.core.dtrain.nn.NNParquetWorker.java

@Override
public void load(GuaguaWritableAdapter<LongWritable> currentKey, GuaguaWritableAdapter<Tuple> currentValue,
        WorkerContext<NNParams, NNParams> workerContext) {
    // init field list for later read
    this.initFieldList();

    LOG.info("subFeatureSet size: {} ; subFeatureSet: {}", subFeatureSet.size(), subFeatureSet);

    super.count += 1;
    if ((super.count) % 5000 == 0) {
        LOG.info("Read {} records.", super.count);
    }//from w  w  w. j  a v a  2 s .  co m

    float[] inputs = new float[super.featureInputsCnt];
    float[] ideal = new float[super.outputNodeCount];

    if (super.isDry) {
        // dry train, use empty data.
        addDataPairToDataSet(0,
                new BasicFloatMLDataPair(new BasicFloatMLData(inputs), new BasicFloatMLData(ideal)));
        return;
    }

    long hashcode = 0;
    float significance = 1f;
    // use guava Splitter to iterate only once
    // use NNConstants.NN_DEFAULT_COLUMN_SEPARATOR to replace getModelConfig().getDataSetDelimiter(), super follows
    // the function in akka mode.
    int index = 0, inputsIndex = 0, outputIndex = 0;

    Tuple tuple = currentValue.getWritable();

    // back from foreach to for loop because of in earlier version, tuple cannot be iterable.
    for (int i = 0; i < tuple.size(); i++) {
        Object element = null;
        try {
            element = tuple.get(i);
        } catch (ExecException e) {
            throw new GuaguaRuntimeException(e);
        }
        float floatValue = 0f;
        if (element != null) {
            if (element instanceof Float) {
                floatValue = (Float) element;
            } else {
                // check here to avoid bad performance in failed NumberFormatUtils.getFloat(input, 0f)
                floatValue = element.toString().length() == 0 ? 0f
                        : NumberFormatUtils.getFloat(element.toString(), 0f);
            }
        }
        // no idea about why NaN in input data, we should process it as missing value TODO , according to norm type
        floatValue = (Float.isNaN(floatValue) || Double.isNaN(floatValue)) ? 0f : floatValue;

        if (index == (super.inputNodeCount + super.outputNodeCount)) {
            // do we need to check if not weighted directly set to 1f; if such logic non-weight at first, then
            // weight, how to process???
            if (StringUtils.isBlank(modelConfig.getWeightColumnName())) {
                significance = 1f;
                // break here if we reach weight column which is last column
                break;
            }

            assert element != null;
            if (element != null && element instanceof Float) {
                significance = (Float) element;
            } else {
                // check here to avoid bad performance in failed NumberFormatUtils.getFloat(input, 0f)
                significance = element.toString().length() == 0 ? 1f
                        : NumberFormatUtils.getFloat(element.toString(), 1f);
            }
            // if invalid weight, set it to 1f and warning in log
            if (Float.compare(significance, 0f) < 0) {
                LOG.warn(
                        "The {} record in current worker weight {} is less than 0f, it is invalid, set it to 1.",
                        count, significance);
                significance = 1f;
            }
            // break here if we reach weight column which is last column
            break;
        } else {
            int columnIndex = requiredFieldList.getFields().get(index).getIndex();
            if (columnIndex >= super.columnConfigList.size()) {
                assert element != null;
                if (element != null && element instanceof Float) {
                    significance = (Float) element;
                } else {
                    // check here to avoid bad performance in failed NumberFormatUtils.getFloat(input, 0f)
                    significance = element.toString().length() == 0 ? 1f
                            : NumberFormatUtils.getFloat(element.toString(), 1f);
                }
                break;
            } else {
                ColumnConfig columnConfig = super.columnConfigList.get(columnIndex);
                if (columnConfig != null && columnConfig.isTarget()) {
                    if (modelConfig.isRegression()) {
                        ideal[outputIndex++] = floatValue;
                    } else {
                        if (modelConfig.getTrain().isOneVsAll()) {
                            // if one vs all, set correlated idea value according to trainerId which means in
                            // trainer with id 0, target 0 is treated with 1, other are 0. Such target value are set
                            // to index of tags like [0, 1, 2, 3] compared with ["a", "b", "c", "d"]
                            ideal[outputIndex++] = Float.compare(floatValue, trainerId) == 0 ? 1f : 0f;
                        } else {
                            if (modelConfig.getTags().size() == 2) {
                                // if only 2 classes, output node is 1 node. if target = 0 means 0 is the index for
                                // positive prediction, set positive to 1 and negative to 0
                                int ideaIndex = (int) floatValue;
                                ideal[0] = ideaIndex == 0 ? 1f : 0f;
                            } else {
                                // for multiple classification
                                int ideaIndex = (int) floatValue;
                                ideal[ideaIndex] = 1f;
                            }
                        }
                    }
                } else {
                    if (subFeatureSet.contains(columnIndex)) {
                        inputs[inputsIndex++] = floatValue;
                        hashcode = hashcode * 31 + Double.valueOf(floatValue).hashCode();
                    }
                }
            }
        }
        index += 1;
    }

    // output delimiter in norm can be set by user now and if user set a special one later changed, this exception
    // is helped to quick find such issue.
    if (inputsIndex != inputs.length) {
        String delimiter = workerContext.getProps().getProperty(Constants.SHIFU_OUTPUT_DATA_DELIMITER,
                Constants.DEFAULT_DELIMITER);
        throw new RuntimeException("Input length is inconsistent with parsing size. Input original size: "
                + inputs.length + ", parsing size:" + inputsIndex + ", delimiter:" + delimiter + ".");
    }

    // sample negative only logic here
    if (modelConfig.getTrain().getSampleNegOnly()) {
        if (this.modelConfig.isFixInitialInput()) {
            // if fixInitialInput, sample hashcode in 1-sampleRate range out if negative records
            int startHashCode = (100 / this.modelConfig.getBaggingNum()) * this.trainerId;
            // here BaggingSampleRate means how many data will be used in training and validation, if it is 0.8, we
            // should take 1-0.8 to check endHashCode
            int endHashCode = startHashCode
                    + Double.valueOf((1d - this.modelConfig.getBaggingSampleRate()) * 100).intValue();
            if ((modelConfig.isRegression()
                    || (modelConfig.isClassification() && modelConfig.getTrain().isOneVsAll())) // regression or
                    // onevsall
                    && (int) (ideal[0] + 0.01d) == 0 // negative record
                    && isInRange(hashcode, startHashCode, endHashCode)) {
                return;
            }
        } else {
            // if not fixed initial input, and for regression or onevsall multiple classification (regression also).
            // if negative record
            if ((modelConfig.isRegression()
                    || (modelConfig.isClassification() && modelConfig.getTrain().isOneVsAll())) // regression or
                    // onevsall
                    && (int) (ideal[0] + 0.01d) == 0 // negative record
                    && Double.compare(super.sampelNegOnlyRandom.nextDouble(),
                            this.modelConfig.getBaggingSampleRate()) >= 0) {
                return;
            }
        }
    }

    FloatMLDataPair pair = new BasicFloatMLDataPair(new BasicFloatMLData(inputs), new BasicFloatMLData(ideal));

    // up sampling logic
    if (modelConfig.isRegression() && isUpSampleEnabled() && Double.compare(ideal[0], 1d) == 0) {
        // Double.compare(ideal[0], 1d) == 0 means positive tags; sample + 1 to avoid sample count to 0
        pair.setSignificance(significance * (super.upSampleRng.sample() + 1));
    } else {
        pair.setSignificance(significance);
    }

    boolean isValidation = false;
    if (workerContext.getAttachment() != null && workerContext.getAttachment() instanceof Boolean) {
        isValidation = (Boolean) workerContext.getAttachment();
    }

    boolean isInTraining = addDataPairToDataSet(hashcode, pair, isValidation);

    // do bagging sampling only for training data
    if (isInTraining) {
        float subsampleWeights = sampleWeights(pair.getIdealArray()[0]);
        if (isPositive(pair.getIdealArray()[0])) {
            this.positiveSelectedTrainCount += subsampleWeights * 1L;
        } else {
            this.negativeSelectedTrainCount += subsampleWeights * 1L;
        }
        // set weights to significance, if 0, significance will be 0, that is bagging sampling
        pair.setSignificance(pair.getSignificance() * subsampleWeights);
    } else {
        // for validation data, according bagging sampling logic, we may need to sampling validation data set, while
        // validation data set are only used to compute validation error, not to do real sampling is ok.
    }
}

From source file:com.mirth.connect.connectors.file.FileMessageReceiver.java

public void sortFiles(FileInfo[] files) {
    String sortAttribute = ((FileConnector) connector).getSortAttribute();

    if (sortAttribute.equals(FileConnector.SORT_DATE)) {
        Arrays.sort(files, new Comparator<FileInfo>() {
            public int compare(FileInfo file1, FileInfo file2) {
                return Float.compare(file1.getLastModified(), file2.getLastModified());
            }//from  w w  w.j a  va 2  s. c  om
        });
    } else if (sortAttribute.equals(FileConnector.SORT_SIZE)) {
        Arrays.sort(files, new Comparator<FileInfo>() {
            public int compare(FileInfo file1, FileInfo file2) {
                return Float.compare(file1.getSize(), file2.getSize());
            }
        });
    } else {
        Arrays.sort(files, new Comparator<FileInfo>() {
            public int compare(FileInfo file1, FileInfo file2) {
                return file1.getName().compareTo(file2.getName());
            }
        });
    }
}

From source file:org.mitre.mpf.wfm.data.entities.transients.Detection.java

@Override
public int compareTo(Detection other) {
    int comparison;
    if (other == null) {
        comparison = 1;//from  w ww . j  a  va2s.  c  om
    } else if ((comparison = Integer.compare(mediaOffsetFrame, other.mediaOffsetFrame)) == 0
            && (comparison = Integer.compare(mediaOffsetTime, other.mediaOffsetTime)) == 0
            && (comparison = Integer.compare(x, other.x)) == 0
            && (comparison = Integer.compare(y, other.y)) == 0
            && (comparison = Integer.compare(width, other.width)) == 0
            && (comparison = Integer.compare(height, other.height)) == 0
            && (comparison = Float.compare(confidence, other.confidence)) == 0
            && (comparison = TextUtils.nullSafeCompare(artifactPath, other.artifactPath)) == 0
            && (comparison = compareMap(detectionProperties, other.detectionProperties)) == 0) {
        comparison = 0;
    }
    return comparison;
}

From source file:Main.java

/**
 * Finds the first occurrence of given value in <code>float</code>
 * array from specified given position.//from  www . j a v  a 2 s .  c  o m
 */
public static int indexOf(float[] array, float value, int startIndex) {
    for (int i = startIndex; i < array.length; i++) {
        if (Float.compare(array[i], value) == 0) {
            return i;
        }
    }
    return -1;
}

From source file:org.diorite.utils.math.FloatRange.java

@Override
public boolean equals(final Object o) {
    if (this == o) {
        return true;
    }/* w w w .  j  ava2  s .c  o m*/
    if (!(o instanceof FloatRange)) {
        return false;
    }

    final FloatRange that = (FloatRange) o;

    return (Float.compare(that.max, this.max) == 0) && (Float.compare(that.min, this.min) == 0);

}

From source file:de.perdian.commons.servlet.ServletUtils.java

/**
 * Extracts the locales supported by the client that sent a given request.
 * According to RFC 2161 the result list will be sorted according to any
 * specified preferenc value (see the RFC for details)
 *
 * @param servletRequest// w w w . j av  a 2 s .  com
 *     the request from which to extract the information
 * @param defaultLocales
 *     the locales to be returned if no locales could be extracted from the
 *     request
 * @return
 *     a {@code List} containing the accepted {@code java.util.Locale}
 *     objects. If no locales are found in the request, then the method will
 *     return the default locale list or an empty list if no default locales
 *     have been passed - never {@code null}
 */
public static List<Locale> extractAcceptedLocales(HttpServletRequest servletRequest,
        List<Locale> defaultLocales) {

    Map<Float, List<Locale>> localeValuesByPriority = new TreeMap<>((o1, o2) -> -1 * Float.compare(o1, o2));
    String headerValue = servletRequest.getHeader("accept-language");
    if (headerValue != null) {
        StringTokenizer headerTokenizer = new StringTokenizer(headerValue, ",");
        while (headerTokenizer.hasMoreElements()) {
            String header = headerTokenizer.nextToken().trim();
            int semicolonSeparator = header.indexOf(";");
            String localeValue = semicolonSeparator > 0 ? header.substring(0, semicolonSeparator) : header;
            Locale locale = LocaleUtils.toLocale(localeValue);
            if (locale != null) {
                Float qValue = Float.valueOf(1f);
                String qParameter = ";q=";
                int qParameterIndex = header.indexOf(qParameter);
                if (qParameterIndex > 0) {
                    try {
                        String qParameterValue = header.substring(qParameterIndex + qParameter.length());
                        qValue = Float.valueOf(qParameterValue);

                    } catch (Exception e) {
                        // Ignore here and use the default
                    }
                }
                List<Locale> targetList = localeValuesByPriority.get(qValue);
                if (targetList == null) {
                    targetList = new ArrayList<>();
                    localeValuesByPriority.put(qValue, targetList);
                }
                targetList.add(locale);
            }
        }
    }

    List<Locale> localeValues = new ArrayList<>();
    for (Map.Entry<Float, List<Locale>> localeValueEntry : localeValuesByPriority.entrySet()) {
        for (Locale locale : localeValueEntry.getValue()) {
            localeValues.add(locale);
        }
    }
    if (localeValues.isEmpty() && defaultLocales != null) {
        localeValues.addAll(defaultLocales);
    }
    return Collections.unmodifiableList(localeValues);

}

From source file:de.blizzy.rust.lootconfig.LootConfigDump.java

private int compareByChances(Map.Entry<Category, Multiset<Float>> entry1,
        Map.Entry<Category, Multiset<Float>> entry2) {
    return -Float.compare(sum(entry1.getValue()), sum(entry2.getValue()));
}

From source file:Main.java

/**
 * Finds the first occurrence in <code>float</code> array from specified given position and upto given length.
 *///from   w w  w .j  a v a2s.co m
public static int indexOf(float[] array, float value, int startIndex, int endIndex) {
    for (int i = startIndex; i < endIndex; i++) {
        if (Float.compare(array[i], value) == 0) {
            return i;
        }
    }
    return -1;
}