下面列出了怎么用com.google.common.collect.Table的API类实例代码及写法,或者点击链接到github查看源代码。
/** 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;
}
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;
}
/**
* 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;
}
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;
}
@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);
}
@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")))));
}
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;
}
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);
}
@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);
}
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;
}
/**
* 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);
}
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();
}
}
}
}
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);
}
}
}
}
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()));
}
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;
}
@Test
public void givenTable_whenColKeySet_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 Set<String> courseSet = universityCourseSeatTable.columnKeySet();
assertThat(courseSet).hasSize(3);
}
/**
* 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);
}
private void addEndSummary(N sP, D d1, N eP, D d2, EdgeFunction<V> f) {
Table<N, D, EdgeFunction<V>> summaries = endSummary.get(sP, d1);
if(summaries==null) {
summaries = HashBasedTable.create();
endSummary.put(sP, d1, summaries);
}
//note: at this point we don't need to join with a potential previous f
//because f is a jump function, which is already properly joined
//within propagate(..)
summaries.put(eP,d2,f);
}
@Override
public Table<String, String, Double> calculateAggregatedSimilarityValues(List<Artifact> artifacts,
Map<String, String> params) {
Table<String, String, Double> result = HashBasedTable.create();
int i = 0;
for (Artifact artifact : artifacts) {
List<Dependency> deps = new ArrayList<>();
if (i % 10 == 0)
logger.info("CROSSRec similarity calculator is computing {} of {} similarity.", i, artifacts.size());
i++;
for (String dependency : artifact.getDependencies()) {
String[] value = dependency.split(":");
if (value.length == 2) {
Dependency dep = new Dependency();
dep.setGroupID(value[0]);
dep.setArtifactID(value[1]);
deps.add(dep);
}
}
try {
Map<String, Double> map = computeWeightCosineSimilarity(deps);
for (Map.Entry<String, Double> entry : map.entrySet()) {
result.put(artifact.getFullName(), artifactRepository.findOne(entry.getKey()).getFullName(),
entry.getValue());
}
} catch (Exception e) {
logger.error(e.getMessage());
}
}
return result;
}
private void mergeResult(Table<String, String, Set<String>> groupRolePrivilegeTableTemp) {
for (Cell<String, String, Set<String>> cell : groupRolePrivilegeTableTemp.cellSet()) {
String groupName = cell.getRowKey();
String roleName = cell.getColumnKey();
Set<String> privileges = groupRolePrivilegeTable.get(groupName, roleName);
if (privileges == null) {
privileges = new HashSet<String>();
groupRolePrivilegeTable.put(groupName, roleName, privileges);
}
privileges.addAll(cell.getValue());
}
}
@Override
public Table<ResourceNamespace, ResourceType, ResourceValueMap> getConfiguredResources(
@NonNull FolderConfiguration referenceConfig) {
synchronized (ITEM_MAP_LOCK) {
Set<ResourceNamespace> namespaces = getNamespaces();
Map<ResourceNamespace, Map<ResourceType, ResourceValueMap>> backingMap;
if (KnownNamespacesMap.canContainAll(namespaces)) {
backingMap = new KnownNamespacesMap<>();
} else {
backingMap = new HashMap<>();
}
Table<ResourceNamespace, ResourceType, ResourceValueMap> table
= Tables.newCustomTable(backingMap, () -> new EnumMap<>(ResourceType.class));
for (ResourceNamespace namespace : namespaces) {
// TODO(namespaces): Move this method to ResourceResolverCache.
// For performance reasons don't mix framework and non-framework resources since
// they have different life spans.
for (ResourceType type : ResourceType.values()) {
// get the local results and put them in the map
table.put(
namespace,
type,
getConfiguredResources(namespace, type, referenceConfig));
}
}
return table;
}
}
@Nonnull
private Table<String, String, Set<Layer2Vni>> computeVniSettings() {
Table<String, String, Set<Layer2Vni>> result = HashBasedTable.create();
for (Node node : _nodes.values()) {
for (Entry<String, VirtualRouter> vr : node.getVirtualRouters().entrySet()) {
result.put(
node.getConfiguration().getHostname(), vr.getKey(), vr.getValue().getLayer2Vnis());
}
}
return result;
}
@Nonnull
private Table<String, String, Set<Bgpv4Route>> computeBgpRoutes() {
Table<String, String, Set<Bgpv4Route>> table = HashBasedTable.create();
_nodes.forEach(
(hostname, node) ->
node.getVirtualRouters()
.forEach(
(vrfName, vr) -> {
table.put(hostname, vrfName, vr.getBgpRoutes());
}));
return table;
}
public GuavaTableModel(Table<Integer, String, V> guavaTable) {
this.guavaTable = guavaTable;
this.columnNames = Lists.newArrayList(guavaTable.columnKeySet());
Collections.sort(this.columnNames);
Set<Integer> rowIndexes = this.guavaTable.rowKeySet();
this.rowCount = Collections.max(rowIndexes) + 1;
}
/**
* Convert VNI setting table obtained from the dataplane into a table format that's easier to work
* with
*/
@Nonnull
private static Table<VrfId, Integer, Layer2Vni> computeVniSettingsTable(
Table<String, String, ? extends Collection<Layer2Vni>> allVniSettings) {
Table<VrfId, Integer, Layer2Vni> table = HashBasedTable.create();
for (Cell<String, String, ? extends Collection<Layer2Vni>> cell : allVniSettings.cellSet()) {
assert cell.getValue() != null;
assert cell.getRowKey() != null;
assert cell.getColumnKey() != null;
for (Layer2Vni vni : cell.getValue()) {
table.put(new VrfId(cell.getRowKey(), cell.getColumnKey()), vni.getVni(), vni);
}
}
return table;
}
private Table<String, ResourceType, Response<Map<String, String>>> getAllFromRedis() {
try {
Set<String> allUsers = scanSet(allUsersKey());
return getAllFromRedis(allUsers);
} catch (Exception e) {
log.error("Storage exception reading all entries.", e);
return null;
}
}
@Test
public void testBatchModeReads() throws Exception {
System.setProperty(CoreConfig.META_CACHE_BATCHED_READS.name(), "true");
Configuration.getInstance().init();
// Verify batch write mode is actually on
Assert.assertTrue(Configuration.getInstance().getBooleanProperty(CoreConfig.META_CACHE_BATCHED_READS));
MetadataCache cache = MetadataCache.createLoadingCacheInstance();
// Write some data to metadata cache.
Locator l0 = Locator.createLocatorFromPathComponents("1", "a", "b");
Locator l1 = Locator.createLocatorFromPathComponents("1", "c", "d");
AMetadataIO metadataIO = new AMetadataIO();
Table<Locator, String, String> metaToWrite = HashBasedTable.create();
// By the pass the cache and write to disk directly.
metaToWrite.put(l0, "foo", "l0_foo");
metaToWrite.put(l0, "bar", "l0_bar");
metaToWrite.put(l1, "zee", "zzzzz");
metadataIO.putAll(metaToWrite);
// Do a cache get on one of those locators. We should get back null immediately.
Assert.assertNull(cache.get(l0, "foo"));
// Wait for the cache to be populated async for that locator + meta.
Thread.sleep(2000);
Assert.assertTrue(cache.get(l0, "foo").equals("l0_foo"));
// We should have also read other meta for that locator.
Assert.assertTrue(cache.get(l0, "bar").equals("l0_bar"));
}
@Test
public void guava_table_example () {
Random r = new Random(3000);
Table<Integer, String, Workout> table = HashBasedTable.create();
table.put(1, "Filthy 50", new Workout(r.nextLong()));
table.put(1, "Fran", new Workout(r.nextLong()));
table.put(1, "The Seven", new Workout(r.nextLong()));
table.put(1, "Murph", new Workout(r.nextLong()));
table.put(1, "The Ryan", new Workout(r.nextLong()));
table.put(1, "King Kong", new Workout(r.nextLong()));
table.put(2, "Filthy 50", new Workout(r.nextLong()));
table.put(2, "Fran", new Workout(r.nextLong()));
table.put(2, "The Seven", new Workout(r.nextLong()));
table.put(2, "Murph", new Workout(r.nextLong()));
table.put(2, "The Ryan", new Workout(r.nextLong()));
table.put(2, "King Kong", new Workout(r.nextLong()));
// for each row key
for (Integer key : table.rowKeySet()) {
logger.info("Person: " + key);
for (Entry<String, Workout> row : table.row(key).entrySet()) {
logger.info("Workout name: " + row.getKey() + " for elapsed time of " + row.getValue().getElapsedTime());
}
}
}
@Override
public Map<String, U> parse(String data) throws IOException {
Table<String, String, String> table = tableParser.parse(data);
ImmutableMap.Builder<String, U> builder = ImmutableMap.builder();
for (Map.Entry<String, Map<String, String>> rowInfo : table.rowMap().entrySet()) {
String key = rowInfo.getKey();
U bean = Translators.translate(rowInfo.getValue(), clazz);
builder.put(key, bean);
}
return builder.build();
}
@Test
public void givenTable_whenVerifying_thenShouldBeCorrect() throws Exception {
final Table<Integer, String, String> table = HashBasedTable.create(2, 2);
table.put(1, "A", "PRESENT");
table.put(1, "B", "ABSENT");
assertThat(table).hasRowCount(1).containsValues("ABSENT").containsCell(1, "B", "ABSENT");
}