Java Code Examples for java.util.LinkedList

The following are top voted examples for showing how to use java.util.LinkedList. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: raylew_algorithm   File: HSOJ1003.java View source code 7 votes vote down vote up
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String inputStr = sc.next();
    String[] str = inputStr.split("/");
    int a1, a2;
    a1 = Integer.parseInt(str[0]) > 7 ? 31 : 0;
    a2 = Integer.parseInt(str[1]);
    LinkedList<Integer> list = getPowerOffDate();
    int j = 0;
    for (int i = 0; i < list.size(); i++) {
        if (list.get(i) >= (a1 + a2)) {
            j++;
        }
    }
    System.out.println("??" + j);
}
 
Example 2
Project: raylew_algorithm   File: POJ1753.java View source code 6 votes vote down vote up
/**
 * enum all possible situation
 */
public void bfs(int[][] matrix) {
    //init
    LinkedList<String> list1 = new LinkedList<String>();
    state[convertMatrixToNum(matrix)] = true;
    list1.add(convertMatrixToString(matrix));
    LinkedList<String> list2 = new LinkedList<String>();
    //start bfs
    while (true) {
        if (list1.size() == 0) {
            if (list2.size() == 0) {
                System.out.println("Impossible");
                break;
            }
            minimumCount++;
            for (String item : list2) {
                list1.add(item);
            }
            list2 = new LinkedList<String>();
        }
        int[][] first_matrix = convertStringToMatrix(list1.removeFirst());
        state[convertMatrixToNum(first_matrix)] = true;
        if (isMatched(first_matrix)) {//matched
            System.out.println(minimumCount);
            //display(first_matrix);
            return;
        }
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                int[][] new_matrix = flip(first_matrix, i, j);
                if (isMatched(new_matrix)) {//matched
                    System.out.println(minimumCount + 1);
                    //display(new_matrix);
                    return;
                } else {
                    //unmatched
                    int hash = convertMatrixToNum(new_matrix);
                    if (!state[hash]) {
                        String matrixStr = convertMatrixToString(new_matrix);
                        list2.add(matrixStr);
                    }
                }
            }
        }
    }
}
 
Example 3
Project: bixie   File: FaultLocalizationThread.java View source code 6 votes vote down vote up
private Set<BasicBlock> getNeighbors(Set<BasicBlock> blocks, boolean forward) {
	LinkedList<BasicBlock> todo = new LinkedList<BasicBlock>();
	HashSet<BasicBlock> done = new HashSet<BasicBlock>();
	todo.addAll(blocks);
	while (!todo.isEmpty()) {
		BasicBlock current = todo.pop();
		done.add(current);
		for (BasicBlock b : getNeighbors(current, forward)) {
			if (!todo.contains(b) && !done.contains(b)) {
				todo.add(b);
			}
		}
	}
	return done;
}
 
Example 4
Project: raylew_algorithm   File: ElevatorSchedule.java View source code 6 votes vote down vote up
/**
 * ????
 *
 * @param disk
 */
public static void driver_scheduling(Disk disk) {
    LinkedList<IOTableNode> iotable = disk.getIotable();
    if (iotable.isEmpty()) {
        System.out.println("????");
        return;
    } else {
        disk.printIOTable();
        disk.schedule();// ????
    }
}
 
Example 5
Project: funCKit   File: ProjectTreeNode.java View source code 6 votes vote down vote up
/**
 * Returns the path from the root node to this node.
 * 
 * @return the path from the root node to this node.
 */
public ProjectTreeNode<?>[] getAbsolutePath() {
    LinkedList<ProjectTreeNode<?>> path = new LinkedList<ProjectTreeNode<?>>();
    for (ProjectTreeNode<?> parent = this; parent != null; parent = parent
            .getParent()) {
        path.addFirst(parent);
    }

    return path.toArray(new ProjectTreeNode<?>[0]);
}
 
Example 6
Project: raylew_algorithm   File: BFS.java View source code 6 votes vote down vote up
public static void bfs_graph() {
    for (int i = 0; i < vs.length; i++) {
        vs[i].setColor("WHITE");
        vs[i].setD(0);
        vs[i].setPre(null);
    }
    vs[1].setColor("GRAY");
    LinkedList Q = new LinkedList();
    Q.add(vs[1]);
    while (!Q.isEmpty()) {
        Vertex u = (Vertex) Q.removeFirst();
        LinkedList u_adj = adjacency_list[u.getIndex()];
        for (int i = 0; i < u_adj.size(); i++) {
            Vertex v = (Vertex) u_adj.get(i);
            if (v.getColor().equals("WHITE")) {
                v.setColor("GRAY");
                v.setD(u.getD() + 1);
                v.setPre(u.getIndex());
                Q.addLast(v);
            }
        }
        u.setColor("BLACK");
    }
}
 
Example 7
Project: raylew_algorithm   File: MemoryManagement.java View source code 6 votes vote down vote up
/**
 * ??????????
 *
 * @param job
 */
public static void callback(Job job) {
    LinkedList<Integer> page_list = job.getPage_list();
    for (Iterator iterator = page_list.iterator(); page_list != null
            && iterator.hasNext(); ) {
        Integer integer = (Integer) iterator.next();
        arr[integer % 8][integer / 8] = 0;
    }
    System.out.println(job.getName() + "????");
}
 
Example 8
Project: netlib   File: AuthCacheImpl.java View source code 6 votes vote down vote up
public synchronized void put (String pkey, AuthCacheValue value) {
    LinkedList list = (LinkedList) hashtable.get (pkey);
    String skey = value.getPath();
    if (list == null) {
        list = new LinkedList ();
        hashtable.put (pkey, list);
    }
    // Check if the path already exists or a super-set of it exists
    ListIterator iter = list.listIterator();
    while (iter.hasNext()) {
        AuthenticationInfo inf = (AuthenticationInfo)iter.next();
        if (inf.path == null || inf.path.startsWith (skey)) {
            iter.remove ();
        }
    }
    iter.add (value);
}
 
Example 9
Project: iot-server-appliances   File: FireAlarmControllerService.java View source code 6 votes vote down vote up
@Path("/readcontrols/{owner}/{deviceId}") @GET public String readControls(@PathParam("owner") String owner,
        @PathParam("deviceId") String deviceId, @Context HttpServletResponse response) {
    String result = null;
    LinkedList<String> deviceControlList = internalControlsQueue.get(deviceId);

    if (deviceControlList == null) {
        result = "No controls have been set for device " + deviceId + " of owner " + owner;
        response.setStatus(HttpStatus.SC_NO_CONTENT);
    } else {
        try {
            result = deviceControlList.remove();
            response.setStatus(HttpStatus.SC_ACCEPTED);
            response.addHeader("Control", result);
        } catch (NoSuchElementException ex) {
            result = "There are no more controls for device " + deviceId + " of owner " + owner;
            response.setStatus(HttpStatus.SC_NO_CONTENT);
        }
    }
    log.info(result);
    return result;
}
 
Example 10
Project: funCKit   File: DrawUtil.java View source code 6 votes vote down vote up
private static Vector<String> parseText(String text, int width,
                                        FontMetrics metrics) {
    Vector<String> parsedStrings = new Vector<String>();

    Set<Character> breakCharacters = BREAK_CHARACTERS;
    LinkedList<Integer> breakPositions = new LinkedList<Integer>();

    int numChars = text.length();
    int lineWidth = width;

    int currentStartPosition = 0;
    while (currentStartPosition < numChars) {
        int currentPosition = currentStartPosition;
        boolean fitsInLine = true;
        while (fitsInLine && currentPosition < numChars) {
            /* Hard break if there is a hard coded new line. */
            if (text.charAt(currentPosition) == NEW_LINE) {
                break;
            }

            int currentWidth = metrics.stringWidth(
                    text.substring(currentStartPosition,
                            currentPosition));

            /*
             * If current line width exceeds line width, jump back to last
             * breakable position.
             */
            if (currentWidth >= lineWidth) {
                fitsInLine = false;
                if (breakPositions.getLast() != null) {
                    currentPosition = breakPositions.getLast();
                }
            } else {
                /* Save possible break position to list. */
                if (breakCharacters.contains(text.charAt(currentPosition))) {
                    breakPositions.add(currentPosition);
                }

                /* Otherwise continue with next character. */
                currentPosition++;
            }
        }
        parsedStrings.add(text.substring(currentStartPosition, currentPosition));
        currentStartPosition = currentPosition + 1;
    }

    return parsedStrings;
}
 
Example 11
Project: netlib   File: AuthCacheImpl.java View source code 6 votes vote down vote up
public synchronized void remove (String pkey, AuthCacheValue entry) {
    LinkedList list = (LinkedList) hashtable.get (pkey);
    if (list == null) {
        return;
    }
    if (entry == null) {
        list.clear();
        return;
    }
    ListIterator iter = list.listIterator ();
    while (iter.hasNext()) {
        AuthenticationInfo inf = (AuthenticationInfo)iter.next();
        if (entry.equals(inf)) {
            iter.remove ();
        }
    }
}
 
Example 12
Project: breakout   File: AWTUtil.java View source code 6 votes vote down vote up
public static void traverse( Component root , Consumer<Component> consumer )
{
	LinkedList<Component> queue = new LinkedList<Component>( );
	queue.add( root );
	
	while( !queue.isEmpty( ) )
	{
		Component c = queue.poll( );
		consumer.accept( c );
		if( c instanceof Container )
		{
			queue.addAll( Arrays.asList( ( ( Container ) c ).getComponents( ) ) );
		}
	}
}
 
Example 13
Project: java-util   File: ReflectionUtils.java View source code 6 votes vote down vote up
/**
 * Determine if the passed in class (classToCheck) has the annotation (annoClass) on itself,
 * any of its super classes, any of it's interfaces, or any of it's super interfaces.
 * This is a exhaustive check throughout the complete inheritance hierarchy.
 * @return the Annotation if found, null otherwise.
 */
public static Annotation getClassAnnotation(final Class classToCheck, final Class annoClass)
{
    final Set<Class> visited = new HashSet<Class>();
    final LinkedList<Class> stack = new LinkedList<Class>();
    stack.add(classToCheck);

    while (!stack.isEmpty())
    {
        Class classToChk = stack.pop();
        if (classToChk == null || visited.contains(classToChk))
        {
            continue;
        }
        visited.add(classToChk);
        Annotation a = classToChk.getAnnotation(annoClass);
        if (a != null)
        {
            return a;
        }
        stack.push(classToChk.getSuperclass());
        addInterfaces(classToChk, stack);
    }
    return null;
}
 
Example 14
Project: TFC2   File: IslandMap.java View source code 6 votes vote down vote up
/**
 * @return May return null if the island is too big.
 */
public Vector<Center> countIsland(Center start, int maxSize) 
{
	Vector<Center> outList = new Vector<Center>();
	LinkedList<Center> checkList = new LinkedList<Center>();

	outList.add(start);
	checkList.add(start);

	while(checkList.size() > 0)
	{
		Center c = checkList.pollFirst();
		for(Center n : c.neighbors)
		{
			if(!checkList.contains(n) && !outList.contains(n) && !n.hasMarker(Marker.Water))
			{
				outList.add(n);
				checkList.addLast(n);
			}
		}

		if(outList.size() >= maxSize)
			return null;
	}


	return outList;
}
 
Example 15
Project: tdq-studio-se   File: ParserRuleTableViewer.java View source code 6 votes vote down vote up
/**
 * DOC klliu Comment method "moveTdExpression".
 * 
 * @param tdExpression
 */
public void moveTdExpression(TdExpression tdExpression, int type) {
    LinkedList<Object> sorter = new LinkedList<Object>();
    TdExpressionContentProvider contentProvider = (TdExpressionContentProvider) parserRuleTableViewer.getContentProvider();
    List<TdExpression> movedElements = contentProvider.getMovedElements();
    sorter.addAll(movedElements);
    int indexOf = sorter.indexOf(tdExpression);
    if (type == 1) {
        if (!(indexOf - 1 < 0)) {
            sorter.remove(tdExpression);
            sorter.add(indexOf - 1, tdExpression);
        }
    } else {
        if (!(indexOf + 1 >= sorter.size())) {
            sorter.remove(tdExpression);
            sorter.add(indexOf + 1, tdExpression);
        }
    }
    parserRuleTableViewer.setInput(sorter);
}
 
Example 16
Project: sysart-itext   File: ColumnText.java View source code 6 votes vote down vote up
protected void setSimpleVars(ColumnText org) {
    maxY = org.maxY;
    minY = org.minY;
    alignment = org.alignment;
    leftWall = null;
    if (org.leftWall != null)
        leftWall = new ArrayList(org.leftWall);
    rightWall = null;
    if (org.rightWall != null)
        rightWall = new ArrayList(org.rightWall);
    yLine = org.yLine;
    currentLeading = org.currentLeading;
    fixedLeading = org.fixedLeading;
    multipliedLeading = org.multipliedLeading;
    canvas = org.canvas;
    canvases = org.canvases;
    lineStatus = org.lineStatus;
    indent = org.indent;
    followingIndent = org.followingIndent;
    rightIndent = org.rightIndent;
    extraParagraphSpace = org.extraParagraphSpace;
    rectangularWidth = org.rectangularWidth;
    rectangularMode = org.rectangularMode;
    spaceCharRatio = org.spaceCharRatio;
    lastWasNewline = org.lastWasNewline;
    linesWritten = org.linesWritten;
    arabicOptions = org.arabicOptions;
    runDirection = org.runDirection;
    descender = org.descender;
    composite = org.composite;
    splittedRow = org.splittedRow;
    if (org.composite) {
        compositeElements = new LinkedList(org.compositeElements);
        if (splittedRow) {
            PdfPTable table = (PdfPTable)compositeElements.getFirst();
            compositeElements.set(0, new PdfPTable(table));
        }
        if (org.compositeColumn != null)
            compositeColumn = duplicate(org.compositeColumn);
    }
    listIdx = org.listIdx;
    firstLineY = org.firstLineY;
    leftX = org.leftX;
    rightX = org.rightX;
    firstLineYDone = org.firstLineYDone;
    waitPhrase = org.waitPhrase;
    useAscender = org.useAscender;
    filledWidth = org.filledWidth;
    adjustFirstLine = org.adjustFirstLine;
}
 
Example 17
Project: tuprolog-5   File: ClauseDatabase.java View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
List<ClauseInfo> getPredicates(String key) {
       LinkedList<ClauseInfo> family = get(key);
       if (family == null)
           return new LinkedList<ClauseInfo>();
       // Unchecked warning: clone returns an object, the cast to
       // List<ClauseInfo> is needed. The cast is safe, because we
       // know to only have LinkedList<ClauseInfo> in the map.
       return (List<ClauseInfo>) family.clone();
   }
 
Example 18
Project: fiji   File: FullInfoMesh.java View source code 6 votes vote down vote up
public ArrayList<ArrayList<Point3f>> getSubmeshes() {
	HashSet<Vertex> open = new HashSet<Vertex>();
	open.addAll(vertices);
	open.remove(null);
	ArrayList<ArrayList<Point3f>> ret =
		new ArrayList<ArrayList<Point3f>>();
	while(!open.isEmpty()) {
		HashSet<Integer> meshSet = new HashSet<Integer>();
		LinkedList<Integer> queue = new LinkedList<Integer>();

		Vertex start = open.iterator().next();
		open.remove(start);
		queue.add(vertexToIndex.get(start));

		while(!queue.isEmpty()) {
			Integer vIdx = queue.poll();
			meshSet.add(vIdx);

			Vertex v = getVertex(vIdx);
			for(Edge e : v.edges) {
				int nIdx = e.p1 == vIdx ? e.p2 : e.p1;
				Vertex n = getVertex(nIdx);
				if(open.contains(n)) {
					open.remove(n);
					queue.offer(nIdx);
				}
			}
		}

		ArrayList<Point3f> tris = new ArrayList<Point3f>();
		for(int f : faces) {
			if(f != -1 && meshSet.contains(f))
				tris.add(getVertex(f));
		}
		ret.add(tris);
	}
	return ret;
}
 
Example 19
Project: extension-aws   File: Category.java View source code 6 votes vote down vote up
/**
 * Returns a list of all the ancestors of this catalog, starting at the
 * catalog at the given level and ending at this catalog itself.
 * 
 * @param inStartLevel
 *            The level at which to start listing ancestors (0 is the root,
 *            1 is the first-level children, etc.)
 * 
 * @return The list of ancestors of this catalog
 */
public List listAncestorsAndSelf(int inStartLevel)
{
	LinkedList result = new LinkedList();
	Category catalog = this;
	while (catalog != null)
	{
		result.addFirst(catalog);
		catalog = catalog.getParentCategory();
	}
	return result.subList(inStartLevel, result.size());
}
 
Example 20
Project: eis   File: EIDefaultImpl.java View source code 6 votes vote down vote up
/**
 * [email protected]}
 */
@Override
public LinkedList<String> getFreeEntities() {
	LinkedList<String> free = getEntities();
	for (String agent : agentsToEntities.keySet()) {
		free.removeAll(agentsToEntities.get(agent));
	}
	return free;
}
 
Example 21
Project: MultimediaForAndroidLibrary   File: TtmlParser.java View source code 6 votes vote down vote up
@Override
public Subtitle parse(InputStream inputStream, String inputEncoding, long startTimeUs)
        throws IOException {
    try {
        XmlPullParser xmlParser = xmlParserFactory.newPullParser();
        xmlParser.setInput(inputStream, inputEncoding);
        TtmlSubtitle ttmlSubtitle = null;
        LinkedList<TtmlNode> nodeStack = new LinkedList<>();
        int unsupportedTagDepth = 0;
        int eventType = xmlParser.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            TtmlNode parent = nodeStack.peekLast();
            if (unsupportedTagDepth == 0) {
                String name = xmlParser.getName();
                if (eventType == XmlPullParser.START_TAG) {
                    if (!isSupportedTag(name)) {
                        Log.w(TAG, "Ignoring unsupported tag: " + xmlParser.getName());
                        unsupportedTagDepth++;
                    } else {
                        TtmlNode node = parseNode(xmlParser, parent);
                        nodeStack.addLast(node);
                        if (parent != null) {
                            parent.addChild(node);
                        }
                    }
                } else if (eventType == XmlPullParser.TEXT) {
                    parent.addChild(TtmlNode.buildTextNode(xmlParser.getText()));
                } else if (eventType == XmlPullParser.END_TAG) {
                    if (xmlParser.getName().equals(TtmlNode.TAG_TT)) {
                        ttmlSubtitle = new TtmlSubtitle(nodeStack.getLast(), startTimeUs);
                    }
                    nodeStack.removeLast();
                }
            } else {
                if (eventType == XmlPullParser.START_TAG) {
                    unsupportedTagDepth++;
                } else if (eventType == XmlPullParser.END_TAG) {
                    unsupportedTagDepth--;
                }
            }
            xmlParser.next();
            eventType = xmlParser.getEventType();
        }
        return ttmlSubtitle;
    } catch (XmlPullParserException xppe) {
        throw new IOException("Unable to parse source", xppe);
    }
}
 
Example 22
Project: keratin-irc   File: IrcMessage.java View source code 6 votes vote down vote up
/**
 * Parse a parameter blob into parameters.
 * 
 * @param paramBlob A bunch of parameters in one string
 * @return Seperated parameters. Last parameter is the trailing parameter, and may have spaces.
 * @throws InvalidMessageException If no parameters were matched
 */
private static String[] parseMessageParams( String paramBlob )
    throws InvalidMessageException
{
    Matcher matcher = parseLineParamsPattern.matcher( paramBlob );

    LinkedList<String> params = new LinkedList<String>();

    while ( matcher.find() )
    {
        params.add( matcher.group( 1 ) );
    }

    if ( params.size() < 1 )
    {
        throw new InvalidMessageException( "Message parameters didn't match pattern" );
    }

    // Standardize the trailing parameter to the RFC
    String lastParam = params.pollLast();
    if ( lastParam.startsWith( ":" ) )
        params.add( lastParam );
    else
        params.add( ":" + lastParam );

    String[] retArray = new String[params.size()];
    params.toArray( retArray );

    return retArray;
}
 
Example 23
Project: google-web-toolkit-svnmirror   File: CollectionsTestServiceImpl.java View source code 6 votes vote down vote up
public LinkedList<MarkerTypeLinkedList> echo(LinkedList<MarkerTypeLinkedList> actual)
    throws CollectionsTestServiceException {
  LinkedList<MarkerTypeLinkedList> expected = TestSetFactory.createLinkedList();
  if (!TestSetValidator.isValid(expected, actual)) {
    throw new CollectionsTestServiceException("expected: "
        + expected.toString() + " actual: " + actual.toString());
  }

  return actual;
}
 
Example 24
Project: trie4j   File: LOUDSTrie.java View source code 6 votes vote down vote up
public LOUDSTrie(Trie orig, int bitSize){
	size = orig.size();
	bv = new BytesSuccinctBitVector(bitSize);
	labels = new char[bitSize / 2];
	tail = new char[bitSize / 2][];
	term = new BitSet(bitSize / 2);
	LinkedList<Node> queue = new LinkedList<Node>();
	int count = 0;
	if(orig.getRoot() != null) queue.add(orig.getRoot());
	while(!queue.isEmpty()){
		Node node = queue.pollFirst();
		int index = count++;
		if(index >= labels.length){
			extend();
		}
		if(node.isTerminate()) term.set(index);
		for(Node c : node.getChildren()){
			bv.append1();
			queue.offerLast(c);
		}
		bv.append0();
		char[] letters = node.getLetters();
		if(letters.length == 0){
			labels[index] = 0xffff;
			tail[index] = emptyChars;
		} else{
			labels[index] = letters[0];
			if(letters.length >= 2){
				tail[index] = Arrays.copyOfRange(letters, 1, letters.length);
			} else{
				tail[index] = emptyChars;
			}
		}
	}
	nodeSize = count;
}
 
Example 25
Project: SmartAndroidSource   File: HtmlTreeBuilder.java View source code 6 votes vote down vote up
private void replaceInQueue(LinkedList<Element> queue, Element out,
		Element in) {
	int i = queue.lastIndexOf(out);
	Validate.isTrue(i != -1);
	queue.remove(i);
	queue.add(i, in);
}
 
Example 26
Project: oliot-fc   File: ReaderImpl.java View source code 6 votes vote down vote up
/**
 * creates a runnable that watches the in queue for new messages and at 
 * arrival, delivers them to the management.
 * @return a runnable.
 */
private Runnable getInQueueWorker() {
	final LinkedList<byte[]> queue = inqueue;
	return new Runnable() {
		public void run() {
			try {
				while (true) {
					synchronized (queue) {
						while (queue.isEmpty()) queue.wait();
						
						byte[] msg = queue.removeFirst();
						deliverMessage(msg);
					}
				}
			} catch (InterruptedException e) {
				log.debug("stopping in queue worker.");
			}
		}			
	};
}
 
Example 27
Project: fiji   File: BalancedRandomTree.java View source code 5 votes vote down vote up
/**
 * Create random tree (non-recursively)
 * 
 * @param data original data
 * @param indices indices of the samples to use
 * @param depth starting depth
 * @param splitFnProducer split function producer
 * @return root node 
 */
private InteriorNode createTree(
		final Instances data,
		final ArrayList<Integer> indices,
		final int depth,
		final Splitter splitFnProducer)
{
	int maxDepth = depth;
	// Create root node
	InteriorNode root = new InteriorNode(depth, splitFnProducer.getSplitFunction(data, indices));
	
	// Create list of nodes to process and add the root to it
	final LinkedList<InteriorNode> remainingNodes = new LinkedList<InteriorNode>();
	remainingNodes.add(root);
	
	// Create list of indices to process (it must match all the time with the node list)
	final LinkedList<ArrayList<Integer>> remainingIndices = new LinkedList<ArrayList<Integer>>();
	remainingIndices.add(indices);
	
	// While there is still nodes to process
	while (!remainingNodes.isEmpty()) 
	{
		final InteriorNode currentNode = remainingNodes.removeLast();
		final ArrayList<Integer> currentIndices = remainingIndices.removeLast();
		// new arrays of indices for the left and right sons
		final ArrayList<Integer> leftArray = new ArrayList<Integer>();
		final ArrayList<Integer> rightArray = new ArrayList<Integer>();

		// split data
		for(final Integer it : currentIndices)
		{
			if( currentNode.splitFn.evaluate( data.get(it.intValue()) ) )
			{
				leftArray.add(it);
			}
			else
			{
				rightArray.add(it);
			}
		}
		//System.out.println("total left = " + leftArray.size() + ", total right = " + rightArray.size() + ", depth = " + currentNode.depth);					
		// Update maximum depth (for the record)
		if(currentNode.depth > maxDepth)
			maxDepth = currentNode.depth;

		if( leftArray.isEmpty() )
		{
			currentNode.left = new LeafNode(data, rightArray);
			//System.out.println("Created leaf with feature " + currentNode.splitFn.index);
		}
		else if ( rightArray.isEmpty() )
		{
			currentNode.left = new LeafNode(data, leftArray);
			//System.out.println("Created leaf with feature " + currentNode.splitFn.index);
		}
		else
		{
			currentNode.left = new InteriorNode(currentNode.depth+1, splitFnProducer.getSplitFunction(data, leftArray));
			remainingNodes.add((InteriorNode)currentNode.left);
			remainingIndices.add(leftArray);

			currentNode.right = new InteriorNode(currentNode.depth+1, splitFnProducer.getSplitFunction(data, rightArray));
			remainingNodes.add((InteriorNode)currentNode.right);
			remainingIndices.add(rightArray);
		}
	}

	System.out.println("Max depth = " + maxDepth);
	return root;
}
 
Example 28
Project: visuwall   File: ClientCnxnSocketNIO.java View source code 5 votes vote down vote up
/**
 * @return true if a packet was received
 * @throws InterruptedException
 * @throws IOException
 */
void doIO(List<Packet> pendingQueue, LinkedList<Packet> outgoingQueue) throws InterruptedException, IOException {
    SocketChannel sock = (SocketChannel) sockKey.channel();
    if (sock == null) {
        throw new IOException("Socket is null!");
    }
    if (sockKey.isReadable()) {
        int rc = sock.read(incomingBuffer);
        if (rc < 0) {
            throw new EndOfStreamException(
                    "Unable to read additional data from server sessionid 0x"
                            + Long.toHexString(sessionId)
                            + ", likely server has closed socket");
        }
        if (!incomingBuffer.hasRemaining()) {
            incomingBuffer.flip();
            if (incomingBuffer == lenBuffer) {
                recvCount++;
                readLength();
            } else if (!initialized) {
                readConnectResult();
                enableRead();
                if (!outgoingQueue.isEmpty()) {
                    enableWrite();
                }
                lenBuffer.clear();
                incomingBuffer = lenBuffer;
                updateLastHeard();
                initialized = true;
            } else {
                sendThread.readResponse(incomingBuffer);
                lenBuffer.clear();
                incomingBuffer = lenBuffer;
                updateLastHeard();
            }
        }
    }
    if (sockKey.isWritable()) {
        LinkedList<Packet> pending = new LinkedList<Packet>();
        synchronized (outgoingQueue) {
            if (!outgoingQueue.isEmpty()) {
                updateLastSend();
                ByteBuffer pbb = outgoingQueue.getFirst().bb;
                sock.write(pbb);
                if (!pbb.hasRemaining()) {
                    sentCount++;
                    Packet p = outgoingQueue.removeFirst();
                    if (p.requestHeader != null
                            && p.requestHeader.getType() != OpCode.ping
                            && p.requestHeader.getType() != OpCode.auth) {
                        pending.add(p);
                    }
                }
            }
        }
        synchronized(pendingQueue) {
            pendingQueue.addAll(pending);
        }
    }
}
 
Example 29
Project: Gui2Go   File: EditorActivity.java View source code 5 votes vote down vote up
public void btnClick_widgetUp(View v) {
    // this is an ugly solution due to API lacking something to change Z
    // order
    // IMPORTANT: bring to front actually puts them in the bottom
    if (currentHighlightedID != 0) {
        View target = findViewById(currentHighlightedID);
        ViewGroup parent = (ViewGroup) target.getParent();
        int position = parent.indexOfChild(target);

        LinkedList<View> viewsToFront = new LinkedList<View>();
        if (position != 0) {
            // do it in the tree
            for (int i = 0; i < treeView.getCount(); i++) {
                View viewFromTree = (View) treeView.getChildAt(i);
                if (viewFromTree != null) {
                    String treeViewTag = viewFromTree.getTag().toString();

                    if (treeViewTag.equals(String.valueOf(target.getId()))) {
                        // before moving we should save all its children
                        List<Long> children = manager
                                        .getChildren((long) target.getId());

                        manager.removeNodeRecursively((long) target.getId());
                        insertViewToTreeParentAfterTarget(target, parent,
                                        parent.getChildAt(position - 1));
                        if (children != null) {
                            // re-add all its children
                            for (int j = 0; j < children.size(); j++) {
                                View tempView = ((ViewGroup) target)
                                                .getChildAt(j);
                                manager.addAfterChild(
                                                (long) target.getId(),
                                                (long) tempView.getId(),
                                                null);
                            }
                        }
                    }
                }
            }

            // for (int i = 0; i < treeView.getCount(); i++) { // all this
            // to
            // // find the new
            // // tree view and
            // // highlight it
            // View viewFromTree = (View) treeView.getChildAt(i);
            // if (viewFromTree != null) {
            // String treeViewTag = viewFromTree.getTag().toString();
            // if (treeViewTag.equals(String.valueOf(target.getId()))) {
            // viewFromTree
            // .setBackgroundResource(R.drawable.hightlight_border);
            // }
            // }
            // }

            viewsToFront.add(parent.getChildAt(position - 1));
            for (int i = position + 1; i < parent.getChildCount(); i++) {
                // store the views we need to bring up after
                // up until the position of 2 before the target
                viewsToFront.add(parent.getChildAt(i));
            }

            // now go over the stack and put em all on top in the correct
            // order
            while (!viewsToFront.isEmpty()) {
                View temp = viewsToFront.pop();
                parent.bringChildToFront(temp);
            }
            target.requestLayout();
        }
    } else {
        Toast.makeText(this, "You must select a widget first!",
                        Toast.LENGTH_SHORT).show();
    }
}
 
Example 30
Project: NucleusFramework   File: PathAreaFinder.java View source code 5 votes vote down vote up
private void searchAdjacent(FinderContext context, Location node) {

        LinkedList<StackItem> stack = new LinkedList<>();
        stack.push(new StackItem(node));
        StackItem curr = stack.peek();

        byte dropHeight = (byte)(-context.astar.getMaxDropHeight());

        while (!stack.isEmpty()) {

            start:
            {
                for (; curr.y >= dropHeight; curr.y--) {
                    for (; curr.x <= 1; curr.x++) {
                        for (; curr.z <= 1; curr.z++) {

                            if (!curr.columns[curr.x + 1][curr.z + 1])
                                continue;

                            // get instance of candidate node
                            Location candidate = curr.node.clone().add(curr.x, curr.y, curr.z);

                            // check if candidate is already checked
                            if (context.invalidNodes.contains(candidate)) {
                                continue;
                            }

                            if (context.validNodes.contains(candidate)) {
                                curr.columns[curr.x + 1][curr.z + 1] = false;
                                continue;
                            }

                            int xRange = Math.abs(context.start.getBlockX() - candidate.getBlockX());
                            int yRange = Math.abs(context.start.getBlockY() - candidate.getBlockY());
                            int zRange = Math.abs(context.start.getBlockZ() - candidate.getBlockZ());

                            // check x & z range
                            if ((context.astar.getRange() - xRange < 0) ||
                                    (context.astar.getRange() - zRange < 0)) {

                                curr.columns[curr.x + 1][curr.z + 1] = false;
                                continue;
                            }

                            // check y range
                            if ((context.astar.getRange() - yRange < 0)) {
                                continue;
                            }

                            // Check for diagonal obstruction
                            if (curr.x != 0 && curr.z != 0 && curr.y >= 0) {
                                Location diagX = curr.node.clone().add(curr.x, curr.y, (short) 0),
                                        diagZ = curr.node.clone().add((short) 0, curr.y, curr.z);

                                if (!isValid(diagX) && !isValid(diagZ)) {
                                    curr.columns[curr.x + 1][curr.z + 1] = false;
                                    continue;
                                }
                            }

                            // check candidate to see if its valid
                            if (!isValid(candidate)) {

                                // invalidate column if material is NOT transparent
                                if (!Materials.isTransparent(candidate.getBlock().getType())) {
                                    curr.columns[curr.x + 1][curr.z + 1] = false;
                                }

                                context.invalidNodes.add(candidate);
                                continue;
                            }

                            context.validNodes.add(candidate);

                            //searchAdjacent(context, candidate);
                            curr.z++;
                            stack.push(new StackItem(candidate));
                            curr = stack.peek();


                            break start;
                        }
                        curr.z = -1;
                    }
                    curr.x = -1;
                }

                stack.pop();
                if (stack.isEmpty()) {
                    return;
                }
                else {
                    curr = stack.peek();
                }
            }

            // "start" break location
        }
    }
 
Example 31
Project: org.pshdl   File: FluidFrame.java View source code 5 votes vote down vote up
public ExecutableModel getExecutable(String moduleName, String source) {
	final FrameRegister register = new FrameRegister();
	for (final FluidFrame entry : references) {
		entry.registerFrame(register);
	}
	final List<Frame> res = toFrame(register);
	final InternalInformation[] internals = new InternalInformation[register.internalIds.size()];
	for (final Entry<String, Integer> e : register.internalIds.entrySet()) {
		final String name = e.getKey();
		final String basicName = InternalInformation.getBaseName(name, false, false);
		final VariableInformation info = vars.get(basicName);
		internals[e.getValue()] = new InternalInformation(name, info);
	}
	final Map<String, List<Frame>> lastID = Maps.newLinkedHashMap();
	for (final Frame frame : res) {
		for (final int outputId : frame.outputIds) {
			final InternalInformation ii = internals[outputId];
			if ("#null".equals(ii.info.name)) {
				continue;
			}
			LinkedList<Frame> lID = (LinkedList<Frame>) lastID.get(ii.info.name);
			if (lID != null) {
				final Iterator<Frame> iterator = lID.descendingIterator();
				final PredicateChain pred = getPredicate(internals, frame);
				while (iterator.hasNext()) {
					final Frame previous = iterator.next();
					final PredicateChain predPrev = getPredicate(internals, previous);
					if ((pred == null) || (predPrev == null) || pred.equals(predPrev)) {
						frame.executionDep = previous.uniqueID;
						break;
					}
					if (!predPrev.isMutual(pred)) {
						frame.executionDep = previous.uniqueID;
						break;
					}
					// System.out.println(pred + " -> \n" + predPrev);
				}
			} else {
				lID = new LinkedList<Frame>();
				lastID.put(ii.info.name, lID);
			}
			int maxData = 0;
			for (final int i : frame.internalDependencies) {
				maxData = Math.max(internals[i].actualWidth, maxData);
			}
			maxData = Math.max(ii.actualWidth, maxData);
			frame.maxDataWidth = Math.max(frame.maxDataWidth, maxData);
			lID.add(frame);
		}
	}
	final VariableInformation[] fVars = vars.values().toArray(new VariableInformation[vars.values().size()]);
	return new ExecutableModel(res.toArray(new Frame[res.size()]), internals, fVars, moduleName, source, annotations);
}