예제 #1
0
// Collect bar summaries for job allocation on node
void NodeMenu::get_lines() {
    // First update summary information; calling get lines updates info
    pcluster_menu->get_lines();

    // Now get job allocation line content
    NodeInfo node = pnode_container->nodes[node_name];
    lines = node.get_job_bar_summary(32);
}
예제 #2
0
int main(int argc,char *argv[])
{ 
    int numtasks, rank, dest, source, rc, count, tag=1, noderank;
    char inmsg, outmsg='x';
    MPI_Init(&argc,&argv);
    NodeInfo NI;
    NI.print();
    MPI_Finalize();
}
예제 #3
0
파일: main.cpp 프로젝트: RusonWong/wimg
int unregister_from_master()
{
    printf("unregister_from_master start\n");
    char hname[128];
    struct hostent *hent;
    int i;

    gethostname(hname, sizeof(hname));
    hent = gethostbyname(hname);

   // printf("hostname: %s/naddress list: ", hent->h_name);
    
    char* ipstr = inet_ntoa(*(struct in_addr*)(hent->h_addr_list[0]));
    string hostaddr(ipstr);
    
    int cLen = 0;
    struct sockaddr_in cli;
    
    cli.sin_family = AF_INET;
    cli.sin_port = htons(globalConfig.masterPort);
    cli.sin_addr.s_addr = inet_addr(globalConfig.masterAddr.c_str());
    
    const int sock = socket(AF_INET, SOCK_STREAM, 0);

    if(sock < 0)
    {
        printf("socket() failure!\n");
        return 0; 
    }
    
    if(connect(sock, (struct sockaddr*)&cli, sizeof(cli)) < 0)
    {
        printf("connect() failure!\n");
        return 0;
    }

    //send method
    cLen = w_send(sock, "4", 1);
    if((cLen < 0)||(cLen == 0))
    {
        printf("send() failure!\n");
        return 0;
    }

    //send body
    NodeInfo req;
    req.set_nodeaddr(globalConfig.localAddr);
    req.set_nodeport(globalConfig.port);

    w_send_pb(sock, &req);

    close(sock);
    printf("unregister_from_master done\n");
    return 1;
}
예제 #4
0
bool captureOpenWriteDevice()
{
  XnStatus nRetVal = XN_STATUS_OK;
  NodeInfoList recordersList;
  
  nRetVal = g_Context.EnumerateProductionTrees(XN_NODE_TYPE_RECORDER, NULL, recordersList);
  START_CAPTURE_CHECK_RC(nRetVal, "Enumerate recorders");

  // take first
  NodeInfo chosen = *recordersList.Begin();
  nRetVal = g_Context.CreateProductionTree(chosen);
  START_CAPTURE_CHECK_RC(nRetVal, "Create recorder");

  g_Capture.pRecorder = new Recorder;
  nRetVal = chosen.GetInstance(*g_Capture.pRecorder);
  START_CAPTURE_CHECK_RC(nRetVal, "Get recorder instance");

  nRetVal = g_Capture.pRecorder->SetDestination(XN_RECORD_MEDIUM_FILE, g_Capture.csFileName);
  START_CAPTURE_CHECK_RC(nRetVal, "Set output file");

  if (getDevice() != NULL)
  {
	  nRetVal = g_Capture.pRecorder->AddNodeToRecording(*getDevice(), XN_CODEC_UNCOMPRESSED);
	  START_CAPTURE_CHECK_RC(nRetVal, "add device node");
  }

  if (isDepthOn() && (g_Capture.DepthFormat != CODEC_DONT_CAPTURE))
  {
	  nRetVal = g_Capture.pRecorder->AddNodeToRecording(*getDepthGenerator(), g_Capture.DepthFormat);
	  START_CAPTURE_CHECK_RC(nRetVal, "add depth node");
  }

  if (isImageOn() && (g_Capture.ImageFormat != CODEC_DONT_CAPTURE))
  {
	  nRetVal = g_Capture.pRecorder->AddNodeToRecording(*getImageGenerator(), g_Capture.ImageFormat);
	  START_CAPTURE_CHECK_RC(nRetVal, "add image node");
  }

  if (isIROn() && (g_Capture.IRFormat != CODEC_DONT_CAPTURE))
  {
	  nRetVal = g_Capture.pRecorder->AddNodeToRecording(*getIRGenerator(), g_Capture.IRFormat);
	  START_CAPTURE_CHECK_RC(nRetVal, "add IR stream");
  }

  if (isAudioOn() && (g_Capture.AudioFormat != CODEC_DONT_CAPTURE))
  {
	  nRetVal = g_Capture.pRecorder->AddNodeToRecording(*getAudioGenerator(), g_Capture.AudioFormat);
	  START_CAPTURE_CHECK_RC(nRetVal, "add Audio stream");
  }

  return true;
}
bool RenderFrameSet::nodeAtPoint(NodeInfo& info, int _x, int _y, int _tx, int _ty,
                                 HitTestAction hitTestAction, bool inside)
{
    RenderBox::nodeAtPoint(info, _x, _y, _tx, _ty, hitTestAction, inside);

    inside = m_resizing || canResize(_x, _y);

    if ( inside && element() && !element()->noResize() && !info.readonly()){
        info.setInnerNode(element());
        info.setInnerNonSharedNode(element());
    }

    return inside || m_clientresizing;
}
Stencil<T>*
MPICUDAStencilFactory<T>::BuildStencil( const OptionParser& options )
{
    // get options for base class
    T wCenter;
    T wCardinal;
    T wDiagonal;
    size_t lRows;
    size_t lCols;
    std::vector<long long> devs;
    CommonCUDAStencilFactory<T>::ExtractOptions( options,
                                                wCenter,
                                                wCardinal,
                                                wDiagonal,
                                                lRows,
                                                lCols,
                                                devs );

    size_t mpiGridRows;
    size_t mpiGridCols;
    unsigned int nItersPerHaloExchange;
    MPI2DGridProgram<T>::ExtractOptions( options,
                                        mpiGridRows,
                                        mpiGridCols,
                                        nItersPerHaloExchange );

    // determine which device to use
    // We would really prefer this to be done in main() but
    // since BuildStencil is a virtual function, we cannot change its
    // signature, and OptionParser provides no way to override an
    // option's value after it is set during parsing.
    NodeInfo ni;
    int myRankInNode = ni.nodeRank();
    // assign tasks to devices in round-robin approach
    // TODO is this really the mapping we want if the CUDA-capable
    // devices are heterogeneous?
    int chosenDevice = (myRankInNode % devs.size());

    return new MPICUDAStencil<T>( wCenter,
                                wCardinal,
                                wDiagonal,
                                lRows,
                                lCols,
                                mpiGridRows,
                                mpiGridCols,
                                nItersPerHaloExchange,
                                chosenDevice
                                );
}
예제 #7
0
파일: pnode.cpp 프로젝트: chaozh/phxpaxos
int PNode :: AddMember(const int iGroupIdx, const NodeInfo & oNode)
{
    if (!CheckGroupID(iGroupIdx))
    {
        return Paxos_GroupIdxWrong;
    }

    SystemVSM * poSystemVSM = m_vecGroupList[iGroupIdx]->GetConfig()->GetSystemVSM();

    if (poSystemVSM->GetGid() == 0)
    {
        return Paxos_MembershipOp_NoGid;
    }

    uint64_t llVersion = 0;
    NodeInfoList vecNodeInfoList;
    poSystemVSM->GetMembership(vecNodeInfoList, llVersion);

    for (auto & oNodeInfo : vecNodeInfoList)
    {
        if (oNodeInfo.GetNodeID() == oNode.GetNodeID())
        {
            return Paxos_MembershipOp_Add_NodeExist;
        }
    }

    vecNodeInfoList.push_back(oNode);

    return ProposalMembership(poSystemVSM, iGroupIdx, vecNodeInfoList, llVersion);
}
예제 #8
0
파일: pnode.cpp 프로젝트: chaozh/phxpaxos
int PNode :: ChangeMember(const int iGroupIdx, const NodeInfo & oFromNode, const NodeInfo & oToNode)
{
    if (!CheckGroupID(iGroupIdx))
    {
        return Paxos_GroupIdxWrong;
    }

    SystemVSM * poSystemVSM = m_vecGroupList[iGroupIdx]->GetConfig()->GetSystemVSM();

    if (poSystemVSM->GetGid() == 0)
    {
        return Paxos_MembershipOp_NoGid;
    }

    uint64_t llVersion = 0;
    NodeInfoList vecNodeInfoList;
    poSystemVSM->GetMembership(vecNodeInfoList, llVersion);

    NodeInfoList vecAfterNodeInfoList;
    bool bFromNodeExist = false;
    bool bToNodeExist = false;
    for (auto & oNodeInfo : vecNodeInfoList)
    {
        if (oNodeInfo.GetNodeID() == oFromNode.GetNodeID())
        {
            bFromNodeExist = true;
            continue;
        }
        else if (oNodeInfo.GetNodeID() == oToNode.GetNodeID())
        {
            bToNodeExist = true;
            continue;
        }

        vecAfterNodeInfoList.push_back(oNodeInfo);
    }

    if ((!bFromNodeExist) && bToNodeExist)
    {
        return Paxos_MembershipOp_Change_NoChange;
    }

    vecAfterNodeInfoList.push_back(oToNode);

    return ProposalMembership(poSystemVSM, iGroupIdx, vecAfterNodeInfoList, llVersion);
}
예제 #9
0
파일: Scheduler.cpp 프로젝트: 4m1g0/IOT_tfg
bool Scheduler::updateSchedules(Pricing& pricing, NodeInfo& nodeInfo)
{
  if (!isMaster())
  {
    Master::schedule(&nodeInfo);
    return true;
  }

  unsigned long now = Clock::getUnixTime();
  bool changed = false;
  for (auto &schedule : nodeInfo.schedules)
  {
    // we already have a designated time or interval expired, so we can get next time
    if (schedule.repeatEvery > 0
        && ((schedule.designatedTime > schedule.startTime && schedule.designatedTime < schedule.startTime + schedule.interval)
            || schedule.startTime + schedule.interval < now))
    {
      schedule.startTime += schedule.repeatEvery * ceil(float(now - schedule.interval - schedule.startTime) / float(schedule.repeatEvery));
      changed = true;
    }

    #if DEBUG_SCHEDULER
    Serial.print("lastRun");
    Serial.println(schedule.lastRun);
    Serial.print("designatedtime");
    Serial.println(schedule.designatedTime);
    Serial.print("duration");
    Serial.println(schedule.duration);
    Serial.print("startime");
    Serial.println(schedule.startTime);
    Serial.print("now");
    Serial.println(now);
    Serial.print("startime");
    Serial.println(schedule.startTime);
    Serial.print("startime-now");
    Serial.println(long(schedule.startTime - now));
    #endif

      // It has already run or the designated time expiered
    if ((schedule.lastRun >= schedule.designatedTime || schedule.designatedTime + schedule.duration > now)
        // and we have a new plan to schedule
       && schedule.startTime > schedule.designatedTime
       // and there are only 30 minutes left to ensure we have data for the interval
       && long(schedule.startTime - now) < 1800)
    {
      if (isMaster())
        schedule.designatedTime = pricing.getBestTime(schedule);
      else
        {} //ask master for best time
      changed = true;
    }
  }

  if (changed)
    nodeInfo.save();

  return changed;
}
예제 #10
0
파일: nodesdb.cpp 프로젝트: mentat/YardSale
void NodesDb::LoadFile(const wxString& file)
{
    NodeInfo *ni = new NodeInfo; 
    ni->Type = wxEmptyString;
    ni->Icon = 0;
    wxPathList paths;
    size_t i;
    
    for (i = 0; i < m_Paths.GetCount(); i++)
        paths.Add(m_Paths[i]);
    
    ni->Read(file, paths);
    
    // maybe we already parsed it?
    for (i = 0; i < m_Infos.GetCount(); i++)
        if (m_Infos[i].NodeClass == ni->NodeClass) return;
    
    m_Infos.Add(ni);
}
예제 #11
0
/**
  * insertionSort
  * 
  * uses a insertion sort algorithm to insert a new node
  * into a vector
  *
  */
void FileSystem::insertionSort(vector<NodeInfo*> nodes) {

    unsigned int ix = 0,
                 jx = 0;

    int nSize = 0;

    for (ix = 1; ix < nodes.size() - 1; ++ix) {

        nSize = allNodes.at(ix)->getSize();

        jx = ix - 1;
        NodeInfo* cmp = allNodes.at(jx);
        while( jx >= 0 && nSize < cmp->getSize() ) {
            
        }
    }

}
예제 #12
0
bool RenderInline::nodeAtPoint(NodeInfo& info, int _x, int _y, int _tx, int _ty,
                               HitTestAction hitTestAction, bool inside)
{
    // Check our kids if our HitTestAction says to.
    if (hitTestAction != HitTestSelfOnly) {
        for (RenderObject* child = lastChild(); child; child = child->previousSibling())
            if (!child->layer() && !child->isFloating() && child->nodeAtPoint(info, _x, _y, _tx, _ty))
                inside = true;
    }
    
    // Check our line boxes if we're still not inside.
    if (hitTestAction != HitTestChildrenOnly && !inside && style()->visibility() != HIDDEN) {
        // See if we're inside one of our line boxes.
        for (InlineRunBox* curr = firstLineBox(); curr; curr = curr->nextLineBox()) {
            if((_y >=_ty + curr->m_y) && (_y < _ty + curr->m_y + curr->m_height) &&
               (_x >= _tx + curr->m_x) && (_x <_tx + curr->m_x + curr->m_width) ) {
                inside = true;
                break;
            }
        }
    }

    if (inside && element()) {
        if (info.innerNode() && info.innerNode()->renderer() &&
            !info.innerNode()->renderer()->isInline()) {
            // Within the same layer, inlines are ALWAYS fully above blocks.  Change inner node.
            info.setInnerNode(element());

            // Clear everything else.
            info.setInnerNonSharedNode(0);
            info.setURLElement(0);
        }

        if (!info.innerNode())
            info.setInnerNode(element());

        if(!info.innerNonSharedNode())
            info.setInnerNonSharedNode(element());
    }

    return inside;
}
예제 #13
0
파일: Capture.cpp 프로젝트: afisa/OpenNI
bool captureOpenWriteDevice()
{
	XnStatus nRetVal = XN_STATUS_OK;
	NodeInfoList recordersList;
	nRetVal = g_Context.EnumerateProductionTrees(XN_NODE_TYPE_RECORDER, NULL, recordersList);
	START_CAPTURE_CHECK_RC(nRetVal, "Enumerate recorders");
	// take first
	NodeInfo chosen = *recordersList.Begin();
	nRetVal = g_Context.CreateProductionTree(chosen);
	START_CAPTURE_CHECK_RC(nRetVal, "Create recorder");

	g_Capture.pRecorder = new Recorder;
	nRetVal = chosen.GetInstance(*g_Capture.pRecorder);
	START_CAPTURE_CHECK_RC(nRetVal, "Get recorder instance");

	nRetVal = g_Capture.pRecorder->SetDestination(XN_RECORD_MEDIUM_FILE, g_Capture.csFileName);
	START_CAPTURE_CHECK_RC(nRetVal, "Set output file");

	return true;
}
예제 #14
0
bool RenderText::nodeAtPoint(NodeInfo& info, int _x, int _y, int _tx, int _ty, HitTestAction /*hitTestAction*/, bool /*inBox*/)
{
    assert(parent());

    bool inside = false;
    if (style()->visibility() != HIDDEN) {
        InlineTextBox *s = m_lines.count() ? m_lines[0] : 0;
        int si = 0;
        while(s) {
            if((_y >=_ty + s->m_y) && (_y < _ty + s->m_y + s->m_height) &&
               (_x >= _tx + s->m_x) && (_x <_tx + s->m_x + s->m_width) ) {
                inside = true;
                break;
            }

            s = si < (int) m_lines.count()-1 ? m_lines[++si] : 0;
        }
    }

    // #### ported over from Safari. Can this happen at all? (lars)

    if (inside && element()) {
        if (info.innerNode() && info.innerNode()->renderer() &&
            !info.innerNode()->renderer()->isInline()) {
            // Within the same layer, inlines are ALWAYS fully above blocks.  Change inner node.
            info.setInnerNode(element());

            // Clear everything else.
            info.setInnerNonSharedNode(0);
            info.setURLElement(0);
        }

        if (!info.innerNode())
            info.setInnerNode(element());

        if(!info.innerNonSharedNode())
            info.setInnerNonSharedNode(element());
    }

    return inside;
}
예제 #15
0
template<class NodeVector> void FileSystem::debugPrintNodes(NodeVector nodes) {
    if( debug) {
        unsigned int ix;
        NodeInfo* node;

        for (ix = 0; ix < nodes.size(); ++ix) {
            node = nodes.at(ix);

            cout << "Node: " << node->getName()
                << "\t\tSize: " << node->getSize()
                << "\tModify: " << node->getModifyTime()
                << "\tPath: " << node->getPath()
                << "\tSimilars: ";
        
            vector<NodeInfo*>::iterator it;
            vector<NodeInfo*> nodes = node->getSimilar();
            for(it=nodes.begin(); it != nodes.end(); ++it) {
                cout << (*it)->getPath() << ", ";
            }

            cout << endl;
        }
    }

}
예제 #16
0
 void on_req_node_remove(const int fd)
 {
 	WNodeManager* nodeManager = WNodeManager::getInstance();

	char* req_buff;
	size_t req_len;
	int cl = w_recv(fd,req_buff);

	if(cl > 0)
	{
		NodeInfo req;
		if(!req.ParseFromArray(req_buff, cl))
		{
			cerr<<"error when parse get request\n";
			//response.set_rspcode(REQ_FAILED);
			//response.set_errcode(ERR_INVALID_PARAMS);
			//w_send_pb(fd, &response);
			return;
		}

		cout<<"client addr is "<<req.nodeaddr()<<",port is "<<req.nodeport()<<endl;
		
		nodeManager->removeNode(req.nodeaddr(), req.nodeport());
		cout<<"node remove ok"<<endl;
	}
	else
	{
		cout<<"can not get node info\n";
	}
 }
예제 #17
0
bool RenderInline::nodeAtPoint(NodeInfo &info, int _x, int _y, int _tx, int _ty, HitTestAction hitTestAction, bool inside)
{
    /*
        if ( hitTestAction != HitTestSelfOnly ) {
            for (RenderObject* child = lastChild(); child; child = child->previousSibling())
                if (!child->layer() && !child->isFloating() && child->nodeAtPoint(info, _x, _y, _tx, _ty, HitTestAll))
                    inside = true;
        }
    */
    // Check our line boxes if we're still not inside.
    if(/*hitTestAction != HitTestChildrenOnly &&*/ !inside && style()->visibility() != HIDDEN)
    {
        // See if we're inside one of our line boxes.
        inside = hitTestLines(info, _x, _y, _tx, _ty, hitTestAction);
    }

    if(inside && element())
    {
        if(info.innerNode() && info.innerNode()->renderer() && !info.innerNode()->renderer()->isInline())
        {
            // Within the same layer, inlines are ALWAYS fully above blocks.  Change inner node.
            info.setInnerNode(element());

            // Clear everything else.
            info.setInnerNonSharedNode(0);
            info.setURLElement(0);
        }

        if(!info.innerNode())
            info.setInnerNode(element());

        if(!info.innerNonSharedNode())
            info.setInnerNonSharedNode(element());
    }

    return inside;
}
예제 #18
0
파일: Scheduler.cpp 프로젝트: 4m1g0/IOT_tfg
bool Scheduler::schedule(NodeInfo& nodeInfo)
{
  if (nodeInfo.getType() != NodeType::SCHEDULABLE)
    return 0;

  unsigned long now = Clock::getUnixTime();
  bool turnOff = true;

  if (nodeInfo.isOn())
  {
    for (auto &schedule : nodeInfo.schedules)
    {
      // If any schedule is still running don't turn off
      if (schedule.lastRun + schedule.duration > now)
        turnOff = false;
    }
  }

  if (!nodeInfo.isOn() || turnOff)
  {
    for (auto &schedule : nodeInfo.schedules)
    {
      if (schedule.designatedTime > schedule.lastRun
        && schedule.designatedTime <= now
        // we still have enough time to run it without overflowing the interval (with a 10m margin)
        && now + schedule.duration <= schedule.startTime + schedule.interval + 60*5)
      {
        schedule.lastRun = now;
        nodeInfo.on();
        turnOff = false;
      }
    }

    if (turnOff)
      nodeInfo.off();
  }
}
예제 #19
0
파일: SysWin32.cpp 프로젝트: peteware/path
/**
 * Gets the basic information about a file and returns
 * a new NodeInfo object (you must delete it).  Throws
 * a PathException if path cannot be accessed.
 *
 * @param path The path to look for
 * @return Newly created NodeInfo object.
 */
NodeInfo * SysWin32::stat(const std::string & path) const
{
#ifdef __WINNT__
    struct stat     statbuf;
    NodeInfo *node = 0;
    NodeInfo::Type type = NodeInfo::OTHER;

    if (::stat(path.c_str(), &statbuf) < 0)
        throw PathException(path, errno);
    node = new NodeInfo();

    node->setSize(statbuf.st_size);
    switch (statbuf.st_mode & S_IFMT) {
    case S_IFDIR:
        type = NodeInfo::DIRECTORY;
        break;
    case S_IFREG:
        type = NodeInfo::FILE;
        break;
    case S_IFLNK:
        type = NodeInfo::SYMLINK;
        break;
    case S_IFCHR:
    case S_IFBLK:
        type = NodeInfo::DEVICE;
        break;
    default:
        type = NodeInfo::OTHER;
        break;
    }
    node->setType(type);
    return node;
#else
    throw Unimplemented ("SysWin32::stat");
#endif
}
예제 #20
0
XnStatus GeneratorWatcher::UpdateFrameSync()
{
	// go over all nodes, and find the frame synced one
	Context context;
	m_generator.GetContext(context);
	
	NodeInfoList nodes;
	XnStatus nRetVal = context.EnumerateExistingNodes(nodes);
	XN_IS_STATUS_OK(nRetVal);

	for (NodeInfoList::Iterator it = nodes.Begin(); it != nodes.End(); ++it)
	{
		NodeInfo info = *it;
		// make sure this is a generator
		if (xnIsTypeDerivedFrom(info.GetDescription().Type, XN_NODE_TYPE_GENERATOR))
		{
			Generator otherGen;
			nRetVal = info.GetInstance(otherGen);
			XN_IS_STATUS_OK(nRetVal);

			if (m_generator.GetFrameSyncCap().IsFrameSyncedWith(otherGen))
			{
				nRetVal = NotifyStringPropChanged(XN_PROP_FRAME_SYNCED_WITH, otherGen.GetName());
				XN_IS_STATUS_OK(nRetVal);

				return XN_STATUS_OK;
			}
		}
	}

	// if we got here, we're not frame synced
	nRetVal = NotifyStringPropChanged(XN_PROP_FRAME_SYNCED_WITH, "");
	XN_IS_STATUS_OK(nRetVal);

	return XN_STATUS_OK;
}
예제 #21
0
void on_req_set(const int fd)
{
	//get req body
	char* req_buff;
	size_t rb_len = w_recv(fd, req_buff);
	if (!rb_len > 0)
	{
		cerr<<"connection error\n";
		return;
	}

	ReqSet reqSet;
	if(!reqSet.ParseFromArray(req_buff, rb_len))
	{
		cerr<<"error when parse get request\n";
		return;
	}

	WNode* node = WNodeManager::getInstance()->dispatchRequest(reqSet.md5());

	NodeInfo ninfo;
	if(node != NULL)
	{
		ninfo.set_nodeaddr(node->nodeIP);
		ninfo.set_nodeport(node->nodePort);
	}
	else
	{
		ninfo.set_nodeaddr("-1");
		ninfo.set_nodeport(-1);
	}
	
	int sl = w_send_pb(fd, &ninfo);

	delete req_buff;
}
예제 #22
0
int parse_ipport(const char * pcStr, NodeInfo & oNodeInfo)
{
    char sIP[32] = {0};
    int iPort = -1;

    int count = sscanf(pcStr, "%[^':']:%d", sIP, &iPort);
    if (count != 2)
    {
        return -1;
    }

    oNodeInfo.SetIPPort(sIP, iPort);

    return 0;
}
예제 #23
0
bool RenderImage::nodeAtPoint(NodeInfo& info, int _x, int _y, int _tx, int _ty,
                              HitTestAction hitTestAction, bool inside)
{
    inside |= RenderReplaced::nodeAtPoint(info, _x, _y, _tx, _ty, hitTestAction, inside);

    if (inside && element()) {
        int tx = _tx + m_x;
        int ty = _ty + m_y;
        
        HTMLMapElementImpl* map = imageMap();
        if (map) {
            // we're a client side image map
            inside = map->mapMouseEvent(_x - tx, _y - ty, contentWidth(), contentHeight(), info);
            info.setInnerNonSharedNode(element());
        }
    }

    return inside;
}
예제 #24
0
bool RenderImage::nodeAtPoint(NodeInfo& info, int _x, int _y, int _tx, int _ty, HitTestAction hitTestAction, bool inside)
{
    inside |= RenderReplaced::nodeAtPoint(info, _x, _y, _tx, _ty, hitTestAction, inside);

    if (inside && element()) {
        int tx = _tx + m_x;
        int ty = _ty + m_y;

        HTMLImageElementImpl* i = element()->id() == ID_IMG ? static_cast<HTMLImageElementImpl*>(element()) : 0;
        HTMLMapElementImpl* map;
        if (i && i->document()->isHTMLDocument() &&
            (map = static_cast<HTMLDocumentImpl*>(i->document())->getMap(i->imageMap()))) {
            // we're a client side image map
            inside = map->mapMouseEvent(_x - tx, _y - ty, contentWidth(), contentHeight(), info);
            info.setInnerNonSharedNode(element());
        }
    }

    return inside;
}
예제 #25
0
파일: pnode.cpp 프로젝트: chaozh/phxpaxos
int PNode :: RemoveMember(const int iGroupIdx, const NodeInfo & oNode)
{
    if (!CheckGroupID(iGroupIdx))
    {
        return Paxos_GroupIdxWrong;
    }

    SystemVSM * poSystemVSM = m_vecGroupList[iGroupIdx]->GetConfig()->GetSystemVSM();

    if (poSystemVSM->GetGid() == 0)
    {
        return Paxos_MembershipOp_NoGid;
    }

    uint64_t llVersion = 0;
    NodeInfoList vecNodeInfoList;
    poSystemVSM->GetMembership(vecNodeInfoList, llVersion);

    bool bNodeExist = false;
    NodeInfoList vecAfterNodeInfoList;
    for (auto & oNodeInfo : vecNodeInfoList)
    {
        if (oNodeInfo.GetNodeID() == oNode.GetNodeID())
        {
            bNodeExist = true;
        }
        else
        {
            vecAfterNodeInfoList.push_back(oNodeInfo);
        }
    }

    if (!bNodeExist)
    {
        return Paxos_MembershipOp_Remove_NodeNotExist;
    }

    return ProposalMembership(poSystemVSM, iGroupIdx, vecAfterNodeInfoList, llVersion);
}
예제 #26
0
파일: config.cpp 프로젝트: chaozh/phxpaxos
Config :: Config(
        const LogStorage * poLogStorage,
        const bool bLogSync,
        const int iSyncInterval,
        const bool bUseMembership,
        const NodeInfo & oMyNode, 
        const NodeInfoList & vecNodeInfoList,
        const FollowerNodeInfoList & vecFollowerNodeInfoList,
        const int iMyGroupIdx,
        const int iGroupCount,
        MembershipChangeCallback pMembershipChangeCallback)
    : m_bLogSync(bLogSync), 
    m_iSyncInterval(iSyncInterval),
    m_bUseMembership(bUseMembership),
    m_iMyNodeID(oMyNode.GetNodeID()), 
    m_iNodeCount(vecNodeInfoList.size()), 
    m_iMyGroupIdx(iMyGroupIdx),
    m_iGroupCount(iGroupCount),
    m_oSystemVSM(iMyGroupIdx, oMyNode.GetNodeID(), poLogStorage, pMembershipChangeCallback),
    m_poMasterSM(nullptr)
{
    m_vecNodeInfoList = vecNodeInfoList;

    m_bIsIMFollower = false;
    m_iFollowToNodeID = nullnode;

    for (auto & oFollowerNodeInfo : vecFollowerNodeInfoList)
    {
        if (oFollowerNodeInfo.oMyNode.GetNodeID() == oMyNode.GetNodeID())
        {
            PLG1Head("I'm follower, ip %s port %d nodeid %lu",
                    oMyNode.GetIP().c_str(), oMyNode.GetPort(), oMyNode.GetNodeID());
            m_bIsIMFollower = true;
            m_iFollowToNodeID = oFollowerNodeInfo.oFollowNode.GetNodeID();

            InsideOptions::Instance()->SetAsFollower();
        }
    }
}
예제 #27
0
// ****************************************************************************
// Function: RunBenchmark
//
// Purpose: 
//   Runs the stablity test. The algorithm for the parallel
//   version of the test, which enables testing of an entire GPU
//   cluster at the same time, is as follows. Each participating node
//   first allocates its data, while node zero additionally determines
//   start and finish times based on a user input parameter. All nodes
//   then enter the outermost loop, copying fresh data from the CPU
//   before entering the core of the test. In the core, each node
//   performs a loop consisting of the forward kernel, a potential
//   check, and then the inverse kernel. After performing a configurable
//   number of forward/inverse iterations, along with a configurable
//   number of checks, each node sends the number of failures it
//   encountered to node zero. Node zero collects and reports the error
//   counts, determines whether the test has run its course, and
//   broadcasts the decision. If the decision is to proceed, each node
//   begins the next iteration of the outer loop, copying fresh data and
//   then performing the kernels and checks of the core loop.
//
// Arguments:
//   resultDB: the benchmark stores its results in this ResultDatabase
//   op: the options parser / parameter database
//
// Returns:  nothing
//
// Programmer: Collin McCurdy
// Creation: September 08, 2009
//
// Modifications:
//
// ****************************************************************************
void RunBenchmark(ResultDatabase &resultDB, OptionParser& op)
{	
    int mpi_rank, mpi_size, node_rank;
    int i, j;
    float2* source, * result;
    void* work, * chk;

#ifdef PARALLEL
    MPI_Comm_size(MPI_COMM_WORLD, &mpi_size);
    MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank);

    NodeInfo NI;
    node_rank = NI.nodeRank();

    cout << "MPI Task " << mpi_rank << " of " << mpi_size 
         << " (noderank=" << node_rank << ") starting....\n";
#else
    mpi_rank = 0;
    mpi_size = 1;
    node_rank = 0;
#endif
   
    // ensure chk buffer alloc succeeds before grabbing the
    // rest of available memory.
    allocDeviceBuffer(&chk, 1);
    unsigned long avail_bytes = findAvailBytes();
    // unsigned long avail_bytes = 1024*1024*1024-1;
    
    // now determine how much available memory will be used (subject
    // to CUDA's constraint on the maximum block dimension size)
    int blocks = avail_bytes / (512*sizeof(float2));
    int slices = 1;
    while (blocks/slices > 65535) {
        slices *= 2;
    }
    int half_n_ffts = ((blocks/slices)*slices)/2;
    int n_ffts = half_n_ffts * 2;
    fprintf(stderr, "avail_bytes=%ld, blocks=%d, n_ffts=%d\n", 
            avail_bytes, blocks, n_ffts);

    int half_n_cmplx = half_n_ffts * 512;
    unsigned long used_bytes = half_n_cmplx * 2 * sizeof(float2);

    cout << mpi_rank << ": testing " 
         << used_bytes/((double)1024*1024) << " MBs\n";

    // allocate host memory
    source = (float2*)malloc(used_bytes);
    result = (float2*)malloc(used_bytes);

    // alloc device memory
    allocDeviceBuffer(&work, used_bytes);

    // alloc gather buffer
    int* recvbuf = (int*)malloc(mpi_size*sizeof(int));
    
    // compute start and finish times
    time_t start = time(NULL);
    time_t finish = start + (time_t)(op.getOptionInt("time")*60);
    struct tm start_tm, finish_tm;
    localtime_r(&start, &start_tm);
    localtime_r(&finish, &finish_tm);
    if (mpi_rank == 0) {
        printf("start = %s", asctime(&start_tm));
        printf("finish = %s", asctime(&finish_tm));
    }
    
    for (int iter = 0; ; iter++) {
        bool failed = false;
        int errorCount = 0, stop = 0;

        // (re-)init host memory...
        for (i = 0; i < half_n_cmplx; i++) {
            source[i].x = (rand()/(float)RAND_MAX)*2-1;
            source[i].y = (rand()/(float)RAND_MAX)*2-1;
            source[i+half_n_cmplx].x = source[i].x;
            source[i+half_n_cmplx].y = source[i].y;
        }

        // copy to device
        copyToDevice(work, source, used_bytes);
        copyToDevice(chk, &errorCount, 1);

        forward(work, n_ffts);
        if (check(work, chk, half_n_ffts, half_n_cmplx)) {
            fprintf(stderr, "First check failed...");
            failed = true;
        }

        if (!failed) {
            for (i = 1; i <= CHECKS; i++) {
                for (j = 1; j <= ITERS_PER_CHECK; j++) {
                    inverse(work, n_ffts);
                    forward(work, n_ffts);
                }

                if (check(work, chk, half_n_ffts, half_n_cmplx)) {
                    failed = true;
                    break;
                }
            }
        }

        // failing node is responsible for verifying failure, counting
        // errors and reporting count to node 0.
        if (failed) {
            fprintf(stderr, "Failure on node %d, iter %d:", mpi_rank, iter);
            
            // repeat check on CPU
            copyFromDevice(result, work, used_bytes);
            float2* result2 = result + half_n_cmplx;
            for (j = 0; j < half_n_cmplx; j++) {
                if (result[j].x != result2[j].x || 
                    result[j].y != result2[j].y) 
                {
                    errorCount++;
                }
            }
            if (!errorCount) {
                fprintf(stderr, "verification failed!\n");
            }
            else {
                fprintf(stderr, "%d errors\n", errorCount);
            }
        }

#ifdef PARALLEL
        MPI_Gather(&errorCount, 1, MPI_INT, recvbuf, 1, MPI_INT, 
                   0, MPI_COMM_WORLD);
#else
        recvbuf[0] = errorCount;
#endif

        // node 0 collects and reports error counts, determines
        // whether test has run its course, and broadcasts decision
        if (mpi_rank == 0) {
            time_t curtime = time(NULL);
            struct tm curtm;
            localtime_r(&curtime, &curtm);
            fprintf(stderr, "iter=%d: %s", iter, asctime(&curtm));
            
            for (i = 0; i < mpi_size; i++) {
                if (recvbuf[i]) {
                    fprintf(stderr, "--> %d failures on node %d\n", recvbuf[i], i);
                }
            }

            if (curtime > finish) {
                stop = 1;
            }
        }
        
#ifdef PARALLEL
        MPI_Bcast(&stop, 1, MPI_INT, 0, MPI_COMM_WORLD);
#endif

        resultDB.AddResult("Check", "", "Failures", errorCount);
        if (stop) break;
    }
    
    freeDeviceBuffer(work);
    freeDeviceBuffer(chk);

    free(source);
    free(result);
    free(recvbuf);
}
예제 #28
0
파일: main.cpp 프로젝트: ManavA/shoc
// ****************************************************************************
// Method:  main()
//
// Purpose:
//   serial and parallel main for OpenCL level0 benchmarks
//
// Arguments:
//   argc, argv
//
// Programmer:  SHOC Team
// Creation:    The Epoch
//
// Modifications:
//   Jeremy Meredith, Tue Jan 12 15:09:33 EST 2010
//   Changed the way device selection works.  It now defaults to the device
//   index corresponding to the process's rank within a node if no devices
//   are specified on the command command line, and otherwise, round-robins
//   the list of devices among the tasks.
//
//   Gabriel Marin, Tue Jun 01 15:38 EST 2010
//   Check that we have valid (not NULL) context and queue objects before
//   running the benchmarks. Errors inside CreateContextFromSingleDevice or
//   CreateCommandQueueForContextAndDevice were not propagated out to the main
//   program.
//
//   Jeremy Meredith, Wed Nov 10 14:20:47 EST 2010
//   Split timing reports into detailed and summary.  For serial code, we
//   report all trial values, and for parallel, skip the per-process vals.
//   Also detect and print outliers from parallel runs.
//
// ****************************************************************************
int main(int argc, char *argv[])
{
    int ret = 0;

    try
    {
#ifdef PARALLEL
        int rank, size;
        MPI_Init(&argc,&argv);
        MPI_Comm_size(MPI_COMM_WORLD, &size);
        MPI_Comm_rank(MPI_COMM_WORLD, &rank);
        cout << "MPI Task "<< rank << "/" << size - 1 << " starting....\n";
#endif

        OptionParser op;

        //Add shared options to the parser
        op.addOption("platform", OPT_INT, "0", "specify OpenCL platform to use",
                'p');
        op.addOption("device", OPT_VECINT, "", "specify device(s) to run on", 'd');
        op.addOption("passes", OPT_INT, "10", "specify number of passes", 'n');
        op.addOption("size", OPT_VECINT, "1", "specify problem size", 's');
        op.addOption("infoDevices", OPT_BOOL, "",
                "show info for available platforms and devices", 'i');
        op.addOption("verbose", OPT_BOOL, "", "enable verbose output", 'v');
        op.addOption("quiet", OPT_BOOL, "", "write minimum necessary to standard output", 'q');

        addBenchmarkSpecOptions(op);

        if (!op.parse(argc, argv))
        {
#ifdef PARALLEL
            if (rank == 0)
                op.usage();
            MPI_Finalize();
#else
            op.usage();
#endif
            return (op.HelpRequested() ? 0 : 1 );
        }

        if (op.getOptionBool("infoDevices"))
        {
#define DEBUG_DEVICE_CONTAINER 0
#ifdef PARALLEL
            // execute following code only if I am the process of lowest
            // rank on this node
            NodeInfo NI;
            int mynoderank = NI.nodeRank();
            if (mynoderank==0)
            {
                int nlrrank, nlrsize;
                MPI_Comm nlrcomm = NI.getNLRComm();
                MPI_Comm_size(nlrcomm, &nlrsize);
                MPI_Comm_rank(nlrcomm, &nlrrank);

                OpenCLNodePlatformContainer ndc1;
                OpenCLMultiNodeContainer localMnc(ndc1);
                localMnc.doMerge (nlrrank, nlrsize, nlrcomm);
                if (rank==0)  // I am the global rank 0, print all configurations
                    localMnc.Print (cout);
            }
#else
            OpenCLNodePlatformContainer ndc1;
            ndc1.Print (cout);
#if DEBUG_DEVICE_CONTAINER
            OpenCLMultiNodeContainer mnc1(ndc1), mnc2;
            mnc1.Print (cout);
            ostringstream oss;
            mnc1.writeObject (oss);
            std::string temp(oss.str());
            cout << "Serialized MultiNodeContainer:\n" << temp;
            istringstream iss(temp);
            mnc2.readObject (iss);
            cout << "Unserialized object2:\n";
            mnc2.Print (cout);
            mnc1.merge (mnc2);
            cout << "==============\nObject1 after merging 1:\n";
            mnc1.Print (cout);
            mnc1.merge (mnc2);
            cout << "==============\nObject1 after merging 2:\n";
            mnc1.Print (cout);
#endif  // DEBUG
#endif  // PARALLEL
            return (0);
        }

        bool verbose = op.getOptionBool("verbose");

        // The device option supports specifying more than one device
        // for now, just choose the first one.
        int platform = op.getOptionInt("platform");

#ifdef PARALLEL
        NodeInfo ni;
        int myNodeRank = ni.nodeRank();
        if (verbose)
        cout << "Global rank "<<rank<<" is local rank "<<myNodeRank << endl;
#else
        int myNodeRank = 0;
#endif

        // If they haven't specified any devices, assume they
        // want the process with in-node rank N to use device N
        int deviceIdx = myNodeRank;

        // If they have, then round-robin the list of devices
        // among the processes on a node.
        vector<long long> deviceVec = op.getOptionVecInt("device");
        if (deviceVec.size() > 0)
        {
        int len = deviceVec.size();
            deviceIdx = deviceVec[myNodeRank % len];
        }

        // Check for an erroneous device
        if (deviceIdx >= GetNumOclDevices(platform)) {
            cerr << "Warning: device index: " << deviceIdx
                 << " out of range, defaulting to device 0.\n";
            deviceIdx = 0;
        }

        // Initialization
        if (verbose) cout << ">> initializing\n";
        cl_device_id devID = ListDevicesAndGetDevice(platform, deviceIdx);
        cl_int clErr;
        cl_context ctx = clCreateContext( NULL,     // properties
                                            1,      // number of devices
                                            &devID, // device
                                            NULL,   // notification function
                                            NULL,
                                            &clErr );
        CL_CHECK_ERROR(clErr);
        cl_command_queue queue = clCreateCommandQueue( ctx,
                                                        devID,
                                                        CL_QUEUE_PROFILING_ENABLE,
                                                        &clErr );
        CL_CHECK_ERROR(clErr);
        ResultDatabase resultDB;

        // Run the benchmark
        RunBenchmark(devID, ctx, queue, resultDB, op);

        clReleaseCommandQueue( queue );
        clReleaseContext( ctx );


#ifndef PARALLEL
        resultDB.DumpDetailed(cout);
#else
        ParallelResultDatabase pardb;
        pardb.MergeSerialDatabases(resultDB,MPI_COMM_WORLD);
        if (rank==0)
        {
            pardb.DumpSummary(cout);
            pardb.DumpOutliers(cout);
        }
#endif
    }
    catch( std::exception& e )
    {
        std::cerr << e.what() << std::endl;
        ret = 1;
    }
    catch( ... )
    {
        std::cerr << "unrecognized exception caught" << std::endl;
        ret = 1;
    }

#ifdef PARALLEL
    MPI_Finalize();
#endif

    return ret;
}
예제 #29
0
/* static */
nsresult
nsNodeUtils::CloneAndAdopt(nsINode *aNode, bool aClone, bool aDeep,
                           nsNodeInfoManager *aNewNodeInfoManager,
                           JS::Handle<JSObject*> aReparentScope,
                           nsCOMArray<nsINode> &aNodesWithProperties,
                           nsINode *aParent, nsINode **aResult)
{
  NS_PRECONDITION((!aClone && aNewNodeInfoManager) || !aReparentScope,
                  "If cloning or not getting a new nodeinfo we shouldn't "
                  "rewrap");
  NS_PRECONDITION(!aParent || aNode->IsNodeOfType(nsINode::eCONTENT),
                  "Can't insert document or attribute nodes into a parent");

  *aResult = nullptr;

  // First deal with aNode and walk its attributes (and their children). Then,
  // if aDeep is true, deal with aNode's children (and recurse into their
  // attributes and children).

  nsAutoScriptBlocker scriptBlocker;
  AutoJSContext cx;
  nsresult rv;

  nsNodeInfoManager *nodeInfoManager = aNewNodeInfoManager;

  // aNode.
  NodeInfo *nodeInfo = aNode->mNodeInfo;
  RefPtr<NodeInfo> newNodeInfo;
  if (nodeInfoManager) {

    // Don't allow importing/adopting nodes from non-privileged "scriptable"
    // documents to "non-scriptable" documents.
    nsIDocument* newDoc = nodeInfoManager->GetDocument();
    NS_ENSURE_STATE(newDoc);
    bool hasHadScriptHandlingObject = false;
    if (!newDoc->GetScriptHandlingObject(hasHadScriptHandlingObject) &&
        !hasHadScriptHandlingObject) {
      nsIDocument* currentDoc = aNode->OwnerDoc();
      NS_ENSURE_STATE((nsContentUtils::IsChromeDoc(currentDoc) ||
                       (!currentDoc->GetScriptHandlingObject(hasHadScriptHandlingObject) &&
                        !hasHadScriptHandlingObject)));
    }

    newNodeInfo = nodeInfoManager->GetNodeInfo(nodeInfo->NameAtom(),
                                               nodeInfo->GetPrefixAtom(),
                                               nodeInfo->NamespaceID(),
                                               nodeInfo->NodeType(),
                                               nodeInfo->GetExtraName());

    nodeInfo = newNodeInfo;
  }

  Element *elem = aNode->IsElement() ? aNode->AsElement() : nullptr;

  nsCOMPtr<nsINode> clone;
  if (aClone) {
    rv = aNode->Clone(nodeInfo, getter_AddRefs(clone));
    NS_ENSURE_SUCCESS(rv, rv);

    if (clone->IsElement()) {
      // The cloned node may be a custom element that may require
      // enqueing created callback and prototype swizzling.
      Element* elem = clone->AsElement();
      if (nsContentUtils::IsCustomElementName(nodeInfo->NameAtom())) {
        elem->OwnerDoc()->SetupCustomElement(elem, nodeInfo->NamespaceID());
      } else {
        // Check if node may be custom element by type extension.
        // ex. <button is="x-button">
        nsAutoString extension;
        if (elem->GetAttr(kNameSpaceID_None, nsGkAtoms::is, extension) &&
            !extension.IsEmpty()) {
          elem->OwnerDoc()->SetupCustomElement(elem, nodeInfo->NamespaceID(),
                                               &extension);
        }
      }
    }

    if (aParent) {
      // If we're cloning we need to insert the cloned children into the cloned
      // parent.
      rv = aParent->AppendChildTo(static_cast<nsIContent*>(clone.get()),
                                  false);
      NS_ENSURE_SUCCESS(rv, rv);
    }
    else if (aDeep && clone->IsNodeOfType(nsINode::eDOCUMENT)) {
      // After cloning the document itself, we want to clone the children into
      // the cloned document (somewhat like cloning and importing them into the
      // cloned document).
      nodeInfoManager = clone->mNodeInfo->NodeInfoManager();
    }
  }
  else if (nodeInfoManager) {
    nsIDocument* oldDoc = aNode->OwnerDoc();
    bool wasRegistered = false;
    if (aNode->IsElement()) {
      Element* element = aNode->AsElement();
      oldDoc->ClearBoxObjectFor(element);
      wasRegistered = oldDoc->UnregisterActivityObserver(element);
    }

    aNode->mNodeInfo.swap(newNodeInfo);
    if (elem) {
      elem->NodeInfoChanged(newNodeInfo);
    }

    nsIDocument* newDoc = aNode->OwnerDoc();
    if (newDoc) {
      // XXX what if oldDoc is null, we don't know if this should be
      // registered or not! Can that really happen?
      if (wasRegistered) {
        newDoc->RegisterActivityObserver(aNode->AsElement());
      }

      nsPIDOMWindow* window = newDoc->GetInnerWindow();
      if (window) {
        EventListenerManager* elm = aNode->GetExistingListenerManager();
        if (elm) {
          window->SetMutationListeners(elm->MutationListenerBits());
          if (elm->MayHavePaintEventListener()) {
            window->SetHasPaintEventListeners();
          }
          if (elm->MayHaveTouchEventListener()) {
            window->SetHasTouchEventListeners();
          }
          if (elm->MayHaveMouseEnterLeaveEventListener()) {
            window->SetHasMouseEnterLeaveEventListeners();
          }
          if (elm->MayHavePointerEnterLeaveEventListener()) {
            window->SetHasPointerEnterLeaveEventListeners();
          }
        }
      }
    }

    if (wasRegistered && oldDoc != newDoc) {
      nsCOMPtr<nsIDOMHTMLMediaElement> domMediaElem(do_QueryInterface(aNode));
      if (domMediaElem) {
        HTMLMediaElement* mediaElem = static_cast<HTMLMediaElement*>(aNode);
        mediaElem->NotifyOwnerDocumentActivityChanged();
      }
      nsCOMPtr<nsIObjectLoadingContent> objectLoadingContent(do_QueryInterface(aNode));
      if (objectLoadingContent) {
        nsObjectLoadingContent* olc = static_cast<nsObjectLoadingContent*>(objectLoadingContent.get());
        olc->NotifyOwnerDocumentActivityChanged();
      }
    }

    if (oldDoc != newDoc && oldDoc->MayHaveDOMMutationObservers()) {
      newDoc->SetMayHaveDOMMutationObservers();
    }

    if (oldDoc != newDoc && oldDoc->MayHaveAnimationObservers()) {
      newDoc->SetMayHaveAnimationObservers();
    }

    if (elem) {
      elem->RecompileScriptEventListeners();
    }

    if (aReparentScope) {
      JS::Rooted<JSObject*> wrapper(cx);
      if ((wrapper = aNode->GetWrapper())) {
        MOZ_ASSERT(IsDOMObject(wrapper));
        JSAutoCompartment ac(cx, wrapper);
        rv = ReparentWrapper(cx, wrapper);
        if (NS_FAILED(rv)) {
          aNode->mNodeInfo.swap(nodeInfo);

          return rv;
        }
      }
    }
  }

  if (aDeep && (!aClone || !aNode->IsNodeOfType(nsINode::eATTRIBUTE))) {
    // aNode's children.
    for (nsIContent* cloneChild = aNode->GetFirstChild();
         cloneChild;
         cloneChild = cloneChild->GetNextSibling()) {
      nsCOMPtr<nsINode> child;
      rv = CloneAndAdopt(cloneChild, aClone, true, nodeInfoManager,
                         aReparentScope, aNodesWithProperties, clone,
                         getter_AddRefs(child));
      NS_ENSURE_SUCCESS(rv, rv);
    }
  }

  // Cloning template element.
  if (aDeep && aClone && IsTemplateElement(aNode)) {
    DocumentFragment* origContent =
      static_cast<HTMLTemplateElement*>(aNode)->Content();
    DocumentFragment* cloneContent =
      static_cast<HTMLTemplateElement*>(clone.get())->Content();

    // Clone the children into the clone's template content owner
    // document's nodeinfo manager.
    nsNodeInfoManager* ownerNodeInfoManager =
      cloneContent->mNodeInfo->NodeInfoManager();

    for (nsIContent* cloneChild = origContent->GetFirstChild();
         cloneChild;
         cloneChild = cloneChild->GetNextSibling()) {
      nsCOMPtr<nsINode> child;
      rv = CloneAndAdopt(cloneChild, aClone, aDeep, ownerNodeInfoManager,
                         aReparentScope, aNodesWithProperties, cloneContent,
                         getter_AddRefs(child));
      NS_ENSURE_SUCCESS(rv, rv);
    }
  }

  // XXX setting document on some nodes not in a document so XBL will bind
  // and chrome won't break. Make XBL bind to document-less nodes!
  // XXXbz Once this is fixed, fix up the asserts in all implementations of
  // BindToTree to assert what they would like to assert, and fix the
  // ChangeDocumentFor() call in nsXULElement::BindToTree as well.  Also,
  // remove the UnbindFromTree call in ~nsXULElement, and add back in the
  // precondition in nsXULElement::UnbindFromTree and remove the line in
  // nsXULElement.h that makes nsNodeUtils a friend of nsXULElement.
  // Note: Make sure to do this witchery _after_ we've done any deep
  // cloning, so kids of the new node aren't confused about whether they're
  // in a document.
#ifdef MOZ_XUL
  if (aClone && !aParent && aNode->IsXULElement()) {
    if (!aNode->OwnerDoc()->IsLoadedAsInteractiveData()) {
      clone->SetFlags(NODE_FORCE_XBL_BINDINGS);
    }
  }
#endif

  if (aNode->HasProperties()) {
    bool ok = aNodesWithProperties.AppendObject(aNode);
    if (aClone) {
      ok = ok && aNodesWithProperties.AppendObject(clone);
    }

    NS_ENSURE_TRUE(ok, NS_ERROR_OUT_OF_MEMORY);
  }

  clone.forget(aResult);

  return NS_OK;
}
예제 #30
0
XnStatus openDeviceFromXmlWithChoice(const char* csXmlFile, EnumerationErrors& errors)
{
	XnStatus nRetVal = XN_STATUS_OK;

	xnLogInitFromXmlFile(csXmlFile);

	nRetVal = g_Context.Init();
	XN_IS_STATUS_OK(nRetVal);

	// find devices
	NodeInfoList list;
	nRetVal = g_Context.EnumerateProductionTrees(XN_NODE_TYPE_DEVICE, NULL, list, &errors);
	XN_IS_STATUS_OK(nRetVal);

	printf("The following devices were found:\n");
	int i = 1;
	for (NodeInfoList::Iterator it = list.Begin(); it != list.End(); ++it, ++i)
	{
		NodeInfo deviceNodeInfo = *it;

		Device deviceNode;
		deviceNodeInfo.GetInstance(deviceNode);
		XnBool bExists = deviceNode.IsValid();
		if (!bExists)
		{
			g_Context.CreateProductionTree(deviceNodeInfo, deviceNode);
			// this might fail.
		}

		if (deviceNode.IsValid() && deviceNode.IsCapabilitySupported(XN_CAPABILITY_DEVICE_IDENTIFICATION))
		{
			const XnUInt32 nStringBufferSize = 200;
			XnChar strDeviceName[nStringBufferSize];
			XnChar strSerialNumber[nStringBufferSize];

			XnUInt32 nLength = nStringBufferSize;
			deviceNode.GetIdentificationCap().GetDeviceName(strDeviceName, nLength);
			nLength = nStringBufferSize;
			deviceNode.GetIdentificationCap().GetSerialNumber(strSerialNumber, nLength);
			printf("[%d] %s (%s)\n", i, strDeviceName, strSerialNumber);
		}
		else
		{
			printf("[%d] %s\n", i, deviceNodeInfo.GetCreationInfo());
		}

		// release the device if we created it
		if (!bExists && deviceNode.IsValid())
		{
			deviceNode.Release();
		}
	}
	printf("\n");
	printf("Choose device to open (1): ");

	int chosen = 1;
	scanf("%d", &chosen);

	// create it
	NodeInfoList::Iterator it = list.Begin();
	for (i = 1; i < chosen; ++i)
	{
		it++;
	}

	NodeInfo deviceNode = *it;
	nRetVal = g_Context.CreateProductionTree(deviceNode, g_Device);
	XN_IS_STATUS_OK(nRetVal);

	// now run the rest of the XML
	nRetVal = g_Context.RunXmlScriptFromFile(csXmlFile, g_scriptNode, &errors);
	XN_IS_STATUS_OK(nRetVal);

	openCommon();

	return (XN_STATUS_OK);
}