Java Code Examples for java.util.Queue#contains()

The following examples show how to use java.util.Queue#contains() . 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: Statistics.java    From olca-app with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * The product system graph is connected if we can visit every process in the
 * product system traversing the graph starting from the reference process and
 * following the incoming process links.
 */
private static boolean isConnectedGraph(ProductSystem system,
		Multimap<Long, Long> inEdges) {
	if (system.referenceProcess == null)
		return false;
	HashMap<Long, Boolean> visited = new HashMap<>();
	Queue<Long> queue = new ArrayDeque<>();
	queue.add(system.referenceProcess.id);
	while (!queue.isEmpty()) {
		Long recipient = queue.poll();
		visited.put(recipient, Boolean.TRUE);
		for (Long provider : inEdges.get(recipient)) {
			Boolean state = visited.get(provider);
			if (!Objects.equals(state, Boolean.TRUE)
					&& !queue.contains(provider))
				queue.add(provider);
		}
	}
	for (Long processId : system.processes) {
		Boolean val = visited.get(processId);
		if (!Objects.equals(val, Boolean.TRUE))
			return false;
	}
	return true;
}
 
Example 2
Source File: Solution2.java    From code with Apache License 2.0 6 votes vote down vote up
/**
 * 题目地址:https://leetcode-cn.com/problems/contains-duplicate-ii/
 * -------------------------------------------------------------------
 * 思考:
 * -------------------------------------------------------------------
 * 思路:维持一个大小为k的队列,在队列大小中存在重复元素
 * -------------------------------------------------------------------
 * 时间复杂度:O(n)
 * 空间复杂度:O(n)
 * -------------------------------------------------------------------
 */
public boolean containsNearbyDuplicate(int[] nums, int k) {
    // 投机取巧,跳过耗时的测试用例
    //if (k == 35000 || nums.length < 1) {
    //    return false;
    //}

    Queue<Integer> queue = new ArrayDeque<>();
    for (int num : nums) {
        if (queue.contains(num)) {
            return true;
        }
        queue.add(num);
        // 维持队列大小
        if (queue.size() > k) {
            queue.poll();
        }
    }
    return false;
}
 
Example 3
Source File: StatelessProcessSession.java    From nifi with Apache License 2.0 6 votes vote down vote up
private StatelessFlowFile validateState(final FlowFile flowFile) {
    Objects.requireNonNull(flowFile);

    final StatelessFlowFile currentVersion = currentVersions.get(flowFile.getId());
    if (currentVersion == null) {
        throw new FlowFileHandlingException(flowFile + " is not known in this session");
    }

    for (final Queue<StatelessFlowFile> flowFiles : outputMap.values()) {
        if (flowFiles.contains(flowFile)) {
            throw new IllegalStateException(flowFile + " has already been transferred");
        }
    }

    return currentVersion;
}
 
Example 4
Source File: DialogManager.java    From CanDialog with Apache License 2.0 6 votes vote down vote up
public static void showNext(DialogManagerInterface dialog) {

        Context context = getCurrentContext(dialog);


        if (currentMap.containsKey(context)) {
            currentMap.remove(context);
        }

        if (map.containsKey(context)) {
            Queue<DialogManagerInterface> dialogs = map.get(context);
            if (dialogs != null && dialogs.contains(dialog)) {
                dialogs.remove(dialog);
            }

            if (dialogs == null || dialogs.isEmpty()) {
                map.remove(context);
            }
        }


        show(null);
    }
 
Example 5
Source File: DialogManager.java    From CanDialog with Apache License 2.0 6 votes vote down vote up
public static void activityDestroy() {

        if (currentActivityDialog != null) {

            Context context = getCurrentContext(currentActivityDialog);
            if (currentMap.containsKey(context)) {
                currentMap.remove(context);
            }
            if (map.containsKey(context)) {
                Queue<DialogManagerInterface> dialogs = map.get(context);

                if (dialogs != null && dialogs.contains(currentActivityDialog)) {
                    dialogs.remove(currentActivityDialog);
                }
                if (dialogs == null || dialogs.isEmpty()) {
                    map.remove(context);
                }
            }
            currentActivityDialog = null;

            show(null);
        }


    }
 
Example 6
Source File: BoaAbstractTraversal.java    From compiler with Apache License 2.0 6 votes vote down vote up
public final void worklistPostorderForward(final Queue<CFGNode> queue, final BoaAbstractFixP fixp, final Traversal.TraversalKind kind) throws Exception {
	while (!queue.isEmpty()) {
		final CFGNode node = queue.remove();
		traverse(node, true);
		final boolean curFlag = outputMapObj.containsKey(node.getId());
		boolean fixpFlag = false;
		if (curFlag) {
			final boolean prevFlag = prevOutputMapObj.containsKey(node.getId());
			if (curFlag && prevFlag) {
				fixpFlag = fixp.invoke((T1)outputMapObj.get(node.getId()), (T1)prevOutputMapObj.get(node.getId()));
			}
		}
		if (!fixpFlag) {
			for (final CFGNode pred : node.getSuccessors()) {
				if (!queue.contains(pred))
					queue.add(pred);
			}
		}
		prevOutputMapObj.put(node.getId(), currentResult);
	}
}
 
Example 7
Source File: MacPropagation.java    From cpsolver with GNU Lesser General Public License v3.0 6 votes vote down vote up
/** propagation over a constraint */
private void propagate(Assignment<V, T> assignment, Constraint<V, T> constraint, V aVariable, Queue<V> queue) {
    if (goodValues(aVariable).isEmpty())
        return;
    List<T> conflicts = conflictValues(assignment, constraint, aVariable);

    if (conflicts != null && !conflicts.isEmpty()) {
        for (T conflictValue : conflicts) {
            if (!queue.contains(conflictValue.variable()))
                queue.add(conflictValue.variable());
            Set<T> reason = reason(assignment, constraint, aVariable, conflictValue);
            // sLogger.debug("  "+conflictValue+" become nogood (c:"+constraint.getName()+", r:"+reason+")");
            setNoGood(conflictValue, reason);
            if (reason.isEmpty())
                (conflictValue.variable()).removeValue(iIteration, conflictValue);
        }
    }
}
 
Example 8
Source File: BoaAbstractTraversal.java    From compiler with Apache License 2.0 6 votes vote down vote up
public final void worklistPostorderBackward(final Queue<CFGNode> queue, final BoaAbstractFixP fixp, final Traversal.TraversalKind kind) throws Exception {
	while (!queue.isEmpty()) {
		final CFGNode node = queue.remove();
		traverse(node, true);
		final boolean curFlag = outputMapObj.containsKey(node.getId());
		boolean fixpFlag = false;
		if (curFlag) {
			final boolean prevFlag = prevOutputMapObj.containsKey(node.getId());
			if (curFlag && prevFlag) {
				fixpFlag = fixp.invoke((T1)outputMapObj.get(node.getId()), (T1)prevOutputMapObj.get(node.getId()));
			}
		}
		if (!fixpFlag) {
			for (final CFGNode pred : node.getPredecessors()) {
				if (!queue.contains(pred))
					queue.add(pred);
			}
		}
		prevOutputMapObj.put(node.getId(), currentResult);
	}
}
 
Example 9
Source File: SankeyProcessList.java    From olca-app with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Checks if each process has a path to the reference process, if not it
 * searches a way to the reference or another connected node and adds the
 * missing nodes.
 */
private void fillUp(Set<Long> processIds) {

	Set<Long> unconnected = new HashSet<>(processIds);
	Set<Long> connected = new HashSet<>();
	Queue<Long> queue = new ArrayDeque<>();
	queue.add(refProcess);
	while (!queue.isEmpty()) {
		Long recipient = queue.poll();
		unconnected.remove(recipient);
		connected.add(recipient);
		for (ProcessLink link : linkSearchMap.getIncomingLinks(recipient)) {
			Long provider = link.providerId;
			if (!processIds.contains(provider))
				continue;
			if (!queue.contains(provider) && !connected.contains(provider))
				queue.add(provider);
		}
	}
	for (Long processId : unconnected) {
		Stack<Long> path = searchPathFor(processId, connected);
		for (Long id : path) {
			processIds.add(id);
			connected.add(id);
		}
	}
}
 
Example 10
Source File: FunctionRegistryHolder.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves all functions (holders) associated with all the jars
 * This is read operation, so several users can perform this operation at the same time.
 * @return list of all functions, mapped by their sources
 */
public Map<String, List<FunctionHolder>> getAllJarsWithFunctionHolders() {
  Map<String, List<FunctionHolder>> allFunctionHoldersByJar = new HashMap<>();

  try (@SuppressWarnings("unused") Closeable lock = readLock.open()) {
    for (String jarName : jars.keySet()) {
      //Capture functionHolders here
      List<FunctionHolder> drillFuncHolderList = new LinkedList<>();

      Map<String, Queue<String>> functionsInJar = jars.get(jarName);
      for (Map.Entry<String, Queue<String>> functionEntry : functionsInJar.entrySet()) {
        String fnName = functionEntry.getKey();
        Queue<String> fnSignatureList = functionEntry.getValue();
        //Get all FunctionHolders (irrespective of source)
        Map<String, DrillFuncHolder> functionHolders = functions.get(fnName);
        //Iterate for matching entries and populate new Map
        for (Map.Entry<String, DrillFuncHolder> entry : functionHolders.entrySet()) {
          if (fnSignatureList.contains(entry.getKey())) {
            drillFuncHolderList.add(new FunctionHolder(fnName, entry.getKey(), entry.getValue()));
          }
        }
      }
      allFunctionHoldersByJar.put(jarName, drillFuncHolderList);
    }
  }
  return allFunctionHoldersByJar;
}
 
Example 11
Source File: VmwareContextPool.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public void unregisterContext(final VmwareContext context) {
    assert (context != null);
    final String poolKey = context.getPoolKey().intern();
    final Queue<VmwareContext> ctxList = _pool.get(poolKey);
    synchronized (poolKey) {
        if (!Strings.isNullOrEmpty(poolKey) && ctxList != null && ctxList.contains(context)) {
            ctxList.remove(context);
        }
    }
}
 
Example 12
Source File: SessionConversationAttributeStore.java    From website with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @param conversationQueueMap
 * @param attributeName
 * @return
 */
private void handleQueueActions(WebRequest request,
    String attributeName, String conversationId) {
    
    if (getNumConversationsToKeep() > 0) { 
    
        // get a reference to the conversation queue map
        Map<String, Queue<String>> conversationQueueMap = getConversationsMap(request);
        
        // get a reference to the conversation queue for the given attribute name
        Queue<String> queue = conversationQueueMap.get(attributeName);
        
        // create queue if necessary.
        if (queue == null) {
            // create new queue if needed.
            queue = new LinkedList<String>();
            conversationQueueMap.put(attributeName, queue);
        }

        // add the conversation id to the queue if it needs it.
        if (!queue.contains(conversationId)) {
            // add the cId to the queue.
            queue.add(conversationId);
            
            // since a new conversation id was added to the queue, we need to 
            // check to see if the queue needs to be pruned.
            pruneQueueIfNeeded(request, queue, attributeName);
        }
        
        // dump to log what is in the queues
        dumpConversationQueuesToLog(request, attributeName);
    }
}
 
Example 13
Source File: BoaAbstractTraversal.java    From compiler with Apache License 2.0 5 votes vote down vote up
public final void worklistPostorderWithoutFixp(final Queue<CFGNode> queue, final Traversal.TraversalKind kind) throws Exception {
	while (!queue.isEmpty()) {
		final CFGNode node = queue.remove();
		traverse(node, true);
		final boolean fixpFlag = true;
		if (!fixpFlag) {
			for (final CFGNode pred : node.getPredecessors()) {
				if (!queue.contains(pred))
					queue.add(pred);
			}
		}
	}
}
 
Example 14
Source File: MacPropagation.java    From cpsolver with GNU Lesser General Public License v3.0 5 votes vote down vote up
/** propagation over a constraint */
private void propagate(Assignment<V, T> assignment, Constraint<V, T> constraint, T anAssignedValue, Queue<V> queue) {
    Set<T> reason = new HashSet<T>(1);
    reason.add(anAssignedValue);
    Collection<T> conflicts = conflictValues(assignment, constraint, anAssignedValue);
    if (conflicts != null && !conflicts.isEmpty())
        for (T conflictValue : conflicts) {
            // sLogger.debug("  "+conflictValue+" become nogood (c:"+constraint.getName()+", r:"+reason+")");
            setNoGood(conflictValue, reason);
            if (!queue.contains(conflictValue.variable()))
                queue.add(conflictValue.variable());
        }
}
 
Example 15
Source File: EventCollector.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Puts the history in the relative FIFO
 * 
 * @param history
 * @return true if it was not remembered already, false otherwise
 */
private boolean rememberHistory(History history) {
	Queue<Long> fifo = fifos.get(history.getClass().getName());
	if (fifo == null) {
		fifo = new CircularFifoQueue<Long>(FIFO_SIZE);
		fifos.put(history.getClass().getName(), fifo);
	}

	if (fifo.contains(history.getId()))
		return false;
	else {
		fifo.add(history.getId());
		return true;
	}
}
 
Example 16
Source File: FunctionRegistryHolder.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Removes jar from {@link #jars} and all associated with jars functions from {@link #functions}
 * Since each jar is loaded with separate class loader before
 * removing we need to close class loader to release opened connection to jar.
 * All jar functions have the same class loader, so we need to close only one time.
 *
 * @param jarName jar name to be removed
 */
private void removeAllByJar(String jarName) {
  Map<String, Queue<String>> jar = jars.remove(jarName);
  if (jar == null) {
    return;
  }

  for (Map.Entry<String, Queue<String>> functionEntry : jar.entrySet()) {
    final String function = functionEntry.getKey();
    Map<String, DrillFuncHolder> functionHolders = functions.get(function);
    Queue<String> functionSignatures = functionEntry.getValue();
    for (Map.Entry<String, DrillFuncHolder> entry : functionHolders.entrySet()) {
      if (functionSignatures.contains(entry.getKey())) {
        ClassLoader classLoader = entry.getValue().getClassLoader();
        if (classLoader instanceof AutoCloseable) {
          try {
            ((AutoCloseable) classLoader).close();
          } catch (Exception e) {
            logger.warn("Problem during closing class loader", e);
          }
        }
        break;
      }
    }
    functionHolders.keySet().removeAll(functionSignatures);

    if (functionHolders.isEmpty()) {
      functions.remove(function);
    }
  }
}
 
Example 17
Source File: FunctionRegistryHolder.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Looks which jar in {@link #jars} contains passed function signature.
 * First looks by function name and if found checks if such function has passed function signature.
 * Returns jar name if found matching function signature, else null.
 * This is read operation, so several users can perform this operation at the same time.
 *
 * @param functionName function name
 * @param functionSignature function signature
 * @return jar name
 */
public String getJarNameByFunctionSignature(String functionName, String functionSignature) {
  try (@SuppressWarnings("unused") Closeable lock = readLock.open()) {
    for (Map.Entry<String, Map<String, Queue<String>>> jar : jars.entrySet()) {
      Queue<String> functionSignatures = jar.getValue().get(functionName);
      if (functionSignatures != null && functionSignatures.contains(functionSignature)) {
        return jar.getKey();
      }
    }
  }
  return null;
}
 
Example 18
Source File: TXManagerImpl.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public boolean tryResume(final TransactionId transactionId, long time,
    final TimeUnit unit) {
  if (transactionId == null || getTXState() != null || !exists(transactionId)) {
    return false;
  }
  Queue<Thread> threadq = waitMap.get(transactionId);
  if (threadq == null || threadq.isEmpty()) {
    if (tryResume(transactionId)) {
      return true;
    }
  }
  long timeout = unit.toNanos(time);
  long startTime = System.nanoTime();
  Thread currentThread = Thread.currentThread();

  while (timeout > 0) {
    // after putting this thread in waitMap, we should check for
    // an entry in suspendedTXs. if no entry is found in suspendedTXs
    // next invocation of suspend() will unblock this thread
    if (tryResume(transactionId)) {
      threadq = waitMap.get(transactionId);
      if (threadq != null) {
        threadq.remove(currentThread);
      }
      return true;
    }
    // put the current thread in the waitingMap along with
    // the transactionId, then suspend the thread
    if (threadq == null) {
      threadq = new ConcurrentLinkedQueue<Thread>();
    }
    if (!threadq.contains(currentThread)) {
      // sync not required as only one thread will try to
      // add itself to the queue
      threadq.add(currentThread);
    }
    Queue<Thread> oldq = waitMap.putIfAbsent(transactionId, threadq);
    if (oldq != null) {
      // add the thread to the list of waiting threads
      if (!oldq.contains(currentThread)) {
        oldq.add(currentThread);
      }
      threadq = null;
    }
    LockSupport.parkNanos(timeout);
    if (tryResume(transactionId)) {
      threadq = waitMap.get(transactionId);
      if (threadq != null) {
        threadq.remove(currentThread);
      }
      return true;
    } else if (!exists(transactionId)) {
      return false;
    }
    long nowTime = System.nanoTime();
    timeout -= nowTime - startTime;
    startTime = nowTime;
  }
  return false;
}
 
Example 19
Source File: TXManagerImpl.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public boolean tryResume(final TransactionId transactionId, long time,
    final TimeUnit unit) {
  if (transactionId == null || getTXState() != null || !exists(transactionId)) {
    return false;
  }
  Queue<Thread> threadq = waitMap.get(transactionId);
  if (threadq == null || threadq.isEmpty()) {
    if (tryResume(transactionId)) {
      return true;
    }
  }
  long timeout = unit.toNanos(time);
  long startTime = System.nanoTime();
  Thread currentThread = Thread.currentThread();

  while (timeout > 0) {
    // after putting this thread in waitMap, we should check for
    // an entry in suspendedTXs. if no entry is found in suspendedTXs
    // next invocation of suspend() will unblock this thread
    if (tryResume(transactionId)) {
      threadq = waitMap.get(transactionId);
      if (threadq != null) {
        threadq.remove(currentThread);
      }
      return true;
    }
    // put the current thread in the waitingMap along with
    // the transactionId, then suspend the thread
    if (threadq == null) {
      threadq = new ConcurrentLinkedQueue<Thread>();
    }
    if (!threadq.contains(currentThread)) {
      // sync not required as only one thread will try to
      // add itself to the queue
      threadq.add(currentThread);
    }
    Queue<Thread> oldq = waitMap.putIfAbsent(transactionId, threadq);
    if (oldq != null) {
      // add the thread to the list of waiting threads
      if (!oldq.contains(currentThread)) {
        oldq.add(currentThread);
      }
      threadq = null;
    }
    LockSupport.parkNanos(timeout);
    if (tryResume(transactionId)) {
      threadq = waitMap.get(transactionId);
      if (threadq != null) {
        threadq.remove(currentThread);
      }
      return true;
    } else if (!exists(transactionId)) {
      return false;
    }
    long nowTime = System.nanoTime();
    timeout -= nowTime - startTime;
    startTime = nowTime;
  }
  return false;
}
 
Example 20
Source File: TabuSearch.java    From tsml with GNU General Public License v3.0 4 votes vote down vote up
@Override
public ArrayList<Shapelet> searchForShapeletsInSeries(Instance timeSeries, ProcessCandidate checkCandidate){
    
    ArrayList<Shapelet> seriesShapelets = new ArrayList<>();
    
    if(!seriesToConsider.get(currentSeries++)) return seriesShapelets;
    
    Queue<CandidateSearchData> tabuList = new LinkedList<>();
    
    CandidateSearchData shapelet;
    
    int numShapeletsEvaluated = 0;

    //Only consider a fixed amount of shapelets.
    while(initialNumShapeletsPerSeries > numShapeletsEvaluated){
        
        //create the random shapelet.
        //if it's the first iteration and we've got a previous best shapelet.
        if(numShapeletsEvaluated == 0 && bsf_shapelet != null){
           shapelet = new CandidateSearchData(bsf_shapelet.startPos,bsf_shapelet.length) ;
           bsf_shapelet = null; //reset the best one for this series.
        }else{
            shapelet = createRandomShapelet(timeSeries);
        }
        
        ArrayList<CandidateSearchData> candidateList = new ArrayList<>();
        candidateList.add(shapelet);
        candidateList.addAll(createNeighbourhood(shapelet, timeSeries.numAttributes()));
        boolean inList = false;
        for(CandidateSearchData neighbour : candidateList){
            //i think if we collide with the tabuList we should abandon the neighbourhood.
            if(tabuList.contains(neighbour)){
                inList = true;
                break;
            }
        }
        //if inList is true we want to abandon this whole search area.
        if(inList){
            continue;
        }

        //find the best local candidate
        CandidateSearchData bestLocal = null;
        Shapelet local_bsf_shapelet = null;
        for(CandidateSearchData shape : candidateList ){
            Shapelet sh = checkCandidate.process(timeSeries, shape.getStartPosition(), shape.getLength());
            numShapeletsEvaluated++;

            //we've abandoned this shapelet, and therefore it is null.
            if(sh == null) continue;
            
            if(local_bsf_shapelet == null){
                bestLocal = shape;
                local_bsf_shapelet = sh;
            }

            //if the comparator says it's better.
            if(comparator.compare(local_bsf_shapelet, sh) > 0){
                bestLocal = shape;
                local_bsf_shapelet = sh;
            }
        }
        
        if(local_bsf_shapelet == null) continue;
        
        
        if(bsf_shapelet == null){
            bsf_shapelet = local_bsf_shapelet;
            seriesShapelets.add(local_bsf_shapelet); //stick the local best ones in the list.
        }
            
        //update bsf shapelet if the local one is better.
        if(comparator.compare(bsf_shapelet, local_bsf_shapelet) > 0){
            bsf_shapelet = local_bsf_shapelet;
            seriesShapelets.add(local_bsf_shapelet); //stick the local best ones in the list.
        }          
        
        //add the best local to the TabuList
        tabuList.add(bestLocal);
        
        if(tabuList.size() > maxTabuSize){
            tabuList.remove();
        }
    }
    
    return seriesShapelets;
}