List of usage examples for com.google.common.collect Sets difference
public static <E> SetView<E> difference(final Set<E> set1, final Set<?> set2)
From source file:eu.lp0.cursus.ui.table.RaceNumbersDatabaseColumnModel.java
@Override protected boolean setValue(Pilot row, String values) { LinkedHashSet<RaceNumber> raceNos = new LinkedHashSet<RaceNumber>(); for (String value : values.toString().split("[ ,;/]+")) { //$NON-NLS-1$ if (value.length() > 0) { RaceNumber raceNo;// w w w . j av a 2 s . c o m try { raceNo = RaceNumber.valueOfFor(value, row); } catch (IllegalArgumentException e) { DatabaseError.unableToSave(win.getFrame(), getName(), Messages.getString("pilot.race-number.invalid", value)); //$NON-NLS-1$ return false; } if (!raceNumberDAO.isRaceNumberOk(raceNo)) { DatabaseError.unableToSave(win.getFrame(), getName(), Messages.getString("pilot.race-number.in-use", raceNo)); //$NON-NLS-1$ return false; } raceNos.add(raceNo); } } Iterator<RaceNumber> it = raceNos.iterator(); row.setRaceNumber(it.hasNext() ? it.next() : null); row.getRaceNumbers().retainAll(raceNos); row.getRaceNumbers().addAll(ImmutableSet.copyOf(Sets.difference(raceNos, row.getRaceNumbers()))); return true; }
From source file:org.glassfish.jersey.gf.cdi.InjecteeSkippingAnalyzer.java
@Override public <T> Set<Field> getFields(Class<T> type) throws MultiException { final Set<Field> originalFields = defaultAnalyzer.getFields(type); final Set<Field> skippedFields = getMembersToSkip(type, fieldsToSkip); return skippedFields == null ? originalFields : Sets.difference(originalFields, skippedFields); }
From source file:com.metamx.druid.index.v1.QueryableIndexIndexableAdapter.java
@Override public Indexed<String> getAvailableMetrics() { final Set<String> columns = Sets.newLinkedHashSet(input.getColumnNames()); final HashSet<String> dimensions = Sets.newHashSet(getAvailableDimensions()); return new ListIndexed<String>(Lists.newArrayList(Sets.difference(columns, dimensions)), String.class); }
From source file:org.dllearner.algorithms.schema.SimpleSchemaGenerator.java
@Override public Set<OWLAxiom> generateSchema() { Set<OWLAxiom> generatedAxiomsTotal = new HashSet<>(); // get the entities SortedSet<OWLEntity> entities = getEntities(); // we repeat the whole process for (int i = 0; i < nrOfIterations; i++) { LOGGER.trace("Iteration " + (i + 1) + " ..."); Set<OWLAxiom> generatedAxioms = new HashSet<>(); // iterate over the entities for (OWLEntity entity : entities) { // get the applicable axiom types SetView<AxiomType<? extends OWLAxiom>> applicableAxiomTypes = Sets .intersection(AxiomAlgorithms.getAxiomTypes(entity.getEntityType()), axiomTypes); // iterate over the axiom types for (AxiomType<? extends OWLAxiom> axiomType : applicableAxiomTypes) { // apply the appropriate learning algorithm try { Set<OWLAxiom> axioms = applyLearningAlgorithm(entity, axiomType); generatedAxioms.addAll(axioms); } catch (Exception e) { LOGGER.error("Exception occured for axiom type " + axiomType.getName() + " and entity " + entity + ".", e); //TODO handle exception despite logging }//from w w w. j a va2 s .co m } } // add the generated axioms to the knowledge base addToKnowledgebase(generatedAxioms); // new axioms SetView<OWLAxiom> newAxioms = Sets.difference(generatedAxioms, generatedAxiomsTotal); LOGGER.trace(newAxioms.isEmpty() ? "Got no new axioms." : ("Got " + newAxioms.size() + " new axioms:")); if (newAxioms.isEmpty()) { // terminate if iteration lead to no new axioms if ((i + 1) < nrOfIterations) LOGGER.trace("Early termination. Ignoring further iterations."); break; } LOGGER.trace(newAxioms.toString()); // add to total set generatedAxiomsTotal.addAll(generatedAxioms); } return generatedAxiomsTotal; }
From source file:org.eclipse.viatra.query.runtime.matchers.planning.helpers.FunctionalDependencyHelper.java
/*** * Returns the dependency set over attributes in {@link targetAttributes} that are implied by a given source dependency set. * <p> Note: exponential in the size of the target attribute set. * <p> Note: minimality of the returned dependency set is currently not guaranteed. * @param originalDependencies all dependencies that are known to hold on a wider set of attributes * @param targetAttributes the set of attributes we are interested in * @since 1.5//from ww w . j ava 2s .c o m */ public static <A> Map<Set<A>, Set<A>> projectDependencies(Map<Set<A>, Set<A>> originalDependencies, Set<A> targetAttributes) { // only those attributes are considered as left-hand-side candidates that occur at least once in dependencies Set<A> leftCandidates = new HashSet<A>(); for (Entry<Set<A>, Set<A>> dependency : originalDependencies.entrySet()) { if (!isTrivial(dependency.getKey(), dependency.getValue())) // only if non-trivial leftCandidates.addAll(Sets.intersection(dependency.getKey(), targetAttributes)); } // Compute an initial list of nontrivial projected dependencies - it does not have to be minimal yet Map<Set<A>, Set<A>> initialDependencies = new HashMap<Set<A>, Set<A>>(); for (Set<A> leftSet : Sets.powerSet(leftCandidates)) { Set<A> rightSet = Sets.intersection(closureOf(leftSet, originalDependencies), targetAttributes); if (!isTrivial(leftSet, rightSet)) { initialDependencies.put(leftSet, rightSet); } } // Don't forget to include constants! Set<A> constants = Sets.intersection(closureOf(Collections.<A>emptySet(), originalDependencies), targetAttributes); if (!constants.isEmpty()) { initialDependencies.put(Collections.<A>emptySet(), constants); } // Omit those dependencies where the LHS has superfluous attributes Map<Set<A>, Set<A>> solidDependencies = new HashMap<Set<A>, Set<A>>(); for (Entry<Set<A>, Set<A>> dependency : initialDependencies.entrySet()) { Set<A> leftSet = dependency.getKey(); Set<A> rightSet = dependency.getValue(); boolean solid = true; for (A skipped : leftSet) { // what if we skip one attribute from the left set? Set<A> singleton = Collections.singleton(skipped); Set<A> candidate = Sets.difference(leftSet, singleton); Set<A> rightCandidate = initialDependencies.get(candidate); if (rightCandidate != null) { if (Sets.union(rightCandidate, singleton).containsAll(rightSet)) { solid = false; break; } } } if (solid) { solidDependencies.put(leftSet, rightSet); } } // TODO perform proper minimization, // see e.g. page 45 in http://www.cs.ubc.ca/~hkhosrav/db/slides/03.design%20theory.pdf return Collections.unmodifiableMap(solidDependencies); }
From source file:webindex.data.fluo.PageObserver.java
@Override public void process(TransactionBase tx, Bytes row, Column col) throws Exception { TypedTransactionBase ttx = Constants.TYPEL.wrap(tx); Map<Column, Value> pages = ttx.get().row(row).columns(Constants.PAGE_NEW_COL, Constants.PAGE_CUR_COL); String nextJson = pages.get(Constants.PAGE_NEW_COL).toString(""); if (nextJson.isEmpty()) { log.error("An empty page was set at row {} col {}", row.toString(), col.toString()); return;// w w w . j a v a2 s . c o m } Page curPage = Page.fromJson(gson, pages.get(Constants.PAGE_CUR_COL).toString("")); Set<Link> curLinks = curPage.getOutboundLinks(); Map<String, UriInfo> updates = new HashMap<>(); String pageUri = getPageRowHasher().removeHash(row).toString(); Page nextPage = Page.fromJson(gson, nextJson); if (nextPage.isDelete()) { ttx.mutate().row(row).col(Constants.PAGE_CUR_COL).delete(); updates.put(pageUri, new UriInfo(0, -1)); } else { ttx.mutate().row(row).col(Constants.PAGE_CUR_COL).set(nextJson); if (curPage.isEmpty()) { updates.put(pageUri, new UriInfo(0, 1)); } pagesIngested.mark(); } Set<Link> nextLinks = nextPage.getOutboundLinks(); List<Link> addLinks = new ArrayList<>(Sets.difference(nextLinks, curLinks)); for (Link link : addLinks) { updates.put(link.getUri(), new UriInfo(1, 0)); } linksIngested.mark(addLinks.size()); List<Link> delLinks = new ArrayList<>(Sets.difference(curLinks, nextLinks)); for (Link link : delLinks) { updates.put(link.getUri(), new UriInfo(-1, 0)); } uriQ.addAll(tx, updates); exportQ.add(tx, pageUri, new PageUpdate(pageUri, nextJson, addLinks, delLinks)); pagesChanged.mark(); // clean up ttx.mutate().row(row).col(Constants.PAGE_NEW_COL).delete(); }
From source file:org.jclouds.elb.loadbalancer.strategy.ELBLoadBalanceNodesStrategy.java
@Override public LoadBalancerMetadata createLoadBalancerInLocation(Location location, String name, String protocol, int loadBalancerPort, int instancePort, Iterable<? extends NodeMetadata> nodes) { checkNotNull(location, "location"); String region = getRegionFromLocationOrNull(location); Set<String> zonesDesired = ImmutableSet.copyOf(transform(nodes, new Function<NodeMetadata, String>() { @Override/*from w w w .ja v a2 s . c om*/ public String apply(NodeMetadata from) { return from.getLocation().getId(); } })); logger.debug(">> creating loadBalancer(%s) in zones(%s)", name, zonesDesired); try { String dnsName = api.getLoadBalancerApiForRegion(region) .createListeningInAvailabilityZones( name, ImmutableSet.of(Listener.builder().port(loadBalancerPort) .instancePort(instancePort).protocol(Protocol.valueOf(protocol)).build()), zonesDesired); logger.debug("<< created loadBalancer(%s) dnsName(%s)", name, dnsName); } catch (IllegalStateException e) { logger.debug("<< converging zones(%s) in loadBalancer(%s)", zonesDesired, name); Set<String> currentZones = api.getLoadBalancerApi().get(name).getAvailabilityZones(); Set<String> zonesToAdd = Sets.difference(zonesDesired, currentZones); if (zonesToAdd.size() > 0) currentZones = api.getAvailabilityZoneApi().addAvailabilityZonesToLoadBalancer(zonesToAdd, name); Set<String> zonesToRemove = Sets.difference(currentZones, zonesDesired); if (zonesToRemove.size() > 0) api.getAvailabilityZoneApi().removeAvailabilityZonesFromLoadBalancer(zonesToRemove, name); } Set<String> instanceIds = ImmutableSet.copyOf(transform(nodes, new Function<NodeMetadata, String>() { @Override public String apply(NodeMetadata from) { return from.getProviderId(); } })); logger.debug(">> converging loadBalancer(%s) to instances(%s)", name, instanceIds); Set<String> registeredInstanceIds = api.getInstanceApiForRegion(region) .registerInstancesWithLoadBalancer(instanceIds, name); Set<String> instancesToRemove = filter(registeredInstanceIds, not(in(instanceIds))); if (instancesToRemove.size() > 0) { logger.debug(">> deregistering instances(%s) from loadBalancer(%s)", instancesToRemove, name); api.getInstanceApiForRegion(region).deregisterInstancesFromLoadBalancer(instancesToRemove, name); } logger.debug("<< converged loadBalancer(%s) ", name); return converter.apply(new LoadBalancerInRegion(api.getLoadBalancerApiForRegion(region).get(name), region)); }
From source file:org.obiba.mica.study.service.IndividualStudyService.java
public void saveInternal(final Study study, String comment, boolean cascade, boolean weightChanged) { log.info("Saving study: {}", study.getId()); // checks if population and dce are still the same if (study.getId() != null) { List<String> list = populationsOrDceAffected(study, studyRepository.findOne(study.getId()), false); if (list != null && list.size() > 0) { checkPopulationOrDceMissingConstraints(list); }/* w ww . j a va 2 s . c om*/ } if (study.getLogo() != null && study.getLogo().isJustUploaded()) { fileStoreService.save(study.getLogo().getId()); study.getLogo().setJustUploaded(false); } ImmutableSet<String> invalidRoles = ImmutableSet.copyOf(Sets.difference(study.membershipRoles(), Sets.newHashSet(micaConfigService.getConfig().getRoles()))); invalidRoles.forEach(study::removeRole); StudyState studyState = findEntityState(study, StudyState::new); if (!study.isNew()) ensureGitRepository(studyState); studyState.incrementRevisionsAhead(); if (weightChanged) { studyState.setPopulationOrDceWeightChange(true); } studyStateRepository.save(studyState); study.setLastModifiedDate(DateTime.now()); if (cascade) studyRepository.saveWithReferences(study); else studyRepository.save(study); gitService.save(study, comment); eventBus.post(new DraftStudyUpdatedEvent(study)); }
From source file:org.jclouds.ohai.functions.NestSlashKeys.java
@VisibleForTesting void mergeAsPeer(String key, JsonBall value, Map<String, JsonBall> insertionContext) { Map<String, JsonBall> immutableValueContext = json.fromJson(insertionContext.get(key).toString(), mapLiteral);/*from w w w . j a va 2 s .c om*/ Map<String, JsonBall> valueContext = Maps.newLinkedHashMap(immutableValueContext); Map<String, JsonBall> toPut = json.<Map<String, JsonBall>>fromJson(value.toString(), mapLiteral); Set<String> uniques = Sets.difference(toPut.keySet(), valueContext.keySet()); for (String k : uniques) { valueContext.put(k, toPut.get(k)); } Set<String> conflicts = Sets.difference(toPut.keySet(), uniques); for (String k : conflicts) { JsonBall v = toPut.get(k); if (v.toString().matches("^\\{.*\\}$")) { mergeAsPeer(k, v, valueContext); } else { // replace valueContext.put(k, v); } } insertionContext.put(key, new JsonBall(json.toJson(valueContext, mapLiteral))); }
From source file:edu.harvard.med.screensaver.ui.screenresults.ScreenResultImporter.java
@UICommand public String doImport() throws IOException { Screen screen = _screenViewer.getEntity(); try {//from w w w .j a v a 2s . c o m ScreenResult screenResult = _screenResultLoader.parseAndLoad(screen, new Workbook("Input Stream for screen: " + screen, _uploadedFile.getInputStream()), (AdministratorUser) getScreensaverUser(), _comments, null, true); screenResult = _dao.reloadEntity(screenResult, true, ScreenResult.screen.to(AuditedAbstractEntity.updateActivities.castToSubtype(Screen.class))); showMessage("screens.screenResultDataLoaded", screenResult.getLastDataLoadingActivity().getComments()); screen = _dao.reloadEntity(screen, true, Screen.assayPlates); int assayPlatesCreated = Sets .difference(screen.getAssayPlatesDataLoaded(), screen.getAssayPlatesScreened()).size(); if (assayPlatesCreated > 0) { showMessage("screens.assayPlatesCreatedForLoadedData", assayPlatesCreated); } } catch (ParseErrorsException e) { log.info("parse errors encountered during import of ScreenResult for Screen " + screen); _lastParseErrors = e.getErrors(); return REDISPLAY_PAGE_ACTION_RESULT; } return _screenViewer.viewEntity(screen); }