Java Code Examples for java.util.LinkedList#size()

The following examples show how to use java.util.LinkedList#size() . 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: ReportletReader.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
protected Long[] createEdges( long offset ) throws IOException
{
	LinkedList parents = new LinkedList( );
	IContent content = reader.loadContent( offset );
	while ( content != null )
	{
		DocumentExtension ext = (DocumentExtension) content
				.getExtension( IContent.DOCUMENT_EXTENSION );
		if ( ext != null )
		{
			parents.addFirst( new Long( ext.getIndex( ) ) );
		}
		content = (IContent) content.getParent( );
	}
	Long[] edges = new Long[parents.size( )];
	Iterator iter = parents.iterator( );
	int length = 0;
	while ( iter.hasNext( ) )
	{
		Long value = (Long) iter.next( );
		edges[length++] = value;
	}
	return edges;
}
 
Example 2
Source File: Automaton.java    From symbolicautomata with Apache License 2.0 6 votes vote down vote up
protected Collection<Integer> getEpsClosure(Collection<Integer> fronteer, BooleanAlgebra<P, S> ba) {

		Collection<Integer> reached = new HashSet<Integer>(fronteer);
		LinkedList<Integer> toVisit = new LinkedList<Integer>(fronteer);

		while (toVisit.size() > 0) {
			for (Move<P, S> t : getMovesFrom(toVisit.removeFirst())) {
				if (t.isEpsilonTransition()) {
					if (!reached.contains(t.to)) {
						reached.add(t.to);
						toVisit.add(t.to);
					}
				}
			}
		}
		return reached;
	}
 
Example 3
Source File: EdgeGuideQueue.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/** @return and removes the head of this queue */
List<EdgeGuide> removeFirstJoinGuide() {
	LinkedList<EdgeGuide> guideGroup = new LinkedList<>();

	for (Iterator<EdgeGuide> iter = edgeGuideQueue.iterator(); iter.hasNext();) {
		EdgeGuide eg = iter.next();
		if (!guideGroup.isEmpty() && !isJoinGroup(guideGroup.getFirst(), eg)) {
			break;
		}
		guideGroup.add(eg);
		if (guideGroup.size() > 1) {
			iter.remove();
		}
	}

	if (guideGroup.size() > 1) {
		edgeGuideQueue.remove(guideGroup.getFirst());
		return guideGroup;
	}

	return Collections.emptyList();
}
 
Example 4
Source File: AggrKey.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
AggrKey(byte[] groupByMask) {
    this.groupByMask = groupByMask;
    LinkedList<Integer> list = Lists.newLinkedList();
    for (int i = 0; i < groupByMask.length; i++) {
        if (groupByMask[i] != 0) {
            list.add(i);
        }
    }
    groupByMaskSet = new int[list.size()];
    for (int i = 0; i < list.size(); i++) {
        groupByMaskSet[i] = list.get(i);
    }
}
 
Example 5
Source File: StateSet.java    From iBioSim with Apache License 2.0 5 votes vote down vote up
/**
 * Determines how many PrjStates are in the StateSet.
 * @return
 * 		A non-negative integer that gives the number of PrjStates are in the StateSet.
 */
public int size(){
	if(_singletonList != null){
		return _singletonList.size();
	}
	int result = 0;
	
	for(LinkedList<TimedPrjState> l : _setList.values()){
		result += l.size();
	}
	
	return result;
}
 
Example 6
Source File: MUCalculator.java    From IngressAnimations with GNU General Public License v3.0 5 votes vote down vote up
public static double calculateMU(double areaPerMU, Portal[][] corners, Portal[] interior) {
	double area = 0;
	for (Portal[] p : corners) {
		area += GeomUtils.getArea(p[0].getPt(), p[1].getPt(), p[2].getPt());
	}
	LinkedList<Portal[]> triangles = new LinkedList<>();
	triangles.addAll(Arrays.asList(corners));
	for (int i=0; i<interior.length; i++) {
		Portal splitter = interior[i];
		// find which triangle it's splitting
		int which = -1;
		for (int j=0; which<0 && j<triangles.size(); j++) {
			Portal[] triangle = triangles.get(j);
			if (GeomUtils.pointInTriangle(splitter.getPt(), triangle[0].getPt(), triangle[1].getPt(), triangle[2].getPt())) {
				which = j;
			}
		}
		if (which < 0) throw new IllegalStateException("splitter " + i+" failed to split!");
		// remove that triangle from the list
		Portal[] toSplit = triangles.get(which);
		area += GeomUtils.getArea(toSplit[0].getPt(), toSplit[1].getPt(), toSplit[2].getPt());
		triangles.remove(which);
		// create animations
		// add new triangles to the list
		triangles.add(new Portal[] {splitter, toSplit[0], toSplit[1]});
		triangles.add(new Portal[] {splitter, toSplit[1], toSplit[2]});
		triangles.add(new Portal[] {splitter, toSplit[2], toSplit[0]});
	}
	return area / areaPerMU;
}
 
Example 7
Source File: LimitedSizeBufferedData.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(final STORAGE_DATA data) {
    final String id = data.id();
    LinkedList<STORAGE_DATA> storageDataList = this.data.get(id);
    if (storageDataList == null) {
        storageDataList = new LinkedList<>();
        this.data.put(id, storageDataList);
    }

    if (storageDataList.size() < limitedSize) {
        storageDataList.add(data);
        return;
    }

    for (int i = 0; i < storageDataList.size(); i++) {
        STORAGE_DATA storageData = storageDataList.get(i);
        if (data.compareTo(storageData) <= 0) {
            if (i == 0) {
                // input data is less than the smallest in top N list, ignore
            } else {
                // Remove the smallest in top N list
                // add the current data into the right position
                storageDataList.add(i, data);
                storageDataList.removeFirst();
            }
            return;
        }
    }

    // Add the data as biggest in top N list
    storageDataList.addLast(data);
    storageDataList.removeFirst();
}
 
Example 8
Source File: BindBean64SharedPreferences.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * for attribute valueCharList serialization
 */
protected String serializeValueCharList(LinkedList<Character> value) {
  if (value==null) {
    return null;
  }
  KriptonJsonContext context=KriptonBinder.jsonBind();
  try (KriptonByteArrayOutputStream stream=new KriptonByteArrayOutputStream(); JacksonWrapperSerializer wrapper=context.createSerializer(stream)) {
    JsonGenerator jacksonSerializer=wrapper.jacksonGenerator;
    jacksonSerializer.writeStartObject();
    int fieldCount=0;
    if (value!=null)  {
      fieldCount++;
      int n=value.size();
      Character item;
      // write wrapper tag
      jacksonSerializer.writeFieldName("valueCharList");
      jacksonSerializer.writeStartArray();
      for (int i=0; i<n; i++) {
        item=value.get(i);
        if (item==null) {
          jacksonSerializer.writeNull();
        } else {
          jacksonSerializer.writeNumber(item);
        }
      }
      jacksonSerializer.writeEndArray();
    }
    jacksonSerializer.writeEndObject();
    jacksonSerializer.flush();
    return stream.toString();
  } catch(Exception e) {
    e.printStackTrace();
    throw(new KriptonRuntimeException(e.getMessage()));
  }
}
 
Example 9
Source File: JarIndexMergeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static void assertFileResolved(JarIndex jarIndex2, String file,
                               String jarName) {
    @SuppressWarnings("unchecked")
    LinkedList<String> jarLists = (LinkedList<String>)jarIndex2.get(file);
    if (jarLists == null || jarLists.size() == 0 ||
        !jarName.equals(jarLists.get(0))) {
        throw new RuntimeException(
            "Unexpected result: the merged index must resolve file: "
            + file);
    }
}
 
Example 10
Source File: QueueUtils.java    From jolie with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns the size of an existing queue, null otherwise
 * 
 * @param queue_name
 * @return The size of the queue, null otherwise
 */
public Integer size( String queue_name ) {
	Integer queue_size = null;
	if( has_queue( queue_name ) ) {
		LinkedList queue = queueMap.get( queue_name );
		queue_size = queue.size();
	}
	return queue_size;
}
 
Example 11
Source File: AnkiDroidHelper.java    From ankihelper with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Remove the duplicates from a list of note fields and tags
 *
 * @param fields  List of fields to remove duplicates from
 * @param tags    List of tags to remove duplicates from
 * @param modelId ID of model to search for duplicates on
 */
public void removeDuplicates(LinkedList<String[]> fields, LinkedList<Set<String>> tags, long modelId) {
    // Build a list of the duplicate keys (first fields) and find all notes that have a match with each key
    List<String> keys = new ArrayList<>(fields.size());
    for (String[] f : fields) {
        keys.add(f[0]);
    }
    SparseArray<List<NoteInfo>> duplicateNotes = getApi().findDuplicateNotes(modelId, keys);
    // Do some sanity checks
    if (tags.size() != fields.size()) {
        throw new IllegalStateException("List of tags must be the same length as the list of fields");
    }
    if (duplicateNotes.size() == 0 || fields.size() == 0 || tags.size() == 0) {
        return;
    }
    if (duplicateNotes.keyAt(duplicateNotes.size() - 1) >= fields.size()) {
        throw new IllegalStateException("The array of duplicates goes outside the bounds of the original lists");
    }
    // Iterate through the fields and tags LinkedLists, removing those that had a duplicate
    ListIterator<String[]> fieldIterator = fields.listIterator();
    ListIterator<Set<String>> tagIterator = tags.listIterator();
    int listIndex = -1;
    for (int i = 0; i < duplicateNotes.size(); i++) {
        int duplicateIndex = duplicateNotes.keyAt(i);
        while (listIndex < duplicateIndex) {
            fieldIterator.next();
            tagIterator.next();
            listIndex++;
        }
        fieldIterator.remove();
        tagIterator.remove();
    }
}
 
Example 12
Source File: ESUtils.java    From yuzhouwan with Apache License 2.0 5 votes vote down vote up
public static RestClientBuilder getESHosts() {
    if (isBlank(ES_HOSTS))
        throw new RuntimeException("Cannot get elasticSearch hosts from config! "
                + "Please check es.hosts config option.");
    String[] hosts = ES_HOSTS.split(",");
    int len;
    if ((len = hosts.length) <= 0)
        throw new RuntimeException("Cannot get elasticSearch hosts from config! "
                + "Please check es.hosts config option.");
    String host;
    String[] hostAndPort;
    LinkedList<HttpHost> httpHosts = new LinkedList<>();
    for (int i = 0; i < len; i++) {
        host = hosts[i];
        hostAndPort = host.split(":");
        if (hostAndPort.length != 2) {
            LOG.warn("Invalid es host: {}!", host);
            continue;
        }
        httpHosts.add(new HttpHost(hostAndPort[0], Integer.parseInt(hostAndPort[1]), "http"));
    }
    int size;
    HttpHost[] httpHostsArray = new HttpHost[size = httpHosts.size()];
    for (int i = 0; i < size; i++) {
        httpHostsArray[i] = httpHosts.get(i);
    }
    return RestClient.builder(httpHostsArray);
}
 
Example 13
Source File: SeatsTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private void addToQueue(CacheType ctype, Reservation r) {
  LinkedList<Reservation> cache = CACHE_RESERVATIONS.get(ctype);
  if (cache == null) throw new TestException("Unexpected " + ctype);
  cache.add(r);
  if (logDML) log().info(String.format("Queued %s for %s [cache=%d]", r, ctype, cache.size()));
  
  while (cache.size() > ctype.limit) {
    cache.remove();
  }
}
 
Example 14
Source File: ExportUtils.java    From keycloak with Apache License 2.0 4 votes vote down vote up
/**
 * Full export of user data stored in federated storage (including role mappings and credentials)
 *
 * @param id
 * @return fully exported user representation
 */
public static UserRepresentation exportFederatedUser(KeycloakSession session, RealmModel realm, String id, ExportOptions options) {
    UserRepresentation userRep = new UserRepresentation();
    userRep.setId(id);
    MultivaluedHashMap<String, String> attributes = session.userFederatedStorage().getAttributes(realm, id);
    if (attributes.size() > 0) {
        Map<String, List<String>> attrs = new HashMap<>();
        attrs.putAll(attributes);
        userRep.setAttributes(attrs);
    }

    Set<String> requiredActions = session.userFederatedStorage().getRequiredActions(realm, id);
    if (requiredActions.size() > 0) {
        List<String> actions = new LinkedList<>();
        actions.addAll(requiredActions);
        userRep.setRequiredActions(actions);
    }


    // Social links
    Set<FederatedIdentityModel> socialLinks = session.userFederatedStorage().getFederatedIdentities(id, realm);
    List<FederatedIdentityRepresentation> socialLinkReps = new ArrayList<>();
    for (FederatedIdentityModel socialLink : socialLinks) {
        FederatedIdentityRepresentation socialLinkRep = exportSocialLink(socialLink);
        socialLinkReps.add(socialLinkRep);
    }
    if (socialLinkReps.size() > 0) {
        userRep.setFederatedIdentities(socialLinkReps);
    }

    // Role mappings
    if (options.isGroupsAndRolesIncluded()) {
        Set<RoleModel> roles = session.userFederatedStorage().getRoleMappings(realm, id);
        List<String> realmRoleNames = new ArrayList<>();
        Map<String, List<String>> clientRoleNames = new HashMap<>();
        for (RoleModel role : roles) {
            if (role.getContainer() instanceof RealmModel) {
                realmRoleNames.add(role.getName());
            } else {
                ClientModel client = (ClientModel) role.getContainer();
                String clientId = client.getClientId();
                List<String> currentClientRoles = clientRoleNames.get(clientId);
                if (currentClientRoles == null) {
                    currentClientRoles = new ArrayList<>();
                    clientRoleNames.put(clientId, currentClientRoles);
                }

                currentClientRoles.add(role.getName());
            }
        }

        if (realmRoleNames.size() > 0) {
            userRep.setRealmRoles(realmRoleNames);
        }
        if (clientRoleNames.size() > 0) {
            userRep.setClientRoles(clientRoleNames);
        }
    }

    // Credentials
    List<CredentialModel> creds = session.userFederatedStorage().getStoredCredentials(realm, id);
    List<CredentialRepresentation> credReps = new ArrayList<>();
    for (CredentialModel cred : creds) {
        CredentialRepresentation credRep = exportCredential(cred);
        credReps.add(credRep);
    }
    userRep.setCredentials(credReps);

    // Grants
    List<UserConsentModel> consents = session.users().getConsents(realm, id);
    LinkedList<UserConsentRepresentation> consentReps = new LinkedList<>();
    for (UserConsentModel consent : consents) {
        UserConsentRepresentation consentRep = ModelToRepresentation.toRepresentation(consent);
        consentReps.add(consentRep);
    }
    if (consentReps.size() > 0) {
        userRep.setClientConsents(consentReps);
    }

    // Not Before
    int notBefore = session.userFederatedStorage().getNotBeforeOfUser(realm, userRep.getId());
    userRep.setNotBefore(notBefore);

    if (options.isGroupsAndRolesIncluded()) {
        List<String> groups = new LinkedList<>();
        for (GroupModel group : session.userFederatedStorage().getGroups(realm, id)) {
            groups.add(ModelToRepresentation.buildGroupPath(group));
        }
        userRep.setGroups(groups);
    }
    return userRep;
}
 
Example 15
Source File: IteratingGSS.java    From rapidminer-studio with GNU Affero General Public License v3.0 4 votes vote down vote up
/** Test if the model is useful according to the given criterion. */
public boolean isUseful(Result current, LinkedList<Result> otherResults, int criterion, ExampleSet exampleSet,
		int min_model_number) {

	boolean result = true;

	switch (criterion) {

		case IteratingGSS.TYPE_WORST_UTILITY:
			double worstUtility = current.getUtility() - current.getConfidence();
			if (worstUtility < this.min_utility_useful) {
				result = false;
			} else {
				result = true;
			}
			break;

		case IteratingGSS.TYPE_UTILITY:
			double utility = current.getUtility();
			if (utility < this.min_utility_useful) {
				result = false;
			} else {
				result = true;
			}
			break;

		case IteratingGSS.TYPE_BEST_UTILITY:
			double bestUtility = current.getUtility() + current.getConfidence();
			if (bestUtility < this.min_utility_useful) {
				result = false;
			} else {
				result = true;
			}
			break;

		case IteratingGSS.TYPE_EXAMPLE:

			if (otherResults.size() == 0 || otherResults.size() < min_model_number) {
				return true;
			}

			// Calculate average number of examples
			double sum = 0.0d;
			for (Result r : otherResults) {
				sum = sum + r.getTotalWeight();
			}
			double average = sum / otherResults.size();

			if (current.getTotalWeight() < this.exampleFactor * average) {
				result = true;
			} else {
				result = false;
			}
			break;
	}

	return result;
}
 
Example 16
Source File: LBFGSMinimizer.java    From murphy with Apache License 2.0 4 votes vote down vote up
private void pushOntoList(double[] vector, LinkedList<double[]> vectorList) {
	vectorList.addFirst(vector);
	if (vectorList.size() > maxHistorySize) vectorList.removeLast();
}
 
Example 17
Source File: InPlace.java    From pegasus with Apache License 2.0 4 votes vote down vote up
/**
 * Reduces the number of edges between the nodes and it's parents.
 *
 * <pre>
 * For the node look at the parents of the Node.
 * For each parent Y see if there is a path to any other parent Z of X.
 * If a path exists, then the edge from Z to node can be removed.
 * </pre>
 *
 * @param node the nodes whose parent edges need to be reduced.
 */
protected void reduceDependency(GraphNode node) {
    if (node == null) {
        return;
    }

    // reduce dependencies. for each cleanup job X, look at the parents of
    // the job. For each parent Y see if there is a path to any other parent Z of X.
    // If a path exists, then the edge from Z to cleanup job can
    // be removed.
    Collection<GraphNode> parents = node.getParents();
    List redundant = new LinkedList();
    HashSet visit = new HashSet();
    for (Iterator itp = node.getParents().iterator(); itp.hasNext(); ) {
        LinkedList mque = new LinkedList();
        mque.add(itp.next());

        while (mque.size() > 0) {
            GraphNode popGN = (GraphNode) mque.removeFirst();

            if (visit.contains(popGN)) {
                continue;
            }

            visit.add(popGN);

            for (Iterator itp_pop = popGN.getParents().iterator(); itp_pop.hasNext(); ) {
                GraphNode pop_pGN = (GraphNode) itp_pop.next();
                // check if its redundant ..if so add it to redundant list
                if (parents.contains(pop_pGN)) {
                    redundant.add(pop_pGN);
                } else {
                    // mque.addAll( pop_pGN.getParents() );
                    for (Iterator itgp = pop_pGN.getParents().iterator(); itgp.hasNext(); ) {
                        GraphNode gpGN = (GraphNode) itgp.next();
                        if (!visit.contains(gpGN)) {
                            mque.add(gpGN);
                        }
                    }
                }
            }
        }
    }

    // remove all redundant nodes that were found
    for (Iterator itr = redundant.iterator(); itr.hasNext(); ) {
        GraphNode r_GN = (GraphNode) itr.next();
        node.removeParent(r_GN);
        r_GN.removeChild(node);
    }
}
 
Example 18
Source File: rebalance.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
private void rebalance(String command) throws Exception
{
	LinkedList<String> list = new LinkedList();
	gfsh.parseCommand(command, list);
	if (list.size() < 2) {
		gfsh.println("Error: 'rebalance' requries a key number or member id");
		return;
	}

	String regionPath = gfsh.getCurrentPath();
	boolean simulate = true;
	Object key = null;
	String memberId = null;
	long timeout = 0;
	for (int i = 1; i < list.size(); i++) {
		String token = list.get(i);
		if (token.equals("-k")) {
			if (i + 1 >= list.size()) {
				gfsh.println("Error: '-k' requires key number");
				return;
			}
			int keyNum = Integer.parseInt((String) list.get(++i));
			key = gfsh.getKeyFromKeyList(keyNum);

		} else if (token.equals("-m")) {
			if (i + 1 >= list.size()) {
				gfsh.println("Error: '-m' requires member Id");
				return;
			}
			memberId = (String) list.get(++i);
		} else if (token.equals("-s")) {
			simulate = true;
		} else if (token.equals("-r")) {
			simulate = false;
		} else if (token.equals("-t")) {
			if (i + 1 >= list.size()) {
				gfsh.println("Error: '-t' requires a timeout value");
				return;
			}
			timeout = Integer.parseInt(list.get(++i));
		}
	}

	if (key == null && memberId == null) {
		gfsh.println("Error: member Id not defined.");
		return;
	}
	
	
	// Execute rebalance
	executeRebalance(regionPath, memberId, simulate, timeout);
}
 
Example 19
Source File: JSONParser.java    From RedProtect with GNU General Public License v3.0 4 votes vote down vote up
private int peekStatus(LinkedList statusStack) {
    if (statusStack.size() == 0)
        return -1;
    Integer status = (Integer) statusStack.getFirst();
    return status.intValue();
}
 
Example 20
Source File: TestSoftReferencesBehaviorOnOOME.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Test that all SoftReferences has been cleared at time of OOM.
 */
void softReferencesOom(long minSize, long maxSize, int semiRefAllocFrequency) {
    System.out.format( "minSize = %d, maxSize = %d, freq = %d%n", minSize, maxSize, semiRefAllocFrequency );
    long counter = 0;

    long multiplier = maxSize - minSize;
    LinkedList<SoftReference> arrSoftRefs = new LinkedList();
    LinkedList arrObjects = new LinkedList();
    long numberOfNotNulledObjects = 0;
    long oomSoftArraySize = 0;

    try {
        while (true) {
            // Keep every Xth object to make sure we hit OOM pretty fast
            if (counter % semiRefAllocFrequency != 0) {
                long allocationSize = ((int) (rndGenerator.nextDouble() * multiplier))
                        + minSize;
                arrObjects.add(new byte[(int)allocationSize]);
            } else {
                arrSoftRefs.add(new SoftReference(new Object()));
            }

            counter++;
            if (counter == Long.MAX_VALUE) {
                counter = 0;
            }
        }
    } catch (OutOfMemoryError oome) {
        // Clear allocated ballast, so we don't get another OOM.

        arrObjects = null;

        // Get the number of soft refs first, so we don't trigger
        // another OOM.
        oomSoftArraySize = arrSoftRefs.size();

        for (SoftReference sr : arrSoftRefs) {
            Object o = sr.get();

            if (o != null) {
                numberOfNotNulledObjects++;
            }
        }

        // Make sure we clear all refs before we return failure
        arrSoftRefs = null;

        if (numberOfNotNulledObjects > 0) {
            throw new RuntimeException(numberOfNotNulledObjects + " out of "
                    + oomSoftArraySize + " SoftReferences was not "
                    + "null at time of OutOfMemoryError");
        }
    } finally {
        arrSoftRefs = null;
        arrObjects = null;
    }
}