Example usage for java.lang Math floor

List of usage examples for java.lang Math floor

Introduction

In this page you can find the example usage for java.lang Math floor.

Prototype

public static double floor(double a) 

Source Link

Document

Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.

Usage

From source file:com.yunmall.ymsdk.net.http.JsonStreamerEntity.java

@Override
public void writeTo(final OutputStream out) throws IOException {
    if (out == null) {
        throw new IllegalStateException("Output stream cannot be null.");
    }// w ww .  ja va2 s.c o  m

    // Record the time when uploading started.
    long now = System.currentTimeMillis();

    // Use GZIP compression when sending streams, otherwise just use
    // a buffered output stream to speed things up a bit.
    OutputStream os = null != contentEncoding ? new GZIPOutputStream(out, BUFFER_SIZE) : out;

    // Always send a JSON object.
    os.write('{');

    // Keys used by the HashMaps.
    Set<String> keys = jsonParams.keySet();

    boolean isFileWrapper;

    // Go over all keys and handle each's value.
    for (String key : keys) {
        // Evaluate the value (which cannot be null).
        Object value = jsonParams.get(key);

        // Bail out prematurely if value's null.
        if (value == null) {
            continue;
        }

        // Write the JSON object's key.
        os.write(escape(key));
        os.write(':');

        // Check if this is a FileWrapper.
        isFileWrapper = value instanceof RequestParams.FileWrapper;

        // If a file should be uploaded.
        if (isFileWrapper || value instanceof RequestParams.StreamWrapper) {
            // All uploads are sent as an object containing the file's details.
            os.write('{');

            // Determine how to handle this entry.
            if (isFileWrapper) {
                writeToFromFile(os, (RequestParams.FileWrapper) value);
            } else {
                writeToFromStream(os, (RequestParams.StreamWrapper) value);
            }

            // End the file's object and prepare for next one.
            os.write('}');
        } else if (value instanceof Boolean) {
            os.write((Boolean) value ? JSON_TRUE : JSON_FALSE);
        } else if (value instanceof Long) {
            os.write((((Number) value).longValue() + "").getBytes());
        } else if (value instanceof Double) {
            os.write((((Number) value).doubleValue() + "").getBytes());
        } else if (value instanceof Float) {
            os.write((((Number) value).floatValue() + "").getBytes());
        } else if (value instanceof Integer) {
            os.write((((Number) value).intValue() + "").getBytes());
        } else {
            os.write(escape(value.toString()));
        }

        os.write(',');
    }

    // Include the elapsed time taken to upload everything.
    // This might be useful for somebody, but it serves us well since
    // there will almost always be a ',' as the last sent character.
    os.write(STREAM_ELAPSED);
    os.write(':');
    long elapsedTime = System.currentTimeMillis() - now;
    os.write((elapsedTime + "}").getBytes());

    YmLog.i(LOG_TAG, "Uploaded JSON in " + Math.floor(elapsedTime / 1000) + " seconds");

    // Flush the contents up the stream.
    os.flush();
    AsyncHttpClient.silentCloseOutputStream(os);
}

From source file:com.android.yijiang.kzx.http.JsonStreamerEntity.java

@Override
public void writeTo(final OutputStream out) throws IOException {
    if (out == null) {
        throw new IllegalStateException("Output stream cannot be null.");
    }/*from www .  j  ava2s  .  c o  m*/

    // Record the time when uploading started.
    long now = System.currentTimeMillis();

    // Use GZIP compression when sending streams, otherwise just use
    // a buffered output stream to speed things up a bit.
    OutputStream os = null != contentEncoding ? new GZIPOutputStream(out, BUFFER_SIZE) : out;

    // Always send a JSON object.
    os.write('{');

    // Keys used by the HashMaps.
    Set<String> keys = jsonParams.keySet();

    boolean isFileWrapper;

    // Go over all keys and handle each's value.
    for (String key : keys) {
        // Evaluate the value (which cannot be null).
        Object value = jsonParams.get(key);

        // Bail out prematurely if value's null.
        if (value == null) {
            continue;
        }

        // Write the JSON object's key.
        os.write(escape(key));
        os.write(':');

        // Check if this is a FileWrapper.
        isFileWrapper = value instanceof RequestParams.FileWrapper;

        // If a file should be uploaded.
        if (isFileWrapper || value instanceof RequestParams.StreamWrapper) {
            // All uploads are sent as an object containing the file's details.
            os.write('{');

            // Determine how to handle this entry.
            if (isFileWrapper) {
                writeToFromFile(os, (RequestParams.FileWrapper) value);
            } else {
                writeToFromStream(os, (RequestParams.StreamWrapper) value);
            }

            // End the file's object and prepare for next one.
            os.write('}');
        } else if (value instanceof Boolean) {
            os.write((Boolean) value ? JSON_TRUE : JSON_FALSE);
        } else if (value instanceof Long) {
            os.write((((Number) value).longValue() + "").getBytes());
        } else if (value instanceof Double) {
            os.write((((Number) value).doubleValue() + "").getBytes());
        } else if (value instanceof Float) {
            os.write((((Number) value).floatValue() + "").getBytes());
        } else if (value instanceof Integer) {
            os.write((((Number) value).intValue() + "").getBytes());
        } else {
            os.write(value.toString().getBytes());
        }

        os.write(',');
    }

    // Include the elapsed time taken to upload everything.
    // This might be useful for somebody, but it serves us well since
    // there will almost always be a ',' as the last sent character.
    os.write(STREAM_ELAPSED);
    os.write(':');
    long elapsedTime = System.currentTimeMillis() - now;
    os.write((elapsedTime + "}").getBytes());

    Log.i(LOG_TAG, "Uploaded JSON in " + Math.floor(elapsedTime / 1000) + " seconds");

    // Flush the contents up the stream.
    os.flush();
    AsyncHttpClient.silentCloseOutputStream(os);
}

From source file:edu.cuny.qc.speech.AuToBI.PitchExtractor.java

/**
 * A Java implementation of Paul Boersma's pitch extraction algorithm. Implemented in Praat, and called by To
 * Pitch(ac)...//  w ww .ja  v  a 2 s  . com
 *
 * @param time_step            The time step to extract pitch values at
 * @param min_pitch            The minimum valid pitch
 * @param periods_per_window   Number of periods per window
 * @param max_candidates       The number of pitch candidates to consider
 * @param silence_thresh       The silence threshold
 * @param voicing_thresh       The voicing threshold
 * @param octave_cost          The octave cost
 * @param octave_jump_cost     The octave jump cost
 * @param voiced_unvoiced_cost The voiced to unvoiced transition cost
 * @param max_pitch            THe maximum valid pitch
 * @return A list of TimeValuePairs containing pitch information
 * @throws AuToBIException if there's a problem
 */
public Contour soundToPitchAc(double time_step, double min_pitch, double periods_per_window, int max_candidates,
        double silence_thresh, double voicing_thresh, double octave_cost, double octave_jump_cost,
        double voiced_unvoiced_cost, double max_pitch) throws AuToBIException {
    double duration;
    double t0;
    int i, j;
    double dt_window; /* Window length in seconds. */
    int nsamp_window, halfnsamp_window; /* Number of samples per window. */
    int nFrames;
    int maximumLag;
    int iframe, nsampFFT;
    double frame[][];
    double ac[];
    double window[];
    double windowR[];
    double globalPeak;
    double interpolation_depth;
    int nsamp_period, halfnsamp_period; /* Number of samples in longest period. */
    int brent_ixmax, brent_depth;

    if (max_candidates < max_pitch / min_pitch)
        max_candidates = (int) Math.floor(max_pitch / min_pitch);

    if (time_step <= 0.0) {
        time_step = periods_per_window / min_pitch / 4.0; /* e.g. 3 periods, 75 Hz: 10 milliseconds. */
    }

    // Exclusively implementing the AC_HANNING case
    brent_depth = NUM_PEAK_INTERPOLATE_SINC70;
    interpolation_depth = 0.5;
    duration = wav.getDuration();
    if (min_pitch < periods_per_window / duration) {
        throw new AuToBIException("For this Sound, the parameter 'minimum pitch' may not be less than "
                + (periods_per_window / duration) + " Hz.");
    }

    /*
    * Determine the number of samples in the longest period.
    * We need this to compute the local mean of the sound (looking one period in both directions),
    * and to compute the local peak of the sound (looking half a period in both directions).
    */
    nsamp_period = (int) Math.floor(1 / wav.getFrameSize() / min_pitch);
    halfnsamp_period = nsamp_period / 2 + 1;

    if (max_pitch > 0.5 / wav.getFrameSize())
        max_pitch = 0.5 / wav.getFrameSize();

    /*
    * Determine window length in seconds and in samples.
    */
    dt_window = periods_per_window / min_pitch;
    nsamp_window = (int) Math.floor(dt_window / wav.getFrameSize());
    halfnsamp_window = nsamp_window / 2 - 1;
    if (halfnsamp_window < 2) {
        throw new AuToBIException("Analysis window too short.");
    }
    nsamp_window = halfnsamp_window * 2;

    /*
    * Determine the maximum lag.
    */
    maximumLag = (int) (Math.floor(nsamp_window / periods_per_window) + 2);
    if (maximumLag > nsamp_window)
        maximumLag = nsamp_window;

    if (wav.getDuration() < dt_window) {
        throw new AuToBIException("Wav data is shorter than pitch analysis window.");
    }

    Pair<Integer, Double> pair = getNFramesAndStartTime(time_step, dt_window);
    nFrames = pair.first;
    t0 = pair.second;

    /*
    * Create the resulting pitch contour.
    */
    Contour pitch = new Contour(t0, time_step, nFrames);

    /*
    * Compute the global absolute peak for determination of silence threshold.
    */
    globalPeak = 0.0;
    for (int channel = 0; channel < wav.numberOfChannels; ++channel) {
        double mean = 0.0;
        for (i = 0; i < wav.getNumSamples(); ++i) {
            mean += wav.getSample(channel, i);
        }
        mean /= wav.getNumSamples();
        for (i = 0; i < wav.getNumSamples(); ++i) {
            double value = Math.abs(wav.getSample(channel, i) - mean);
            if (value > globalPeak)
                globalPeak = value;
        }
    }
    if (globalPeak == 0.0) {
        return pitch;
    }

    /*
    * Compute the number of samples needed for doing FFT.
    * To avoid edge effects, we have to append zeroes to the window.
    * The maximum lag considered for maxima is maximumLag.
    * The maximum lag used in interpolation is nsamp_window * interpolation_depth.
    */
    nsampFFT = 1;
    while (nsampFFT < nsamp_window * (1 + interpolation_depth))
        nsampFFT *= 2;

    /*
    * Create buffers for autocorrelation analysis.
    */
    frame = new double[wav.numberOfChannels][nsampFFT];

    windowR = new double[nsampFFT];
    window = new double[nsamp_window];
    ac = new double[nsampFFT];

    /* Hanning window. */
    for (i = 0; i < nsamp_window; i++) {
        window[i] = 0.5 - 0.5 * Math.cos((i + 1) * 2 * Math.PI / (nsamp_window + 1));
    }

    /*
    * Compute the normalized autocorrelation of the window.
    */
    for (i = 0; i < nsamp_window; i++) {
        windowR[i] = window[i];
    }
    for (i = nsamp_window; i < nsampFFT; ++i) {
        windowR[i] = 0.0;
    }

    // Forward FFT
    RealDoubleFFT_Radix2 window_fft = new RealDoubleFFT_Radix2(nsampFFT);
    window_fft.transform(windowR);

    windowR[0] *= windowR[0];
    for (i = 1; i < nsampFFT; ++i) {
        // calculate the power spectrum
        // absolute value of the fft
        if (i <= nsampFFT / 2) {
            // The real part
            windowR[i] = windowR[i] * windowR[i] + windowR[nsampFFT - i] * windowR[nsampFFT - i];
        } else {
            // The imaginary part
            windowR[i] = 0;
        }
    }
    window_fft.inverse(windowR);

    for (i = 1; i < nsamp_window; i++) {
        windowR[i] = windowR[i] / windowR[0]; /* Normalize. */
    }
    windowR[0] = 1.0;

    brent_ixmax = (int) (nsamp_window * interpolation_depth);
    int[] imax = new int[max_candidates];

    // Start to calculate pitch
    ArrayList<PitchFrame> pitchFrames = new ArrayList<PitchFrame>();
    for (iframe = 0; iframe < nFrames; iframe++) {

        // It's unclear to me what Sound_to_Pitch.c:224 means
        //  Pitch_Frame pitchFrame = & thy frame [iframe];
        // it seems as though there are two 'frame' variables.
        // 'thy frame' is an array of Pitch_Frames with nFrames elements
        // 'frame' is a channels by nsampFFT matrix

        PitchFrame pitchFrame = new PitchFrame();
        double t = indexToX(t0, time_step, iframe);
        double localPeak;
        int leftSample = xToLowIndex(0.0, wav.getFrameSize(), t);
        int rightSample = leftSample + 1;
        int startSample, endSample;

        double localMean[] = new double[wav.numberOfChannels];
        for (int channel = 0; channel < wav.numberOfChannels; ++channel) {
            /*
            * Compute the local mean; look one longest period to both sides.
            */
            startSample = Math.max(0, rightSample - nsamp_period);
            endSample = Math.min(wav.getNumSamples(), leftSample + nsamp_period);

            localMean[channel] = 0.0;
            for (i = startSample; i <= endSample; i++) {
                localMean[channel] += wav.getSample(channel, i);
            }
            localMean[channel] /= 2 * nsamp_period;

            /*
            * Copy a window to a frame and subtract the local mean.
            * We are going to kill the DC component before windowing.
            */
            startSample = Math.max(0, rightSample - halfnsamp_window);
            //endSample = Math.min(wav.getNumSamples()-1, leftSample + halfnsamp_window);
            for (j = 0, i = startSample; j < nsamp_window; j++)
                frame[channel][j] = (wav.getSample(channel, i++) - localMean[channel]) * window[j];
            for (j = nsamp_window + 1; j < nsampFFT; j++)
                frame[channel][j] = 0.0;
        }

        /*
        * Compute the local peak; look half a longest period to both sides.
        */
        localPeak = 0.0;
        if ((startSample = halfnsamp_window + 1 - halfnsamp_period) < 1) {
            startSample = 0;
        }
        if ((endSample = halfnsamp_window + halfnsamp_period) > nsamp_window)
            endSample = nsamp_window;

        for (int channel = 0; channel < wav.numberOfChannels; ++channel) {
            for (j = startSample; j <= endSample; j++) {
                double value = Math.abs(frame[channel][j]);
                if (value > localPeak)
                    localPeak = value;
            }
        }

        pitchFrame.setIntensity(localPeak > globalPeak ? 1.0 : localPeak / globalPeak);

        /*
        * The FFT of the autocorrelation is the power spectrum.
        */
        for (i = 0; i < nsampFFT; i++) {
            ac[i] = 0.0;
        }

        for (int channel = 0; channel < wav.numberOfChannels; ++channel) {

            // FFT forward
            RealDoubleFFT_Radix2 frame_fft = new RealDoubleFFT_Radix2(nsampFFT);
            frame_fft.transform(frame[channel]);
            ac[0] += frame[channel][0] * frame[channel][0]; /* DC component. */
            for (i = 1; i < nsampFFT - 1; ++i) {
                /* Power spectrum. */
                if (i <= nsampFFT / 2) {
                    // The real part
                    ac[i] += frame[channel][i] * frame[channel][i]
                            + frame[channel][nsampFFT - i] * frame[channel][nsampFFT - i];
                }
            }
        }
        // FFT backward
        RealDoubleFFT_Radix2 ac_fft = new RealDoubleFFT_Radix2(nsampFFT);
        ac_fft.inverse(ac);

        /*
        * Normalize the autocorrelation to the value with zero lag,
        * and divide it by the normalized autocorrelation of the window.
        */
        NegativeSymmetricList r = new NegativeSymmetricList();
        r.add(1.0);
        for (i = 0; i < brent_ixmax; i++) {
            r.add(ac[i + 1] / (ac[0] * windowR[i + 1]));
        }

        /*
        * Register the first candidate, which is always present: voicelessness.
        */
        pitchFrame.addCandidate();
        pitchFrame.getCandidate(0).frequency = 0.0; // Voiceless: always present.
        pitchFrame.getCandidate(0).strength = 0.0;

        /*
        * Shortcut: absolute silence is always voiceless.
        * Go to next frame.
        */
        if (localPeak == 0) {
            pitchFrames.add(pitchFrame);
            continue;
        }

        /*
        * Find the strongest maxima of the correlation of this frame,
        * and register them as candidates.
        */
        imax[1] = 0;
        for (i = 1; i < maximumLag && i < brent_ixmax; i++) {
            if (r.get(i) > 0.5 * voicing_thresh && /* Not too unvoiced? */
                    r.get(i) > r.get(i - 1) && r.get(i) >= r.get(i + 1)) /* Maximum? */ {
                int place = 0;

                /*
                * Use parabolic interpolation for first estimate of frequency,
                * and sin(x)/x interpolation to compute the strengths of this frequency.
                */
                double dr = 0.5 * (r.get(i + 1) - r.get(i - 1)),
                        d2r = 2 * r.get(i) - r.get(i - 1) - r.get(i + 1);

                double frequencyOfMaximum = 1.0 / wav.getFrameSize() / (i + dr / d2r);
                int offset = -brent_ixmax - 1;
                double strengthOfMaximum = /* method & 1 ? */
                        interpolateSinc(r, offset, brent_ixmax - offset,
                                1.0 / wav.getFrameSize() / frequencyOfMaximum - offset, 30)
                /* : r [i] + 0.5 * dr * dr / d2r */;

                /* High values due to short windows are to be reflected around 1. */
                if (strengthOfMaximum > 1.0)
                    strengthOfMaximum = 1.0 / strengthOfMaximum;

                /*
                * Find a place for this maximum.
                */
                if (pitchFrame.getNumCandidates() < max_candidates) { /* Is there still a free place? */
                    place = pitchFrame.getNumCandidates();
                    pitchFrame.addCandidate();
                } else {
                    /* Try the place of the weakest candidate so far. */
                    double weakest = 1;
                    int iweak;
                    for (iweak = 1; iweak < max_candidates; ++iweak) {
                        /* High frequencies are to be favoured */
                        /* if we want to analyze a perfectly periodic signal correctly. */
                        double localStrength = pitchFrame.getCandidate(iweak).strength - octave_cost
                                * Math.log(min_pitch / pitchFrame.getCandidate(iweak).frequency) / Math.log(2);
                        if (localStrength < weakest) {
                            weakest = localStrength;
                            place = iweak;
                        }
                    }
                    /* If this maximum is weaker than the weakest candidate so far, give it no place. */
                    if (strengthOfMaximum
                            - octave_cost * Math.log(min_pitch / frequencyOfMaximum) / Math.log(2) <= weakest) {
                        place = -1;
                    }
                }
                /* Have we found a place for this candidate? */
                if (place >= 0) {
                    pitchFrame.getCandidate(place).frequency = frequencyOfMaximum;
                    pitchFrame.getCandidate(place).strength = strengthOfMaximum;
                    imax[place] = i;
                }
            }
        }
        /*
        * Second pass: for extra precision, maximize sin(x)/x interpolation ('sinc').
        */
        for (i = 1; i < pitchFrame.getNumCandidates(); i++) {
            if (pitchFrame.getCandidate(i).frequency > 0.0) {
                double xmid;
                double ymid;
                int offset = -brent_ixmax - 1;

                Pair<Double, Double> max_results = improveMaximum(r, offset, brent_ixmax - offset,
                        imax[i] - offset,
                        pitchFrame.getCandidate(i).frequency > 0.3 / wav.getFrameSize()
                                ? NUM_PEAK_INTERPOLATE_SINC700
                                : brent_depth);

                ymid = max_results.first;
                xmid = max_results.second;

                xmid += offset;
                pitchFrame.getCandidate(i).frequency = 1.0 / wav.getFrameSize() / xmid;

                if (ymid > 1.0)
                    ymid = 1.0 / ymid;
                pitchFrame.getCandidate(i).strength = ymid;
            }
        }
        pitchFrames.add(pitchFrame);
    } /* Next frame. */

    // Use path finding with constraints to find the lowest cost path through pitch candidates
    pitch = pathFinder(pitchFrames, silence_thresh, voicing_thresh, octave_cost, octave_jump_cost,
            voiced_unvoiced_cost, max_pitch, max_candidates, time_step, t0);

    return pitch;
}

From source file:IBDMUT.Tools.java

public static double floorToSignificantDigits(double value, int places) {
    //        System.out.println(value + "\t" + places + "\t");
    return Math.floor(value * Math.pow(10., places)) / Math.pow(10., places);
}

From source file:com.clutch.ClutchView.java

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
    double zoomDouble = parentWidth / 640.0;
    int zoom = (int) Math.floor(zoomDouble * 100.0);
    this.setInitialScale(zoom);
    String js = "javascript:(function() { var d = document.getElementById('view'); if(d) { d.setAttribute('content', 'user-scalable=yes, width=device-width, minimum-scale="
            + zoomDouble + ", maximum-scale=" + zoomDouble
            + "'); } else { var e = document.createElement('meta'); e.setAttribute('name', 'viewport'); e.setAttribute('id', 'view'); e.setAttribute('content', 'user-scalable=yes, width=device-width minimum-scale="
            + zoomDouble + ", maximum-scale=" + zoomDouble
            + "'); document.getElementsByTagName('head')[0].appendChild(e); }})();";
    this.loadUrl(js);
}

From source file:com.garyclayburg.UserRestSmokeTest.java

@Test
@Ignore/*  ww w.j ava2 s  .  c  o  m*/
public void testPlainApache() throws Exception {
    RestTemplate rest = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
    SimpleUser user1 = new SimpleUser();
    user1.setFirstname("Tommy");
    user1.setLastname("Deleteme");
    user1.setId("112" + (int) (Math.floor(Math.random() * 10000)));

    ResponseEntity<SimpleUser> userResponseEntity = rest
            .postForEntity("http://" + endpoint + "/audited-users/auditedsave", user1, SimpleUser.class);
    log.info("got a response");
    MatcherAssertionErrors.assertThat(userResponseEntity.getStatusCode(), Matchers.equalTo(HttpStatus.OK));

}

From source file:com.act.lcms.db.io.report.IonAnalysisInterchangeModel.java

/**
 * This function is used to compute log frequency distribution of the ion model vs a metric.
 * @param metric The metric on which the frequency distribution is plotted
 * @return A map of a range to the count of molecules that get bucketed in that range
 *//*  www. ja va  2s .  co m*/
public Map<Pair<Double, Double>, Integer> computeLogFrequencyDistributionOfMoleculeCountToMetric(
        METRIC metric) {
    Map<Pair<Double, Double>, Integer> rangeToHitCount = new HashMap<>();

    // This variable represents the total number of statistics that have zero values.
    Integer countOfZeroStats = 0;

    // This statistic represents the log value of the min statistic.
    Double minLogValue = Double.MAX_VALUE;

    for (ResultForMZ resultForMZ : this.getResults()) {
        for (HitOrMiss molecule : resultForMZ.getMolecules()) {

            Double power = 0.0;

            switch (metric) {
            case TIME:
                power = Math.log10(molecule.getTime());
                break;
            case INTENSITY:
                power = Math.log10(molecule.getIntensity());
                break;
            case SNR:
                power = Math.log10(molecule.getSnr());
                break;
            }

            if (power.equals(Double.NEGATIVE_INFINITY)) {
                // We know the statistic was 0 here.
                countOfZeroStats++;
                break;
            }

            Double floor = Math.floor(power);
            Double lowerBound = Math.pow(10.0, floor);
            Double upperBound = Math.pow(10.0, floor + 1);

            minLogValue = Math.min(minLogValue, lowerBound);
            Pair<Double, Double> key = Pair.of(lowerBound, upperBound);
            rangeToHitCount.compute(key, (k, v) -> (v == null) ? 1 : v + 1);
        }

        // We count the total number of zero statistics and put them in the 0 to minLog metric bucket.
        if (countOfZeroStats > 0) {
            Pair<Double, Double> key = Pair.of(0.0, minLogValue);
            rangeToHitCount.put(key, countOfZeroStats);
        }
    }

    return rangeToHitCount;
}

From source file:com.alibaba.jstorm.yarn.registry.SlotPortsView.java

private int getSlotCount(int memory, int vcores) {
    int cpuports = (int) Math.ceil(vcores / JOYConstants.JSTORM_VCORE_WEIGHT);
    int memoryports = (int) Math.floor(memory / JOYConstants.JSTORM_MEMORY_WEIGHT);
    //        return cpuports > memoryports ? memoryports : cpuports;
    return memoryports;
}

From source file:de.tud.kom.p2psim.impl.network.gnp.topology.GnpSpace.java

/**
 * Iterates through all Positions to calculate statistical data like -
 * statistic 1: maximum relative error - statistic 2: directional relative
 * errors grouped by rtt - statistic 3: hosts grouped by maximum relative
 * error - statistic 4: distribution of relative errors
 */// www.  ja  v a  2s  .c o  m
public void builtStatisticalData() {

    // set calculation status to 3 (calculation of statistical data)
    calculationStepStatus = 3;

    maxRelativeError = 0;
    directionalRelativeErrors = new LinkedList[21];
    hostsByRelativeError = new HashSet[21];
    ArrayList<Double> relativeErrorsList = new ArrayList<Double>(4000000);

    for (int d = 0; d < hostsByRelativeError.length; d++)
        hostsByRelativeError[d] = new HashSet<Host>();
    for (int d = 0; d < directionalRelativeErrors.length; d++)
        directionalRelativeErrors[d] = new LinkedList<Double>();

    calculationProgressStatus = 0;
    for (GnpPosition host : coordinateIndex.values()) {
        calculationProgressStatus++;
        double maxError = 0;
        for (GnpPosition monitor : monitorPositions) {
            double measuredDistace = host.getMeasuredRtt(monitor);
            if (measuredDistace > 0) {
                double directionalRelativeError = host.getDirectionalRelativError(monitor);
                double relativeError = Math.abs(directionalRelativeError);
                relativeErrorsList.add(relativeError);

                // statistic 1: maximum relative error
                if (maxError < relativeError)
                    maxError = relativeError;

                // statistic 2: directional relative errors grouped by rtt
                int groupID = (int) Math.floor(measuredDistace / 50);
                if (groupID < 20)
                    directionalRelativeErrors[groupID].add(directionalRelativeError);
                else
                    directionalRelativeErrors[20].add(directionalRelativeError);
            }
            // statistic 3: hosts grouped by maximum relative error
            int groupID = (int) Math.floor(maxError * 10);
            if (groupID >= 20)
                hostsByRelativeError[20].add(host.getHostRef());
            else
                hostsByRelativeError[groupID].add(host.getHostRef());

        }
        // statistic 1: maximum relative error
        if (maxRelativeError < maxError)
            maxRelativeError = maxError;
    }

    // statistic 4: distribution of relative errors
    double[] relativeErrorsArray = new double[relativeErrorsList.size()];
    for (int c = 0; c < relativeErrorsList.size(); c++)
        relativeErrorsArray[c] = relativeErrorsList.get(c);
    relativeErrorDistribution = new double[100];
    for (int c = 1; c < 100; c++)
        relativeErrorDistribution[c] = StatUtils.percentile(relativeErrorsArray, c);

    // set calculation status to 0 (no calculation)
    calculationStepStatus = 0;
}

From source file:com.galactogolf.specificobjectmodel.GalactoGolfWorld.java

@Override
public void Render(long timeSinceLastFrame) {
    super.Render(timeSinceLastFrame);
    RenderInstructionBuffer instructionList = _renderer.GetOpenRenderInstructionBuffer();

    // work out which tiles to draw based on the mininum x & y corner, then
    // draw four tiles to cover the other parts
    // of the screen. NB this only works if the screen is small enough so
    // four repeated tiles can cover
    // the whole screen
    float hazeScale = 2.0f;
    float tileWidth = _hazeSprite.GetRenderable().getWidth() * hazeScale;
    float tileHeight = _hazeSprite.GetRenderable().getHeight() * hazeScale;
    float minX = (float) (Math.floor((getCameraLocation().x - GetScreenWidth() / 2) / tileWidth) * tileWidth);
    float minY = (float) (Math.floor((getCameraLocation().y - GetScreenHeight() / 2) / tileHeight)
            * tileHeight);/*from w  w w.  j  a va  2s  . c  om*/
    float halfX = (_hazeSprite.GetRenderable().getWidth() / 2) * hazeScale;
    float halfY = (_hazeSprite.GetRenderable().getHeight() / 2) * hazeScale;

    // 0,0
    instructionList.AddRenderSimpleSpriteInstruction(minX + halfX, minY + halfY, 0.0f, hazeScale, hazeScale,
            _hazeSprite.GetCurrentFrameSet(), _hazeSprite.GetCurrentFrame(), _hazeSprite.GetRenderable());
    // 1,0
    instructionList.AddRenderSimpleSpriteInstruction(minX + halfX + tileWidth, minY + halfY, 0.0f, hazeScale,
            hazeScale, _hazeSprite.GetCurrentFrameSet(), _hazeSprite.GetCurrentFrame(),
            _hazeSprite.GetRenderable());
    // 0,1
    instructionList.AddRenderSimpleSpriteInstruction(minX + halfX, minY + halfY + tileHeight, 0.0f, hazeScale,
            hazeScale, _hazeSprite.GetCurrentFrameSet(), _hazeSprite.GetCurrentFrame(),
            _hazeSprite.GetRenderable());

    // 1,1
    instructionList.AddRenderSimpleSpriteInstruction(minX + halfX + tileWidth, minY + halfY + tileHeight, 0.0f,
            hazeScale, hazeScale, _hazeSprite.GetCurrentFrameSet(), _hazeSprite.GetCurrentFrame(),
            _hazeSprite.GetRenderable());

    // -1,0
    instructionList.AddRenderSimpleSpriteInstruction(minX + halfX - tileWidth, minY + halfY, 0.0f, hazeScale,
            hazeScale, _hazeSprite.GetCurrentFrameSet(), _hazeSprite.GetCurrentFrame(),
            _hazeSprite.GetRenderable());
    // 0,-1
    instructionList.AddRenderSimpleSpriteInstruction(minX + halfX, minY + halfY - tileHeight, 0.0f, hazeScale,
            hazeScale, _hazeSprite.GetCurrentFrameSet(), _hazeSprite.GetCurrentFrame(),
            _hazeSprite.GetRenderable());

    // -1,-1
    instructionList.AddRenderSimpleSpriteInstruction(minX + halfX - tileWidth, minY + halfY - tileHeight, 0.0f,
            hazeScale, hazeScale, _hazeSprite.GetCurrentFrameSet(), _hazeSprite.GetCurrentFrame(),
            _hazeSprite.GetRenderable());

    // -1,+1
    instructionList.AddRenderSimpleSpriteInstruction(minX + halfX - tileWidth, minY + halfY + tileHeight, 0.0f,
            hazeScale, hazeScale, _hazeSprite.GetCurrentFrameSet(), _hazeSprite.GetCurrentFrame(),
            _hazeSprite.GetRenderable());

    // +1,-1
    instructionList.AddRenderSimpleSpriteInstruction(minX + halfX + tileWidth, minY + halfY - tileHeight, 0.0f,
            hazeScale, hazeScale, _hazeSprite.GetCurrentFrameSet(), _hazeSprite.GetCurrentFrame(),
            _hazeSprite.GetRenderable());

    synchronized (getStars()) {

        for (StarSprite sprite : getStars()) {

            if (sprite.visible(getCameraLocation().x - (GetScreenWidth() / getCameraLocation().z / 2),
                    getCameraLocation().y - (GetScreenHeight() / getCameraLocation().z / 2),
                    getCameraLocation().x + (GetScreenWidth() / getCameraLocation().z / 2),
                    getCameraLocation().y + (GetScreenHeight() / getCameraLocation().z / 2))) {

                instructionList.AddRenderSimpleSpriteInstruction(sprite.getPosition().x, sprite.getPosition().y,
                        0.0f, sprite.GetCurrentFrameSet(), sprite.GetCurrentFrame(), sprite.GetRenderable());
            }
        }
    }

    for (NonPlayerEntity ent : getNpcs()) {
        if (ent.isVisibleAndInFrustrum(getCameraLocation().x - (GetScreenWidth() / getCameraLocation().z / 2),
                getCameraLocation().y - (GetScreenHeight() / getCameraLocation().z / 2),
                getCameraLocation().x + (GetScreenWidth() / getCameraLocation().z / 2),
                getCameraLocation().y + (GetScreenHeight() / getCameraLocation().z / 2)
        /*
         * -_world.getCameraLocation().x, -_world.getCameraLocation().y,
         * _world.GetScreenWidth() - _world.getCameraLocation().x ,
         * _world.GetScreenHeight() - _world.getCameraLocation().y
         */
        )) {
            ent.render(instructionList, timeSinceLastFrame);
        }
    }
    GetPlayer().render(instructionList, timeSinceLastFrame);
    instructionList.AddRenderSimpleSpriteInstruction(GetScreenWidth() / 2, GetScreenHeight() - 32,
            _infoBar.getAngle(), GetScreenWidth() / 16.0f, 1.0f, true, 0, 0, _infoBar.GetRenderable());

    if (!_isEditing && !((GalactoGolfPlayerEntity) GetPlayer()).HasPlayerHitWormhole()) {
        if (!runningPhysics()) {
            // draw the power handle and the reset button
            if (userIsSettingPower()) {
                _powerHandle.getPosition().x = _probePowerLine.getEnd().x;
                _powerHandle.getPosition().y = _probePowerLine.getEnd().y;
            } else {
                _powerHandle.getPosition().x = _player.getPosition().x;
                _powerHandle.getPosition().y = _player.getPosition().y + 100;
                instructionList.AddRenderSimpleSpriteInstruction(_powerHandle.getPosition().x,
                        _powerHandle.getPosition().y, _powerHandle.getAngle(), 1.0f, 1.0f, 0, 0,
                        _powerHandle.GetRenderable());
            }

        }

        instructionList.AddRenderSimpleSpriteInstruction(GetScreenWidth() - 64, GetScreenHeight() - 32,
                _resetButton.getAngle(), 1.0f, 1.0f, true, 0, 0, _resetButton.GetRenderable());

    }

    // pool specific, draw the power lines if needed
    if (userIsSettingPower()) {
        _currentPowerLine = Vector2D.Sub(_probePowerLine.getEnd(), _probePowerLine.getStart()).magnitude();
        // getProbePowerLine().render(gl);
        _currentPowerLine = _currentPowerLine / 50 + 0.1f;
        instructionList.AddRenderSimpleSpriteInstruction(_player.getPosition().x, _player.getPosition().y,
                _player.getAngle(), 1.0f, _currentPowerLine, GameConstants.POWER_ARROW_RED_FRAMESET, 0,
                _powerArrow.GetRenderable());
        // set the previous power line

    }

    if (_previousPowerLineSet) {
        instructionList.AddRenderSimpleSpriteInstruction(_previousPowerLineLocation.x,
                _previousPowerLineLocation.y, _previousPowerLineAngle, 1.0f, _previousPowerLine,
                GameConstants.POWER_ARROW_BLUE_FRAMESET, _powerArrow.GetCurrentFrame(),
                _powerArrow.GetRenderable());
    }

    if (isUserSelectingEntity()) {
        instructionList.AddRenderSimpleSpriteInstruction(_selectedEntity.getPosition().x,
                _selectedEntity.getPosition().y - 150, (float) 180, 1.0f, 1.0f,
                _powerArrow.GetCurrentFrameSet(), _powerArrow.GetCurrentFrame(), _powerArrow.GetRenderable());

    }

}