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:me.Wundero.Ray.utils.TextUtils.java

private static void addPadding(Text padding, Text.Builder build, int count) {
    if (count > 0) {
        build.append(Collections.nCopies(count, padding));
    }/*from www  .  ja va  2s.c  om*/
}

From source file:org.broadinstitute.sting.utils.codecs.bcf2.BCF2EncoderDecoderUnitTest.java

@Test(dataProvider = "BCF2EncodingTestProviderBasicTypes")
public void testBCF2EncodingVectors(final List<BCF2TypedValue> toEncode) throws IOException {
    for (final BCF2TypedValue tv : toEncode) {
        for (final int length : Arrays.asList(2, 5, 10, 15, 20, 25)) {
            BCF2Encoder encoder = new BCF2Encoder();
            List<Object> expected = Collections.nCopies(length, tv.value);
            encoder.encodeTyped(expected, tv.type);

            BCF2Decoder decoder = new BCF2Decoder(encoder.getRecordBytes());
            final Object decoded = decoder.decodeTypedValue();

            Assert.assertTrue(decoded instanceof List);
            final List<Object> decodedList = (List<Object>) decoded;
            Assert.assertEquals(decodedList.size(), expected.size());
            for (Object decodedValue : decodedList)
                myAssertEquals(tv, decodedValue);
        }/*from   w w  w  . j  a  v a 2s.c o m*/
    }
}

From source file:GenAppStoreSales.java

private static void readSales(String periodTime, boolean restoreSales, boolean computeSales)
        throws IOException {
    countryLabels = new ArrayList<String>();
    countryUnits = new ArrayList<ArrayList<Integer>>();
    countryInAppLabels = new ArrayList<String>();
    countryInAppUnits = new ArrayList<ArrayList<Integer>>();
    int t = 0, periodDays = 0;
    boolean anotherDay = true;
    if (periodTime.equals("day"))
        periodDays = 1;// w  w w.  ja v a  2 s  .  com
    else if (periodTime.equals("week"))
        periodDays = 7;
    else if (periodTime.equals("month"))
        periodDays = rollCalendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    else if (periodTime.equals("year"))
        periodDays = rollCalendar.getActualMaximum(Calendar.DAY_OF_YEAR);
    else if (periodTime.equals("custom")) {
        while (rollCalendar.compareTo(customCalendar) > 0) {
            rollCalendar.add(Calendar.DATE, -1);
            periodDays++;
        }
        rollCalendar.add(Calendar.DATE, periodDays);
    }

    while (anotherDay) {
        String dateCode = String.format("%d%02d%02d", pursuedYear, pursuedMonth, pursuedDay);
        String reportName = "S_D_" + appID + "_" + dateCode + ".txt";
        File salesFile = new File(sourcePath + "/" + reportName);
        if (salesFile.isFile()) {
            String SKU, productCountry;
            int productUnits;
            boolean update;
            float productPrice;
            BufferedReader salesFileReader = new BufferedReader(new FileReader(sourcePath + "/" + reportName));
            String line = salesFileReader.readLine(); // skips the first line
            while ((line = salesFileReader.readLine()) != null) {
                String[] columns = line.split("\t");
                // SKU
                SKU = columns[2];
                // Product Units
                if (columns[6].equals("7T"))
                    update = true;
                else
                    update = false;
                productUnits = Integer.parseInt(columns[7]);
                // Product Price
                productPrice = Float.parseFloat(columns[8]);
                // Country Code
                productCountry = columns[12];

                //                 System.out.println("SKU " + SKU + " Units " + productUnits + " Country Code " + productCountry);

                if (SKU.equals(appSKU)) {
                    if (periodTime.equals("day")) {
                        dayUnits += productUnits;
                    }
                    if (computeSales) {
                        totalUnits += productUnits;
                        if (update) {
                            totalUpdateUnits += productUnits;
                        }
                    }
                    if (restoreSales) {
                        int index = countryLabels.indexOf(productCountry);
                        if (index < 0) {
                            countryLabels.add(productCountry);
                            countryUnits.add(new ArrayList<Integer>(Collections.nCopies(periodDays, 0)));
                            countryUnits.get(countryUnits.size() - 1).set(t, productUnits);
                        } else
                            countryUnits.get(index).set(t, productUnits);
                    }
                } else {
                    if (periodTime.equals("day")) {
                        dayINAPPUnits += productUnits;
                    }
                    if (computeSales) {
                        totalInAppUnits += productUnits;
                    }
                    if (restoreSales) {
                        int index = countryInAppLabels.indexOf(productCountry);
                        if (index < 0) {
                            countryInAppLabels.add(productCountry);
                            countryInAppUnits.add(new ArrayList<Integer>(Collections.nCopies(periodDays, 0)));
                            countryInAppUnits.get(countryInAppUnits.size() - 1).set(t, productUnits);
                        } else
                            countryInAppUnits.get(index).set(t, productUnits);
                    }
                }
            }
            salesFileReader.close();
        }

        if (periodTime.equals("day")) {
            anotherDay = false;
        } else if (periodTime.equals("week")) {
            if (rollCalendar.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
                anotherDay = false;
            }
        } else if (periodTime.equals("month")) {
            if (rollCalendar.get(Calendar.DAY_OF_MONTH) == 1) {
                anotherDay = false;
            }
        } else if (periodTime.equals("year")) {
            if (rollCalendar.get(Calendar.DAY_OF_YEAR) == 1) {
                anotherDay = false;
            }
        } else if (periodTime.equals("custom")) {
            if (rollCalendar.compareTo(customCalendar) <= 0) {
                anotherDay = false;
            }
        }
        rollCalendar.add(Calendar.DATE, -1);
        updateRollCalendar();
        t++;
    }
}

From source file:org.broadinstitute.gatk.tools.walkers.genotyper.afcalc.AFCalcTestBuilder.java

public VariantContext makeACTest(final int[] nhet, final int[] nhomvar, final int nNonInformative,
        final int nonTypePL) {
    List<Genotype> samples = new ArrayList<Genotype>(nSamples);

    for (int altI = 0; altI < nhet.length; altI++) {
        for (int i = 0; i < nhet[altI]; i++)
            samples.add(makePL(GenotypeType.HET, nonTypePL, altI + 1));
        for (int i = 0; i < nhomvar[altI]; i++)
            samples.add(makePL(GenotypeType.HOM_VAR, nonTypePL, altI + 1));
    }//from ww  w  . j a va  2  s .c  o  m

    final Genotype nonInformative = makeNonInformative();
    samples.addAll(Collections.nCopies(nNonInformative, nonInformative));

    final int nRef = Math.max((int) (nSamples - nNonInformative - MathUtils.sum(nhet) - MathUtils.sum(nhomvar)),
            0);
    samples.addAll(Collections.nCopies(nRef, makePL(GenotypeType.HOM_REF, nonTypePL, 0)));

    samples = samples.subList(0, nSamples);

    if (samples.size() > nSamples)
        throw new IllegalStateException("too many samples");

    VariantContextBuilder vcb = new VariantContextBuilder("x", "1", 1, 1, getAlleles());
    vcb.genotypes(samples);
    return vcb.make();
}

From source file:io.syndesis.jsondb.impl.SqlJsonDB.java

private int deleteJsonRecords(Handle dbi, String baseDBPath, String like) {

    LinkedList<String> params = getAllParentPaths(baseDBPath);

    StringBuilder sql = new StringBuilder("DELETE from jsondb where path LIKE ?");
    if (!params.isEmpty()) {
        sql.append(" OR path in ( ").append(String.join(", ", Collections.nCopies(params.size(), "?")))
                .append(" )");
    }//from   w w  w.j  a  va2 s . co  m

    params.addFirst(like);
    return dbi.update(sql.toString(), params.toArray());
}

From source file:com.github.mrstampy.esp.neurosky.MultiConnectionThinkGearSocket.java

@Override
public List<EspChannel> getChannels() {
    return Collections.nCopies(1, thinkGearChannel);
}

From source file:com.android.contacts.database.SimContactDaoImpl.java

private Cursor queryRawContactsForSimContacts(List<SimContact> contacts) {
    final StringBuilder selectionBuilder = new StringBuilder();

    int phoneCount = 0;
    int nameCount = 0;
    for (SimContact contact : contacts) {
        if (contact.hasPhone()) {
            phoneCount++;//from   w ww.  j a va2  s .c o  m
        } else if (contact.hasName()) {
            nameCount++;
        }
    }
    List<String> selectionArgs = new ArrayList<>(phoneCount + 1);

    selectionBuilder.append('(');
    selectionBuilder.append(Data.MIMETYPE).append("=? AND ");
    selectionArgs.add(Phone.CONTENT_ITEM_TYPE);

    selectionBuilder.append(Phone.NUMBER).append(" IN (")
            .append(Joiner.on(',').join(Collections.nCopies(phoneCount, '?'))).append(')');
    for (SimContact contact : contacts) {
        if (contact.hasPhone()) {
            selectionArgs.add(contact.getPhone());
        }
    }
    selectionBuilder.append(')');

    if (nameCount > 0) {
        selectionBuilder.append(" OR (");

        selectionBuilder.append(Data.MIMETYPE).append("=? AND ");
        selectionArgs.add(StructuredName.CONTENT_ITEM_TYPE);

        selectionBuilder.append(Data.DISPLAY_NAME).append(" IN (")
                .append(Joiner.on(',').join(Collections.nCopies(nameCount, '?'))).append(')');
        for (SimContact contact : contacts) {
            if (!contact.hasPhone() && contact.hasName()) {
                selectionArgs.add(contact.getName());
            }
        }
        selectionBuilder.append(')');
    }

    return mResolver.query(
            Data.CONTENT_URI.buildUpon().appendQueryParameter(Data.VISIBLE_CONTACTS_ONLY, "true").build(),
            DataQuery.PROJECTION, selectionBuilder.toString(),
            selectionArgs.toArray(new String[selectionArgs.size()]), null);
}

From source file:edu.stanford.slac.archiverappliance.PB.data.BoundaryConditionsSimulationValueGenerator.java

public DBR getJCASampleValue(ArchDBRTypes type, int secondsIntoYear) {
    switch (type) {
    case DBR_SCALAR_STRING:
        DBR_TIME_String retvalss = new DBR_TIME_String(new String[] { Integer.toString(secondsIntoYear) });
        retvalss.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear));
        retvalss.setSeverity(1);/*  ww w.j a  v  a2 s  .com*/
        retvalss.setStatus(0);
        return retvalss;
    case DBR_SCALAR_SHORT:
        DBR_TIME_Short retvalsh;
        if (0 <= secondsIntoYear && secondsIntoYear < 1000) {
            // Check for some numbers around the minimum value
            retvalsh = new DBR_TIME_Short(new short[] { (short) (Short.MIN_VALUE + secondsIntoYear) });
        } else if (1000 <= secondsIntoYear && secondsIntoYear < 2000) {
            // Check for some numbers around the maximum value
            retvalsh = new DBR_TIME_Short(new short[] { (short) (Short.MAX_VALUE - (secondsIntoYear - 1000)) });
        } else {
            // Check for some numbers around 0
            retvalsh = new DBR_TIME_Short(new short[] { (short) (secondsIntoYear - 2000) });
        }
        retvalsh.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear));
        retvalsh.setSeverity(1);
        retvalsh.setStatus(0);
        return retvalsh;
    case DBR_SCALAR_FLOAT:
        DBR_TIME_Float retvalfl;
        if (0 <= secondsIntoYear && secondsIntoYear < 1000) {
            // Check for some numbers around the minimum value
            retvalfl = new DBR_TIME_Float(new float[] { Float.MIN_VALUE + secondsIntoYear });
        } else if (1000 <= secondsIntoYear && secondsIntoYear < 2000) {
            // Check for some numbers around the maximum value
            retvalfl = new DBR_TIME_Float(new float[] { Float.MAX_VALUE - (secondsIntoYear - 1000) });
        } else {
            // Check for some numbers around 0. Divide by a large number to make sure we cater to the number of precision digits
            retvalfl = new DBR_TIME_Float(new float[] { (secondsIntoYear - 2000.0f) / secondsIntoYear });
        }
        retvalfl.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear));
        retvalfl.setSeverity(1);
        retvalfl.setStatus(0);
        return retvalfl;
    case DBR_SCALAR_ENUM:
        DBR_TIME_Enum retvalen;
        retvalen = new DBR_TIME_Enum(new short[] { (short) (secondsIntoYear) });
        retvalen.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear));
        retvalen.setSeverity(1);
        retvalen.setStatus(0);
        return retvalen;
    case DBR_SCALAR_BYTE:
        DBR_TIME_Byte retvalby;
        retvalby = new DBR_TIME_Byte(new byte[] { ((byte) (secondsIntoYear % 255)) });
        retvalby.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear));
        retvalby.setSeverity(1);
        retvalby.setStatus(0);
        return retvalby;
    case DBR_SCALAR_INT:
        DBR_TIME_Int retvalint;
        if (0 <= secondsIntoYear && secondsIntoYear < 1000) {
            // Check for some numbers around the minimum value
            retvalint = new DBR_TIME_Int(new int[] { Integer.MIN_VALUE + secondsIntoYear });
        } else if (1000 <= secondsIntoYear && secondsIntoYear < 2000) {
            // Check for some numbers around the maximum value
            retvalint = new DBR_TIME_Int(new int[] { Integer.MAX_VALUE - (secondsIntoYear - 1000) });
        } else {
            // Check for some numbers around 0
            retvalint = new DBR_TIME_Int(new int[] { (secondsIntoYear - 2000) });
        }
        retvalint.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear));
        retvalint.setSeverity(1);
        retvalint.setStatus(0);
        return retvalint;
    case DBR_SCALAR_DOUBLE:
        DBR_TIME_Double retvaldb;
        if (0 <= secondsIntoYear && secondsIntoYear < 1000) {
            // Check for some numbers around the minimum value
            retvaldb = new DBR_TIME_Double(new double[] { (Double.MIN_VALUE + secondsIntoYear) });
        } else if (1000 <= secondsIntoYear && secondsIntoYear < 2000) {
            // Check for some numbers around the maximum value
            retvaldb = new DBR_TIME_Double(new double[] { (Double.MAX_VALUE - (secondsIntoYear - 1000)) });
        } else {
            // Check for some numbers around 0. Divide by a large number to make sure we cater to the number of precision digits
            retvaldb = new DBR_TIME_Double(
                    new double[] { ((secondsIntoYear - 2000.0) / (secondsIntoYear * 1000000)) });
        }
        retvaldb.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear));
        retvaldb.setSeverity(1);
        retvaldb.setStatus(0);
        return retvaldb;
    case DBR_WAVEFORM_STRING:
        DBR_TIME_String retvst;
        // Varying number of copies of a typical value
        retvst = new DBR_TIME_String(
                Collections.nCopies(secondsIntoYear, Integer.toString(secondsIntoYear)).toArray(new String[0]));
        retvst.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear));
        retvst.setSeverity(1);
        retvst.setStatus(0);
        return retvst;
    case DBR_WAVEFORM_SHORT:
        DBR_TIME_Short retvsh;
        retvsh = new DBR_TIME_Short(
                ArrayUtils.toPrimitive(Collections.nCopies(1, (short) secondsIntoYear).toArray(new Short[0])));
        retvsh.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear));
        retvsh.setSeverity(1);
        retvsh.setStatus(0);
        return retvsh;
    case DBR_WAVEFORM_FLOAT:
        DBR_TIME_Float retvf;
        // Varying number of copies of a typical value
        retvf = new DBR_TIME_Float(ArrayUtils.toPrimitive(
                Collections.nCopies(secondsIntoYear, (float) Math.cos(secondsIntoYear * Math.PI / 3600))
                        .toArray(new Float[0])));
        retvf.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear));
        retvf.setSeverity(1);
        retvf.setStatus(0);
        return retvf;
    case DBR_WAVEFORM_ENUM:
        DBR_TIME_Enum retven;
        retven = new DBR_TIME_Enum(ArrayUtils
                .toPrimitive(Collections.nCopies(1024, (short) secondsIntoYear).toArray(new Short[0])));
        retven.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear));
        retven.setSeverity(1);
        retven.setStatus(0);
        return retven;
    case DBR_WAVEFORM_BYTE:
        DBR_TIME_Byte retvb;
        // Large number of elements in the array
        retvb = new DBR_TIME_Byte(ArrayUtils.toPrimitive(Collections
                .nCopies(65536 * secondsIntoYear, ((byte) (secondsIntoYear % 255))).toArray(new Byte[0])));
        retvb.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear));
        retvb.setSeverity(1);
        retvb.setStatus(0);
        return retvb;
    case DBR_WAVEFORM_INT:
        DBR_TIME_Int retvint;
        // Varying number of copies of a typical value
        retvint = new DBR_TIME_Int(ArrayUtils.toPrimitive(Collections
                .nCopies(secondsIntoYear, secondsIntoYear * secondsIntoYear).toArray(new Integer[0])));
        retvint.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear));
        retvint.setSeverity(1);
        retvint.setStatus(0);
        return retvint;
    case DBR_WAVEFORM_DOUBLE:
        DBR_TIME_Double retvd;
        // Varying number of copies of a typical value
        retvd = new DBR_TIME_Double(ArrayUtils.toPrimitive(Collections
                .nCopies(secondsIntoYear, Math.sin(secondsIntoYear * Math.PI / 3600)).toArray(new Double[0])));
        retvd.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear));
        retvd.setSeverity(1);
        retvd.setStatus(0);
        return retvd;
    case DBR_V4_GENERIC_BYTES:
        throw new RuntimeException("Currently don't support " + type + " when generating sample data");
    default:
        throw new RuntimeException("We seemed to have missed a DBR type when generating sample data");
    }
}

From source file:org.proninyaroslav.libretorrent.fragments.AddTorrentFragment.java

private void buildTorrent() {
    AddTorrentFilesFragment fileFrag = (AddTorrentFilesFragment) adapter.getItem(FILE_FRAG_POS);
    AddTorrentInfoFragment infoFrag = (AddTorrentInfoFragment) adapter.getItem(INFO_FRAG_POS);

    if (fileFrag != null || infoFrag != null) {
        ArrayList<Integer> selectedIndexes = fileFrag.getSelectedFileIndexes();
        String downloadDir = infoFrag.getDownloadDir();
        String torrentName = infoFrag.getTorrentName();
        boolean sequentialDownload = infoFrag.isSequentialDownload();
        boolean startTorrent = infoFrag.startTorrent();

        if (info != null) {
            ArrayList<BencodeFileItem> files = info.getFiles();
            if (files.size() != 0 && selectedIndexes.size() != 0 && !TextUtils.isEmpty(torrentName)) {
                if (FileIOUtils.getFreeSpace(downloadDir) >= fileFrag.getSelectedFileSize()) {
                    Intent intent = new Intent();

                    ArrayList<Integer> priorities = new ArrayList<>(
                            Collections.nCopies(files.size(), Priority.IGNORE.swig()));

                    for (int index : selectedIndexes) {
                        priorities.set(index, Priority.NORMAL.swig());
                    }//from  www .  j  a  v  a 2  s  . c  o m

                    Torrent torrent = new Torrent(info.getSha1Hash(), torrentName, priorities, downloadDir);

                    torrent.setSequentialDownload(sequentialDownload);
                    torrent.setPaused(!startTorrent);
                    torrent.setTorrentFilePath(pathToTempTorrent);

                    intent.putExtra(AddTorrentActivity.TAG_RESULT_TORRENT, torrent);

                    finish(intent, FragmentCallback.ResultCode.OK);

                } else {
                    Snackbar snackbar = Snackbar.make(coordinatorLayout, R.string.error_free_space,
                            Snackbar.LENGTH_LONG);
                    snackbar.show();
                }

            } else {
                if (selectedIndexes.size() == 0) {
                    Snackbar snackbar = Snackbar.make(coordinatorLayout, R.string.error_no_files_selected,
                            Snackbar.LENGTH_LONG);
                    snackbar.show();
                }
            }
        }
    }
}

From source file:com.tage.calcite.adapter.druid.DruidConnectionImpl.java

/** Executes a request and returns the resulting rows as an
 * {@link Enumerable}, running the parser in a thread provided by
 * {@code service}. *///from   w  w  w .  j  a v  a 2 s.  c  o  m
public Enumerable<Row> enumerable(final com.tage.calcite.adapter.druid.QueryType queryType,
        final String request, final List<String> fieldNames, final ExecutorService service) throws IOException {
    return new AbstractEnumerable<Row>() {
        public Enumerator<Row> enumerator() {
            final BlockingQueueEnumerator<Row> enumerator = new BlockingQueueEnumerator<>();
            final RunnableQueueSink sink = new RunnableQueueSink() {
                public void send(Row row) throws InterruptedException {
                    enumerator.queue.put(row);
                }

                public void end() {
                    enumerator.done.set(true);
                }

                public void setSourceEnumerable(Enumerable<Row> enumerable) throws InterruptedException {
                    for (Row row : enumerable) {
                        send(row);
                    }
                    end();
                }

                public void run() {
                    try {
                        final Page page = new Page();
                        final List<Primitive> fieldTypes = Collections.nCopies(fieldNames.size(), null);
                        request(queryType, request, this, fieldNames, fieldTypes, page);
                        enumerator.done.set(true);
                    } catch (Throwable e) {
                        enumerator.throwableHolder.set(e);
                        enumerator.done.set(true);
                    }
                }
            };
            service.execute(sink);
            return enumerator;
        }
    };
}