Example usage for java.util Collections nCopies

List of usage examples for java.util Collections nCopies

Introduction

In this page you can find the example usage for java.util Collections nCopies.

Prototype

public static <T> List<T> nCopies(int n, T o) 

Source Link

Document

Returns an immutable list consisting of n copies of the specified object.

Usage

From source file:com.facebook.presto.operator.aggregation.AbstractTestApproximateCountDistinct.java

private Page createPage(List<Object> values, double maxStandardError) {
    if (values.isEmpty()) {
        return new Page(0);
    } else {/* w w  w  .ja v  a  2 s  .c o m*/
        return new Page(values.size(), createBlock(getValueType(), values), createBlock(DOUBLE,
                ImmutableList.copyOf(Collections.nCopies(values.size(), maxStandardError))));
    }
}

From source file:io.prestosql.operator.aggregation.AbstractTestApproximateCountDistinct.java

private Page createPage(List<?> values, double maxStandardError) {
    if (values.isEmpty()) {
        return new Page(0);
    } else {/*from   w w w  .j  a v  a 2 s  . c om*/
        return new Page(values.size(), createBlock(getValueType(), values), createBlock(DOUBLE,
                ImmutableList.copyOf(Collections.nCopies(values.size(), maxStandardError))));
    }
}

From source file:org.apache.hadoop.hdfs.server.namenode.BlockPlacementPolicyStair.java

/** {@inheritDoc} */
public void initialize(Configuration conf, FSClusterStats stats, NetworkTopology clusterMap,
        HostsFileReader hostsReader, DNSToSwitchMapping dnsToSwitchMapping, FSNamesystem ns) {
    super.initialize(conf, stats, clusterMap, hostsReader, dnsToSwitchMapping, ns);
    this.namesystem = ns;
    // Default/*from  ww  w .  j  a  va2  s  . c om*/
    this.stripeLen = 0;
    this.considerLoad = conf.getBoolean("dfs.replication.considerLoad", true);
    FSNamesystem.LOG.info("F4: Block placement will consider load: " + this.considerLoad);
    initParityConfigs();
    this.stagingDir = conf.get("dfs.f4.staging", "/staging");
    this.localDir = conf.get("dfs.f4.local", "/local");

    /* Added by RH Jul 26th, 2015 begins
     * TODO: reading rstair code settings */
    this.stairRow = conf.getInt("hdfs.raid.stair.row", 4);
    this.stairCol = conf.getInt("hdfs.raid.stair.col", 5);
    this.stairRowParityNum = conf.getInt("hdfs.raid.stair.rowParityNum", 1);
    this.stairColParityNum = conf.getInt("hdfs.raid.stair.colParityNum", 1);

    totalLen = stairRow * stairCol;
    stripeIdxToRack = new ArrayList<Integer>(Collections.nCopies(totalLen, 0));
    stripeIdxToNodeInRack = new ArrayList<Integer>(Collections.nCopies(totalLen, 0));

    /* parsing err vec */
    int i;
    parityLen = 0;
    for (i = 0; i < stairColParityNum; i++) {
        stairErrVec.add(this.stairRow);
        parityLen += this.stairRow;
    }
    //LOG.info("RHDEBUG: parityLen=" + parityLen);
    String errVec = conf.get("hdfs.raid.stair.errVec", "1");
    if (errVec.contains(",")) {
        for (String str : errVec.split(",")) {
            stairErrVec.add(this.stairRowParityNum + Integer.parseInt(str));
            parityLen += (this.stairRowParityNum + Integer.parseInt(str));
            i++;
        }
    } else {
        // single element array
        stairErrVec.add(this.stairRowParityNum + Integer.parseInt(errVec));
        parityLen += (this.stairRowParityNum + Integer.parseInt(errVec));
        i++;
    }
    //LOG.info("RHDEBUG: parityLen=" + parityLen);
    for (; i < this.stairCol; i++) {
        stairErrVec.add(this.stairRowParityNum);
        parityLen += (this.stairRowParityNum);
    }
    //LOG.info("RHDEBUG: parityLen=" + parityLen);

    dataLen = totalLen - parityLen;

    int[] numberParityInRow = new int[this.stairRow];
    int currPos = this.stairCol - 1;
    for (i = this.stairRow - 1; i >= 0; i--) {
        numberParityInRow[i] = stairCol;
        for (int j = 0; j < stairErrVec.size(); j++) {
            if (stairErrVec.get(j) <= stairRow - 1 - i)
                numberParityInRow[i]--;
        }
        //LOG.info("numberParityInRow[" + i + "]=" + numberParityInRow[i]);
    }
    //LOG.info("RHDEBUG: " + stairErrVec);

    int dataCount = 0;
    int parityCount = 0;
    for (i = 0; i < this.stairRow; i++) {
        for (int j = 0; j < this.stairCol; j++) {
            //LOG.info("i=" + i + " j=" + j + " dataCount=" + dataCount + " parityCount=" + parityCount);
            if (j < this.stairCol - numberParityInRow[i]) {
                stripeIdxToRack.set(dataCount, j);
                stripeIdxToNodeInRack.set(dataCount++, i);
            } else {
                stripeIdxToRack.set(dataLen + parityCount, j);
                stripeIdxToNodeInRack.set(dataLen + (parityCount++), i);
            }
        }
    }

    LOG.info("R-STAIR code placement initialized: dataLen: " + dataLen + " parityLen: " + parityLen
            + " stripeIdxToRack: " + stripeIdxToRack + " stripeIdxToNodeInRack: " + stripeIdxToNodeInRack);
    /* Added by RH Jul 26th, 2015 ends */
}

From source file:org.sonar.db.AbstractDbTester.java

/**
 * Very simple helper method to insert some data into a table.
 * It's the responsibility of the caller to convert column values to string.
 */// w ww  . j  a v a2  s.  c o  m
public void executeInsert(String table, Map<String, Object> valuesByColumn) {
    if (valuesByColumn.isEmpty()) {
        throw new IllegalArgumentException("Values cannot be empty");
    }

    String sql = "insert into " + table.toLowerCase(Locale.ENGLISH) + " ("
            + COMMA_JOINER.join(valuesByColumn.keySet()) + ") values ("
            + COMMA_JOINER.join(Collections.nCopies(valuesByColumn.size(), '?')) + ")";
    executeUpdateSql(sql, valuesByColumn.values().toArray(new Object[valuesByColumn.size()]));
}

From source file:com.kyleszombathy.sms_scheduler.MessageAlarmReceiver.java

/** Sends the actual messaage and handles errors*/
private boolean sendSMSMessage(String phoneNumber, final ArrayList<String> messageArrayList) {
    int size = messageArrayList.size();

    // Sent and delivery intents
    Intent sentIntent = new Intent(SENT);
    Intent deliveryIntent = new Intent(DELIVERED);

    /*Create Pending Intents*/
    PendingIntent sentPI = PendingIntent.getBroadcast(context.getApplicationContext(), 0, sentIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    PendingIntent deliverPI = PendingIntent.getBroadcast(context.getApplicationContext(), 0, deliveryIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Sends single or multiple messages based off message length
    if (size == 1) {
        smsManager.sendTextMessage(phoneNumber, null, messageArrayList.get(0), sentPI, deliverPI);
    } else {// www.  j ava  2  s. co  m
        // Create sending/delivery lists for sending to multiple recipients
        ArrayList<PendingIntent> sentPIList = new ArrayList<>(Collections.nCopies(size, sentPI));
        ArrayList<PendingIntent> deliveryPIList = new ArrayList<>(Collections.nCopies(size, deliverPI));
        smsManager.sendMultipartTextMessage(phoneNumber, null, messageArrayList, sentPIList, deliveryPIList);
    }
    return true;
}

From source file:org.hspconsortium.cwfdemo.ui.mar.model.MarModel.java

/**
 * Initializes the MAR by transforming each FHIR medication administration into a corresponding
 * row in the MAR.//from   w  ww.  ja v a2s .  c  o m
 * 
 * @param medAdmins
 */
private void init(List<MedicationRequest> medOrders, List<MedicationAdministration> medAdmins) {
    Map<String, Integer> headerIndex = new HashMap<String, Integer>();
    headers = new ListModelList<String>();
    rows = new ListModelList<List<Object>>();
    medicationRowIndex = new HashMap<String, List<Object>>();
    orderIndex = new HashMap<String, MedicationRequest>();

    headers.add("Medication");
    int index = 0;
    for (MedicationAdministration medAdmin : medAdmins) {
        String timeHeader;
        try {
            timeHeader = dateFormat.format(medAdmin.getEffectiveDateTimeType());
        } catch (FHIRException e) {
            timeHeader = "";
        }
        if (!headerIndex.containsKey(timeHeader)) {
            headerIndex.put(timeHeader, index++);
            headers.add(timeHeader);
        }
    }

    // Index the orders by ID for easy retrieval
    // TODO May wish to filter somehow in future
    for (MedicationRequest order : medOrders) {
        if (order.getId() != null || order.getIdElement().getValue() == null) {
            orderIndex.put(order.getIdElement().getIdPart(), order);
            String sentence = MarRenderer.generateMedicationOrderSentence(order);
            List<Object> row = medicationRowIndex.get(sentence);
            if (row == null) {
                row = new ListModelList<Object>(Collections.nCopies(headers.size() + 1, ""));
                medicationRowIndex.put(sentence, row);
                row.set(headers.size(), order);
                row.set(0, sentence);
                rows.add(row);
            }
        } else {
            log.error("Skipping Order. Medication order does not have an ID");
        }
    }

    for (MedicationAdministration medAdmin : medAdmins) {
        try {
            String medicationName = FhirUtil.getDisplayValueForType(medAdmin.getMedicationCodeableConcept());
        } catch (FHIRException e) {

        }
        MedicationRequest associatedPrescription = orderIndex
                .get(medAdmin.getPrescription().getReferenceElement().getIdPart());// TODO Surface reference in generated code
        String sentence = MarRenderer.generateMedicationOrderSentence(associatedPrescription);
        List<Object> row = medicationRowIndex.get(sentence);
        String timeHeader;
        try {
            timeHeader = dateFormat.format(medAdmin.getEffectiveDateTimeType());
        } catch (FHIRException e) {
            timeHeader = "";
        }
        int ind = headerIndex.get(timeHeader);
        // row.set(ind + 1, checkboxPlaceholder);
        //         row.set(ind + 1, "eafry: " + medAdmin.getDosage().getQuantity().getValue() + " "
        //               + medAdmin.getDosage().getQuantity().getUnit());
        MarRenderer.recordAdministrationNotes(row, ind + 1, medAdmin, associatedPrescription, "eafry");
    }
}

From source file:org.apache.hadoop.hbase.procedure2.store.wal.ProcedureWALLoaderPerformanceEvaluation.java

/**
 * @return a list of shuffled integers which represent state of proc id. First occurrence of a
 * number denotes insert state, consecutive occurrences denote update states, and -ve value
 * denotes delete state.//from   w  w  w. java2  s. co m
 */
private List<Integer> shuffleProcWriteSequence() {
    Random rand = new Random();
    List<Integer> procStatesSequence = new ArrayList<>();
    Set<Integer> toBeDeletedProcs = new HashSet<>();
    // Add n + 1 entries of the proc id for insert + updates. If proc is chosen for delete, add
    // extra entry which is marked -ve in the loop after shuffle.
    for (int procId = 1; procId <= numProcs; ++procId) {
        procStatesSequence.addAll(Collections.nCopies(updatesPerProc + 1, procId));
        if (rand.nextFloat() < deleteProcsFraction) {
            procStatesSequence.add(procId);
            toBeDeletedProcs.add(procId);
        }
    }
    Collections.shuffle(procStatesSequence);
    // Mark last occurrences of proc ids in toBeDeletedProcs with -ve to denote it's a delete state.
    for (int i = procStatesSequence.size() - 1; i >= 0; --i) {
        int procId = procStatesSequence.get(i);
        if (toBeDeletedProcs.contains(procId)) {
            procStatesSequence.set(i, -1 * procId);
            toBeDeletedProcs.remove(procId);
        }
    }
    return procStatesSequence;
}

From source file:org.apache.hadoop.hive.serde2.teradata.TeradataBinaryDataOutputStream.java

/**
 * Write CHAR(N).// www  .  jav  a2 s. co m
 * The representation of char in Teradata binary format is:
 * the byte number to read is based on the [charLength] * [bytePerChar] <- totalLength,
 * bytePerChar is decided by the charset: LATAIN charset is 2 bytes per char and UNICODE charset is 3 bytes per char.
 * the null char will use space to pad.
 *
 * @param writable the writable
 * @param length the byte n
 * @throws IOException the io exception
 */
public void writeChar(HiveCharWritable writable, int length) throws IOException {
    if (writable == null) {
        String pad = join("", Collections.nCopies(length, " "));
        write(pad.getBytes("UTF8"));
        return;
    }
    Text t = writable.getStrippedValue();
    int contentLength = t.getLength();
    write(t.getBytes(), 0, contentLength);
    if (length - contentLength < 0) {
        throw new IOException(format(
                "The byte num %s of HiveCharWritable is more than the byte num %s we can hold. "
                        + "The content of HiveCharWritable is %s",
                contentLength, length, writable.getPaddedValue()));
    }
    if (length > contentLength) {
        String pad = join("", Collections.nCopies(length - contentLength, " "));
        write(pad.getBytes("UTF8"));
    }
}

From source file:de.bund.bfr.math.MathUtils.java

public static List<StartValues> createStartValuesList(List<ParamRange> ranges, int n,
        ToDoubleFunction<List<Double>> errorFunction, DoubleConsumer progessListener, ExecutionContext exec)
        throws CanceledExecutionException {
    List<StartValues> valuesList = new ArrayList<>();

    for (int i = 0; i < n; i++) {
        valuesList.add(new StartValues(Collections.nCopies(ranges.size(), i + 1.0), Double.POSITIVE_INFINITY));
    }//from w  w w  . j  a  v a  2s  .c o  m

    List<Integer> paramStepIndex = new ArrayList<>(Collections.nCopies(ranges.size(), 0));
    boolean done = false;
    int allStepSize = 1;
    int count = 0;

    for (ParamRange range : ranges) {
        allStepSize *= range.getStepCount();
    }

    while (!done) {
        List<Double> values = new ArrayList<>();

        for (int i = 0; i < ranges.size(); i++) {
            values.add(ranges.get(i).getMin() + paramStepIndex.get(i) * ranges.get(i).getStepSize());
        }

        double error = errorFunction.applyAsDouble(values);

        if (Double.isFinite(error) || error < valuesList.get(n - 1).getError()) {
            for (int i = 0; i < n; i++) {
                if (error < valuesList.get(i).getError()) {
                    valuesList.add(i, new StartValues(values, error));
                    valuesList.remove(n);
                    break;
                }
            }
        }

        for (int i = 0;; i++) {
            if (i >= ranges.size()) {
                done = true;
                break;
            }

            paramStepIndex.set(i, paramStepIndex.get(i) + 1);

            if (paramStepIndex.get(i) >= ranges.get(i).getStepCount()) {
                paramStepIndex.set(i, 0);
            } else {
                break;
            }
        }

        if (exec != null) {
            exec.checkCanceled();
        }

        progessListener.accept((double) ++count / (double) allStepSize);
    }

    return valuesList;
}

From source file:de.bund.bfr.knime.pmm.common.math.ParameterOptimizer.java

public void optimize(AtomicInteger progress, int nParameterSpace, int nLevenberg, boolean stopWhenSuccessful) {
    List<Double> paramMin = new ArrayList<>();
    List<Integer> paramStepCount = new ArrayList<>();
    List<Double> paramStepSize = new ArrayList<>();
    int maxCounter = 1;
    int paramsWithRange = 0;
    int maxStepCount = 10;

    for (int i = 0; i < parameters.size(); i++) {
        Double min = minParameterValues.get(i);
        Double max = maxParameterValues.get(i);

        if (min != null && max != null) {
            paramsWithRange++;//  w  ww  . j  a  v  a2s  .  co m
        }
    }

    if (paramsWithRange != 0) {
        maxStepCount = (int) Math.pow(nParameterSpace, 1.0 / paramsWithRange);
        maxStepCount = Math.max(maxStepCount, 2);
        maxStepCount = Math.min(maxStepCount, 10);
    }

    for (int i = 0; i < parameters.size(); i++) {
        Double min = minParameterValues.get(i);
        Double max = maxParameterValues.get(i);

        if (min != null && max != null) {
            paramMin.add(min);
            paramStepCount.add(maxStepCount);
            maxCounter *= maxStepCount;

            if (max > min) {
                paramStepSize.add((max - min) / (maxStepCount - 1));
            } else {
                paramStepSize.add(1.0);
            }
        } else if (min != null) {
            if (min != 0.0) {
                paramMin.add(min);
            } else {
                paramMin.add(MathUtilities.EPSILON);
            }

            paramStepCount.add(1);
            paramStepSize.add(1.0);
        } else if (max != null) {
            if (max != 0.0) {
                paramMin.add(max);
            } else {
                paramMin.add(-MathUtilities.EPSILON);
            }

            paramStepCount.add(1);
            paramStepSize.add(1.0);
        } else {
            paramMin.add(MathUtilities.EPSILON);
            paramStepCount.add(1);
            paramStepSize.add(1.0);
        }
    }

    List<List<Double>> bestValues = new ArrayList<>();
    List<Double> bestError = new ArrayList<>();

    for (int i = 0; i < nLevenberg; i++) {
        bestValues.add(new ArrayList<>(Collections.nCopies(parameters.size(), i + 1.0)));
        bestError.add(Double.POSITIVE_INFINITY);
    }

    List<Integer> paramStepIndex = new ArrayList<>(Collections.nCopies(parameters.size(), 0));
    boolean done = false;
    int counter = 0;

    while (!done) {
        progress.set(Float.floatToIntBits((float) counter / (float) maxCounter));
        counter++;

        List<Double> values = new ArrayList<>();
        double error = 0.0;

        for (int i = 0; i < parameters.size(); i++) {
            double value = paramMin.get(i) + paramStepIndex.get(i) * paramStepSize.get(i);

            values.add(value);
            parser.setVarValue(parameters.get(i), value);
        }

        for (int i = 0; i < targetValues.size(); i++) {
            for (int j = 0; j < arguments.size(); j++) {
                parser.setVarValue(arguments.get(j), argumentValues.get(j).get(i));
            }

            try {
                double value = (Double) parser.evaluate(function);
                double diff = targetValues.get(i) - value;

                error += diff * diff;
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (ClassCastException e) {
                error = Double.POSITIVE_INFINITY;
                break;
            }
        }

        for (int i = nLevenberg; i >= 0; i--) {
            if (i == 0 || !(error < bestError.get(i - 1))) {
                if (i != nLevenberg) {
                    bestError.add(i, error);
                    bestValues.add(i, values);
                    bestError.remove(nLevenberg);
                    bestValues.remove(nLevenberg);
                }

                break;
            }
        }

        for (int i = 0;; i++) {
            if (i >= parameters.size()) {
                done = true;
                break;
            }

            paramStepIndex.set(i, paramStepIndex.get(i) + 1);

            if (paramStepIndex.get(i) >= paramStepCount.get(i)) {
                paramStepIndex.set(i, 0);
            } else {
                break;
            }
        }
    }

    successful = false;

    for (List<Double> startValues : bestValues) {
        try {
            optimize(startValues);

            double cost = optimizerValues.getCost();

            if (!successful || cost * cost < sse) {
                useCurrentResults(startValues);

                if (rSquare != 0.0) {
                    successful = true;

                    if (stopWhenSuccessful) {
                        break;
                    }
                }
            }
        } catch (TooManyEvaluationsException e) {
            break;
        } catch (ConvergenceException e) {
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}