List of usage examples for com.google.common.collect Sets intersection
public static <E> SetView<E> intersection(final Set<E> set1, final Set<?> set2)
From source file:org.apache.rya.indexing.IndexPlanValidator.IndexPlanValidator.java
private boolean isJoinValid(Join join) { Set<String> leftBindingNames = join.getLeftArg().getBindingNames(); Set<String> rightBindingNames = join.getRightArg().getBindingNames(); //System.out.println("Left binding names are " + leftBindingNames + " and right binding names are " + rightBindingNames); if (Sets.intersection(leftBindingNames, rightBindingNames).size() == 0) { if (omitCrossProd) { return false; } else {// w w w . java2 s . co m return true; } } else { if (join.getRightArg() instanceof ExternalTupleSet) { return ((ExternalTupleSet) join.getRightArg()).supportsBindingSet(leftBindingNames); } else { return true; } } }
From source file:com.ggvaidya.scinames.summary.DatasetSimilarityView.java
public void init() { // Setup stage. stage.setTitle("Timepoint similarity"); // Setup table. controller.getTableEditableProperty().set(false); //controller.setTableColumnResizeProperty(TableView.CONSTRAINED_RESIZE_POLICY); ObservableList<TableColumn> cols = controller.getTableColumnsProperty(); cols.clear();// ww w . j a v a 2 s .co m // Set up columns. TableColumn<Dataset, String> colTimepointName = new TableColumn<>("Timepoint"); colTimepointName.setCellValueFactory(new PropertyValueFactory<>("name")); colTimepointName.setPrefWidth(100.0); cols.add(colTimepointName); // Precalculating. double lowest = 100.0; Dataset tpLowest1 = null; Dataset tpLowest2 = null; LOGGER.info("Starting precalculating."); Table<Dataset, Dataset, String> data = HashBasedTable.create(); for (Dataset tp : projectView.getProject().getDatasets()) { for (Dataset colTP : projectView.getProject().getDatasets()) { if (data.contains(tp, colTP)) continue; NameClusterManager manager = projectView.getProject().getNameClusterManager(); Set<NameCluster> leftTP = tp.getRecognizedNames(projectView.getProject()) .map(n -> manager.getCluster(n).get()).collect(Collectors.toSet()); Set<NameCluster> rightTP = colTP.getRecognizedNames(projectView.getProject()) .map(n -> manager.getCluster(n).get()).collect(Collectors.toSet()); // Overlapping name concepts. Sets.SetView<NameCluster> union = Sets.union(leftTP, rightTP); Sets.SetView<NameCluster> intersection = Sets.intersection(leftTP, rightTP); double res = (((double) intersection.size()) / union.size() * 100); if (lowest > res) { lowest = res; tpLowest1 = tp; tpLowest2 = colTP; } String result = new BigDecimal(res).setScale(2, RoundingMode.DOWN).toPlainString() + "% (" + intersection.size() + " identical out of " + union.size() + ")"; data.put(tp, colTP, result); data.put(colTP, tp, result); } } LOGGER.info("Precalculating done."); // Setup headertext. String str_lowest = ""; if (tpLowest1 != null && tpLowest2 != null) { str_lowest = " (lowest: " + new BigDecimal(lowest).setScale(2, RoundingMode.DOWN).toPlainString() + "% between " + tpLowest1.getName() + " and " + tpLowest2.getName() + ")"; } controller.getHeaderTextProperty().set("How similar is each timepoint to every other?" + str_lowest); controller.getHeaderTextEditableProperty().set(false); // Create a column for every timepoint here. projectView.getProject().getDatasets().forEach((Dataset colTP) -> { TableColumn<Dataset, String> colTimepoint = new TableColumn<>(colTP.getName()); colTimepoint.setCellValueFactory((TableColumn.CellDataFeatures<Dataset, String> features) -> { Dataset tp = features.getValue(); return new ReadOnlyStringWrapper(data.get(tp, colTP)); }); colTimepoint.setPrefWidth(100.0); cols.add(colTimepoint); }); // Set table items. List<Dataset> timepoints = projectView.getProject().getDatasets(); controller.getTableItemsProperty().set(FXCollections.observableList(timepoints)); }
From source file:com.google.errorprone.bugpatterns.IncompatibleModifiersChecker.java
@Override public Description matchAnnotation(AnnotationTree tree, VisitorState state) { Set<Modifier> incompatibleModifiers = getIncompatibleModifiers(tree, state); if (incompatibleModifiers.isEmpty()) { return Description.NO_MATCH; }//from w w w .j a v a2s . c om Tree parent = state.getPath().getParentPath().getLeaf(); if (!(parent instanceof ModifiersTree)) { // e.g. An annotated package name return Description.NO_MATCH; } Set<Modifier> incompatible = Sets.intersection(incompatibleModifiers, ((ModifiersTree) parent).getFlags()); if (incompatible.isEmpty()) { return Description.NO_MATCH; } String annotationName = ASTHelpers.getAnnotationName(tree); String nameString = annotationName != null ? String.format("The annotation '@%s'", annotationName) : "This annotation"; String customMessage = String.format(MESSAGE_TEMPLATE, nameString, incompatible.toString()); return buildDescription(tree).setMessage(customMessage).build(); }
From source file:org.eclipse.elk.alg.layered.intermediate.compaction.NetworkSimplexCompaction.java
/** * @return true if both passed nodes originate from the same (set) of {@link LEdge}. *///from w w w . j a v a2 s. co m private boolean isVerticalSegmentsOfSameEdge(final CNode cNode1, final CNode cNode2) { return cNode1.parentNode != null && cNode2.parentNode != null && (cNode1 instanceof CLEdge && cNode2 instanceof CLEdge) // this might seem quite expensive but in most cases the sets // contain only one element && !Sets.intersection(((CLEdge) cNode1).originalLEdges, ((CLEdge) cNode2).originalLEdges).isEmpty(); }
From source file:org.dllearner.learningproblems.EvaluationCache.java
private SortedSetTuple<OWLIndividual> handleMultiConjunction(OWLObjectIntersectionOf mc) { List<OWLClassExpression> operands = mc.getOperandsAsList(); Set<OWLIndividual> pos = cache.get(operands.get(0)); for (int i = 1; i < operands.size(); i++) { pos = Sets.intersection(pos, cache.get(operands.get(i))); }/*w ww . j a v a2 s . c om*/ // TODO: handle the case that some children may not be in cache return null; }
From source file:org.mitre.oauth2.token.ChainedTokenGranter.java
@Override protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) throws AuthenticationException, InvalidTokenException { // read and load up the existing token String incomingTokenValue = tokenRequest.getRequestParameters().get("token"); OAuth2AccessTokenEntity incomingToken = tokenServices.readAccessToken(incomingTokenValue); // check for scoping in the request, can't up-scope with a chained request Set<String> approvedScopes = incomingToken.getScope(); Set<String> requestedScopes = tokenRequest.getScope(); if (requestedScopes == null) { requestedScopes = new HashSet<String>(); }//from www . j a va 2 s.c o m // do a check on the requested scopes -- if they exactly match the client scopes, they were probably shadowed by the token granter if (client.getScope().equals(requestedScopes)) { requestedScopes = new HashSet<String>(); } // if our scopes are a valid subset of what's allowed, we can continue if (approvedScopes.containsAll(requestedScopes)) { if (requestedScopes.isEmpty()) { // if there are no scopes, inherit the original scopes from the token tokenRequest.setScope(approvedScopes); } else { // if scopes were asked for, give only the subset of scopes requested // this allows safe downscoping tokenRequest.setScope(Sets.intersection(requestedScopes, approvedScopes)); } // NOTE: don't revoke the existing access token // create a new access token OAuth2Authentication authentication = new OAuth2Authentication( getRequestFactory().createOAuth2Request(client, tokenRequest), incomingToken.getAuthenticationHolder().getAuthentication().getUserAuthentication()); return authentication; } else { throw new InvalidScopeException("Invalid scope requested in chained request", approvedScopes); } }
From source file:com.opengamma.master.impl.InMemoryExternalIdCache.java
private Set<V> getMatchesAll(ExternalIdSearch search) { Set<V> result = null;/*from w w w . ja v a2 s . c o m*/ for (ExternalId id : search.getExternalIds()) { Map<T, V> matches = _store.get(id); if (matches == null) { // We can short circuit it here because by definition // these can't be satisfied. return Collections.emptySet(); } if (result == null) { result = new HashSet<V>(matches.values()); } else { result = Sets.intersection(result, new HashSet<V>(matches.values())); } } return result; }
From source file:org.eclipse.sirius.common.tools.api.interpreter.VariableType.java
/** * Return a {@link TypeName} representation of a common type matching all * the definitions. This should only be used by interpreters or code which * can't take into account the fact that a Variable can have multiple types * which no common super type in a Viewpoint Specification model. * /*from w ww . j av a 2 s . co m*/ * When a {@link VariableType} is defined by several typeNames common super * types will be searched for but if several common types are found, then * one will be arbitrarly choosen. * * @param availableEPackages * the available EPackages to use. * * @return A TypeName of a type which matches all the definitions. */ public TypeName getCommonType(Collection<EPackage> availableEPackages) { TypeName result = TypeName.ANY_TYPENAME; if (types.size() == 1) { result = types.get(0); } if (types.size() > 1) { Iterator<TypeName> typeNameIt = types.iterator(); Set<EClass> commonSuperTypes = Sets.newLinkedHashSet(); if (typeNameIt.hasNext()) { TypeName first = typeNameIt.next(); commonSuperTypes = getAllSuperTypes(first, availableEPackages); } while (typeNameIt.hasNext() && commonSuperTypes.size() > 0) { TypeName type = typeNameIt.next(); Set<EClass> nextTypeSuperTypes = getAllSuperTypes(type, availableEPackages); commonSuperTypes = Sets.intersection(commonSuperTypes, nextTypeSuperTypes); } if (commonSuperTypes.size() > 0) { EClass firstCommonSuperType = commonSuperTypes.iterator().next(); result = TypeName.fromEClassifier(firstCommonSuperType); } else { result = TypeName.EOBJECT_TYPENAME; } } return result; }
From source file:squash.booking.lambdas.core.BookingManager.java
@Override public List<Booking> createBooking(Booking bookingToCreate, boolean isSquashServiceUserCall) throws Exception { if (!initialised) { throw new IllegalStateException("The booking manager has not been initialised"); }/*from ww w.ja v a 2s. c o m*/ getLifecycleManager().throwIfOperationInvalidForCurrentLifecycleState(false, isSquashServiceUserCall); logger.log("About to create booking in database: " + bookingToCreate); // Get today's bookings (and version number), via consistent read: String itemName = bookingToCreate.getDate(); // We retry the creation of the booking if necessary if we get a // ConditionalCheckFailed exception, i.e. if someone else modifies // the database between us reading and writing it. return RetryHelper.DoWithRetries(() -> { ImmutablePair<Optional<Integer>, List<Booking>> versionedBookings = getVersionedBookings(itemName); // Check that the court(s) we're booking is/are currently free // Get individual booked courts as (court, slot) pairs Set<ImmutablePair<Integer, Integer>> bookedCourts = new HashSet<>(); versionedBookings.right.forEach((booking) -> { addBookingToSet(booking, bookedCourts); }); // Get courts we're trying to book as (court, slot) pairs Set<ImmutablePair<Integer, Integer>> courtsToBook = new HashSet<>(); addBookingToSet(bookingToCreate, courtsToBook); // Does the new booking clash with existing bookings? boolean bookingClashes = Boolean.valueOf(Sets.intersection(courtsToBook, bookedCourts).size() > 0); if (bookingClashes) { // Case of trying to book an already-booked slot - this // probably means either: // - more than one person was trying to book the slot at once, // or // - not all courts in our block booking are free logger.log( "Cannot book courts which are already booked, so throwing a 'Booking creation failed' exception"); throw new Exception("Booking creation failed"); } logger.log("Required courts are currently free - so proceeding to make booking"); // Do a conditional put - so we don't overwrite someone else's // booking String attributeName = getAttributeNameFromBooking(bookingToCreate); String attributeValue = bookingToCreate.getName(); logger.log("ItemName: " + itemName); logger.log("AttributeName: " + attributeName); logger.log("AttributeValue: " + attributeValue); ReplaceableAttribute bookingAttribute = new ReplaceableAttribute(); bookingAttribute.setName(attributeName); bookingAttribute.setValue(attributeValue); getOptimisticPersister().put(itemName, versionedBookings.left, bookingAttribute); logger.log("Created booking in database"); // Add the booking we've just made to the pre-existing ones. List<Booking> bookings = versionedBookings.right; bookings.add(bookingToCreate); return bookings; }, Exception.class, Optional.of("Database put failed - conditional check failed"), logger); }
From source file:org.mitre.oauth2.service.impl.DefaultIntrospectionResultAssembler.java
@Override public Map<String, Object> assembleFrom(OAuth2RefreshTokenEntity refreshToken, UserInfo userInfo, Set<String> authScopes) { Map<String, Object> result = newLinkedHashMap(); OAuth2Authentication authentication = refreshToken.getAuthenticationHolder().getAuthentication(); result.put(ACTIVE, true);//from w w w . ja va 2s . co m Set<String> scopes = Sets.intersection(authScopes, authentication.getOAuth2Request().getScope()); result.put(SCOPE, Joiner.on(SCOPE_SEPARATOR).join(scopes)); if (refreshToken.getExpiration() != null) { try { result.put(EXPIRES_AT, dateFormat.valueToString(refreshToken.getExpiration())); result.put(EXP, refreshToken.getExpiration().getTime() / 1000L); } catch (ParseException e) { logger.error("Parse exception in token introspection", e); } } if (userInfo != null) { // if we have a UserInfo, use that for the subject result.put(SUB, userInfo.getSub()); } else { // otherwise, use the authentication's username result.put(SUB, authentication.getName()); } if (authentication.getUserAuthentication() != null) { result.put(USER_ID, authentication.getUserAuthentication().getName()); } result.put(CLIENT_ID, authentication.getOAuth2Request().getClientId()); return result; }