下面列出了java.util.Set#contains ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Get the current solution.
* <p>
* {@link #solve} should be called first for this to be the optimal solution.
* </p>
* @return current solution
*/
protected RealPointValuePair getSolution() {
double[] coefficients = new double[getOriginalNumDecisionVariables()];
Integer basicRow =
getBasicRow(getNumObjectiveFunctions() + getOriginalNumDecisionVariables());
double mostNegative = basicRow == null ? 0 : getEntry(basicRow, getRhsOffset());
Set<Integer> basicRows = new HashSet<Integer>();
for (int i = 0; i < coefficients.length; i++) {
basicRow = getBasicRow(getNumObjectiveFunctions() + i);
if (basicRows.contains(basicRow)) {
// if multiple variables can take a given value
// then we choose the first and set the rest equal to 0
coefficients[i] = 0;
} else {
basicRows.add(basicRow);
coefficients[i] =
(basicRow == null ? 0 : getEntry(basicRow, getRhsOffset())) -
(restrictToNonNegative ? 0 : mostNegative);
}
}
return new RealPointValuePair(coefficients, f.getValue(coefficients));
}
private String parseMember(ShapeId parent, Set<String> requiredMembers) {
// Parse optional member traits.
List<TraitEntry> memberTraits = parseDocsAndTraits();
SourceLocation memberLocation = currentLocation();
String memberName = ParserUtils.parseIdentifier(this);
// Only enforce "allowedMembers" if it isn't empty.
if (!requiredMembers.isEmpty() && !requiredMembers.contains(memberName)) {
throw syntax("Unexpected member of " + parent + ": '" + memberName + '\'');
}
ws();
expect(':');
ws();
ShapeId memberId = parent.withMember(memberName);
MemberShape.Builder memberBuilder = MemberShape.builder().id(memberId).source(memberLocation);
SourceLocation targetLocation = currentLocation();
String target = ParserUtils.parseShapeId(this);
visitor.onShape(memberBuilder);
onShapeTarget(target, targetLocation, memberBuilder::target);
addTraits(memberId, memberTraits);
return memberName;
}
/**
* Add a block to the hierarchy.
*
* @param block block to add
*/
private void addBlockToHierarchy(Block block)
{
if (m_parentStack.isEmpty())
{
m_blocks.add(block);
addParentBlockToHierarchy(block);
}
else
{
Block parentBlock = m_parentStack.getFirst();
Set<String> set = EXPECTED_CHILD_CLASSES.get(parentBlock.getName());
if (set != null && set.contains(block.getName()))
{
parentBlock.getChildBlocks().add(block);
addParentBlockToHierarchy(block);
}
else
{
m_parentStack.pop();
addBlockToHierarchy(block);
}
}
}
protected List<ActivityInstance> getActivityInstancesForActivity(ActivityInstance tree, Set<String> parentScopeIds) {
// prune all search paths that are not in the scope hierarchy of the activity in question
if (!parentScopeIds.contains(tree.getActivityId())) {
return Collections.emptyList();
}
List<ActivityInstance> instances = new ArrayList<ActivityInstance>();
if (activityId.equals(tree.getActivityId())) {
instances.add(tree);
}
for (ActivityInstance child : tree.getChildActivityInstances()) {
instances.addAll(getActivityInstancesForActivity(child, parentScopeIds));
}
return instances;
}
private void executeDiscardedPairs(VioGenQuery vioGenQuery, CellChanges allCellChanges, Set<TuplePair> discardedTuples, Set<Tuple> usedTuples, NumberOfChanges numberOfChanges, int sampleSize, long start, EGTask task) {
Iterator<TuplePair> it = discardedTuples.iterator();
while (it.hasNext()) {
if (BartUtility.isTimeout(start, task)) {
logger.warn("Timeout for vioGenQuery " + vioGenQuery);
return;
}
TuplePair tuplePair = it.next();
if (usedTuples.contains(tuplePair.getFirstTuple()) || usedTuples.contains(tuplePair.getSecondTuple())) {
continue;
}
boolean verified = AlgebraUtility.verifyComparisonsOnTuplePair(tuplePair.getFirstTuple(), tuplePair.getSecondTuple(), vioGenQuery.getFormula(), task);
if (!verified) {
continue;
}
changesGenerator.handleTuplePair(tuplePair.getFirstTuple(), tuplePair.getSecondTuple(), vioGenQuery, allCellChanges, numberOfChanges, usedTuples, valueSelector, task);
if (ExecuteVioGenQueryUtility.checkIfFinished(numberOfChanges.getChanges(), sampleSize)) {
return;
}
}
}
private List<String> getIndicesToDelete(Set<String> tables, Set<String> currentIndices) {
List<String> indicesToDelete = new ArrayList<>();
for(String currentIndex : currentIndices) {
String table = ElasticsearchUtils.getTableNameFromIndex(currentIndex);
if(table != null && tables.contains(table)) {
boolean indexEligibleForDeletion;
try {
indexEligibleForDeletion = ElasticsearchUtils.isIndexEligibleForDeletion(currentIndex, tableMetadataManager.get(table));
if(indexEligibleForDeletion) {
logger.warn("Index eligible for deletion : {}", currentIndex);
indicesToDelete.add(currentIndex);
}
} catch (Exception ex) {
logger.error("Unable to Get Table details for Table : {}", table, ex);
}
}
}
return indicesToDelete;
}
public List<ErrorMessage> validate(Class klass, Object contextMsg) {
List<ErrorMessage> errors = new ArrayList<>();
List<ConfigGroups> allConfigGroups = getAllConfigGroups(klass);
Set<String> allGroupNames = new HashSet<>();
if (!allConfigGroups.isEmpty()) {
for (ConfigGroups configGroups : allConfigGroups) {
Class<? extends Label> gKlass = configGroups.value();
if (!gKlass.isEnum()) {
errors.add(new ErrorMessage(DefinitionError.DEF_100, contextMsg, gKlass.getSimpleName()));
} else {
for (Label label : gKlass.getEnumConstants()) {
String groupName = label.toString();
if (allGroupNames.contains(groupName)) {
errors.add(new ErrorMessage(DefinitionError.DEF_101, contextMsg, groupName));
}
allGroupNames.add(groupName);
}
}
}
}
return errors;
}
static Set<String> breadthFirstTraversal(Graph graph, String root) {
Set<String> visited = new LinkedHashSet<String>();
Queue<String> queue = new LinkedList<String>();
queue.add(root);
visited.add(root);
while (!queue.isEmpty()) {
String vertex = queue.poll();
for (Vertex v : graph.getAdjVertices(vertex)) {
if (!visited.contains(v.label)) {
visited.add(v.label);
queue.add(v.label);
}
}
}
return visited;
}
public synchronized ServerLocation findServer(Set excludedServers) {
if(PoolImpl.TEST_DURABLE_IS_NET_DOWN) {
return null;
}
ServerLocation nextServer;
int startIndex = nextServerIndex;
do {
nextServer = (ServerLocation) serverList.get(nextServerIndex);
if(++nextServerIndex >= serverList.size()) {
nextServerIndex = 0;
}
if(!excludedServers.contains(nextServer)) {
return nextServer;
}
} while(nextServerIndex != startIndex);
return null;
}
/**Find all methods in given type and its supertypes, which are overridable.
*
* @param type to inspect
* @return list of all overridable methods
*
* @since 0.136
*/
public List<? extends ExecutableElement> findOverridableMethods(TypeElement type) {
List<ExecutableElement> overridable = new ArrayList<>();
final Set<Modifier> notOverridable = EnumSet.copyOf(NOT_OVERRIDABLE);
if (!type.getModifiers().contains(Modifier.ABSTRACT)) {
notOverridable.add(Modifier.ABSTRACT);
}
DeclaredType dt = (DeclaredType)type.asType();
Types types = JavacTypes.instance(ctx);
Set<String> typeStrings = new HashSet<>();
for (ExecutableElement ee : ElementFilter.methodsIn(info.getElements().getAllMembers(type))) {
TypeMirror methodType = types.erasure(types.asMemberOf(dt, ee));
String methodTypeString = ee.getSimpleName().toString() + methodType.toString();
if (typeStrings.contains(methodTypeString)) {
continue;
}
Set<Modifier> set = EnumSet.copyOf(notOverridable);
set.removeAll(ee.getModifiers());
if (set.size() == notOverridable.size()
&& !overridesPackagePrivateOutsidePackage(ee, type) //do not offer package private methods in case they're from different package
&& !isOverridden(ee, type)) {
overridable.add(ee);
if (ee.getModifiers().contains(Modifier.ABSTRACT)) {
typeStrings.add(methodTypeString);
}
}
}
Collections.reverse(overridable);
return overridable;
}
HashMap<String,String> getRightProjectMapping(){
HashMap<String,String> projectMapping = new HashMap<String, String>();
Set<Variable> unionVariables=planNode.getAvailableVariables();
String rightSQLCte = wrapper.getPlanNodeCTE(right, false);
Set<Variable> rightAvailable = right.getAvailableVariables();
Set<Variable> iriBoundVariables = wrapper.getIRIBoundVariables();
for(Variable v : unionVariables){
if(rightAvailable != null)
if(rightAvailable.contains(v)){
String vPredName = wrapper.getPlanNodeVarMapping(right,v.getName());
projectMapping.put(v.getName(),rightSQLCte+"."+vPredName);
if(!iriBoundVariables.contains(v)){
projectMapping.put(v.getName()+Constants.TYP_COLUMN_SUFFIX_IN_SPARQL_RS,rightSQLCte+"."+vPredName+Constants.TYP_COLUMN_SUFFIX_IN_SPARQL_RS);
}
}
else{
projectMapping.put(v.getName(),"null");
if(!iriBoundVariables.contains(v)){
projectMapping.put(v.getName()+Constants.TYP_COLUMN_SUFFIX_IN_SPARQL_RS,"null");
}
}
}
return projectMapping;
}
public static void checkNamedQuery(Class<?> entityClass, String namedQuery) {
Set<String> namedQueries = namedQueryMap.get(entityClass.getName());
if (namedQueries == null || !namedQueries.contains(namedQuery)) {
throw new PanacheQueryException("The named query '" + namedQuery +
"' must be defined on your JPA entity or one of its super classes");
}
}
@Override
public String getSparqlQueryAsString(TestCase testCase) {
StringBuilder sb = new StringBuilder();
sb.append(getPrefixDeclarations(testCase));
sb.append(SELECT_DISTINCT_RESOURCE);
Set<String> existingVariables = new HashSet<>();
existingVariables.add(RESOURCE_VAR);
// Add all defined variables in the query
for (ResultAnnotation annotation : testCase.getVariableAnnotations()) {
String value = annotation.getAnnotationVarName().get().trim();
// if variable is not redefined don't add it again
// This is needed if the same variable takes part in different annotations
if (! existingVariables.contains(value)) {
sb.append(" ?");
sb.append(value);
sb.append(' ');
existingVariables.add(value);
}
}
sb.append(WHERE_CLAUSE);
sb.append(testCase.getSparqlWhere());
sb.append(ORDER_BY_RESOURCE_ASC);
return sb.toString();
}
protected void setUpTestSetWithRandomContent(int size, int run) throws Exception {
// int seedForThisTrial = BenchmarkUtils.seedFromSizeAndRun(size, run);
// same seed for different sizes to achieve subsume relationship
int seedForThisTrial = BenchmarkUtils.seedFromSizeAndRun(0, run);
Random rand = new Random(seedForThisTrial);
System.out.println(String.format("Seed for this trial: %d.", seedForThisTrial));
// select sample based on random indices
Set<Integer> sampledIndices = new HashSet<>(size * 2);
while (sampledIndices.size() <= size) {
sampledIndices.add(rand.nextInt(DATA_SET_FULL.size()));
}
// sample data
sampledGraphs = new ArrayList<>(size);
int dataSetCursor = 0;
for (Iterator<IValue> dataSetIterator = DATA_SET_FULL.iterator(); dataSetIterator.hasNext(); dataSetCursor++) {
if (sampledIndices.contains(dataSetCursor)) {
IValue mapKey = dataSetIterator.next();
ISet mapValue = (ISet) DATA_SET_FULL.get(mapKey);
sampledGraphs.add(mapValue);
} else {
dataSetIterator.next();
}
}
}
/**
* Adds an animation step, with the specified elements.
*
* @param elements the elements that should be shown in the animation step
*/
public void addAnimation(Element... elements) {
if (elements == null || elements.length == 0) {
throw new IllegalArgumentException("One or more elements must be specified.");
}
Set<String> elementIdsInPreviousAnimationSteps = new HashSet<>();
for (Animation animationStep : animations) {
elementIdsInPreviousAnimationSteps.addAll(animationStep.getElements());
}
Set<Element> elementsInThisAnimationStep = new HashSet<>();
Set<Relationship> relationshipsInThisAnimationStep = new HashSet<>();
for (Element element : elements) {
if (isElementInView(element)) {
if (!elementIdsInPreviousAnimationSteps.contains(element.getId())) {
elementIdsInPreviousAnimationSteps.add(element.getId());
elementsInThisAnimationStep.add(element);
}
}
}
if (elementsInThisAnimationStep.size() == 0) {
throw new IllegalArgumentException("None of the specified elements exist in this view.");
}
for (RelationshipView relationshipView : this.getRelationships()) {
if (
(elementsInThisAnimationStep.contains(relationshipView.getRelationship().getSource()) && elementIdsInPreviousAnimationSteps.contains(relationshipView.getRelationship().getDestination().getId())) ||
(elementIdsInPreviousAnimationSteps.contains(relationshipView.getRelationship().getSource().getId()) && elementsInThisAnimationStep.contains(relationshipView.getRelationship().getDestination()))
) {
relationshipsInThisAnimationStep.add(relationshipView.getRelationship());
}
}
animations.add(new Animation(animations.size() + 1, elementsInThisAnimationStep, relationshipsInThisAnimationStep));
}
private static boolean containsAll(Set<ColumnDesc> allColumnDescs, Set<TblColRef> allColumns) {
for (TblColRef col : allColumns) {
if (allColumnDescs.contains(col.getColumnDesc()) == false)
return false;
}
return true;
}
protected void onSessionClosed() {
// support for live data
Set<Integer> daosWithEvents=_context.onSessionClosed();
if (_daoPerson!=null && daosWithEvents.contains(DAO_PERSON_UID)) {
_daoPerson.invalidateLiveData();
}
}
/**
* Get the List of child Channels of the passed in base Channel that contain the
* packages found in the Profile. This is useful if you want to compute the child
* channels required to be subscribed to in order to get a system to sync with a
* profile.
*
* This method iterates over *each* package in the profile and checks for the proper
* child channel. Can be expensive.
*
* @param user making the call
* @param baseChannel to look for child channels for
* @param profileIn to iterate over the set of packages for.
* @return List of Channel objects.
*/
public static List<Channel> getChildChannelsNeededForProfile(User user, Channel baseChannel,
Profile profileIn) {
List<Channel> retval = new LinkedList<>();
List<PackageListItem> profilePackages = canonicalProfilePackages(profileIn.getId(),
user.getOrg().getId(), null);
log.debug("getChildChannelsNeededForProfile profile has: " +
profilePackages.size() + " packages in it.");
Set<String> evrNameIds = new HashSet<>();
// Create the Set of evr_id's
Iterator<PackageListItem> pi = profilePackages.iterator();
while (pi.hasNext()) {
PackageListItem pli = pi.next();
evrNameIds.add(pli.getNevr());
log.debug("Added nevr: " + pli.getNevr());
}
Iterator<Channel> i = ChannelManager.userAccessibleChildChannels(
user.getOrg().getId(), baseChannel.getId()).iterator();
while (i.hasNext()) {
Channel child = i.next();
log.debug("working with child channel: " + child.getLabel());
List<PackageListItem> packages = getPackagesInChannelByIdCombo(child.getId());
for (int x = 0; x < packages.size(); x++) {
PackageListItem row = packages.get(x);
log.debug("Checking: " + row.getNevr());
if (evrNameIds.contains(row.getNevr())) {
retval.add(child);
log.debug("found package, breaking out of loop");
break;
}
}
}
return retval;
}
private boolean checkReferences( SchemaObject reference, SchemaObject referee, String message )
{
SchemaObjectWrapper referenceWrapper = new SchemaObjectWrapper( reference );
SchemaObjectWrapper refereeWrapper = new SchemaObjectWrapper( referee );
// Check the references : Syntax -> SyntaxChecker
if ( !using.containsKey( referenceWrapper ) )
{
if ( LOG.isDebugEnabled() )
{
LOG.debug(
I18n.msg( I18n.MSG_13730_SYN_DOES_NOT_REFERENCE, reference.getObjectType(), reference.getOid(), message ) );
}
return false;
}
Set<SchemaObjectWrapper> usings = using.get( referenceWrapper );
if ( !usings.contains( refereeWrapper ) )
{
if ( LOG.isDebugEnabled() )
{
LOG.debug( I18n.msg( I18n.MSG_13732_NOT_REFERENCE_ANY, reference.getObjectType(), reference.getOid(), message ) );
}
return false;
}
// Check the referees : SyntaxChecker -> Syntax
if ( !usedBy.containsKey( refereeWrapper ) )
{
if ( LOG.isDebugEnabled() )
{
LOG.debug( I18n.msg( I18n.MSG_13733_NOT_REFERENCED_BY_ANY, referee.getObjectType(), referee.getOid(), message ) );
}
return false;
}
Set<SchemaObjectWrapper> used = usedBy.get( refereeWrapper );
if ( !used.contains( referenceWrapper ) )
{
if ( LOG.isDebugEnabled() )
{
LOG.debug( I18n.msg( I18n.MSG_13733_NOT_REFERENCED_BY_ANY, referee.getObjectType(), referee.getOid(), message ) );
}
return false;
}
return true;
}
private static Metrics buildOrcMetrics(final long numOfRows, final TypeDescription orcSchema,
final ColumnStatistics[] colStats) {
final Schema schema = ORCSchemaUtil.convert(orcSchema);
final Set<TypeDescription> columnsInContainers = findColumnsInContainers(schema, orcSchema);
Map<Integer, Long> columnSizes = Maps.newHashMapWithExpectedSize(colStats.length);
Map<Integer, Long> valueCounts = Maps.newHashMapWithExpectedSize(colStats.length);
Map<Integer, Long> nullCounts = Maps.newHashMapWithExpectedSize(colStats.length);
Map<Integer, ByteBuffer> lowerBounds = Maps.newHashMap();
Map<Integer, ByteBuffer> upperBounds = Maps.newHashMap();
for (int i = 0; i < colStats.length; i++) {
final ColumnStatistics colStat = colStats[i];
final TypeDescription orcCol = orcSchema.findSubtype(i);
final Optional<Types.NestedField> icebergColOpt = ORCSchemaUtil.icebergID(orcCol)
.map(schema::findField);
if (icebergColOpt.isPresent()) {
final Types.NestedField icebergCol = icebergColOpt.get();
final int fieldId = icebergCol.fieldId();
columnSizes.put(fieldId, colStat.getBytesOnDisk());
if (!columnsInContainers.contains(orcCol)) {
// Since ORC does not track null values nor repeated ones, the value count for columns in
// containers (maps, list) may be larger than what it actually is, however these are not
// used in experssions right now. For such cases, we use the value number of values
// directly stored in ORC.
if (colStat.hasNull()) {
nullCounts.put(fieldId, numOfRows - colStat.getNumberOfValues());
} else {
nullCounts.put(fieldId, 0L);
}
valueCounts.put(fieldId, colStat.getNumberOfValues() + nullCounts.get(fieldId));
Optional<ByteBuffer> orcMin = (colStat.getNumberOfValues() > 0) ?
fromOrcMin(icebergCol, colStat) : Optional.empty();
orcMin.ifPresent(byteBuffer -> lowerBounds.put(icebergCol.fieldId(), byteBuffer));
Optional<ByteBuffer> orcMax = (colStat.getNumberOfValues() > 0) ?
fromOrcMax(icebergCol, colStat) : Optional.empty();
orcMax.ifPresent(byteBuffer -> upperBounds.put(icebergCol.fieldId(), byteBuffer));
}
}
}
return new Metrics(numOfRows,
columnSizes,
valueCounts,
nullCounts,
lowerBounds,
upperBounds);
}