static void chaseDownPredecessors(iterator node, Register value,
	DataflowGraph* dfg,
	dataflow_iterator block, NodeList& nodes,
	InstructionToNodeMap& instructionToNodes, BlockSet& visited)
{
	if(!visited.insert(block).second) return;
	
	assert(block->aliveIn().count(value) != 0);

	for(auto predecessor : block->predecessors())
	{
		if(predecessor->aliveOut().count(value) == 0) continue;
		
		bool foundAnyDefinitions = false;
		
		// check the body for a definition
		for(auto instruction = predecessor->instructions().rbegin();
			instruction != predecessor->instructions().rend(); ++instruction)
		{
			for(auto destination : instruction->d)
			{
				if(*destination.pointer == value)
				{
					auto producer = nodes.end();
					
					auto ptx = static_cast<PTXInstruction*>(instruction->i);
					
					auto existingNode = instructionToNodes.find(ptx);
		
					if(existingNode == instructionToNodes.end())
					{
						producer = nodes.insert(nodes.end(), Node(ptx));
						
						instructionToNodes.insert(
							std::make_pair(ptx, producer));
					}
					else
					{
						producer = existingNode->second;
					}
					
					report(" " << producer->instruction->toString() << " -> "
						<< node->instruction->toString());
					
					node->predecessors.push_back(producer);
					producer->successors.push_back(node);
					
					foundAnyDefinitions = true;
					break;
				}
			}
		}
		
		if(foundAnyDefinitions) continue;
		
		// if no definitions were found, recurse through predecessors
		chaseDownPredecessors(node, value, dfg, predecessor, nodes,
			instructionToNodes, visited);
	}
}
Esempio n. 2
0
Node Node::parent(NodeList parents) {
	Node clone = Node(this->parent_x, this->parent_y);
	NodeList::iterator it = find(parents.begin(), parents.end(), clone);
	if (it != parents.end()) {
		return *it;
	}
	//Return clone of this
	return Node(this->x, this->y);
}
static void analyzeBlock(dataflow_iterator block, DataflowGraph* dfg,
	NodeList& nodes, InstructionToNodeMap& instructionToNodes)
{
	typedef std::unordered_map<Register, iterator> RegisterToProducerMap;
	
	RegisterToProducerMap lastProducers;
	
	for(auto& instruction : block->instructions())
	{
		// Create a node
		auto node = nodes.end();
		
		auto ptx = static_cast<PTXInstruction*>(instruction.i);
		
		auto existingNode = instructionToNodes.find(ptx);
		
		if(existingNode == instructionToNodes.end())
		{
			node = nodes.insert(nodes.end(), Node(ptx));
		
			instructionToNodes.insert(std::make_pair(ptx, node));
		}
		else
		{
			node = existingNode->second;
		}
		
		// Add predecessors
		for(auto source : instruction.s)
		{
			auto producer = lastProducers.find(*source.pointer);
		
			if(producer == lastProducers.end())
			{
				BlockSet visited;
			
				chaseDownPredecessors(node, *source.pointer, dfg, block, nodes,
					instructionToNodes, visited);
				continue;
			}
			
			report(" " << producer->second->instruction->toString() << " -> "
				<< node->instruction->toString());
			
			node->predecessors.push_back(producer->second);
			producer->second->successors.push_back(node);
		}
		
		// Update last producers
		for(auto destination : instruction.d)
		{	
			lastProducers[*destination.pointer] = node;
		}
	}
}
Esempio n. 4
0
void BFS(NodeMap* nMap, string startNode, string goalNode)
{
    QUEUE *q = new QUEUE();

    NodeList* nlist = nMap->find(startNode)->second;

    for (NodeList::iterator it = nlist->begin(); it != nlist->end(); it++)
    {
        (*it)->path->push_back(startNode);
        (*it)->visitedNodes->insert(pair<string, NodeList*> (startNode, nlist));
        q->push(*it);
    }

    cout << startNode << endl;


    while(!q->empty())
    {
        Node* firstNode = q->front();
        q->pop();
        cout << firstNode->name << endl;

        if (firstNode->name == goalNode)
        {
            cout << "END" << endl;
            cout << "Final path : ";

            for(list<string>::iterator sit = firstNode->path->begin(); sit != firstNode->path->end(); sit++)
            {
                cout << (*sit) << endl;
                cout << firstNode->name << endl;
            }
            break;
        }

        if (firstNode->visitedNodes->find(firstNode->name) != firstNode->visitedNodes->end())
        {
            continue;
        }

        nlist = nMap->find(firstNode->name)->second;

        for (NodeList::iterator it = nlist->begin(); it != nlist->end(); it++)
        {
            (*it)->path = new list<string>(firstNode->path->begin(), firstNode->path->end());
            (*it)->visitedNodes = new NodeMap(firstNode->visitedNodes->begin(), firstNode->visitedNodes->end());

            (*it)->path->push_back(firstNode->name);
            (*it)->visitedNodes->insert(pair<string, NodeList*> (firstNode->name, NULL));
            q->push(*it);
        }

    }
}
Esempio n. 5
0
void SplitTree::printShaderFunction( const NodeList& inOutputs, std::ostream& inStream ) const
{
  unsigned long startPrint = getTime();

  SplitArgumentTraversal printArguments(inStream,_outputPositionInterpolant);
  SplitStatementTraversal printStatements(inStream,_outputPositionInterpolant);

  for( size_t i = 0; i < _dagOrderNodeList.size(); i++ )
    _dagOrderNodeList[i]->unmarkAsOutput();
  _outputPositionInterpolant->unmarkAsOutput();

  for( NodeList::const_iterator j = inOutputs.begin(); j != inOutputs.end(); ++j )
    (*j)->markAsOutput();

  // create the wrapper for the function
  inStream << "void main(" << std::endl;

  unmark( SplitNode::kMarkBit_SubPrinted );
  printArguments( inOutputs );

  inStream << " ) {" << std::endl;

  unmark( SplitNode::kMarkBit_SubPrinted );
  printStatements( inOutputs );

  inStream << "}" << std::endl;

  unsigned long stopPrint = getTime();
  timePrintingCounter += stopPrint - startPrint;
}
Esempio n. 6
0
  void DOMElement::dumpInfo(FILE * f, int recursion)
  {
    NodeList nodes = getChildNodes();

    addSpace(f, recursion);
    fprintf(f, "NODE <%s> (%d children, %d deep)",
	    getTagName().c_str(), (int) nodes.size(), recursion);

    std::string str = getTextContent();
    if(str.size() > 0 && str.size() < 100) {
      fprintf(f, " TEXT = \"%s\"", str.c_str());
    }

    fprintf(f, "\n");

    int i = 1;

    fflush(f);

    for(NodeList::iterator it = nodes.begin(); it != nodes.end(); it++) {
      addSpace(f, recursion);
      fprintf(f, "Child %d/%d\n", i, (int) nodes.size());
      (*it).dumpInfo(f, recursion + 1);
      i++;
    }
  }
bool JurisdictionListener::queueJurisdictionRequest() {
    //qDebug() << "JurisdictionListener::queueJurisdictionRequest()\n";

    static unsigned char buffer[MAX_PACKET_SIZE];
    unsigned char* bufferOut = &buffer[0];
    ssize_t sizeOut = populateTypeAndVersion(bufferOut, PACKET_TYPE_JURISDICTION_REQUEST);
    int nodeCount = 0;

    NodeList* nodeList = NodeList::getInstance();
    for (NodeList::iterator node = nodeList->begin(); node != nodeList->end(); node++) {
        if (nodeList->getNodeActiveSocketOrPing(&(*node)) &&
                node->getType() == getNodeType()) {
            const HifiSockAddr* nodeAddress = node->getActiveSocket();
            PacketSender::queuePacketForSending(*nodeAddress, bufferOut, sizeOut);
            nodeCount++;
        }
    }

    if (nodeCount > 0) {
        setPacketsPerSecond(nodeCount);
    } else {
        setPacketsPerSecond(NO_SERVER_CHECK_RATE);
    }

    // keep going if still running
    return isStillRunning();
}
Esempio n. 8
0
void Module::processExtendedAttributes()
{
    NodeList* list = getExtendedAttributes();
    if (!list)
    {
        return;
    }

    for (NodeList::iterator i = list->begin(); i != list->end(); ++i)
    {
        ExtendedAttribute* ext = dynamic_cast<ExtendedAttribute*>(*i);
        assert(ext);
        if (ext->getName() == "Prefix")
        {
            if (ScopedName* name = dynamic_cast<ScopedName*>(ext->getDetails()))
            {
                prefix = name->getName();
            }
        }
        else if (ext->getName() == "NamespaceObject")
        {
            attr |= NamespaceObject;
        }
        else if (ext->getName() == "ExceptionConsts")
        {
            ext->report("Warning: '%s' has been deprecated.", ext->getName().c_str());
        }
        else
        {
            ext->report("Warning: unknown extended attribute '%s'.", ext->getName().c_str());
        }
    }
}
Esempio n. 9
0
void* removeSilentNodes(void *args) {
    NodeList* nodeList = (NodeList*) args;
    uint64_t checkTimeUSecs;
    int sleepTime;
    
    while (!silentNodeThreadStopFlag) {
        checkTimeUSecs = usecTimestampNow();
        
        for(NodeList::iterator node = nodeList->begin(); node != nodeList->end(); ++node) {
            
            if ((checkTimeUSecs - node->getLastHeardMicrostamp()) > NODE_SILENCE_THRESHOLD_USECS) {
            
                qDebug() << "Killed " << *node << "\n";
                
                nodeList->notifyHooksOfKilledNode(&*node);
                
                node->setAlive(false);
            }
        }
        
        sleepTime = NODE_SILENCE_THRESHOLD_USECS - (usecTimestampNow() - checkTimeUSecs);
        #ifdef _WIN32
        Sleep( static_cast<int>(1000.0f*sleepTime) );
        #else
        usleep(sleepTime);
        #endif
    }
    
    pthread_exit(0);
    return NULL;
}
Esempio n. 10
0
void VoxelEditPacketSender::queuePacketToNodes(unsigned char* buffer, ssize_t length) {
    if (!_shouldSend) {
        return; // bail early
    }
    
    assert(voxelServersExist()); // we must have jurisdictions to be here!!

    int headerBytes = numBytesForPacketHeader(buffer) + sizeof(short) + sizeof(uint64_t);
    unsigned char* octCode = buffer + headerBytes; // skip the packet header to get to the octcode
    
    // We want to filter out edit messages for voxel servers based on the server's Jurisdiction
    // But we can't really do that with a packed message, since each edit message could be destined 
    // for a different voxel server... So we need to actually manage multiple queued packets... one
    // for each voxel server
    NodeList* nodeList = NodeList::getInstance();
    for (NodeList::iterator node = nodeList->begin(); node != nodeList->end(); node++) {
        // only send to the NodeTypes that are NODE_TYPE_VOXEL_SERVER
        if (node->getActiveSocket() != NULL && node->getType() == NODE_TYPE_VOXEL_SERVER) {
            QUuid nodeUUID = node->getUUID();
            bool isMyJurisdiction = true;
            // we need to get the jurisdiction for this 
            // here we need to get the "pending packet" for this server
            const JurisdictionMap& map = (*_voxelServerJurisdictions)[nodeUUID];
            isMyJurisdiction = (map.isMyJurisdiction(octCode, CHECK_NODE_ONLY) == JurisdictionMap::WITHIN);
            if (isMyJurisdiction) {
                queuePacketToNode(nodeUUID, buffer, length);
            }
        }
    }
}
Esempio n. 11
0
void Pathfinder::ResetNodes(NodeList& toReset, int dx, int dy) {
	for(NodeList::iterator i = toReset.begin(); i != toReset.end(); i++) {
		Node* n = *i;
		n->SetDistance(NODE_INFINITY);
		n->CalculateHeuristic(dx, dy);
	}
}
Esempio n. 12
0
 void DataFlow::append(const DataFlow& df)
 {
   // merge library usage
   m_libs.insert(df.m_libs.begin(),df.m_libs.end());
   // append dataflow
   NodeList fNodes = Graph<NodeDesc>::finalNodes();
   const Graph<NodeDesc>& dfg = (const Graph<NodeDesc>&) df;
   NodeList rNodes = dfg.rootNodes();
   if (rNodes.size()==0)
   {
     cerr << "WARNING: appending empty dataflow ..." << endl;
     return;
   }
   if (fNodes.size()>1)
   {
     cerr << "ERROR: try to append a dataflow to a dataflow having " << fNodes.size() << " final nodes !" << endl;
     return;
   }
   map<Node*,Node*> mapping;
   for (NodeListCIt it=rNodes.begin();it!=rNodes.end();it++)
   {
     Node* n = Graph<NodeDesc>::createNode((*it)->v);
     if (fNodes.size()>0)
       Graph<NodeDesc>::link(fNodes[0],"",n,"");
     mapping[*it] = n;
   }
   mergeFlow(this,&dfg,mapping);
 }
Esempio n. 13
0
bool JurisdictionListener::queueJurisdictionRequest() {
    static unsigned char buffer[MAX_PACKET_SIZE];
    unsigned char* bufferOut = &buffer[0];
    ssize_t sizeOut = populateTypeAndVersion(bufferOut, PACKET_TYPE_VOXEL_JURISDICTION_REQUEST);
    int nodeCount = 0;

    NodeList* nodeList = NodeList::getInstance();
    for (NodeList::iterator node = nodeList->begin(); node != nodeList->end(); node++) {

        // only send to the NodeTypes that are interested in our jurisdiction details
        const int numNodeTypes = 1; 
        const NODE_TYPE nodeTypes[numNodeTypes] = { NODE_TYPE_VOXEL_SERVER };
        if (node->getActiveSocket() != NULL && memchr(nodeTypes, node->getType(), numNodeTypes)) {
            sockaddr* nodeAddress = node->getActiveSocket();
            PacketSender::queuePacketForSending(*nodeAddress, bufferOut, sizeOut);
            nodeCount++;
        }
    }

    // set our packets per second to be the number of nodes
    setPacketsPerSecond(nodeCount);
    
    // keep going if still running
    return isStillRunning();
}
Esempio n. 14
0
bool VoxelEditPacketSender::voxelServersExist() const {
    bool hasVoxelServers = false;
    bool atLeastOnJurisdictionMissing = false; // assume the best
    NodeList* nodeList = NodeList::getInstance();
    for (NodeList::iterator node = nodeList->begin(); node != nodeList->end(); node++) {
        // only send to the NodeTypes that are NODE_TYPE_VOXEL_SERVER
        if (node->getType() == NODE_TYPE_VOXEL_SERVER) {
            if (nodeList->getNodeActiveSocketOrPing(&(*node))) {
                QUuid nodeUUID = node->getUUID();
                // If we've got Jurisdictions set, then check to see if we know the jurisdiction for this server
                if (_voxelServerJurisdictions) {
                    // lookup our nodeUUID in the jurisdiction map, if it's missing then we're 
                    // missing at least one jurisdiction
                    if ((*_voxelServerJurisdictions).find(nodeUUID) == (*_voxelServerJurisdictions).end()) {
                        atLeastOnJurisdictionMissing = true;
                    }
                }
                hasVoxelServers = true;
            }
        }
        if (atLeastOnJurisdictionMissing) {
            break; // no point in looking further...
        }
    }
    return (hasVoxelServers && !atLeastOnJurisdictionMissing);
}
 DirichletProcessParameters(const std::string& name, float concentration,
     NodeList& managed_nodes)
     : component_counters_(), component_name_(name), concentration_(
         concentration), managed_nodes_(managed_nodes.begin(),
         managed_nodes.end()), parameters_name_(name + "Parameters")
 {
 }
Esempio n. 16
0
void Attribute::processExtendedAttributes()
{
    NodeList* list = getExtendedAttributes();
    if (!list)
    {
        return;
    }
    uint32_t attr = getAttr();
    for (NodeList::iterator i = list->begin(); i != list->end(); ++i)
    {
        ExtendedAttribute* ext = dynamic_cast<ExtendedAttribute*>(*i);
        assert(ext);
        if (ext->getName() == "Replaceable")
        {
            attr |= Replaceable;
        }
        else if (ext->getName() == "TreatNullAs")
        {
            if (ScopedName* name = dynamic_cast<ScopedName*>(ext->getDetails()))
            {
                if (name->getName() == "EmptyString")
                {
                    attr |= NullIsEmpty;
                }
            }
        }
        else if (ext->getName() == "TreatUndefinedAs")
        {
            if (ScopedName* name = dynamic_cast<ScopedName*>(ext->getDetails()))
            {
                if (name->getName() == "EmptyString")
                {
                    attr |= UndefinedIsEmpty;
                }
                else if (name->getName() == "Null")
                {
                    attr |= UndefinedIsNull;
                }
            }
        }
        else if (ext->getName() == "PutForwards")
        {
            if (ScopedName* name = dynamic_cast<ScopedName*>(ext->getDetails()))
            {
                putForwards = name->getName();
            }
        }
        else if (ext->getName() == "Null" ||
                 ext->getName() == "Undefined")
        {
            ext->report("Warning: '%s' has been deprecated.", ext->getName().c_str());
        }
        else
        {
            ext->report("Warning: unknown extended attribute '%s'.", ext->getName().c_str());
        }
    }
    setAttr(attr);
}
Esempio n. 17
0
	bool contains(NodeId id) const {
		// TODO better datastructure: set of closed node ids
		for(NodeList::const_iterator i = nodes.begin(); i != nodes.end(); ++i) {
			if((*i)->getId() == id) {
				return true;
			}
		}
		return false;
	}
Esempio n. 18
0
    void Pathgrid::invertSelected()
    {
        NodeList temp = NodeList(mSelected);
        mSelected.clear();

        const CSMWorld::Pathgrid* source = getPathgridSource();
        if (source)
        {
            for (unsigned short i = 0; i < static_cast<unsigned short>(source->mPoints.size()); ++i)
            {
                if (std::find(temp.begin(), temp.end(), i) == temp.end())
                    mSelected.push_back(i);
            }

            createSelectedGeometry(*source);
        }
        else
        {
            removeSelectedGeometry();
        }
    }
Esempio n. 19
0
  DOMElement DOMElement::getChildNode(const char * tagname)
  {
    NodeList nodes = getChildNodes();
    
    for(NodeList::iterator it = nodes.begin(); it != nodes.end(); it++) {
      DOMElement e = *it;
      if(e.getTagName() == tagname)
	return e;
    }

    return DOMElement(0);
  }
Esempio n. 20
0
void InternodeSyncer::getNodesAsInfoList(CapacityInfoList& outCapacityInfos)
{
   App* app = Program::getApp();
   NodeStoreServersEx* metaNodes = app->getMetaNodes();
   NodeList metaNodeList;

   metaNodes->referenceAllNodes(&metaNodeList);

   for (NodeListIter nodeIt = metaNodeList.begin(); nodeIt != metaNodeList.end(); ++nodeIt)
      outCapacityInfos.push_back( CapacityInfo( (*nodeIt)->getNumID() ) );

   metaNodes->releaseAllNodes(&metaNodeList);
}
Esempio n. 21
0
void PrintList()
{
	for(NodeMap::iterator it = nMap->begin(); it != nMap->end(); it++)
	{
		cout << (*it).first << " -> ";
		NodeList *lt = (*it).second;

		for (NodeList::iterator lit = lt->begin(); lit != lt->end(); lit++) 
		{
			cout << (*lit)->name << "," << (*lit)->cost << "," << (*lit)->reliability << " -> ";
		}
		cout << endl;
	}
}
Esempio n. 22
0
	/**
	 * If a node with the same ID exists, update it.
	 * Otherwise add a new node.
	 * Assumes that remaining never changes for the same node id.
	 **/
	inline void add(NodeId id, const Node * parent, float distance, float remaining) {
		
		// Check if node is already in open list.
		for(NodeList::iterator i = nodes.begin(); i != nodes.end(); ++i) {
			if((*i)->getId() == id) {
				if((*i)->getDistance() > distance) {
					(*i)->newParent(parent, distance);
				}
				return;
			}
		}
		
		nodes.push_back(new Node(id, parent, distance, remaining));
	}
Esempio n. 23
0
void NetworkVisualiser::process()
{
    const int NODE_WIDTH = 80;
    const int NODE_HEIGHT = 40;
    Canvas c = NodeCore::Canvas(300, 300);
    Network* net = (Network*)asData("network");
    NodeList nodes = net->getNodes();
    for (NodeIterator iter = nodes.begin(); iter != nodes.end(); ++iter) {
        Node* node = (*iter);
        NodeCore::BezierPath p = NodeCore::BezierPath();
        p.rect(node->getX(), node->getY(), NODE_WIDTH, NODE_HEIGHT);
        c.append(p);
    }
    _setOutput(c);
}
Esempio n. 24
0
Node* osgDB::readNodeFiles(std::vector<std::string>& commandLine,const ReaderWriter::Options* options)
{
    typedef std::vector<osg::Node*> NodeList;
    NodeList nodeList;

    // note currently doesn't delete the loaded file entries from the command line yet...

    for(std::vector<std::string>::iterator itr=commandLine.begin();
        itr!=commandLine.end();
        ++itr)
    {
        if ((*itr)[0]!='-')
        {
            // not an option so assume string is a filename.
            osg::Node *node = osgDB::readNodeFile( *itr , options );

            if( node != (osg::Node *)0L )
            {
                if (node->getName().empty()) node->setName( *itr );
                nodeList.push_back(node);
            }

        }
    }
    
    if (nodeList.empty())
    {
        return NULL;
    }

    if (nodeList.size()==1)
    {
        return nodeList.front();
    }
    else  // size >1
    {
        osg::Group* group = new osg::Group;
        for(NodeList::iterator itr=nodeList.begin();
            itr!=nodeList.end();
            ++itr)
        {
            group->addChild(*itr);
        }

        return group;
    }
    
}
Esempio n. 25
0
void Node::coalesce()
{
    printf("%sCoalescing %c at (%d,%d)\n", indent(), color() + 'A', x(), y());
    std::shared_ptr<Node> sharedThis = shared_from_this();

    NodeList adjacents = adjacentNodes_; // Copy the list so we can modify it as we iterate through it
    for (NodeList::iterator i = adjacents.begin(); i != adjacents.end(); ++i)
    {
        std::shared_ptr<Node> const & aNode = *i;
        if (color_ == aNode->color())
        {
            // Disconnect the adjacent node from everyone and connect this node to its adjacent nodes
            for (NodeList::iterator i2 = aNode->adjacentNodes_.begin(); i2 != aNode->adjacentNodes_.end(); ++i2)
            {
                std::shared_ptr<Node> const & aaNode = *i2;
                printf("%sDisconnecting %c at (%d,%d) from %c at (%d,%d)\n",
                    indent(),
                    aNode->color() + 'A',
                    aNode->x(),
                    aNode->y(),
                    aaNode->color() + 'A',
                    aaNode->x(),
                    aaNode->y());

                // Disconnect the adjacent-adjacent node (which might be this node) from the adjacent node
                aaNode->disconnect(aNode);

                // If the adjacent-adjacent node is not this node and is not already connected to this node,
                // then connect it
                if (aaNode.get() != this && !connectedTo(aaNode))
                {
                    printf("%sConnecting %c at (%d,%d) to %c at (%d,%d)\n",
                        indent(),
                        aaNode->color() + 'A',
                        aaNode->x(),
                        aaNode->y(),
                        color() + 'A',
                        x(),
                        y());
                    connect(aaNode);
                    aaNode->connect(sharedThis);
                }
            }
            // At this point, the adjacent node is only referenced by the copied list and will be deleted when
            // the list goes out of scope
        }
    }
}
Esempio n. 26
0
bool DomainServer::checkInWithUUIDMatchesExistingNode(sockaddr* nodePublicSocket,
                                                      sockaddr* nodeLocalSocket,
                                                      const QUuid& checkInUUID) {
    NodeList* nodeList = NodeList::getInstance();
    
    for (NodeList::iterator node = nodeList->begin(); node != nodeList->end(); node++) {
        if (node->getLinkedData()
            && socketMatch(node->getPublicSocket(), nodePublicSocket)
            && socketMatch(node->getLocalSocket(), nodeLocalSocket)
            && node->getUUID() == checkInUUID) {
            // this is a matching existing node if the public socket, local socket, and UUID match
            return true;
        }
    }
    
    return false;
}
Esempio n. 27
0
void BronKerbosch::bkDegeneracy(const NodeList& order)
{
  BitSet mask(_n);

  for (typename NodeList::const_iterator it = order.begin(); it != order.end(); ++it)
  {
    Node v = *it;
    // ~mask includes v but we're fine as _bitNeighborhood[v] excludes v
    BitSet P = _bitNeighborhood[v] & ~mask;
    BitSet X = _bitNeighborhood[v] & mask;
    BitSet R(_n);
    R.set(_nodeToBit[v]);

    bkPivot(P, R, X);
    mask.set(_nodeToBit[v]);
  }
}
Esempio n. 28
0
static bool Graph_divide(Graph& graph, size_t loops, PositionList* position_tbl) {
    typedef std::set< size_t > NodeList;
    NodeList nodes;

    // nodes
    for (Graph::const_iterator i = graph.begin(); i != graph.end(); ++i) {
        nodes.insert(i->first);
    }

    while (!nodes.empty()) {
        // BFS
        Graph component;
        std::deque< size_t > Q = boost::assign::list_of(*nodes.begin());
        while (!Q.empty()) {
            size_t xi = Q.front();
            Q.pop_front();

            if (nodes.find(xi) == nodes.end()) {
                continue;
            }

            nodes.erase(xi);

            Graph::const_iterator i = graph.find(xi);
            if (i != graph.end()) {
                for (Children::const_iterator j = i->second.children.begin(); j != i->second.children.end(); ++j) {
                    Graph_addEdge(component, xi, j->first, j->second);
                    Q.push_back(j->first);
                }
                for (Parents::const_iterator j = i->second.parents.begin(); j != i->second.parents.end(); ++j) {
                    Q.push_back(*j);
                }
            }
        }

        LOG4CXX_TRACE(logger, boost::format("component:%d/%d") % component.size() % graph.size());

        if (!Graph_solve(component, loops, position_tbl)) {
            LOG4CXX_ERROR(logger, "solve component failed");
            return false;
        }
    }

    return true;
}
// Print the node data structure
bool DataScaling::printNodes()
{
	for (int i = 0; i < this->levels; ++i)
	{
		cout << "Level:" << i << endl;

		// Get the nodeList for this level
		NodeList* nodeList = this->nodes[i];

		for (auto it = nodeList->begin(); it != nodeList->end(); ++it)
		{
			Node* node = *it;
			node->print();
		}
	}

	return(true);
}
Esempio n. 30
0
void DomainServer::possiblyAddStaticAssignmentsBackToQueueAfterRestart(timeval* startTime) {
    // if the domain-server has just restarted,
    // check if there are static assignments in the file that we need to
    // throw into the assignment queue
    const uint64_t RESTART_HOLD_TIME_USECS = 5 * 1000 * 1000;
    
    if (!_hasCompletedRestartHold && usecTimestampNow() - usecTimestamp(startTime) > RESTART_HOLD_TIME_USECS) {
        _hasCompletedRestartHold = true;
        
        // pull anything in the static assignment file that isn't spoken for and add to the assignment queue
        for (int i = 0; i < MAX_STATIC_ASSIGNMENT_FILE_ASSIGNMENTS; i++) {
            if (_staticAssignments[i].getUUID().isNull()) {
                // reached the end of static assignments, bail
                break;
            }
            
            bool foundMatchingAssignment = false;
            
            NodeList* nodeList = NodeList::getInstance();
            
            // enumerate the nodes and check if there is one with an attached assignment with matching UUID
            for (NodeList::iterator node = nodeList->begin(); node != nodeList->end(); node++) {
                if (node->getLinkedData()) {
                    Assignment* linkedAssignment = (Assignment*) node->getLinkedData();
                    if (linkedAssignment->getUUID() == _staticAssignments[i].getUUID()) {
                        foundMatchingAssignment = true;
                        break;
                    }
                }
            }
            
            if (!foundMatchingAssignment) {
                // this assignment has not been fulfilled - reset the UUID and add it to the assignment queue
                _staticAssignments[i].resetUUID();
                
                qDebug() << "Adding static assignment to queue -" << _staticAssignments[i] << "\n";
                
                _assignmentQueueMutex.lock();
                _assignmentQueue.push_back(&_staticAssignments[i]);
                _assignmentQueueMutex.unlock();
            }
        }
    }
}