com.google.common.collect.Table Java Examples

The following examples show how to use com.google.common.collect.Table. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GuavaTableUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenArrayTable_whenGet_returnsSuccessfully() {
    final List<String> universityRowTable = Lists.newArrayList("Mumbai", "Harvard");
    final List<String> courseColumnTables = Lists.newArrayList("Chemical", "IT", "Electrical");
    final Table<String, String, Integer> universityCourseSeatTable = ArrayTable.create(universityRowTable, courseColumnTables);
    universityCourseSeatTable.put("Mumbai", "Chemical", 120);
    universityCourseSeatTable.put("Mumbai", "IT", 60);
    universityCourseSeatTable.put("Harvard", "Electrical", 60);
    universityCourseSeatTable.put("Harvard", "IT", 120);

    final int seatCount = universityCourseSeatTable.get("Mumbai", "IT");

    assertThat(seatCount).isEqualTo(60);
}
 
Example #2
Source File: GuavaTableUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenTable_whenContains_returnsSuccessfully() {
    final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
    universityCourseSeatTable.put("Mumbai", "Chemical", 120);
    universityCourseSeatTable.put("Mumbai", "IT", 60);
    universityCourseSeatTable.put("Harvard", "Electrical", 60);
    universityCourseSeatTable.put("Harvard", "IT", 120);

    final boolean entryIsPresent = universityCourseSeatTable.contains("Mumbai", "IT");
    final boolean entryIsAbsent = universityCourseSeatTable.contains("Oxford", "IT");
    final boolean courseIsPresent = universityCourseSeatTable.containsColumn("IT");
    final boolean universityIsPresent = universityCourseSeatTable.containsRow("Mumbai");
    final boolean seatCountIsPresent = universityCourseSeatTable.containsValue(60);

    assertThat(entryIsPresent).isEqualTo(true);
    assertThat(entryIsAbsent).isEqualTo(false);
    assertThat(courseIsPresent).isEqualTo(true);
    assertThat(universityIsPresent).isEqualTo(true);
    assertThat(seatCountIsPresent).isEqualTo(true);
}
 
Example #3
Source File: WeightedBoomerang.java    From SPDS with Eclipse Public License 2.0 6 votes vote down vote up
public Table<Statement, Val, W> getResults(Query seed) {
    final Table<Statement, Val, W> results = HashBasedTable.create();
    WeightedPAutomaton<Statement, INode<Val>, W> fieldAut = queryToSolvers.getOrCreate(seed).getCallAutomaton();
    for (Entry<Transition<Statement, INode<Val>>, W> e : fieldAut.getTransitionsToFinalWeights().entrySet()) {
        Transition<Statement, INode<Val>> t = e.getKey();
        W w = e.getValue();
        if (t.getLabel().equals(Statement.epsilon()))
            continue;
        if (t.getStart().fact().value() instanceof Local
                && !t.getLabel().getMethod().equals(t.getStart().fact().m()))
            continue;
        if (t.getLabel().getUnit().isPresent())
            results.put(t.getLabel(), t.getStart().fact(), w);
    }
    return results;
}
 
Example #4
Source File: ReliableTaildirEventReader.java    From uavstack with Apache License 2.0 6 votes vote down vote up
/**
 * Create a ReliableTaildirEventReader to watch the given directory. map<serverid.appid.logid, logpath>
 */
private ReliableTaildirEventReader(Map<String, LogPatternInfo> filePaths, Table<String, String, String> headerTable,
        String positionFilePath, boolean skipToEnd, boolean addByteOffset, String os) throws IOException {
    // Sanity checks
    Preconditions.checkNotNull(filePaths);
    Preconditions.checkNotNull(positionFilePath);
    // get operation system info
    if (logger.isDebugEnable()) {
        logger.debug(this, "Initializing {" + ReliableTaildirEventReader.class.getSimpleName()
                + "} with directory={" + filePaths + "}");
    }

    // tailFile
    this.tailFileTable = CacheBuilder.newBuilder().expireAfterWrite(2, TimeUnit.DAYS)
            .<String, LogPatternInfo> build();
    this.headerTable = headerTable;
    this.addByteOffset = addByteOffset;
    this.os = os;
    updatelog(filePaths);
    updateTailFiles(skipToEnd);

    logger.info(this, "tailFileTable: " + tailFileTable.toString());
    logger.info(this, "headerTable: " + headerTable.toString());
    logger.info(this, "Updating position from position file: " + positionFilePath);
    loadPositionFile(positionFilePath);
}
 
Example #5
Source File: CashFlowReport.java    From Strata with Apache License 2.0 6 votes vote down vote up
private CashFlowReport(
    LocalDate valuationDate,
    Instant runInstant,
    List<ExplainKey<?>> columnKeys,
    List<String> columnHeaders,
    Table<Integer, Integer, Object> data) {
  JodaBeanUtils.notNull(valuationDate, "valuationDate");
  JodaBeanUtils.notNull(runInstant, "runInstant");
  JodaBeanUtils.notNull(columnKeys, "columnKeys");
  JodaBeanUtils.notNull(columnHeaders, "columnHeaders");
  JodaBeanUtils.notNull(data, "data");
  this.valuationDate = valuationDate;
  this.runInstant = runInstant;
  this.columnKeys = ImmutableList.copyOf(columnKeys);
  this.columnHeaders = ImmutableList.copyOf(columnHeaders);
  this.data = ImmutableTable.copyOf(data);
}
 
Example #6
Source File: FhirR4.java    From synthea with Apache License 2.0 6 votes vote down vote up
private static Table<String, String, String> loadMapping(String filename) {
  Table<String, String, String> mappingTable = HashBasedTable.create();

  List<LinkedHashMap<String, String>> csvData;
  try {
    csvData = SimpleCSV.parse(Utilities.readResource(filename));
  } catch (IOException e) {
    e.printStackTrace();
    return null;
  }

  for (LinkedHashMap<String, String> line : csvData) {
    String system = line.get("SYSTEM");
    String code = line.get("CODE");
    String url = line.get("URL");

    mappingTable.put(system, code, url);
  }

  return mappingTable;
}
 
Example #7
Source File: TestingResultReporter.java    From SPDS with Eclipse Public License 2.0 6 votes vote down vote up
public void onSeedFinished(Node<Statement, Val> seed, final ForwardBoomerangResults<W> res) {
    Table<Statement, Val, W> results = res.asStatementValWeightTable();
    for (final Entry<Unit, Assertion> e : stmtToResults.entries()) {
        if (e.getValue() instanceof ComparableResult) {
            final ComparableResult<W, Val> expectedResults = (ComparableResult) e.getValue();
            W w2 = results.get(new Statement((Stmt) e.getKey(), null), expectedResults.getVal());
            if (w2 != null) {
                expectedResults.computedResults(w2);
            }
        }
        // check if any of the methods that should not be analyzed have been analyzed
        if (e.getValue() instanceof ShouldNotBeAnalyzed) {
            final ShouldNotBeAnalyzed shouldNotBeAnalyzed = (ShouldNotBeAnalyzed) e.getValue();
            Unit analyzedUnit = e.getKey();
            if (analyzedUnit.equals(shouldNotBeAnalyzed.unit)) {
                shouldNotBeAnalyzed.hasBeenAnalyzed();
            }
        }
    }
}
 
Example #8
Source File: SubscriberStatusChecker.java    From qmq with Apache License 2.0 6 votes vote down vote up
private void cleanPullLogAndCheckpoint() {
    final Table<String, String, PullLog> pullLogs = storage.allPullLogs();
    if (pullLogs == null || pullLogs.size() == 0) return;

    // delete all pull log without max pulled message sequence
    for (final String groupAndSubject : pullLogs.columnKeySet()) {
        final GroupAndSubject gs = GroupAndSubject.parse(groupAndSubject);
        final long maxPulledMessageSequence = storage.getMaxPulledMessageSequence(gs.getSubject(), gs.getGroup());
        if (maxPulledMessageSequence == -1) {
            for (final Map.Entry<String, PullLog> entry : pullLogs.column(groupAndSubject).entrySet()) {
                final String consumerId = entry.getKey();
                LOG.info("remove pull log. subject: {}, group: {}, consumerId: {}", gs.getSubject(), gs.getGroup(), consumerId);
                storage.destroyPullLog(gs.getSubject(), gs.getGroup(), consumerId);
            }
        }
    }
}
 
Example #9
Source File: ConfigCommand.java    From bazel with Apache License 2.0 6 votes vote down vote up
private static ConfigurationDiffForOutput getConfigurationDiffForOutput(
    String configHash1,
    String configHash2,
    Table<Class<? extends FragmentOptions>, String, Pair<Object, Object>> diffs) {
  ImmutableSortedSet.Builder<FragmentDiffForOutput> fragmentDiffs =
      ImmutableSortedSet.orderedBy(comparing(e -> e.name));
  diffs.rowKeySet().stream()
      .forEach(
          fragmentClass -> {
            String fragmentName =
                fragmentClass.equals(UserDefinedFragment.class)
                    ? UserDefinedFragment.DESCRIPTIVE_NAME
                    : fragmentClass.getName();
            ImmutableSortedMap<String, Pair<String, String>> sortedOptionDiffs =
                diffs.row(fragmentClass).entrySet().stream()
                    .collect(
                        toImmutableSortedMap(
                            Ordering.natural(),
                            Map.Entry::getKey,
                            e -> toNullableStringPair(e.getValue())));
            fragmentDiffs.add(new FragmentDiffForOutput(fragmentName, sortedOptionDiffs));
          });
  return new ConfigurationDiffForOutput(
      configHash1, configHash2, ImmutableList.copyOf(fragmentDiffs.build()));
}
 
Example #10
Source File: YarnTwillRunnerService.java    From twill with Apache License 2.0 6 votes vote down vote up
/**
 * Renews the {@link SecureStore} for all the running applications.
 *
 * @param liveApps set of running applications that need to have secure store renewal
 * @param renewer the {@link SecureStoreRenewer} for renewal
 * @param mergeCredentials {@code true} to merge with existing credentials
 * @return a {@link Multimap} containing the application runs that were failed to have secure store renewed
 */
private Multimap<String, RunId> renewSecureStore(Table<String, RunId, YarnTwillController> liveApps,
                                                 SecureStoreRenewer renewer, boolean mergeCredentials) {
  Multimap<String, RunId> failureRenews = HashMultimap.create();

  // Renew the secure store for each running application
  for (Table.Cell<String, RunId, YarnTwillController> liveApp : liveApps.cellSet()) {
    String application = liveApp.getRowKey();
    RunId runId = liveApp.getColumnKey();
    YarnTwillController controller = liveApp.getValue();

    try {
      renewer.renew(application, runId, new YarnSecureStoreWriter(application, runId, controller, mergeCredentials));
    } catch (Exception e) {
      LOG.warn("Failed to renew secure store for {}:{}", application, runId, e);
      failureRenews.put(application, runId);
    }
  }

  return failureRenews;
}
 
Example #11
Source File: MathUtil.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
public static Table<String, String, Float> parseMatrix(Reader reader) throws IOException {
    Table<String, String, Float> table = HashBasedTable.create();
    try (ICsvListReader csvReader = new CsvListReader(reader, CsvPreference.STANDARD_PREFERENCE)) {
        List<String> columnHeaders = csvReader.read();
        List<String> row;
        while ((row = csvReader.read()) != null) {
            String rowHeader = row.get(0);
            for (int i = 1; i < row.size(); i++) {
                String columnHeader = columnHeaders.get(i);
                String value = row.get(i);
                table.put(rowHeader, columnHeader, value == null ? Float.NaN : Float.parseFloat(value));
            }
        }
    }
    return table;
}
 
Example #12
Source File: AbstractBoomerangResults.java    From SPDS with Eclipse Public License 2.0 6 votes vote down vote up
public Table<Statement, Val, W> asStatementValWeightTable(ForwardQuery query) {
    final Table<Statement, Val, W> results = HashBasedTable.create();
    WeightedPAutomaton<Statement, INode<Val>, W> callAut = queryToSolvers.getOrCreate(query).getCallAutomaton();
    for (Entry<Transition<Statement, INode<Val>>, W> e : callAut.getTransitionsToFinalWeights().entrySet()) {
        Transition<Statement, INode<Val>> t = e.getKey();
        W w = e.getValue();
        if (t.getLabel().equals(Statement.epsilon()))
            continue;
        if (t.getStart().fact().value() instanceof Local
                && !t.getLabel().getMethod().equals(t.getStart().fact().m()))
            continue;
        if (t.getLabel().getUnit().isPresent())
            results.put(t.getLabel(), t.getStart().fact(), w);
    }
    return results;
}
 
Example #13
Source File: EvpnCumulusTest.java    From batfish with Apache License 2.0 6 votes vote down vote up
@Test
public void testRoutePresence() throws IOException {
  final String leaf1 = "leaf1";
  final String leaf2 = "leaf2";
  final String spine = "spine";
  Batfish batfish =
      BatfishTestUtils.getBatfishFromTestrigText(
          TestrigText.builder()
              .setConfigurationFiles(SNAPSHOT_FOLDER, ImmutableSet.of(leaf1, leaf2, spine))
              .setLayer1TopologyPrefix(SNAPSHOT_FOLDER)
              .build(),
          _folder);
  batfish.computeDataPlane(batfish.getSnapshot());
  DataPlane dp = batfish.loadDataPlane(batfish.getSnapshot());

  Table<String, String, Set<EvpnRoute<?, ?>>> ribs = dp.getEvpnRoutes();

  assertThat(
      ribs.get(leaf1, DEFAULT_VRF_NAME),
      hasItem(isEvpnType3RouteThat(hasPrefix(Prefix.parse("3.3.3.3/32")))));
  assertThat(
      ribs.get(leaf2, DEFAULT_VRF_NAME),
      hasItem(isEvpnType3RouteThat(hasPrefix(Prefix.parse("1.1.1.1/32")))));
}
 
Example #14
Source File: Transaction.java    From sequence-mining with GNU General Public License v3.0 6 votes vote down vote up
/** Calculate cached cost for structural EM-step */
private double calculateCachedCost(final Table<Sequence, Integer, Double> sequences,
		final Multiset<Sequence> covering) {
	double totalCost = 0;
	int lenCovering = 0;
	for (final Sequence seq : cachedSequences.rowKeySet()) {
		if (sequences.containsRow(seq)) {
			if (covering.contains(seq)) {
				final int occur = covering.count(seq);
				totalCost += -Math.log(sequences.get(seq, occur));
				for (int m = 1; m <= occur; m++) {
					totalCost += sumLogRange(lenCovering + 1, lenCovering + seq.size());
					lenCovering += seq.size();
				}
			} else if (seq.size() == 1 && sum(cachedSequences.row(seq).values()) == 0.) {
				continue; // ignore seqs used to fill incomplete coverings
			} else {
				totalCost += -Math.log(sequences.get(seq, 0));
			}
		}
	}
	return totalCost;
}
 
Example #15
Source File: TypeAnnotationPass.java    From clutz with MIT License 6 votes vote down vote up
public TypeAnnotationPass(
    AbstractCompiler compiler,
    PathUtil pathUtil,
    NameUtil nameUtil,
    Map<String, FileModule> symbolMap,
    Table<String, String, String> typeRewrite,
    NodeComments nodeComments,
    Map<String, String> externsMap) {
  this.compiler = compiler;
  this.pathUtil = pathUtil;
  this.nameUtil = nameUtil;
  this.nodeComments = nodeComments;

  this.symbolToModule = new HashMap<>(symbolMap);
  this.typeRewrite = HashBasedTable.create(typeRewrite);
  this.externsMap = externsMap;
}
 
Example #16
Source File: GuavaTableUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenTable_whenGet_returnsSuccessfully() {
    final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
    universityCourseSeatTable.put("Mumbai", "Chemical", 120);
    universityCourseSeatTable.put("Mumbai", "IT", 60);
    universityCourseSeatTable.put("Harvard", "Electrical", 60);
    universityCourseSeatTable.put("Harvard", "IT", 120);

    final int seatCount = universityCourseSeatTable.get("Mumbai", "IT");
    final Integer seatCountForNoEntry = universityCourseSeatTable.get("Oxford", "IT");

    assertThat(seatCount).isEqualTo(60);
    assertThat(seatCountForNoEntry).isEqualTo(null);
}
 
Example #17
Source File: ReliableTaildirEventReader.java    From ns4_gear_watchdog with Apache License 2.0 5 votes vote down vote up
/**
 * Create a ReliableTaildirEventReader to watch the given directory.
 */
private ReliableTaildirEventReader(Map<String, String> filePaths,
                                   Map<String, String[]> exclusiveFiles,
                                   long fileExpiredTime,
                                   Table<String, String, String> headerTable, String positionFilePath,
                                   boolean skipToEnd, boolean addByteOffset, boolean cachePatternMatching,
                                   boolean annotateFileName, String fileNameHeader) throws IOException {
    // Sanity checks
    Preconditions.checkNotNull(filePaths);
    Preconditions.checkNotNull(positionFilePath);

    if (logger.isDebugEnabled()) {
        logger.debug("Initializing {} with directory={}, metaDir={}",
                new Object[]{ReliableTaildirEventReader.class.getSimpleName(), filePaths});
    }

    List<TaildirMatcher> taildirCache = Lists.newArrayList();
    for (Map.Entry<String, String> e : filePaths.entrySet()) {
        taildirCache.add(new TaildirMatcher(e.getKey(), e.getValue(), exclusiveFiles.get(e.getKey()), fileExpiredTime, cachePatternMatching));
    }
    logger.info("taildirCache: " + taildirCache.toString());
    logger.info("headerTable: " + headerTable.toString());

    this.taildirCache = taildirCache;
    this.headerTable = headerTable;
    this.addByteOffset = addByteOffset;
    this.cachePatternMatching = cachePatternMatching;
    this.annotateFileName = annotateFileName;
    this.fileNameHeader = fileNameHeader;
    updateTailFiles(skipToEnd);

    logger.info("Updating position from position file: " + positionFilePath);
    loadPositionFile(positionFilePath);
}
 
Example #18
Source File: Adapters.java    From activitystreams with Apache License 2.0 5 votes vote down vote up
public Table<?, ?, ?> deserialize(
  JsonElement json, 
  Type typeOfT,
  JsonDeserializationContext context) 
    throws JsonParseException {
  ImmutableTable.Builder<String,String,Object> table = 
    ImmutableTable.builder();
  checkArgument(json.isJsonObject());
  JsonObject obj = json.getAsJsonObject();
  for (Map.Entry<String,JsonElement> rowentry : obj.entrySet()) {
    String row = rowentry.getKey();
    JsonElement cell = rowentry.getValue();
    checkArgument(cell.isJsonObject());
    for (Map.Entry<String,JsonElement> cellentry : cell.getAsJsonObject().entrySet()) {
      String ckey = cellentry.getKey();
      JsonElement val = cellentry.getValue();
      Object desval = null;
      if (val.isJsonArray())
        desval = MultimapAdapter.arraydes(val.getAsJsonArray(),context);
      else if (val.isJsonObject())
        desval = context.deserialize(val, ASObject.class);
      else if (val.isJsonPrimitive())
        desval = primConverter.convert(val.getAsJsonPrimitive());
      if (desval != null)
        table.put(row,ckey,desval);
    }
  }
  return table.build();
}
 
Example #19
Source File: CommitAckRequestCodec.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
@Override
public CommitAckRequest decode(JoyQueueHeader header, ByteBuf buffer) throws Exception {
    short size = buffer.readShort();
    Table<String, Short, List<CommitAckData>> data = HashBasedTable.create();

    for (int i = 0; i < size; i++) {
        String topic = Serializer.readString(buffer, Serializer.SHORT_SIZE);
        short partitionSize = buffer.readShort();
        for (int j = 0; j < partitionSize; j++) {
            short partition = buffer.readShort();
            short dataSize = buffer.readShort();
            List<CommitAckData> dataList = Lists.newArrayListWithCapacity(dataSize);
            for (int k = 0; k < dataSize; k++) {
                CommitAckData commitAckData = new CommitAckData();
                commitAckData.setPartition(buffer.readShort());
                commitAckData.setIndex(buffer.readLong());
                commitAckData.setRetryType(RetryType.valueOf(buffer.readByte()));
                dataList.add(commitAckData);
            }
            data.put(topic, partition, dataList);
        }
    }

    CommitAckRequest commitAckRequest = new CommitAckRequest();
    commitAckRequest.setData(data);
    commitAckRequest.setApp(Serializer.readString(buffer, Serializer.SHORT_SIZE));
    return commitAckRequest;
}
 
Example #20
Source File: SeenRules.java    From EasySRL with Apache License 2.0 5 votes vote down vote up
private int addToTable(final Table<Category, Category, List<RuleProduction>> tab, int maxID, final Category left,
		final Category right) {
	// Check if any rules can apply to this pair of categories.
	List<RuleProduction> combinators = Combinator.getRules(left, right, Combinator.STANDARD_COMBINATORS);
	if (combinators.size() == 0) {
		return maxID;
	} else if (combinators.size() == 1) {
		combinators = Collections.singletonList(combinators.get(0));
	}
	maxID = Math.max(left.getID(), maxID);
	maxID = Math.max(right.getID(), maxID);
	tab.put(left, right, combinators);
	return maxID;
}
 
Example #21
Source File: SequenceMiningCore.java    From sequence-mining with GNU General Public License v3.0 5 votes vote down vote up
/** Evaluate a candidate sequence to see if it should be included */
private static boolean evaluateCandidate(final Table<Sequence, Integer, Double> sequences,
		final TransactionDatabase transactions, final InferenceAlgorithm inferenceAlgorithm,
		final Sequence candidate) {

	logger.finer("\n Candidate: " + candidate);

	// Find cost in parallel
	Tuple2<Double, Map<Integer, Double>> costAndProb;
	// if (transactions instanceof TransactionRDD) {
	// costAndProb = SparkEMStep.structuralEMStep(transactions,
	// inferenceAlgorithm, candidate);
	// } else {
	costAndProb = EMStep.structuralEMStep(transactions, inferenceAlgorithm, candidate);
	// }
	final double curCost = costAndProb._1;
	final Map<Integer, Double> prob = costAndProb._2;
	logger.finer(String.format(", cost: %.2f", curCost));

	// Return if better collection of seqs found
	if (curCost < transactions.getAverageCost()) {
		logger.finer("\n Candidate Accepted.\n");
		// Update cache with candidate
		Table<Sequence, Integer, Double> newSequences;
		// if (transactions instanceof TransactionRDD) {
		// newItemsets = SparkEMStep.addAcceptedCandidateCache(
		// transactions, candidate, prob);
		// } else {
		newSequences = EMStep.addAcceptedCandidateCache(transactions, candidate, prob);
		// }
		// Update sequences with newly inferred sequences
		sequences.clear();
		sequences.putAll(newSequences);
		transactions.setAverageCost(curCost);
		return true;
	} // otherwise keep trying

	// No better candidate found
	return false;
}
 
Example #22
Source File: IDEALRunner.java    From SPDS with Eclipse Public License 2.0 5 votes vote down vote up
private boolean isInErrorState(WeightedForwardQuery<TransitionFunction> key, ForwardBoomerangResults<TransitionFunction> forwardBoomerangResults) {
    Table<Statement, Val, TransitionFunction> objectDestructingStatements = forwardBoomerangResults.asStatementValWeightTable();
    for(Table.Cell<Statement,Val,TransitionFunction> c : objectDestructingStatements.cellSet()){
        for(ITransition t : c.getValue().values()){
            if(t.to() != null){
                if(t.to().isErrorState()){
                    return true;
                }
            }
        }

    }
  return false;
}
 
Example #23
Source File: HistoDbClientImpl.java    From ipst with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public HistoDbStats queryStats(Set<Country> countries, Set<HistoDbEquip> equips,
                               Set<HistoDbAttr> attrs, Interval interval, HistoDbHorizon horizon, boolean async) throws IOException, InterruptedException {
    try (Reader reader = new InputStreamReader(queryCsv(HistoQueryType.stats, countries, equips, attrs, interval, horizon, true, async))) {
        Table<String, String, Float> table = MathUtil.parseMatrix(reader);
        return new HistoDbStats(table);
    }
}
 
Example #24
Source File: TableUtils.java    From argument-reasoning-comprehension-task with Apache License 2.0 5 votes vote down vote up
/**
 * Converts Guava table to a CSV table
 *
 * @param table                   table
 * @param csvFormat               CSV format
 * @param missingValuePlaceholder print if a value is missing (empty string by default)
 * @param <T>                     object type (string)
 * @return table
 * @throws IOException exception
 */
public static <T> String tableToCsv(Table<String, String, T> table, CSVFormat csvFormat,
        String missingValuePlaceholder)
        throws IOException
{
    StringWriter sw = new StringWriter();
    CSVPrinter printer = new CSVPrinter(sw, csvFormat);

    List<String> firstRow = new ArrayList<>();
    firstRow.add(" ");
    firstRow.addAll(table.columnKeySet());
    printer.printRecord(firstRow);

    for (String rowKey : table.rowKeySet()) {
        printer.print(rowKey);
        for (String columnKey : table.columnKeySet()) {
            T value = table.get(rowKey, columnKey);

            if (value == null) {
                printer.print(missingValuePlaceholder);
            }
            else {
                printer.print(value);
            }
        }
        printer.println();
    }

    printer.close();

    return sw.toString();
}
 
Example #25
Source File: DemographicsTest.java    From synthea with Apache License 2.0 5 votes vote down vote up
/**
 * Set up the demographics to use for testing.
 */
@BeforeClass
@SuppressWarnings("rawtypes")
public static void setUp() throws IOException {
  demographicsFile = Config.get("generate.demographics.default_file");
  Config.set("generate.demographics.default_file", "geography/test_demographics.csv");
  Table pa = Demographics.load("Pennsylvania");
  philly = (Demographics) pa.get("Pennsylvania", "27237");
  random = new Random();
}
 
Example #26
Source File: SentryIniPolicyFileFormatter.java    From incubator-sentry with Apache License 2.0 5 votes vote down vote up
/**
 * parse the ini file and return a map with all data
 * 
 * @param resourcePath
 *        The path of the input file
 * @param conf
 *        The configuration info
 * @return the result of sentry mapping data in map structure.
 */
@Override
public Map<String, Map<String, Set<String>>> parse(String resourcePath, Configuration conf)
    throws Exception {
  Map<String, Map<String, Set<String>>> resultMap = Maps.newHashMap();
  // SimpleFileProviderBackend is used for parse the ini file
  SimpleFileProviderBackend policyFileBackend = new SimpleFileProviderBackend(conf, resourcePath);
  ProviderBackendContext context = new ProviderBackendContext();
  context.setAllowPerDatabase(true);
  // parse the ini file
  policyFileBackend.initialize(context);

  // SimpleFileProviderBackend parsed the input file and output the data in Table format.
  Table<String, String, Set<String>> groupRolePrivilegeTable = policyFileBackend
      .getGroupRolePrivilegeTable();
  Map<String, Set<String>> groupRolesMap = Maps.newHashMap();
  Map<String, Set<String>> rolePrivilegesMap = Maps.newHashMap();
  for (String groupName : groupRolePrivilegeTable.rowKeySet()) {
    for (String roleName : groupRolePrivilegeTable.columnKeySet()) {
      // get the roles set for the current groupName
      Set<String> tempRoles = groupRolesMap.get(groupName);
      if (tempRoles == null) {
        tempRoles = Sets.newHashSet();
      }
      Set<String> privileges = groupRolePrivilegeTable.get(groupName, roleName);
      // if there has privilege for [group,role], if no privilege exist, the [group, role] info
      // will be discard.
      if (privileges != null) {
        // update [group, role] mapping data
        tempRoles.add(roleName);
        groupRolesMap.put(groupName, tempRoles);
        // update [role, privilege] mapping data
        rolePrivilegesMap.put(roleName, privileges);
      }
    }
  }
  resultMap.put(PolicyFileConstants.GROUPS, groupRolesMap);
  resultMap.put(PolicyFileConstants.ROLES, rolePrivilegesMap);
  return resultMap;
}
 
Example #27
Source File: BrowserTest.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
public void addColumnsToTable(Table<Integer, Integer, String> table,
    Multimap<String, Object> column, int columnKey) {
  for (String key : column.keySet()) {
    shiftTable(table, columnKey);
    table.put(0, columnKey, key);
    Collection<Object> content = column.get(key);
    Iterator<Object> iterator = content.iterator();
    log.debug("Adding columun {} ({} elements) to table in position {}", key, content.size(),
        columnKey);
    for (int i = 0; i < content.size(); i++) {
      table.put(i + 1, columnKey, iterator.next().toString());
    }
    columnKey++;
  }
}
 
Example #28
Source File: AnnotationUtils.java    From Alink with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static Table<String, IOType, Wrapper<AlgoOperator>> loadIoOpClasses() {
    Reflections reflections = new Reflections("com.alibaba.alink");
    Table<String, IOType, Wrapper<AlgoOperator>> table = HashBasedTable.create();
    for (Class<?> clazz : reflections.getTypesAnnotatedWith(IoOpAnnotation.class)) {
        if (!AlgoOperator.class.isAssignableFrom(clazz)) {
            LOG.error("Class annotated with @IoOpAnnotation should be subclass of AlgoOperator: {}",
                    clazz.getCanonicalName());
            continue;
        }

        IoOpAnnotation annotation = clazz.getAnnotation(IoOpAnnotation.class);
        String name = annotation.name();
        IOType ioType = annotation.ioType();
        boolean hasTimestamp = annotation.hasTimestamp();

        Wrapper<AlgoOperator> origin = table.put(name, ioType,
                new Wrapper<>((Class<? extends AlgoOperator>) clazz, hasTimestamp));


        if (origin != null) {
            LOG.error("Multiple IO Operator class with same name {} and IOType: {}: {} and {}",
                    name, ioType, origin.clazz.getCanonicalName(), clazz.getCanonicalName());
        }
    }

    return ImmutableTable.copyOf(table);
}
 
Example #29
Source File: TmfAbstractToolTipHandler.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Point computePreferredSize() {
    Table<ToolTipString, ToolTipString, ToolTipString> model = getModel();
    int widestCat = 0;
    int widestKey = 0;
    int widestVal = 0;
    int totalHeight = 0;
    Set<ToolTipString> rowKeySet = model.rowKeySet();
    GC gc = new GC(Display.getDefault());
    for (ToolTipString row : rowKeySet) {
        if (!row.equals(UNCATEGORIZED)) {
            Point catExtent = gc.textExtent(row.toString());
            widestCat = Math.max(widestCat, catExtent.x);
            totalHeight += catExtent.y + 8;
        }
        Set<Entry<ToolTipString, ToolTipString>> entrySet = model.row(row).entrySet();
        for (Entry<ToolTipString, ToolTipString> entry : entrySet) {
            Point keyExtent = gc.textExtent(entry.getKey().toString());
            Point valExtent = gc.textExtent(entry.getValue().toString());
            widestKey = Math.max(widestKey, keyExtent.x);
            widestVal = Math.max(widestVal, valExtent.x);
            totalHeight += Math.max(keyExtent.y, valExtent.y) + 4;
        }
    }
    gc.dispose();
    int w = Math.max(widestCat, widestKey + CELL_PADDING + widestVal) + 2 * CONTENT_MARGIN + 2 * BODY_MARGIN;
    int h = totalHeight + 2 * CONTENT_MARGIN + 2 * BODY_MARGIN;
    Point scrollBarSize = getScrollbarSize(getParent());
    return new Point(w + scrollBarSize.x, h);
}
 
Example #30
Source File: SymbolWriter.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
private Table<String, String, SymbolEntry> getAllSymbols() {
    Table<String, String, SymbolEntry> symbols = HashBasedTable.create();

    for (SymbolLoader symbolLoader : mSymbols) {
        symbols.putAll(symbolLoader.getSymbols());
    }

    return symbols;
}