Example usage for java.util Arrays fill

List of usage examples for java.util Arrays fill

Introduction

In this page you can find the example usage for java.util Arrays fill.

Prototype

public static void fill(Object[] a, Object val) 

Source Link

Document

Assigns the specified Object reference to each element of the specified array of Objects.

Usage

From source file:cz.paulrz.montecarlo.random.ParallelPercentile.java

/** {@inheritDoc} */
@Override// w  w  w .j  a v  a 2 s  .c o m
public void setData(final double[] values, final int begin, final int length) {
    if (values == null) {
        cachedPivots = null;
    } else {
        cachedPivots = new int[(0x1 << MAX_CACHED_LEVELS) - 1];
        Arrays.fill(cachedPivots, -1);
    }
    super.setData(values, begin, length);
}

From source file:net.sf.jclal.activelearning.singlelabel.querystrategy.VarianceReductionQueryStrategy.java

/**
 *
 * Analyzes how informative is an instance.
 *
 * @param instance The instance to query.
 * @return The utility of the instance./*w  w  w. j  a v  a 2 s  . com*/
 */
@Override
public double utilityInstance(Instance instance) {

    Instances unlabeled = getUnlabelledData().getDataset();

    if (unlabelledSize != unlabeled.numInstances()) {
        unlabelledSize = unlabeled.numInstances();

        //it is initialized q_sub_i
        int n = unlabeled.numInstances();
        double[] q = new double[n];
        //1. q_sub_i = 1/n, i = 1, 2, ..., n
        //Arrays.fill(q, 1.0 / n);
        //further on it fills, to optimize

        //it is initialized pi_sub_i
        //2. pi_sub_i
        double[] piSubI = getPiSubI(unlabeled);

        //to create the Fisher matrix
        int dimensionMatrix = unlabeled.numAttributes() - 1;
        int classIndex = unlabeled.classIndex();

        Matrix matrixFisher = null;
        try {
            matrixFisher = new Matrix(dimensionMatrix, dimensionMatrix);
        } catch (Exception ex) {
            Logger.getLogger(VarianceReductionQueryStrategy.class.getName()).log(Level.SEVERE, null, ex);
        }

        for (int i = 0; i < piSubI.length; i++) {
            double mult = piSubI[i] * (1 - piSubI[i]);

            //the values of the instance are had
            double[] atributos = unlabeled.instance(i).toDoubleArray();

            //the attribute class is eliminated, only the features are left
            double[] vectorX = DatasetUtils.copyFeatures(atributos, classIndex);

            Matrix current = null;
            try {
                current = new Matrix(vectorX.length, vectorX.length);
            } catch (Exception ex) {
                Logger.getLogger(VarianceReductionQueryStrategy.class.getName()).log(Level.SEVERE, null, ex);
            }

            productVector(current, vectorX);

            //it multiplies current * multi
            current.timesEquals(mult);

            //it adds current to matrixFisher
            //plusEquals saves the result in matrixFisher
            matrixFisher.plusEquals(current);

        }

        double factorRegularizationValue = getFactorRegularization();

        Matrix identity = Matrix.identity(dimensionMatrix, dimensionMatrix);

        identity.timesEquals(factorRegularizationValue);

        //the result joins to matrixFisher
        matrixFisher.plusEquals(identity);

        //do eigen decomposition
        EigenvalueDecomposition eigen = matrixFisher.eig();

        //in case of file, the matrix v takes the matrix file from eigen
        //in this case eigen cant not be destroy for the moment
        Matrix v = eigen.getV();

        double[] landa = eigen.getRealEigenvalues();

        double epsilonValue = getEpsilon();

        //variable copies of q to know if there has been some change
        double[] copiaQ = new double[q.length];
        Arrays.fill(copiaQ, 1.0 / n);

        //while it finds change in q, it keeps on iterating
        currentEpsilonIteration = 0;
        do {
            ++currentEpsilonIteration;
            //the value of q is updated
            //in the first iteration it fills with 1.0/n
            System.arraycopy(copiaQ, 0, q, 0, q.length);

            //process of finding f_sub_i
            double[] f = new double[landa.length];
            for (int j = 0; j < f.length; j++) {
                f[j] = 0;

                for (int i = 0; i < n; i++) {
                    double mult = q[i] * piSubI[i] * (1 - piSubI[i]);

                    //the values of the instance are had
                    double[] atributos = unlabeled.instance(i).toDoubleArray();

                    //the attribute class is eliminated, only the features are left
                    double[] vectorX = DatasetUtils.copyFeatures(atributos, classIndex);

                    //it multiplies vector_x with vector_columna of V
                    //vector_x it is: 1 X n
                    //vector_de_V it is: n X 1
                    //result: a number
                    double multVectores = 0;
                    for (int k = 0; k < vectorX.length; k++) {
                        multVectores += vectorX[k] * v.get(k, j);
                    }

                    //the result rises up to the square
                    multVectores *= multVectores;

                    //it joins to f[j]
                    f[j] += mult * multVectores;
                }
            }

            //the first process of finding q of the current iteration       
            for (int i = 0; i < n; i++) {
                double mult = copiaQ[i] * copiaQ[i] * piSubI[i] * (1 - piSubI[i]);

                //the values of the instance are had
                double[] atributos = unlabeled.instance(i).toDoubleArray();

                //the attribute class is eliminated, only the features are left
                double[] vectorX = DatasetUtils.copyFeatures(atributos, classIndex);

                //the following  is realized
                double sumatoria = 0;
                for (int j = 0; j < landa.length; j++) {

                    //it multiplies vector_x with vector_columna of V
                    //vector_x is: 1 X n
                    //vector_de_V is: n X 1
                    //result: a number
                    double multVectores = 0;
                    for (int k = 0; k < vectorX.length; k++) {
                        multVectores += vectorX[k] * v.get(k, j);
                    }

                    //the result multiplies with landa[j]
                    multVectores *= landa[j];

                    //it rises up to the square
                    multVectores *= multVectores;

                    //it splits between the square of f [j]
                    multVectores /= f[j] * f[j];

                    //the sumatoria is added
                    sumatoria += multVectores;
                }

                //the value of copia_q [i] is: mult * sumatoria
                copiaQ[i] = mult * sumatoria;
            }

            //the second step to find q in the iteration

            /*the sum must be out, if it was inside and with copia_q then 
             *one would give priority to the last instance and the last one 
             * would be always chosen
             */
            double suma = 0;
            for (int j = 0; j < n; j++) {
                suma += copiaQ[j];
            }

            for (int i = 0; i < n; i++) {
                copiaQ[i] = copiaQ[i] / suma;
            }

        } while (change(q, copiaQ, epsilonValue));

        //the values are saved
        tempValues = new double[copiaQ.length];

        System.arraycopy(copiaQ, 0, tempValues, 0, copiaQ.length);

    }

    int indice = unlabeled.indexOf(instance);

    return tempValues[indice];
}

From source file:de.uniba.wiai.kinf.pw.projects.lillytab.reasoner.abox.ABoxNode.java

public String toString(final int indent) {
    char[] fill = new char[indent];
    Arrays.fill(fill, ' ');
    return toString(String.valueOf(fill));
}

From source file:com.ibuildapp.romanblack.CataloguePlugin.utils.Utils.java

/**
 * download file url and save it/*from w  w w .  j a  va2s  .  c o  m*/
 *
 * @param url
 */
public static String downloadFile(String url) {
    int BYTE_ARRAY_SIZE = 1024;
    int CONNECTION_TIMEOUT = 30000;
    int READ_TIMEOUT = 30000;

    // downloading cover image and saving it into file
    try {
        URL imageUrl = new URL(URLDecoder.decode(url));
        URLConnection conn = imageUrl.openConnection();
        conn.setConnectTimeout(CONNECTION_TIMEOUT);
        conn.setReadTimeout(READ_TIMEOUT);
        BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());

        File resFile = new File(
                Statics.moduleCachePath + File.separator + com.appbuilder.sdk.android.Utils.md5(url));
        if (!resFile.exists()) {
            resFile.createNewFile();
        }

        FileOutputStream fos = new FileOutputStream(resFile);
        int current = 0;
        byte[] buf = new byte[BYTE_ARRAY_SIZE];
        Arrays.fill(buf, (byte) 0);
        while ((current = bis.read(buf, 0, BYTE_ARRAY_SIZE)) != -1) {
            fos.write(buf, 0, current);
            Arrays.fill(buf, (byte) 0);
        }

        bis.close();
        fos.flush();
        fos.close();
        Log.d("", "");
        return resFile.getAbsolutePath();
    } catch (SocketTimeoutException e) {
        return null;
    } catch (IllegalArgumentException e) {
        return null;
    } catch (Exception e) {
        return null;
    }
}

From source file:edu.berkeley.compbio.ml.cluster.kohonen.KohonenSOM2D.java

public KohonenSOM2D(final DissimilarityMeasure<T> dm, final Set<String> potentialTrainingBins,
        final Map<String, Set<String>> predictLabelSets, final ProhibitionModel<T> prohibitionModel,
        final Set<String> testLabels, @NotNull final Integer[] cellsPerDimension,
        final SimpleFunction moveFactorFunction, final SimpleFunction radiusFunction,
        final SimpleFunction weightFunction, final boolean decrementLosingNeighborhood, final boolean edgesWrap,
        final double minRadius, final KohonenSOM2DSearchStrategy<T> searchStrategy) {
    super(dm, potentialTrainingBins, predictLabelSets, prohibitionModel, testLabels);

    this.cellsPerDimension = DSArrayUtils.toPrimitive(cellsPerDimension);

    this.dimensions = cellsPerDimension.length;
    this.moveFactorFunction = moveFactorFunction;
    this.radiusFunction = radiusFunction;
    this.weightFunction = weightFunction;
    this.decrementLosingNeighborhood = decrementLosingNeighborhood;
    this.edgesWrap = edgesWrap;
    this.minRadius = minRadius;
    this.searchStrategy = searchStrategy;

    if (dimensions != 2) {
        throw new ClusterRuntimeException("KohonenSOM2D accepts only two-dimensional grid.");
    }//from  w w w. j  a  v a  2  s .  c om

    // precompute stuff for listIndexFor
    /*
    blockSize = new int[dimensions];
    blockSize[1] = 1;
    blockSize[0] = cellsPerDimension[1];
    */
    final int totalCells = cellsPerDimension[0] * cellsPerDimension[1];

    setNumClusters(totalCells);

    final int[] zeroCell = new int[dimensions];
    Arrays.fill(zeroCell, 0);
    //createClusters(zeroCell, -1, prototype);
    //createClusters(totalCells, prototype);
    //List<Interval<Double>> axisRanges;
    //   initializeClusters(axisRanges);

    maxRadius = DSArrayUtils.norm(this.cellsPerDimension) / 2.;//Math.ceil();

    searchStrategy.setDistanceMeasure(measure);
}

From source file:feature.lowLevel.audio.FeatureExtractor.java

/**
 * @param waveSegment audio data//  ww w  .j a  v a2 s . com
 * @param opt Feature Extraction Options
 * @param fftWindowSize size of window for FFT calculation
 * @return RealMatrixExt array containing one RealMatrixExt for each feature set extracted
 */
public RealMatrixExt[] extractFeatureSets(short[] waveSegment, FeatureExtractionOptions opt,
        int fftWindowSize) {
    int segmentSize = waveSegment.length;
    int fi = 0; // feature set index
    RealMatrixExt[] featureSets = new RealMatrixExt[opt.getNumberOfFeatureSets()];

    /* convert to double precision and */
    /* scale wave data to adjust according to hearing threshold */

    @SuppressWarnings("unused")
    double divisor;

    if (sampleSizeInBits == 8) {
        divisor = 256;
    } else {
        divisor = 32768;
    }

    double[] wav = new double[segmentSize];

    for (int i = 0; i < segmentSize; i++) {
        wav[i] = waveSegment[i];
    }

    /*
     * compute spectrogram for each wave segment (with 50 % overlap in FFT computation)
     */

    double[][] spec = Spectrogram.computeSpectrogram(wav, fftWindowSize, fftWindowSize / 2, Window.HAMMING);

    int nFrames = spec.length;

    /* group to bark bands */

    BarkScale barkScale = new BarkScale(sampleRate, fftWindowSize);
    int nBands = barkScale.getNumberOfBarkBands();

    double[][] specBark = new double[nFrames][nBands];

    for (int t = 0; t < nFrames; t++) {
        specBark[t] = barkScale.apply(spec[t]);
    }

    /* decibel */
    for (int t = 0; t < nFrames; t++) {
        for (int b = 0; b < nBands; b++) {
            if (specBark[t][b] < 1) {
                specBark[t][b] = 0; // in Matlab code this is 1
            } else {
                specBark[t][b] = 10.0 * Math.log10(specBark[t][b]); // in
            }
        }
    }

    /* Sone */

    for (int t = 0; t < nFrames; t++) {
        for (int b = 0; b < nBands; b++) {
            if (specBark[t][b] >= 40) {
                specBark[t][b] = Math.pow(2, ((specBark[t][b] - 40) / 10));
            } else {
                specBark[t][b] = Math.pow((specBark[t][b] / 40), 2.642);
            }
        }
    }

    /* transpose matrix (for efficient row processing) */
    RealMatrix specBarkT = new RealMatrixExt(specBark).transpose();

    /* compute SSD features */

    if (opt.hasSSD()) {
        featureSets[fi++] = computeStatisticalSpectrumDescriptor(specBarkT, opt.getBandLimit());
    }

    if (!(opt.hasRP() || opt.hasRH()))
        return featureSets;

    /* FFT */

    double[][] specModAmp = new double[nBands][];

    FFT FFTreal = new FFT();

    for (int b = 0; b < nBands; b++) {
        // compute FFT magnitude of each band
        specModAmp[b] = FFTreal.computeMagnitude(specBarkT.getRow(b));
    }

    /* Fluctuation Strength Curve */

    // resolution of modulation frequency axis (0.17 Hz)
    double modulationFreqResolution = 1 / ((double) segmentSize / (double) sampleRate);

    for (int b = 0; b < nBands; b++) {
        specModAmp[b][0] = 0; // omit DC component (would cause deviations while blurring)
        for (int t = 1; t <= nFrames; t++) // skip DC component (avoid div/0)
        {
            double modFreq = modulationFreqResolution * t;
            double fluctWeight = 1 / (modFreq / 4 + 4 / modFreq);
            specModAmp[b][t] = specModAmp[b][t] * fluctWeight;
        }
    }

    /* Blurring */
    int bandLimit = opt.getBandLimit();
    int modAmplLimit = opt.getModAmpLimit();
    double[][] result = new double[bandLimit][modAmplLimit];

    if (nBands < bandLimit) {
        // requested number of bands is > than actual # of bands
        // fill remainder with 0
        for (int b = nBands; b < bandLimit; b++) {
            Arrays.fill(result[b], 0);
        }
        bandLimit = nBands;
    }

    for (int b = 0; b < bandLimit; b++) {
        for (int t = 1; t <= modAmplLimit; t++) {
            // skip DC component: start with 1
            result[b][t - 1] = specModAmp[b][t];
        }
    }

    RealMatrixExt rhythmPattern = new RealMatrixExt(result);
    rhythmPattern.setType(RealMatrixExt.TYPE_RP);

    if (opt.hasRP()) {
        featureSets[fi++] = rhythmPattern;
    }

    /* compute RH features */

    if (opt.hasRH()) {
        featureSets[fi++] = computeRhythmHistogram(rhythmPattern);
    }

    return featureSets;
}

From source file:net.nicholaswilliams.java.licensing.TestObjectSerializer.java

@Test
public void testReadObject3() throws Exception {
    MockTestObject1 object = new MockTestObject1();
    object.coolTest = true;// ww w.  ja va  2 s  .c  o  m
    Arrays.fill(object.myArray, (byte) 12);

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    ObjectOutputStream stream = new ObjectOutputStream(bytes);

    stream.writeObject(object);
    stream.close();

    byte[] data = bytes.toByteArray();

    MockTestObject1 returned = this.serializer.readObject(MockTestObject1.class, data);

    assertNotNull("The returned object should not be null.", returned);
    assertFalse("The returned object should not be the same.", returned == object);
    assertEquals("The returned object should be equal.", object, returned);
}

From source file:RectListManager.java

public void clear() {
    Arrays.fill(rects, null);
    size = 0;
    bounds = null;
}

From source file:bftsmart.tom.ServiceProxy.java

/**
 * This method sends a request to the replicas, and returns the related reply.
 * If the servers take more than invokeTimeout seconds the method returns null.
 * This method is thread-safe.//from   www.j  a  v a2 s. c om
 *
 * @param request Request to be sent
 * @param reqType TOM_NORMAL_REQUESTS for service requests, and other for
 *        reconfig requests.
 * @return The reply from the replicas related to request
 */
public byte[] invoke(byte[] request, TOMMessageType reqType) {
    canSendLock.lock();

    // Clean all statefull data to prepare for receiving next replies
    Arrays.fill(replies, null);
    receivedReplies = 0;
    response = null;
    replyListener = null;

    // Send the request to the replicas, and get its ID
    reqId = generateRequestId(reqType);
    requestType = reqType;
    TOMulticast(request, reqId, reqType);

    Logger.println("Sending request (" + reqType + ") with reqId=" + reqId);
    Logger.println("Expected number of matching replies: " + replyQuorum);
    /*try{
       this.sm.acquire();
    }catch(Exception e){
       Logger.println("Problems acquiering the sem in line 195 of class ServiceProxy.");
    }*/
    // This instruction blocks the thread, until a response is obtained.
    // The thread will be unblocked when the method replyReceived is invoked
    // by the client side communication system
    try {
        if (!this.sm.tryAcquire(invokeTimeout, TimeUnit.SECONDS)) {
            Logger.println("###################TIMEOUT#######################");
            Logger.println("Reply timeout for reqId=" + reqId);
            canSendLock.unlock();

            System.out.print(getProcessId() + " // " + reqId + " // TIMEOUT // ");
            System.out.println("Replies received: " + receivedReplies);
            System.exit(0);
            return null;
        }
    } catch (InterruptedException ex) {
    }

    Logger.println("Response extracted = " + response);

    byte[] ret = null;

    if (response == null) {
        //the response can be null if n-f replies are received but there isn't
        //a replyQuorum of matching replies
        Logger.println("Received n-f replies and no response could be extracted.");

        canSendLock.unlock();
        if (reqType == TOMMessageType.UNORDERED_REQUEST) {
            //invoke the operation again, whitout the read-only flag
            Logger.println("###################RETRY#######################");
            return invokeOrdered(request);
        } else {
            throw new RuntimeException("Received n-f replies without f+1 of them matching.");
        }
    } else {
        //normal operation
        //******* EDUARDO BEGIN **************//
        if (reqType == TOMMessageType.ORDERED_REQUEST) {
            //Reply to a normal request!
            if (response.getViewID() == getViewManager().getCurrentViewId()) {
                ret = response.getContent(); // return the response
            } else {//if(response.getViewID() > getViewManager().getCurrentViewId())
                //updated view received
                reconfigureTo((View) TOMUtil.getObject(response.getContent()));

                canSendLock.unlock();
                return invoke(request, reqType);
            }
        } else {
            if (response.getViewID() > getViewManager().getCurrentViewId()) {
                //Reply to a reconfigure request!
                Logger.println("Reconfiguration request' reply received!");
                Object r = TOMUtil.getObject(response.getContent());
                if (r instanceof View) { //did not executed the request because it is using an outdated view
                    reconfigureTo((View) r);

                    canSendLock.unlock();
                    return invoke(request, reqType);
                } else { //reconfiguration executed!
                    reconfigureTo(((ReconfigureReply) r).getView());
                    ret = response.getContent();
                }
            } else {
                // Reply to readonly request
                ret = response.getContent();
            }
        }
    }
    //******* EDUARDO END **************//

    canSendLock.unlock();
    return ret;
}

From source file:WorkerRunnable.java

/**
 *  Once we have sampled the local counts, trash the 
 *   "global" type topic counts and reuse the space to 
 *   build a summary of the type topic counts specific to 
 *   this worker's section of the corpus.
 *///from  www. j  a v  a2s  . c  o  m
public void buildLocalTypeTopicCounts() {

    // Clear the topic totals
    Arrays.fill(tokensPerTopic, 0);

    // Clear the type/topic counts, only 
    //  looking at the entries before the first 0 entry.

    for (int type = 0; type < typeTopicCounts.length; type++) {

        int[] topicCounts = typeTopicCounts[type];

        int position = 0;
        while (position < topicCounts.length && topicCounts[position] > 0) {
            topicCounts[position] = 0;
            position++;
        }
    }

    for (int doc = startDoc; doc < data.size() && doc < startDoc + numDocs; doc++) {

        TopicAssignment document = data.get(doc);

        FeatureSequence tokens = (FeatureSequence) document.instance.getData();
        LabelSequence topicSequence = (LabelSequence) document.topicSequence;

        int[] topics = topicSequence.getFeatures();
        for (int position = 0; position < tokens.size(); position++) {

            int topic = topics[position];

            if (topic == UNASSIGNED_TOPIC) {
                continue;
            }

            tokensPerTopic[topic]++;

            // The format for these arrays is 
            //  the topic in the rightmost bits
            //  the count in the remaining (left) bits.
            // Since the count is in the high bits, sorting (desc)
            //  by the numeric value of the int guarantees that
            //  higher counts will be before the lower counts.

            int type = tokens.getIndexAtPosition(position);

            int[] currentTypeTopicCounts = typeTopicCounts[type];

            // Start by assuming that the array is either empty
            //  or is in sorted (descending) order.

            // Here we are only adding counts, so if we find 
            //  an existing location with the topic, we only need
            //  to ensure that it is not larger than its left neighbor.

            int index = 0;
            int currentTopic = currentTypeTopicCounts[index] & topicMask;
            int currentValue;

            while (currentTypeTopicCounts[index] > 0 && currentTopic != topic) {
                index++;
                if (index == currentTypeTopicCounts.length) {
                    System.out.println("overflow on type " + type);
                }
                currentTopic = currentTypeTopicCounts[index] & topicMask;
            }
            currentValue = currentTypeTopicCounts[index] >> topicBits;

            if (currentValue == 0) {
                // new value is 1, so we don't have to worry about sorting
                //  (except by topic suffix, which doesn't matter)

                currentTypeTopicCounts[index] = (1 << topicBits) + topic;
            } else {
                currentTypeTopicCounts[index] = ((currentValue + 1) << topicBits) + topic;

                // Now ensure that the array is still sorted by 
                //  bubbling this value up.
                while (index > 0 && currentTypeTopicCounts[index] > currentTypeTopicCounts[index - 1]) {
                    int temp = currentTypeTopicCounts[index];
                    currentTypeTopicCounts[index] = currentTypeTopicCounts[index - 1];
                    currentTypeTopicCounts[index - 1] = temp;

                    index--;
                }
            }
        }
    }

}