Example usage for com.google.common.collect Table rowMap

List of usage examples for com.google.common.collect Table rowMap

Introduction

In this page you can find the example usage for com.google.common.collect Table rowMap.

Prototype

Map<R, Map<C, V>> rowMap();

Source Link

Document

Returns a view that associates each row key with the corresponding map from column keys to values.

Usage

From source file:edu.cmu.lti.oaqa.baseqa.answer.collective_score.scorers.DistanceCollectiveAnswerScorer.java

private static <K1, K2> Table<K1, K2, Double> normalize(Table<K1, K2, Double> orig) {
    Table<K1, K2, Double> ret = HashBasedTable.create();
    orig.rowMap().entrySet().forEach(entry -> {
        K1 key1 = entry.getKey();//from www.ja  va 2s .co  m
        double sum = entry.getValue().values().stream().mapToDouble(x -> x).sum();
        entry.getValue().entrySet().forEach(e -> ret.put(key1, e.getKey(), e.getValue() / sum));
    });
    return ret;
}

From source file:org.sonar.xoo.rule.MultilineIssuesSensor.java

private static void createIssues(InputFile file, SensorContext context,
        Map<Integer, TextPointer> startPositions, Map<Integer, TextPointer> endPositions,
        Map<Integer, Table<Integer, Integer, TextPointer>> startFlowsPositions,
        Map<Integer, Table<Integer, Integer, TextPointer>> endFlowsPositions) {
    RuleKey ruleKey = RuleKey.of(XooRulesDefinition.XOO_REPOSITORY, RULE_KEY);

    for (Map.Entry<Integer, TextPointer> entry : startPositions.entrySet()) {
        NewIssue newIssue = context.newIssue().forRule(ruleKey);
        Integer issueId = entry.getKey();
        NewIssueLocation primaryLocation = newIssue.newLocation().on(file)
                .at(file.newRange(entry.getValue(), endPositions.get(issueId)));
        newIssue.at(primaryLocation.message("Primary location"));
        if (startFlowsPositions.containsKey(issueId)) {
            Table<Integer, Integer, TextPointer> flows = startFlowsPositions.get(issueId);
            for (Map.Entry<Integer, Map<Integer, TextPointer>> flowEntry : flows.rowMap().entrySet()) {
                Integer flowId = flowEntry.getKey();
                List<NewIssueLocation> flowLocations = Lists.newArrayList();
                List<Integer> flowNums = Lists.newArrayList(flowEntry.getValue().keySet());
                Collections.sort(flowNums);
                for (Integer flowNum : flowNums) {
                    TextPointer start = flowEntry.getValue().get(flowNum);
                    TextPointer end = endFlowsPositions.get(issueId).row(flowId).get(flowNum);
                    NewIssueLocation newLocation = newIssue.newLocation().on(file).at(file.newRange(start, end))
                            .message("Flow step #" + flowNum);
                    flowLocations.add(newLocation);
                }// w w w.j  av  a 2  s .  com
                if (flowLocations.size() == 1) {
                    newIssue.addLocation(flowLocations.get(0));
                } else {
                    newIssue.addFlow(flowLocations);
                }
            }
        }
        newIssue.save();
    }
}

From source file:org.pau.assetmanager.viewmodel.stocks.HistoricalStockBalanceState.java

public static Table<Integer, Integer, Set<StockState>> getConiniousHistoricalStockBalanceStateTable(
        BookSelection bookSelection, Integer lastYear, Optional<String> optionalStockLabel) {
    Table<Integer, Integer, Set<StockState>> uncontiniousHistoricalStockBalanceStateTable = getDiscontiniousHistoricalStockBalanceStateTable(
            bookSelection, lastYear, optionalStockLabel);
    Table<Integer, Integer, Set<StockState>> continiousHistoricalStockBalanceStateTable = HashBasedTable
            .<Integer, Integer, Set<StockState>>create();
    List<Integer> yearsWithHistoricalValues = Lists
            .newArrayList(uncontiniousHistoricalStockBalanceStateTable.rowMap().keySet());
    Map<String, StockState> stockToStockState = new HashMap<String, StockState>();
    if (yearsWithHistoricalValues.size() > 0) {
        Collections.sort(yearsWithHistoricalValues);
        for (Integer currentYear = yearsWithHistoricalValues.get(0); currentYear <= lastYear; currentYear++) {
            Map<Integer, Set<StockState>> yearHistoricalStockBalanceStateTable = uncontiniousHistoricalStockBalanceStateTable
                    .rowMap().get(currentYear);
            for (Integer currentMonth = 0; currentMonth <= 11; currentMonth++) {
                Set<StockState> stockStateSet = new HashSet<StockState>();
                if (yearHistoricalStockBalanceStateTable != null
                        && yearHistoricalStockBalanceStateTable.get(currentMonth) != null) {
                    stockStateSet = yearHistoricalStockBalanceStateTable.get(currentMonth);
                }//from   w w w . j  ava  2  s .c  om
                Map<String, StockState> currentStockToStockState = Maps.uniqueIndex(stockStateSet,
                        new Function<StockState, String>() {
                            @Override
                            public String apply(StockState input) {
                                return input.getSymbol();
                            }
                        });
                stockToStockState.putAll(currentStockToStockState);
                continiousHistoricalStockBalanceStateTable.put(currentYear, currentMonth,
                        Sets.newHashSet(stockToStockState.values()));
            }
        }
    }
    return continiousHistoricalStockBalanceStateTable;
}

From source file:org.pau.assetmanager.viewmodel.chart.ChartDataModel.java

private static Double getYearBeforeFinalVirtualStockBalance(Integer year,
        Table<Integer, Integer, Set<StockState>> historicalStockBalanceStateTable) {
    Double balance = 0.0;//from w ww. j a va2s .  c  o  m
    final Integer yearBefore = year - 1;
    Map<Integer, Map<Integer, Set<StockState>>> historicalStockBalanceStateRowMap = historicalStockBalanceStateTable
            .rowMap();
    historicalStockBalanceStateRowMap = Maps.filterKeys(historicalStockBalanceStateRowMap,
            new Predicate<Integer>() {
                @Override
                public boolean apply(Integer year) {
                    return year <= yearBefore;
                }
            });
    List<Integer> years = Lists.newArrayList(historicalStockBalanceStateRowMap.keySet());
    if (years.size() > 0) {
        Collections.sort(years);
        // get last year
        Integer lastYear = years.get(years.size() - 1);
        Map<Integer, Set<StockState>> historicalStockBalanceStateLastYear = historicalStockBalanceStateRowMap
                .get(lastYear);
        List<Integer> months = Lists.newArrayList(historicalStockBalanceStateLastYear.keySet());
        Collections.sort(months);
        Integer lastMonth = months.get(months.size() - 1);
        Set<StockState> historicalStockLastMonth = historicalStockBalanceStateLastYear.get(lastMonth);
        for (StockState currentStockState : historicalStockLastMonth) {
            balance += currentStockState.getVirtualBalance();
        }
    }
    return balance;
}

From source file:edu.cmu.lti.oaqa.framework.report.CsvReportGeneratorConsumer.java

private String print(ReportComponent rc) {
    Joiner joiner = Joiner.on(",");
    StringBuilder sb = new StringBuilder();
    List<String> headers = rc.getHeaders();
    joiner.appendTo(sb, headers);//from  www .  jav a2 s  .  c om
    sb.append("\n");
    Table<String, String, String> table = rc.getTable();
    for (Map<String, String> row : table.rowMap().values()) {
        List<String> values = Lists.newArrayList();
        for (String header : headers) {
            values.add(escape(row.get(header)));
        }
        joiner.appendTo(sb, values);
        sb.append("\n");
    }
    return sb.toString();
}

From source file:de.cosmocode.rendering.TableValueRenderer.java

@Override
public void render(@Nullable Table<?, ?, ?> value, Renderer r) throws RenderingException {
    if (value == null) {
        r.nullValue();//ww  w. j av  a2s.  c  om
    } else {
        r.value(value.rowMap());
    }
}

From source file:co.cask.tigon.internal.app.runtime.flow.FlowUtils.java

/**
 * Configures all queues being used in a flow.
 *
 * @return A Multimap from flowletId to QueueName where the flowlet is a consumer of.
 *//*from   w w w. ja va 2 s .  c  o m*/
public static Multimap<String, QueueName> configureQueue(Program program, FlowSpecification flowSpec,
        QueueAdmin queueAdmin) {
    // Generate all queues specifications
    Table<QueueSpecificationGenerator.Node, String, Set<QueueSpecification>> queueSpecs = new SimpleQueueSpecificationGenerator()
            .create(flowSpec);

    // For each queue in the flow, gather a map of consumer groupId to number of instances
    Table<QueueName, Long, Integer> queueConfigs = HashBasedTable.create();

    // For storing result from flowletId to queue.
    ImmutableSetMultimap.Builder<String, QueueName> resultBuilder = ImmutableSetMultimap.builder();

    // Loop through each flowlet
    for (Map.Entry<String, FlowletDefinition> entry : flowSpec.getFlowlets().entrySet()) {
        String flowletId = entry.getKey();
        long groupId = FlowUtils.generateConsumerGroupId(program, flowletId);
        int instances = entry.getValue().getInstances();

        // For each queue that the flowlet is a consumer, store the number of instances for this flowlet
        for (QueueSpecification queueSpec : Iterables.concat(queueSpecs.column(flowletId).values())) {
            queueConfigs.put(queueSpec.getQueueName(), groupId, instances);
            resultBuilder.put(flowletId, queueSpec.getQueueName());
        }
    }

    try {
        // For each queue in the flow, configure it through QueueAdmin
        for (Map.Entry<QueueName, Map<Long, Integer>> row : queueConfigs.rowMap().entrySet()) {
            LOG.info("Queue config for {} : {}", row.getKey(), row.getValue());
            queueAdmin.configureGroups(row.getKey(), row.getValue());
        }
        return resultBuilder.build();
    } catch (Exception e) {
        LOG.error("Failed to configure queues", e);
        throw Throwables.propagate(e);
    }
}

From source file:com.garethahealy.camelmapstruct.converter.MapStructTypeConverterLoader.java

public void init() {
    if (camelContext == null) {
        throw new IllegalArgumentException("CamelContext == null");
    }/*w  w w.j  a va2  s.c  om*/

    TypeConverterRegistry registry = camelContext.getTypeConverterRegistry();
    MapStructTypeConverter converter = new MapStructTypeConverter<M>(configuration);

    Table<Class<?>, Class<?>, String> resolved = configuration.getResolvedMappingMethods();
    for (Map.Entry<Class<?>, Map<Class<?>, String>> row : resolved.rowMap().entrySet()) {
        for (Map.Entry<Class<?>, String> col : row.getValue().entrySet()) {
            Class<?> from = row.getKey();
            Class<?> to = col.getKey();

            LOG.debug("{} -> {} via {}->{}", from, to, configuration.getMapperInterface().getName(),
                    col.getValue());
            LOG.info("Added MapStruct as Camel type converter: {} -> {}", from, to);

            registry.addTypeConverter(to, from, converter);
        }
    }
}

From source file:me.kenzierocks.plugins.currencysnowmen.implementation.DataMapAdapter.java

@Override
public JsonElement serialize(Table<Currency, Set<Context>, BigDecimal> src, Type typeOfSrc,
        JsonSerializationContext context) {
    Map<String, Map<Map<String, String>, BigDecimal>> data = new HashMap<>();
    src.rowMap().forEach((currency, contextToAmount) -> {
        String id = ((ExtendedCurrency) currency).getIdentifer();
        contextToAmount.forEach((contextSet, amount) -> {
            data.computeIfAbsent(id, k -> new HashMap<>())
                    .put(contextSet.stream().collect(Collectors.toMap(Entry::getKey, Entry::getValue)), amount);
        });//from   w  ww .j  av a2 s .  com
    });
    return NORMAL_JSON.toJsonTree(data, DATA_TYPE);
}

From source file:su.opencode.shuffler.MarkovBuildingVisitor.java

private Table<String, String, Double> probabilityTable(Table<String, String, Integer> chainTable) {

    ImmutableTable.Builder<String, String, Double> builder = ImmutableTable.builder();

    for (Map.Entry<String, Map<String, Integer>> row : chainTable.rowMap().entrySet()) {
        if (row.getValue().isEmpty())
            continue;

        double total = 0;

        for (Map.Entry<String, Integer> cell : row.getValue().entrySet()) {
            total += cell.getValue();// w w  w  .  j a  v  a  2  s. c  o m
        }

        for (Map.Entry<String, Integer> cell : row.getValue().entrySet()) {
            double prob = cell.getValue() / total;
            builder.put(row.getKey(), cell.getKey(), prob);
        }
    }

    builder.orderRowsBy(StringComparator.INSTANCE);
    builder.orderColumnsBy(StringComparator.INSTANCE);

    return builder.build();
}