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:de.xwic.appkit.core.model.queries.resolver.hbn.PropertyQueryTest.java

/**
 *
 *//*from w w  w  .jav  a2 s . co m*/
@Test
public void testInQuery() {
    {
        final List<QueryElement> values = new ArrayList<QueryElement>();
        final PropertyQuery pq = new PropertyQuery();
        final List<Integer> ids = Arrays.asList(1, 2, 3, 4, 5);
        pq.addIn("id", ids);

        final String expectedQuery = BASIC_QUERY + "AND obj.id IN (?,?,?,?,?) ";
        assertEquals(expectedQuery, generate(pq, values));
        printQuery(expectedQuery);

        //         test arguments
        assertSame(1, values.size());
        final Set<Integer> ints = new HashSet<Integer>();
        for (final QueryElement integer : values) {
            ints.addAll((Collection<Integer>) integer.getValue());
        }
        assertEquals(cloneToSet(ids), ints);
    }

    {
        final List<QueryElement> values = new ArrayList<QueryElement>();
        final PropertyQuery pq = new PropertyQuery();
        final List<Integer> ids = countTo(1001);
        pq.addIn("id", ids);

        final String thousandQs = StringUtils.join(Collections.nCopies(1000, '?'), ',');
        final String expectedQuery = BASIC_QUERY + "AND (obj.id IN (" + thousandQs + ") OR obj.id IN (?)) ";
        assertEquals(expectedQuery, generate(pq, values));
        printQuery(expectedQuery);

        //         test arguments
        assertSame(2, values.size());

        //         test arguments
        final Set<Integer> ints = new HashSet<Integer>();
        for (final QueryElement integer : values) {
            ints.addAll((Collection<Integer>) integer.getValue());
        }
        assertEquals(cloneToSet(ids), ints);
    }

    {
        final List<QueryElement> values = new ArrayList<QueryElement>();
        final PropertyQuery pq = new PropertyQuery();
        pq.addIn("life", null);
        pq.addOrIn("gf", null);

        final String expectedQuery = BASIC_QUERY + "AND (obj.id IS NULL OR obj.id IS NULL) ";
        assertEquals(expectedQuery, generate(pq, values));
        printQuery(expectedQuery);
    }

    {
        final List<QueryElement> values = new ArrayList<QueryElement>();
        final PropertyQuery pq = new PropertyQuery();
        final List<Integer> ids = countTo(1001);
        pq.addNotIn("comfortLevel", ids);

        final String thousandQs = StringUtils.join(Collections.nCopies(1000, '?'), ',');
        final String expectedQuery = BASIC_QUERY + "AND (obj.comfortLevel NOT IN (" + thousandQs
                + ") AND obj.comfortLevel NOT IN (?)) ";
        assertEquals(expectedQuery, generate(pq, values));
        printQuery(expectedQuery);

        //         test arguments
        assertSame(2, values.size());

        //         test arguments
        final Set<Integer> ints = new HashSet<Integer>();
        for (final QueryElement integer : values) {
            ints.addAll((Collection<Integer>) integer.getValue());
        }
        assertEquals(cloneToSet(ids), ints);
    }
}

From source file:gobblin.service.SimpleKafkaSpecExecutorInstanceConsumer.java

public SimpleKafkaSpecExecutorInstanceConsumer(Config config, Optional<Logger> log) {
    super(config, log);

    // Consumer/* w  w w . jav a 2 s .  c  o m*/
    _kafka08Consumer = new Kafka08ConsumerClient.Factory().create(config);
    List<KafkaTopic> kafkaTopics = _kafka08Consumer.getFilteredTopics(Collections.EMPTY_LIST,
            Lists.newArrayList(Pattern.compile(config.getString(SPEC_KAFKA_TOPICS_KEY))));
    _partitions = kafkaTopics.get(0).getPartitions();
    _lowWatermark = Lists.newArrayList(Collections.nCopies(_partitions.size(), 0L));
    _nextWatermark = Lists.newArrayList(Collections.nCopies(_partitions.size(), 0L));
    _highWatermark = Lists.newArrayList(Collections.nCopies(_partitions.size(), 0L));

    InputStream dummyInputStream = new ByteArrayInputStream(new byte[0]);
    _decoder = DecoderFactory.get().binaryDecoder(dummyInputStream, null);
    _reader = new SpecificDatumReader<AvroJobSpec>(AvroJobSpec.SCHEMA$);
    _versionWriter = new FixedSchemaVersionWriter();
}

From source file:org.apache.mahout.knn.tools.TestNewsGroupsKMeanLogisticRegression.java

public void run(PrintWriter output) throws IOException {

    // Contains the best model.
    OnlineLogisticRegression classifier = ModelSerializer.readBinary(new FileInputStream(modelFile),
            OnlineLogisticRegression.class);

    // Get the cluster labels.
    List<String> lines = Files.readLines(new File(labelFile), Charset.defaultCharset());
    Map<String, Integer> labels = Maps.newHashMap();
    for (String line : lines.subList(1, lines.size())) {
        String[] chunks = line.split(", ");
        Preconditions.checkArgument(chunks.length == 2, "Invalid labels line " + chunks.toString());
        labels.put(chunks[0], Integer.parseInt(chunks[1]));
        System.out.printf("%s: %s\n", chunks[0], chunks[1]);
    }/* w ww .ja v  a 2s  .  c o m*/
    List<String> reverseLabels = new ArrayList(Collections.nCopies(labels.size(), ""));
    for (Map.Entry<String, Integer> pair : labels.entrySet()) {
        reverseLabels.set(pair.getValue(), pair.getKey());
    }

    Configuration conf = new Configuration();
    // Get the centroids used for computing the distances for this model.
    SequenceFileDirValueIterable<CentroidWritable> centroidIterable = new SequenceFileDirValueIterable<CentroidWritable>(
            new Path(centroidsFile), PathType.LIST, conf);
    List<Centroid> centroids = Lists
            .newArrayList(CreateCentroids.getCentroidsFromCentroidWritableIterable(centroidIterable));
    // Get the encoded documents (the vectors from tf-idf).
    SequenceFileDirIterable<Text, VectorWritable> inputIterable = new SequenceFileDirIterable<Text, VectorWritable>(
            new Path(inputFile), PathType.LIST, conf);

    ResultAnalyzer ra = new ResultAnalyzer(labels.keySet(), "DEFAULT");
    for (Pair<Text, VectorWritable> pair : inputIterable) {
        int actual = labels.get(pair.getFirst().toString());
        Vector encodedInput = distancesFromCentroidsVector(pair.getSecond().get(), centroids);
        Vector result = classifier.classifyFull(encodedInput);
        int cat = result.maxValueIndex();
        double score = result.maxValue();
        double ll = classifier.logLikelihood(actual, encodedInput);
        ClassifierResult cr = new ClassifierResult(reverseLabels.get(cat), score, ll);
        ra.addInstance(pair.getFirst().toString(), cr);
    }
    output.println(ra);
}

From source file:edu.washington.gs.skyline.model.quantification.GroupComparisonDataSet.java

public LinearFitResult calculateFoldChange(String label) {
    List<Replicate> replicates = removeIncompleteReplicates(label, this.replicates);
    if (replicates.size() == 0) {
        return null;
    }//w  w  w  .j a va  2  s  .  com
    List<Replicate> summarizedRows;
    if (replicates.stream().anyMatch(row -> null != row.getBioReplicate())) {
        Map<Pair<Boolean, Object>, List<Replicate>> groupedByBioReplicate = replicates.stream().collect(
                Collectors.groupingBy(replicate -> Pair.of(replicate.isControl(), replicate.bioReplicate)));
        summarizedRows = new ArrayList<>();
        for (Map.Entry<Pair<Boolean, Object>, List<Replicate>> entry : groupedByBioReplicate.entrySet()) {
            Double log2Abundance = calculateMean(entry.getValue().stream()
                    .map(replicateData -> replicateData.getLog2Abundance(label)).collect(Collectors.toList()));
            if (log2Abundance == null) {
                continue;
            }
            Replicate combinedReplicate = new Replicate(entry.getKey().getLeft(), entry.getKey().getValue());
            ResultFileData resultFileData = combinedReplicate.ensureResultFileData();
            resultFileData.setTransitionAreas(label,
                    TransitionAreas.fromMap(Collections.singletonMap("", Math.pow(2.0, log2Abundance))));
            if (getNormalizationMethod() instanceof NormalizationMethod.RatioToLabel) {
                TransitionAreas denominator = TransitionAreas.fromMap(Collections.singletonMap("", 1.0));
                resultFileData.setTransitionAreas(
                        ((NormalizationMethod.RatioToLabel) getNormalizationMethod()).getIsotopeLabelTypeName(),
                        denominator);
            }
            summarizedRows.add(combinedReplicate);
        }
    } else {
        summarizedRows = replicates;
    }

    List<Double> abundances = summarizedRows.stream()
            .map(replicateData -> replicateData.getLog2Abundance(label)).collect(Collectors.toList());
    List<Integer> features = Collections.nCopies(summarizedRows.size(), 0);
    List<Integer> runs = IntStream.range(0, summarizedRows.size()).boxed().collect(Collectors.toList());
    List<Integer> subjects = IntStream.range(0, summarizedRows.size()).boxed().collect(Collectors.toList());
    List<Boolean> subjectControls = summarizedRows.stream().map(Replicate::isControl)
            .collect(Collectors.toList());
    FoldChangeDataSet foldChangeDataSet = new FoldChangeDataSet(abundances, features, runs, subjects,
            subjectControls);
    DesignMatrix designMatrix = DesignMatrix.getDesignMatrix(foldChangeDataSet, false);
    LinearFitResult linearFitResult = designMatrix.performLinearFit().get(0);
    return linearFitResult;
}

From source file:org.openmrs.module.idcards.web.controller.TemplateFormController.java

/**
 * Handles the user's submission of the form.
 *///from w  ww. java2 s .c  o  m
@RequestMapping(method = RequestMethod.POST, params = "action=saveAndPrintEmpty")
public void onSaveAndPrintEmpty(@ModelAttribute("template") IdcardsTemplate template,
        HttpServletRequest request, HttpServletResponse response) throws IOException {

    if (Context.isAuthenticated()) {
        IdcardsService service = (IdcardsService) Context.getService(IdcardsService.class);
        service.saveIdcardsTemplate(template);

        try {
            StringBuffer requestURL = request.getRequestURL();
            String baseURL = requestURL.substring(0, requestURL.indexOf("/module"));

            PrintEmptyIdcardsServlet.generateOutput(template, baseURL, response, Collections.nCopies(10, 0),
                    null);
        } catch (Exception e) {
            log.error("Unable to print cards", e);
            e.printStackTrace(response.getWriter());
        }
    }

}

From source file:org.openmrs.module.idcards.web.servlet.PrintEmptyIdcardsServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 *//*from w  w  w .ja va2s  . co m*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Integer mrnCount = ServletRequestUtils.getRequiredIntParameter(request, "mrn_count");
    Integer templateId = ServletRequestUtils.getIntParameter(request, "templateId", 1);
    String generatedMRNs = ServletRequestUtils.getStringParameter(request, "generated_mrns", "none");
    String password = ServletRequestUtils.getStringParameter(request, "pdf_password");
    if (!StringUtils.hasLength(password))
        throw new ServletException("A non-empty password is required.");

    IdcardsTemplate card = getIdcardsService().getIdcardsTemplate(templateId);

    StringBuffer requestURL = request.getRequestURL();
    String baseURL = requestURL.substring(0, requestURL.indexOf("/moduleServlet"));

    List<Integer> identifiers = null;

    if ("none".equals(generatedMRNs)) {
        identifiers = Collections.nCopies(mrnCount, 0);
    } else if ("pregenerated".equals(generatedMRNs)) {
        identifiers = getIdcardsService().printGeneratedIdentifiers(mrnCount, card);
    } else if ("generateNew".equals(generatedMRNs)) {
        Integer min = Integer
                .valueOf(Context.getAdministrationService().getGlobalProperty("idcards.generateMin"));
        Integer max = Integer
                .valueOf(Context.getAdministrationService().getGlobalProperty("idcards.generateMax"));
        identifiers = getIdcardsService().generateAndPrintIdentifiers(mrnCount, min, max, card);
    } else
        throw new ServletException("Invalid choice for 'generatedMRNs' parameter");

    generateOutput(card, baseURL, response, identifiers, password);

}

From source file:com.thoughtworks.gauge.Table.java

private void addDashes(int maxStringLength, List<String> formattedHeaderAndRows) {

    String dashesString = Joiner.on(StringUtils.EMPTY).join(Collections.nCopies(maxStringLength, DASH));
    List<String> dashes = Collections.nCopies(headers.size(), dashesString);
    String formattedDashes = formattedRow(dashes, maxStringLength);
    formattedHeaderAndRows.add(formattedDashes);
}

From source file:org.netflux.core.Record.java

/**
 * Creates a record that can store the kind of data described by the supplied metadata, possibly setting all the fields to the
 * <code>null</code> value./*from  w  ww .ja v a2s  .co  m*/
 * 
 * @param metadata the metadata describing the data this record may hold
 * @param nullFields <code>true</code> to indicate that all fields should be set to <code>null</code>.
 * @throws NullPointerException if the supplied metadata is <code>null</code>.
 */
public Record(RecordMetadata metadata, boolean nullFields) {
    this.metadata = new RecordMetadata(metadata.getFieldMetadata());
    this.data = new ArrayList<Field<? extends Serializable>>(
            Collections.nCopies(this.metadata.getFieldCount(), (Field<Serializable>) null));
    if (nullFields) {
        this.nullFields(this.getMetadata().getFieldNames());
    }
}

From source file:org.jtalks.jcommune.service.transactional.TransactionalTopicFetchServiceTest.java

@Test
public void testGetUnansweredTopics() {
    String pageNumber = "1";
    int pageSize = 20;
    List<Topic> expectedList = Collections.nCopies(2, new Topic(user, "title"));
    Page<Topic> expectedPage = new PageImpl<>(expectedList);
    when(topicDao.getUnansweredTopics(Matchers.<PageRequest>any(), eq(user))).thenReturn(expectedPage);
    user.setPageSize(pageSize);// w ww.  j  a v a 2 s .c  o  m
    when(userService.getCurrentUser()).thenReturn(user);

    Page<Topic> actualPage = topicFetchService.getUnansweredTopics(pageNumber);
    assertNotNull(actualPage);
    assertEquals(actualPage, expectedPage);
}

From source file:com.networknt.limit.LimitHandlerTest.java

@Test
public void testMoreRequests() throws Exception {
    Callable<String> task = this::callApi;
    List<Callable<String>> tasks = Collections.nCopies(10, task);
    long start = System.currentTimeMillis();
    ExecutorService executorService = Executors.newFixedThreadPool(10);
    List<Future<String>> futures = executorService.invokeAll(tasks);
    List<String> resultList = new ArrayList<>(futures.size());
    // Check for exceptions
    for (Future<String> future : futures) {
        // Throws an exception if an exception was thrown by the task.
        resultList.add(future.get());//  w ww . j  a  v a  2  s.co m
    }
    long last = (System.currentTimeMillis() - start);
    // make sure that there are at least one element in resultList is :513
    Assert.assertTrue(resultList.contains(":513"));
    System.out.println("resultList = " + resultList + " response time = " + last);
}