inline custom_iterator_type custom_end() { return m_hidden_deque.end(); }
Beispiel #2
0
	inline const_iterator
	end() const { return data.end(); }
 inline custom_const_iterator_type custom_end() const { return m_hidden_deque.end(); }
 //vector<int> d_;
 // Adds a number into the data structure.
 void addNum(int num)
 {
     auto it = lower_bound(d_.begin(), d_.end(), num);
     d_.insert(it, num);
 }
Beispiel #5
0
	inline iterator
	end() { return data.end(); }
Beispiel #6
0
int main(int argc, const char* argv[]) {
    
    qInstallMessageHandler(Logging::verboseMessageHandler);
    
    NodeList* nodeList = NodeList::createInstance(NODE_TYPE_DOMAIN, DOMAIN_LISTEN_PORT);

    setvbuf(stdout, NULL, _IOLBF, 0);
    
    ssize_t receivedBytes = 0;
    char nodeType = '\0';
    
    unsigned char broadcastPacket[MAX_PACKET_SIZE];
    
    unsigned char* currentBufferPos;
    unsigned char* startPointer;
    
    sockaddr_in nodePublicAddress, nodeLocalAddress, replyDestinationSocket;
    nodeLocalAddress.sin_family = AF_INET;
    
    in_addr_t serverLocalAddress = getLocalAddress();
    
    nodeList->startSilentNodeRemovalThread();
    
    timeval lastStatSendTime = {};
    const char ASSIGNMENT_SERVER_OPTION[] = "-a";
    
    // grab the overriden assignment-server hostname from argv, if it exists
    const char* customAssignmentServer = getCmdOption(argc, argv, ASSIGNMENT_SERVER_OPTION);
    if (customAssignmentServer) {
        sockaddr_in customAssignmentSocket = socketForHostnameAndHostOrderPort(customAssignmentServer, ASSIGNMENT_SERVER_PORT);
        nodeList->setAssignmentServerSocket((sockaddr*) &customAssignmentSocket);
    }
    
    // use a map to keep track of iterations of silence for assignment creation requests
    const long long GLOBAL_ASSIGNMENT_REQUEST_INTERVAL_USECS = 1 * 1000 * 1000;
    timeval lastGlobalAssignmentRequest = {};
    
    // as a domain-server we will always want an audio mixer and avatar mixer
    // setup the create assignments for those
    Assignment audioMixerAssignment(Assignment::CreateCommand,
                                    Assignment::AudioMixerType,
                                    Assignment::LocalLocation);
    
    Assignment avatarMixerAssignment(Assignment::CreateCommand,
                                     Assignment::AvatarMixerType,
                                     Assignment::LocalLocation);
    
    // construct a local socket to send with our created assignments to the global AS
    sockaddr_in localSocket = {};
    localSocket.sin_family = AF_INET;
    localSocket.sin_port = htons(nodeList->getInstance()->getNodeSocket()->getListeningPort());
    localSocket.sin_addr.s_addr = serverLocalAddress;
    
    // setup the mongoose web server
    struct mg_context *ctx;
    struct mg_callbacks callbacks = {};
    
    // list of options. Last element must be NULL.
    const char *options[] = {"listening_ports", "8080",
                             "document_root", "./resources/web", NULL};
    
    callbacks.begin_request = mongooseRequestHandler;
    callbacks.upload = mongooseUploadHandler;
    
    // Start the web server.
    ctx = mg_start(&callbacks, NULL, options);
    
    while (true) {
        
        ::assignmentQueueMutex.lock();
        // check if our audio-mixer or avatar-mixer are dead and we don't have existing assignments in the queue
        // so we can add those assignments back to the front of the queue since they are high-priority
        if (!nodeList->soloNodeOfType(NODE_TYPE_AVATAR_MIXER) &&
            std::find(::assignmentQueue.begin(), assignmentQueue.end(), &avatarMixerAssignment) == ::assignmentQueue.end()) {
            qDebug("Missing an avatar mixer and assignment not in queue. Adding.\n");
            ::assignmentQueue.push_front(&avatarMixerAssignment);
        }
        
        if (!nodeList->soloNodeOfType(NODE_TYPE_AUDIO_MIXER) &&
            std::find(::assignmentQueue.begin(), ::assignmentQueue.end(), &audioMixerAssignment) == ::assignmentQueue.end()) {
            qDebug("Missing an audio mixer and assignment not in queue. Adding.\n");
            ::assignmentQueue.push_front(&audioMixerAssignment);
        }
        ::assignmentQueueMutex.unlock();
        
        while (nodeList->getNodeSocket()->receive((sockaddr *)&nodePublicAddress, packetData, &receivedBytes) &&
               packetVersionMatch(packetData)) {
            if (packetData[0] == PACKET_TYPE_DOMAIN_REPORT_FOR_DUTY || packetData[0] == PACKET_TYPE_DOMAIN_LIST_REQUEST) {
                // this is an RFD or domain list request packet, and there is a version match
                std::map<char, Node *> newestSoloNodes;
                
                int numBytesSenderHeader = numBytesForPacketHeader(packetData);
                
                nodeType = *(packetData + numBytesSenderHeader);
                int numBytesSocket = unpackSocket(packetData + numBytesSenderHeader + sizeof(NODE_TYPE),
                                                  (sockaddr*) &nodeLocalAddress);
                
                replyDestinationSocket = nodePublicAddress;
                
                // check the node public address
                // if it matches our local address
                // or if it's the loopback address we're on the same box
                if (nodePublicAddress.sin_addr.s_addr == serverLocalAddress ||
                    nodePublicAddress.sin_addr.s_addr == htonl(INADDR_LOOPBACK)) {
                    
                    nodePublicAddress.sin_addr.s_addr = 0;
                }
                
                Node* newNode = nodeList->addOrUpdateNode((sockaddr*) &nodePublicAddress,
                                                          (sockaddr*) &nodeLocalAddress,
                                                          nodeType,
                                                          nodeList->getLastNodeID());
                
                // if addOrUpdateNode returns NULL this was a solo node we already have, don't talk back to it
                if (newNode) {
                    if (newNode->getNodeID() == nodeList->getLastNodeID()) {
                        nodeList->increaseNodeID();
                    }
                    
                    int numHeaderBytes = populateTypeAndVersion(broadcastPacket, PACKET_TYPE_DOMAIN);
                    
                    currentBufferPos = broadcastPacket + numHeaderBytes;
                    startPointer = currentBufferPos;
                    
                    unsigned char* nodeTypesOfInterest = packetData + numBytesSenderHeader + sizeof(NODE_TYPE)
                    + numBytesSocket + sizeof(unsigned char);
                    int numInterestTypes = *(nodeTypesOfInterest - 1);
                    
                    if (numInterestTypes > 0) {
                        // if the node has sent no types of interest, assume they want nothing but their own ID back
                        for (NodeList::iterator node = nodeList->begin(); node != nodeList->end(); node++) {
                            if (!node->matches((sockaddr*) &nodePublicAddress, (sockaddr*) &nodeLocalAddress, nodeType) &&
                                memchr(nodeTypesOfInterest, node->getType(), numInterestTypes)) {
                                // this is not the node themselves
                                // and this is an node of a type in the passed node types of interest
                                // or the node did not pass us any specific types they are interested in
                                
                                if (memchr(SOLO_NODE_TYPES, node->getType(), sizeof(SOLO_NODE_TYPES)) == NULL) {
                                    // this is an node of which there can be multiple, just add them to the packet
                                    // don't send avatar nodes to other avatars, that will come from avatar mixer
                                    if (nodeType != NODE_TYPE_AGENT || node->getType() != NODE_TYPE_AGENT) {
                                        currentBufferPos = addNodeToBroadcastPacket(currentBufferPos, &(*node));
                                    }
                                    
                                } else {
                                    // solo node, we need to only send newest
                                    if (newestSoloNodes[node->getType()] == NULL ||
                                        newestSoloNodes[node->getType()]->getWakeMicrostamp() < node->getWakeMicrostamp()) {
                                        // we have to set the newer solo node to add it to the broadcast later
                                        newestSoloNodes[node->getType()] = &(*node);
                                    }
                                }
                            }
                        }
                        
                        for (std::map<char, Node *>::iterator soloNode = newestSoloNodes.begin();
                             soloNode != newestSoloNodes.end();
                             soloNode++) {
                            // this is the newest alive solo node, add them to the packet
                            currentBufferPos = addNodeToBroadcastPacket(currentBufferPos, soloNode->second);
                        }
                    }
                    
                    // update last receive to now
                    uint64_t timeNow = usecTimestampNow();
                    newNode->setLastHeardMicrostamp(timeNow);
                    
                    if (packetData[0] == PACKET_TYPE_DOMAIN_REPORT_FOR_DUTY
                        && memchr(SOLO_NODE_TYPES, nodeType, sizeof(SOLO_NODE_TYPES))) {
                        newNode->setWakeMicrostamp(timeNow);
                    }
                    
                    // add the node ID to the end of the pointer
                    currentBufferPos += packNodeId(currentBufferPos, newNode->getNodeID());
                    
                    // send the constructed list back to this node
                    nodeList->getNodeSocket()->send((sockaddr*)&replyDestinationSocket,
                                                    broadcastPacket,
                                                    (currentBufferPos - startPointer) + numHeaderBytes);
                }
            } else if (packetData[0] == PACKET_TYPE_REQUEST_ASSIGNMENT) {
                
                qDebug("Received a request for assignment.\n");
                
                ::assignmentQueueMutex.lock();
                
                // this is an unassigned client talking to us directly for an assignment
                // go through our queue and see if there are any assignments to give out
                std::deque<Assignment*>::iterator assignment = ::assignmentQueue.begin();
                
                while (assignment != ::assignmentQueue.end()) {
                    
                    // give this assignment out, no conditions stop us from giving it to the local assignment client
                    int numHeaderBytes = populateTypeAndVersion(broadcastPacket, PACKET_TYPE_CREATE_ASSIGNMENT);
                    int numAssignmentBytes = (*assignment)->packToBuffer(broadcastPacket + numHeaderBytes);
                    
                    nodeList->getNodeSocket()->send((sockaddr*) &nodePublicAddress,
                                                    broadcastPacket,
                                                    numHeaderBytes + numAssignmentBytes);
                    
                    // remove the assignment from the queue
                    ::assignmentQueue.erase(assignment);
                    
                    if ((*assignment)->getType() == Assignment::AgentType) {
                        // if this is a script assignment we need to delete it to avoid a memory leak
                        delete *assignment;
                    }
                    
                    // stop looping, we've handed out an assignment
                    break;
                }
                
                ::assignmentQueueMutex.unlock();
            }
        }
        
        // if ASSIGNMENT_REQUEST_INTERVAL_USECS have passed since last global assignment request then fire off another
        if (usecTimestampNow() - usecTimestamp(&lastGlobalAssignmentRequest) >= GLOBAL_ASSIGNMENT_REQUEST_INTERVAL_USECS) {
            gettimeofday(&lastGlobalAssignmentRequest, NULL);
            
            ::assignmentQueueMutex.lock();
            
            // go through our queue and see if there are any assignments to send to the global assignment server
            std::deque<Assignment*>::iterator assignment = ::assignmentQueue.begin();
            
            while (assignment != assignmentQueue.end()) {
                
                if ((*assignment)->getLocation() != Assignment::LocalLocation) {                    
                    // attach our local socket to the assignment so the assignment-server can optionally hand it out
                    (*assignment)->setAttachedLocalSocket((sockaddr*) &localSocket);
                    
                    nodeList->sendAssignment(*(*assignment));
                    
                    // remove the assignment from the queue
                    ::assignmentQueue.erase(assignment);
                    
                    if ((*assignment)->getType() == Assignment::AgentType) {
                        // if this is a script assignment we need to delete it to avoid a memory leak
                        delete *assignment;
                    }
                    
                    // stop looping, we've handed out an assignment
                    break;
                } else {
                    // push forward the iterator to check the next assignment
                    assignment++;
                }
            }
            
            ::assignmentQueueMutex.unlock();
        }
        
        if (Logging::shouldSendStats()) {
            if (usecTimestampNow() - usecTimestamp(&lastStatSendTime) >= (NODE_COUNT_STAT_INTERVAL_MSECS * 1000)) {
                // time to send our count of nodes and servers to logstash
                const char NODE_COUNT_LOGSTASH_KEY[] = "ds-node-count";
                
                Logging::stashValue(STAT_TYPE_TIMER, NODE_COUNT_LOGSTASH_KEY, nodeList->getNumAliveNodes());
                
                gettimeofday(&lastStatSendTime, NULL);
            }
        }
    }

    return 0;
}
Beispiel #7
0
void
Soup::set (const  std::deque<Eigen::Vector3f>& pos) {
        this->_pos.clear();
        this->_pos.insert( this->_pos.end(), pos.begin(), pos.end());
        return;
}
void generate_outliers(const std::vector<std::string>& word_list, std::deque<std::string>& outliers)
{
   std::cout << "Generating outliers..... ";
   for (std::vector<std::string>::const_iterator it = word_list.begin(); it != word_list.end(); ++it)
   {
      if ((*it) != reverse((*it)))
      {
         outliers.push_back((*it) + reverse((*it)));
         outliers.push_back((*it) + (*it));
         outliers.push_back(reverse((*it)) + (*it) + reverse((*it)));
      }

      std::string ns = *it;
      for (unsigned int i = 0; i < ns.size(); ++i)
      {
         if (1 == (i & 0x00)) ns[i] = ~ns[i];
      }

      outliers.push_back(ns);
   }

   static const std::string rand_str[] =
                  {
                     "oD5l", "pccW", "5yHt", "ndaN", "OaJh", "tWPc", "Cr9C", "a9zE",
                     "H1wL", "yo1V", "16D7", "f2WR", "0MVQ", "PkKn", "PlVa", "MvzL",
                     "9Csl", "JQTv", "IveD", "FDVS", "Q7HE", "QgcF", "Q9Vo", "V8zJ",
                     "EJWT", "GuLC", "rM3d", "PJF4", "HXPW", "qKx3", "ztRP", "t4KP",
                     "m1zV", "fn12", "B1QP", "Jr4I", "Mf8M", "4jBd", "anGR", "Pipt",
                     "QHon", "GNlc", "UeXM", "mVM5", "ABI8", "RhB3", "5h2s", "hOYo",
                     "gaId", "DX40", "THMu", "EwlP", "n9Mz", "oC1S", "BfMl", "uCZ1",
                     "G2bA", "MOH9", "zZ0O", "PKDO", "3nRU", "Z6ie", "4cso", "LnQO",
                     "MJTtT","td3rC","A5JNR","1yL5B","rQnJk","jNKYF","CD0XD","pFLSG",
                     "fxO1a","CAjBE","ORk4e","0LERI","R7d0x","Qqd7v","6Kih5","9tTCB",
                     "yCg9U","D2Tv7","XpNHn","6zeFQ","BT2cs","WGhKW","zTv6B","TTPFk",
                     "XjNVX","pg9yW","4pKiZ","mQUhL","xrXzR","kVRm5","NSyC4","olXm9",
                     "UWkYy","8Ys6r","yd4Fl","5L4mB","nP3nH","f0DFb","glnQa","DlXQa",
                     "cQdH6","eBmIN","fDj6F","ezLow","C15vu","I2Z2j","BQgzg","eVBid",
                     "hn5TO","WZyQN","xXgsE","sL6nK","8DKD8","jcrbp","AcRak","h8N5o",
                     "LViwC","ThEKf","O7fd5","oN0Id","OM1m0","4OLiR","VIa8N","bJZFG",
                     "9j3rL","SzW0N","7m7pY","mY9bg","k1p3e","3OFm1","r45se","VYwz3",
                     "pDjXt","ZcqcJ","npPHx","hA3bw","w7lSO","jEmZL","1x3AZ","FN47G",
                     "kThNf","aC4fq","rzDwi","CYRNG","gCeuG","wCVqO","d1R60","bEauW",
                     "KeUwW","lIKhO","RfPv3","dK5wE","1X7qu","tRwEn","1c03P","GwHCl",
                     "CsJaO","zl4j1","e0aEc","Uskgi","rgTGR","jyR4g","Tt6l4","lRoaw",
                     "94ult","qZwBX","eYW8S","Qf6UH","AbV56","N1hJq","JIaVe","8LHEx",
                     "DeNbS","30I0a","hm6qw","3jcaO","4WkuA","mQ219","Gb81C","yx4HM",
                     "Chlqfi9S1y", "BMwUgVFu2X", "ZmpEGOVrVe", "13ggJxrPkC", "fcJJpyMGjm", "9T00Dv4ZAb",
                     "p3YRcP7M2o", "sR0qNUXCHv", "gCxWZbJ6rb", "R4YtzRXXUl", "vwyYz5j6pY", "XPWUvLXhJ7",
                     "7PwfnVVb7U", "1f34Q6hOYz", "1EM2abZY61", "0a6Ivi4S0a", "Teq2LrQs2T", "dWXLCgWHc8",
                     "LawMv7ujn4", "N8VFgbZQx5", "tfvHHxoDgi", "ImwYgXA2tf", "KkIES9NqZO", "ajcz0qjjda",
                     "6Vz28vlGs9", "VMCc5W8cCt", "BiQB8BRJ98", "43CpOJSMpA", "jfBJdqwXcU", "ecHR9EO2ib",
                     "LH7CcXyCZ7", "JntqGSgSpa", "0MbTMpZPFW", "5FJSdiCXzR", "5gda2AhA2x", "lrDFc1lnXk",
                     "zrEwECHvjs", "B0JldDxFa1", "6DYal4QxKa", "Hsqx6kP2S4", "zZwnALSuFh", "Shh4ISZcKW",
                     "P9VDaNSk7Z", "mEI2PLSCO6", "WyTyrQORtu", "IvJyMMRgh3", "Q6pgJq8Nkv", "dhOgR3tDAD",
                     "Y9h6bVgbxO", "wA15tiOPTm", "8TaIKf1zCO", "z75dzabHBs", "AS6OPnwoJI", "2DSZka9Auj",
                     "QLzUjV2CWs", "KZSN2SVhia", "7ttYKWF2ue", "1Zxfu7B2ST", "RnkpmwjsCi", "YpcSIzaqx5",
                     "RDEwFD9gmX", "Nlx3V4Cjw4", "9ZdvITOj8M", "httUPWMNXO", "Ypv9PjxGwa", "LlwyNolNnH",
                     "6xpJOht47a", "tbmz4WIdcG", "OwzuVDlb7D", "PBQKJxo8DQ", "uVnMQn7hK6", "rlnZINuDUa",
                     "2feyyYukPa", "teOlpKuDBn", "LxBSWh0dL1", "Onyb7r4Jp0", "bZxXE6xOXg", "d9NSvNTunQ",
                     "ONerLBic32", "8mar4rKmFk", "5cCN9uwaCg", "ElVrYOHHMv", "YF6Og8DX40", "OgiCwpCQ5a",
                     "K6nSRZVxdR", "gqyXXXoVFW", "ulyRYizcBP", "khUx31K5UR", "qZFRzVthju", "pQBh0vnB20",
                     "dk8NIN7ajy", "XP7ed1OjZx", "IRYNwA5iFR", "hiSEBhTukC", "Ns4jJ3jzGo", "dYoCSxjIvM",
                     "HzGLbl5i1g", "baizENd4ko", "6rCqGBO8t1", "QWGfC8UaA7", "JFhRfxQe4K", "8R4W6IWANz",
                     "2TnWf1w7JH", "0z69e0wcoG", "8SN1mRHCY7", "oFGCYHHwGX", "G8xqnBgxjO", "6B3SAOayHt",
                     "XRW3ZSG1gw", "WcIjTxMxOM", "wNqCAIaTb2", "gO4em4HW8H", "TgGFSMEtbG", "WiwmbEw3QA",
                     "D2xshYUgpu", "xRUZCQVzBs", "nCnUmMgIjE", "p4Ewt1yCJr", "MeOjDcaMY5", "1XelMeXiiI"
                  };
   static const std::size_t rand_str_size = sizeof(rand_str) / sizeof(std::string);

   for (unsigned int i = 0; i < rand_str_size; ++i)
   {
      std::string s0 = rand_str[i];
      std::string s1 = rand_str[(i + 1) % rand_str_size];
      std::string s2 = rand_str[(i + 2) % rand_str_size];
      std::string s3 = rand_str[(i + 3) % rand_str_size];
      std::string s4 = rand_str[(i + 4) % rand_str_size];
      std::string s5 = rand_str[(i + 5) % rand_str_size];
      std::string s6 = rand_str[(i + 6) % rand_str_size];

      outliers.push_back(s0);
      outliers.push_back(s0 + s1);
      outliers.push_back(s0 + s2 + s4);
      outliers.push_back(s0 + s1 + s3);
      outliers.push_back(s0 + s1 + s2 + s3 + s4 + s5);
      outliers.push_back(s0 + s1 + s2 + s3 + s4 + s5 + s6);

      outliers.push_back(reverse(s0));
      outliers.push_back(reverse(s0 + s1));
      outliers.push_back(reverse(s0 + s2 + s4));
      outliers.push_back(reverse(s0 + s1 + s3));
      outliers.push_back(reverse(s0 + s1 + s2 + s3 + s4 + s5));
      outliers.push_back(reverse(s0 + s1 + s2 + s3 + s4 + s5 + s6));
   }
   std::sort(outliers.begin(),outliers.end());
   purify_outliers(word_list,outliers);
   std::cout << "Complete." << std::endl;
}
//
//  函数: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  目的:    处理主窗口的消息。
//
//  WM_COMMAND  - 处理应用程序菜单
//  WM_PAINT    - 绘制主窗口
//  WM_DESTROY  - 发送退出消息并返回
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
	case WM_CREATE:
	{
		LOGFONT LogFont, LogFont1;
		memset(&LogFont, 0, sizeof(LOGFONT));
		lstrcpy(LogFont.lfFaceName, L"Segoe UI Light");
		LogFont.lfWeight = FW_BLACK;//FW_NORMAL; 
		LogFont.lfCharSet = 134;
		LogFont.lfOutPrecision = 3;
		LogFont.lfClipPrecision = 2;
		LogFont.lfOrientation = 45;
		LogFont.lfHeight = -24;
		LogFont.lfQuality = ANTIALIASED_QUALITY| PROOF_QUALITY;
		LogFont.lfPitchAndFamily = 2;
		
		memset(&LogFont1, 0, sizeof(LOGFONT));
		lstrcpy(LogFont1.lfFaceName, L"Segoe UI");
		LogFont1.lfWeight = FW_NORMAL;//FW_NORMAL; 
		LogFont1.lfCharSet = 134;
		LogFont1.lfOutPrecision = 3;
		LogFont1.lfClipPrecision = 2;
		LogFont1.lfOrientation = 45;
		LogFont.lfHeight = -18;  
		LogFont1.lfQuality = ANTIALIASED_QUALITY| PROOF_QUALITY;
		LogFont1.lfPitchAndFamily = 2;
		HFONT hFont = CreateFontIndirect(&LogFont), hFont1 = CreateFontIndirect(&LogFont1);
		
		hButton = CreateWindow(L"Button", L"Draw.", WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON, 900, 600, 160, 65, hWnd, (HMENU)ID_Button1, hInst, NULL);
		hButtonC = CreateWindow(L"Button", L"Clear", WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON, 1070, 600, 160, 65, hWnd, (HMENU)ID_ButtonC, hInst, NULL);
		hButtonQ = CreateWindow(L"Button", L"Quit", WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON, 1240, 600, 160, 65, hWnd, (HMENU)ID_ButtonQ, hInst, NULL);
		hEditx1 = CreateWindow(L"Edit", L"", WS_VISIBLE | WS_CHILD | WS_BORDER, 800, 600, 80, 30, hWnd, (HMENU)ID_Edit, hInst, NULL);
		hEditx2 = CreateWindow(L"Edit", L"", WS_VISIBLE | WS_CHILD | WS_BORDER, 800, 635, 80, 30, hWnd, (HMENU)ID_Editx2, hInst, NULL);
		hEdity1 = CreateWindow(L"Edit", L"", WS_VISIBLE | WS_CHILD | WS_BORDER, 700, 600, 80, 30, hWnd, (HMENU)ID_Edity1, hInst, NULL);
		hEdity2 = CreateWindow(L"Edit", L"", WS_VISIBLE | WS_CHILD | WS_BORDER, 700, 635, 80, 30, hWnd, (HMENU)ID_Edity2, hInst, NULL);

		SendMessage(hButton, WM_SETFONT, (WPARAM)hFont, TRUE);
		SendMessage(hButtonQ, WM_SETFONT, (WPARAM)hFont, TRUE);
		SendMessage(hButtonC, WM_SETFONT, (WPARAM)hFont, TRUE);
		SendMessage(hEditx1, WM_SETFONT, (WPARAM)hFont1, TRUE);
		SendMessage(hEditx2, WM_SETFONT, (WPARAM)hFont1, TRUE);
		SendMessage(hEdity1, WM_SETFONT, (WPARAM)hFont1, TRUE);
		SendMessage(hEdity2, WM_SETFONT, (WPARAM)hFont1, TRUE);
	}
	break;
    case WM_COMMAND:
        {
            int wmId = LOWORD(wParam);
            // 分析菜单选择: 
            switch (wmId)
            {
            case IDM_ABOUT:
                DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
                break;
            case IDM_EXIT:
                DestroyWindow(hWnd);
                break;
			case ID_Button1:
			{
				WCHAR *str = new WCHAR[10000];
				GetWindowText(hEditx1, str, 10000);
				x1s.push_back(myatoi(str));
				GetWindowText(hEditx2, str, 10000);
				x2s.push_back(myatoi(str));
				GetWindowText(hEdity1, str, 10000);
				y1s.push_back(myatoi(str));
				GetWindowText(hEdity2, str, 10000);
				y2s.push_back(myatoi(str));

				RECT rect;
				GetWindowRect(hWnd, &rect);
				InvalidateRect(hWnd, &rect, true);
				UpdateWindow(hWnd);
			}
			break;
			case ID_ButtonC: {
				x1s.clear();
				x2s.clear();
				y1s.clear();
				y2s.clear();
				RECT rect;
				GetWindowRect(hWnd, &rect);
				InvalidateRect(hWnd, &rect, true);
				UpdateWindow(hWnd);
			}
			break;
			case ID_ButtonQ:
			{
				SendMessage(hWindow, WM_COMMAND, IDM_EXIT, NULL);
			}
				break;
			default:
                return DefWindowProc(hWnd, message, wParam, lParam);
            }
        }
        break;
    case WM_PAINT:
        {
	        PAINTSTRUCT ps;
            HDC hdc = BeginPaint(hWnd, &ps);
    
			std::deque<int>::iterator itx1 = x1s.begin(), ity1 = y1s.begin(), itx2 = x2s.begin(), ity2 = y2s.begin();
			while (itx1 != x1s.end()) {
				DrawLine(hdc, *itx1, *itx2, *ity1, *ity2);
				itx2++;
				ity2++;
				itx1++;
				ity1++;
			}
			
			EndPaint(hWnd, &ps);
        }
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}
Beispiel #10
0
inline void INC_CH::convexHull(std::deque<point>& points, const int numPoints, std::deque<point> &result) {
	std::deque<point> LUpper;	/* List of upper hull points */
	std::deque<point> LLower;	/* List of lower hull points */

	point last, middel, first; /* The last three points on stack */
	
	/* Sort the points by x-coordinate */
	std::sort(points.begin(), points.end(), point_cmp_x());
	/* Put the points p1 and p2 in a list L_Upper, with p1 as the first point */
	LUpper.push_front(points[0]);
	LUpper.push_front(points[1]);
	
	for(int i = 2; i < numPoints; i++) {
		/* Append p_i to upper list */
		LUpper.push_front(points[i]);
		while(LUpper.size() > 2) {
			/* While upper list contains more than two points */
			/* And the last three points do not make a right turn */
			first = LUpper.front(); LUpper.pop_front();
			middel = LUpper.front(); LUpper.pop_front();
			last = LUpper.front(); 

			if(ccw(&first, &middel, &last)) {
				/* BREAK if the last three points make a right turn */
				LUpper.push_front(middel);
				LUpper.push_front(first);
				break;
			} else {
				/* Otherwise remove the middle and continue */
				LUpper.push_front(first);
			}
		}
	}
	
	/* Put p_n and p_n-1 in lower list with p_n as first point */
	LLower.push_front(points[numPoints - 1]);
	LLower.push_front(points[numPoints - 2]);
	
	for(int i = numPoints - 3; i >= 0; i--) {
		/* Append p_i to upper list */
		LLower.push_front(points[i]);
		
		while(LLower.size() > 2) {
			first = LLower.front(); LLower.pop_front();
			middel = LLower.front(); LLower.pop_front();
			last = LLower.front();
			
			if(ccw(&first, &middel, &last)) {
				/* BREAK if the last three points make a right turn */
				LLower.push_front(middel);
				LLower.push_front(first);
				break;
			} else {
				/* Otherwise remove the middle and continue */
				LLower.push_front(first);
			}
		}
	}

	/* Remove first and last element in lower hull to avoid duplicates */
	LLower.pop_front();
	LLower.pop_back();
	
	
	/* Merge the two into the result */
	for(unsigned int i = 0; i < LLower.size(); i++) {
		result.push_front(LLower[i]);
	}
	for(unsigned int i = 0; i < LUpper.size(); i++) {
		result.push_front(LUpper[i]);
	}
}
Beispiel #11
0
void work()
{
	scanf("%d", &n);
	top = 0;
	mp.clear();
	q.clear();
	for (int i = 1; i <= n; ++i) {
		k = i;
		printf("Operation #%d: ", i);
		scanf("%s", buf);
		int x;
		if (buf[1] == 'd') { // Add
			scanf("%d", &x);
			if (mp.count(x)) {
				puts("same priority.");
				continue;
			}
			q.push_back(x);
			mp[x] = 0;
			puts("success.");
		} else if (buf[0] == 'C' && buf[1] == 'l') { // Close
			scanf("%d", &x);
			auto it = mp.find(x);
			if (it == mp.end()) {
				puts("invalid priority.");
				continue;
			}
			long long c = it->second;
			mp.erase(it);
			if (top == x)
				top = 0;
			auto jt = std::find(q.begin(), q.end(), x);
			q.erase(jt);
			printf("close %d with " LL ".\n", x, c);
		} else if (buf[0] == 'C' && buf[2] == 'a') { // Chat
			scanf("%d", &x);
			if (top) {
				mp[top] += x;
			} else if (q.empty()) {
				puts("empty.");
				continue;
			} else {
				mp[q.front()] += x;
			}
			puts("success.");
		} else if (buf[0] == 'R') { // Rotate
			scanf("%d", &x);
			if (x < 1 || x > q.size()) {
				puts("out of range.");
				continue;
			}
			int tmp = q[x - 1];
			for (int i = x - 1; i > 0; --i)
				q[i] = q[i - 1];
			q[0] = tmp;
			puts("success.");
		} else if (buf[0] == 'P') { // Prior
			// XXX
			if (q.empty()) {
				puts("empty.");
				continue;
			}
			auto p = mp.rbegin()->first;
			auto it = std::find(q.begin(), q.end(), p);
			for (; it != q.begin(); --it)
				*it = *(it - 1);
			q[0] = p;
			puts("success.");
		} else if (buf[0] == 'C' && buf[1] == 'h') { // Choose
			scanf("%d", &x);
			//if (x == top) {
				// XXX
			//	puts("success.");
			//	continue;
			//}
			auto jt = mp.find(x);
			if (jt == mp.end()) {
				puts("invalid priority.");
				continue;
			}
			auto it = std::find(q.begin(), q.end(), x);
			for (; it != q.begin(); --it)
				*it = *(it - 1);
			q[0] = x;
			puts("success.");
		} else if (buf[0] == 'T') { // Top
			scanf("%d", &x);
			if (x == top) {
				puts("success.");
				continue;
			}
			auto it = mp.find(x);
			if (it == mp.end()) {
				puts("invalid priority.");
				continue;
			}
			//auto jt = std::find(q.begin(), q.end(), x);
			//q.erase(jt);
			top = x;
			puts("success.");
		} else if (buf[0] == 'U') { // Untop
			if (!top) {
				puts("no such person.");
				continue;
			} else {
				//q.push_front(top);
				top = 0;
			}
			puts("success.");
		}
	}
	if (top && mp[top])
		bye(top);
	for (auto& p : q) {
		if (p == top)
			continue;
		if (mp[p])
			bye(p);
	}
}
Beispiel #12
0
template <class T> bool isPresent(const T *value, const std::deque<T *> &d) {
  auto result = std::find(d.begin(), d.end(), value);
  return result != d.end();
}
    void GenerateFaceIndicators(const int &sampleIdx,
                                std::vector<double> &eyesHeightVec, 
                                FaceFeature &faceFeatures,
                                std::deque<InfoPERCLOS> &PERCLOSDeque, 
                                std::deque<InfoBLINK> &BLINKDeque, 
                                const double &intervalTime)
    {
        double eyesHeight = 0, lastEyesHeight = faceFeatures.lastHeight;
        double PERCLOS = 0, MICROSLEEP = 0, MICROSLEEPTime = faceFeatures.MICROSLEEPTime, BLINK = 0;
        
        double eyesHeight_b = faceFeatures.Height_Baseline;
        //Find the min size between two eyes.
        if (!eyesHeightVec.empty()) {
            sort(eyesHeightVec.begin(), eyesHeightVec.end(), SortBigger);
            eyesHeight = eyesHeightVec.front();
            if(eyesHeight > 2*eyesHeight_b )
                eyesHeight = 2*eyesHeight_b;
        }
        else {
            //Negative, if can NOT detect eyes correctly
            eyesHeight = lastEyesHeight;
        }

/*********************************************/
/*  PERCLOS: Percentage of eye closure       */
/*********************************************/   
        InfoPERCLOS perclosInfo;
        perclosInfo.time = intervalTime;
        if(!PERCLOSDeque.empty()){
            /// Calculate the number of frames in fixed time
            if (eyesHeight < faceFeatures.Height_Baseline * THRESHOLD_PERCLOS) {
                perclosInfo.eyePERCLOS = 1; // eye closed
                perclosInfo.timePERCLOS = PERCLOSDeque.back().timePERCLOS +intervalTime;
            }
            else {
                perclosInfo.eyePERCLOS = 0;
                perclosInfo.timePERCLOS = PERCLOSDeque.back().timePERCLOS;
                
            }
            perclosInfo.winTimePERCLOS = PERCLOSDeque.back().winTimePERCLOS + intervalTime;

            //! Only focus on the fixed time interval.
            while(perclosInfo.winTimePERCLOS > TIME_PERCLOS_WINDOW)
            {
                perclosInfo.winTimePERCLOS -= PERCLOSDeque.front().time;
                if(PERCLOSDeque.front().eyePERCLOS == 1)
                {
                    perclosInfo.timePERCLOS -= PERCLOSDeque.front().time;
                }
                PERCLOSDeque.pop_front();
            }
            
            //cout << "time PERCLOS: " << perclosInfo.timePERCLOS << endl;
        }
        else 
        {// The first frames without any PERCLOSInfo
            if (eyesHeight < faceFeatures.Height_Baseline * THRESHOLD_PERCLOS) {
                perclosInfo.eyePERCLOS = 1;
                perclosInfo.timePERCLOS = intervalTime;
            }
            else {
                perclosInfo.eyePERCLOS = 0;
                perclosInfo.timePERCLOS = 0;
            }
            perclosInfo.winTimePERCLOS = intervalTime;
        }
        PERCLOSDeque.push_back(perclosInfo);
        
        //! PERCLOS
        if(perclosInfo.winTimePERCLOS < TIME_PERCLOS_WINDOW / 2)
            PERCLOS = 0;//In first time interval too high value
        else 
            PERCLOS = perclosInfo.timePERCLOS / perclosInfo.winTimePERCLOS;
        
/************************************************/
/*  Statistics of Continuous Eye Closure        */
/*  MICROSLEEP: ND: 0~0.5                       */
/*              SD: 0.5~1                       */
/*              MD: 1~2                         */
/*              VD: 2~4                         */
/*              ED: 4~                          */
/************************************************/
        if (eyesHeight < faceFeatures.Height_Baseline * THRESHOLD_CLOSURE) {
            MICROSLEEPTime += intervalTime;
        } 
        else {
            MICROSLEEPTime -= intervalTime;
            MICROSLEEPTime = MICROSLEEPTime > 0 ? MICROSLEEPTime : 0;
        }
        
        //! When MICROSLEEPTime not equal to 0, Update the MICROSLEEP
        if (MICROSLEEPTime < 0.5)
            MICROSLEEP = 0.25 * MICROSLEEPTime;  //Alert
        else if (MICROSLEEPTime >= 0.5 && MICROSLEEPTime < 1)
            MICROSLEEP = 0.5 * MICROSLEEPTime - 0.125;  //Slightly Drowsy
        else if (MICROSLEEPTime >= 1 && MICROSLEEPTime < 2)
            MICROSLEEP = 0.25 * MICROSLEEPTime + 0.125;  //Moderately Drowsy
        else if(MICROSLEEPTime >= 2 && MICROSLEEPTime < 4)
            MICROSLEEP = 0.125 * MICROSLEEPTime + 0.375;  //Very Drowsy
        else if(MICROSLEEPTime >= 4 && MICROSLEEPTime < 5)
            MICROSLEEP = 0.125 * MICROSLEEPTime + 0.375;
        else
            MICROSLEEP = 1;    //Extremely Drowsy
        
/************************************************/
//! BLINK: Blink Frequency Statistics 
/************************************************/
        InfoBLINK blinkInfo;
        blinkInfo.time = intervalTime;
        if(!BLINKDeque.empty()) {
            /// Calculate the number of frames in fixed time
            if (eyesHeight < faceFeatures.Height_Baseline * THRESHOLD_CLOSURE) {
                blinkInfo.eyeBLINK = 1;
            }
            else {
                blinkInfo.eyeBLINK = 0;
            }
            blinkInfo.winTimeBLINK = BLINKDeque.back().winTimeBLINK + intervalTime;
            
            //! Only focus on the fixed time interval.
            while(blinkInfo.winTimeBLINK  > TIME_BLINK_WINDOW)
            {
                blinkInfo.winTimeBLINK  -= BLINKDeque.front().time;
                BLINKDeque.pop_front();
            }
        }
        else {
            if (eyesHeight < faceFeatures.Height_Baseline * THRESHOLD_CLOSURE) {
                blinkInfo.eyeBLINK = 1;
            }
            else {
                blinkInfo.eyeBLINK = 0;
            }
            blinkInfo.winTimeBLINK = intervalTime;
        }
        BLINKDeque.push_back(blinkInfo);

        //! Calculate the BLINK number 
        int flagBLINK = 0, numBLINK = 0;//start with open eyes
        for (std::deque<InfoBLINK>::const_iterator iter = BLINKDeque.begin(); iter != BLINKDeque.end(); ++iter)
        {
            if (iter->eyeBLINK == 1) {   
                //! closed eyes at first should change flag = 1.
                if (flagBLINK == 0) {
                    flagBLINK = 1;
                    numBLINK ++;
                }
            }
            else {  
                //! open eyes will change flag = 0.
                if (flagBLINK == 1) {
                    flagBLINK = 0;
                } 
            }// end if
        }// end for
        
        BLINK = numBLINK;
//        BLINK = (double)numBLINK / (double)BLINKDeque.size();
//        BLINK = (BLINK - faceFeatures.BLINK_Baseline) / faceFeatures.BLINK_Baseline;
//        BLINK = BLINK < 0 ? 0 : BLINK; 
//        BLINK = BLINK > 1 ? 1 : BLINK; 
        
        
        //! Update the faceFeatures
        faceFeatures.frame  = sampleIdx;
        faceFeatures.Height = eyesHeight;
        faceFeatures.lastHeight = eyesHeight;
        faceFeatures.PERCLOS = PERCLOS;
        faceFeatures.MICROSLEEPTime = MICROSLEEPTime;
        faceFeatures.MICROSLEEP = MICROSLEEP;
        faceFeatures.BLINK = BLINK;
        
    }///GenerateFaceIndicators
Beispiel #14
0
  void RemoveChild( WidgetIDT  c) { children.erase( find( children.begin(),
							  children.end(), c));}
Beispiel #15
0
int main(int argc, char *argv[])
{
    if(argc != 4)
    {
        std::cout << "Usage: " << basename(argv[0]) << " <database> <model uri> <model path>" << std::endl;
        return 0;
    }
    const char *database_path = argv[1], *model_uri = argv[2], *model_path = argv[3];

    // Open source file
    FILE *fp = std::fopen(model_path, "r");
    if(fp == NULL)
    {
        std::cerr << "Unable to open file \"" << model_path
                  << "\" for reading!" << std::endl;
        return 1;
    }

    // Initialize sqlite
    if(!initialize_sqlite(database_path, model_uri))
        return 1;

    std::cerr << "Reading model <" << model_uri << ">"
              << " from file \"" << model_path << "\"... " << std::flush;

    // Step 1: read quads from input file
    if(parse_turtle(fp_reader, (void*)fp, triple_handler, NULL) != 0)
    {
        std::cerr << "\nParsing failed!" << std::endl;
        finalize_sqlite();
        return 1;
    }
    if( sqlite3_exec(db, "COMMIT;", NULL, NULL, NULL) != SQLITE_OK ||
        sqlite3_exec(db, "BEGIN;", NULL, NULL, NULL) != SQLITE_OK )
    {
        std::cerr << "\nUnable to commit and restart transaction!\n" 
                  << "sqlite: " << sqlite3_errmsg(db) << std::endl;
        finalize_sqlite();
        return 1;
    }
    std::cerr << "done.\n\t" << triples.size() << " triples read." << std::endl;

    // Step 2: sort and remove duplicates
    std::cerr << "Sorting... " << std::flush;
    size_t dups = 0;
    {
        std::sort(triples.begin(), triples.end());
        std::deque<Triple>::iterator i =
            std::unique(triples.begin(), triples.end());
        if(i != triples.end())
        {
            dups = triples.size();
            triples.erase(i, triples.end());
            dups -= triples.size();
        }
    }
    std::cerr << "done." << std::endl;
    if(dups > 0)
    {
        std::cerr << "\tWARNING: " << dups
                  << " duplicate triples removed!" << std::endl;
    }

    // Step 3: compare with stored model
    std::cerr << "Comparing with database... " << std::flush;
    if(compare_triples() != 0)
    {
        std::cerr << "\nUnable to read triples from database!\n"
                  << "sqlite: " << sqlite3_errmsg(db) << std::endl;
        finalize_sqlite();
        return 1;
    }
    std::cerr << "done.\n"
              << '\t' << removed.size() << " triples to be removed;\n"
              << '\t' << added.size()   << " triples to be added.\n"
              << std::flush;

    // Step 4: update database
    std::cerr << "Updating database... " << std::flush;
    if(update_triples() != 0)
    {
        std::cerr << "\nUnable to write updates to database!\n"
                  << "sqlite: " << sqlite3_errmsg(db) << std::endl;
        finalize_sqlite();
        return 1;
    }
    std::cerr << "done." << std::endl;

    // Step 5: commit transaction
    std::cerr << "Committing transaction... " << std::flush;
    if(sqlite3_exec(db, "COMMIT;", NULL, NULL, NULL) != SQLITE_OK)
    {
        std::cerr << "Unable to commit transaction!\n" 
                  << "sqlite: " << sqlite3_errmsg(db) << std::endl;
        finalize_sqlite();
        return 1;
    }
    std::cerr << "done." << std::endl;

    finalize_sqlite();
    return 0;
}
Beispiel #16
0
void record_sim(int i)
{
	std::deque<str_and_Bond>::iterator iter;
	double temp_x;
	double temp_y;
	double temp_r_sq;

	for(iter=growth.begin(); iter!=growth.end(); iter++)
	{
		temp_x = iter->second.second.first;
		temp_y = iter->second.second.second;
		temp_r_sq = temp_x*temp_x+temp_y*temp_y;
		r_squared_array.insert(temp_r_sq);
	}

	long int count = 0;

	std::multiset<long long int>::iterator iter2 = r_squared_array.begin();

	for(int j=0; j<num_r_values; j++)
	{

		while(count<growth.size() && *iter2 < r[j]*r[j])
		{
			count++;
			iter2++;
		}
		M_array[i][j] = count;
	}

	for(iter=removed.begin(); iter!=removed.end(); iter++)
	{
		temp_x = iter->second.second.first;
		temp_y = iter->second.second.second;
		temp_r_sq = temp_x*temp_x+temp_y*temp_y;
		r_squared_array.insert(temp_r_sq);
	}

	count = 0;
	iter2 = r_squared_array.begin();

	for(int j=0; j<num_r_values; j++)
	{

		while(count<growth.size() + removed.size() && *iter2 < r[j]*r[j])
		{
			count++;
			iter2++;
		}
		Both_array[i][j] = count;
	}

	r_squared_array.clear();

	for(iter=removed.begin(); iter!=removed.end(); iter++)
	{
		temp_x = iter->second.second.first;
				temp_y = iter->second.second.second;
				temp_r_sq = temp_x*temp_x+temp_y*temp_y;
				r_squared_array.insert(temp_r_sq);
	}

	count = 0;
	iter2 = r_squared_array.begin();

	for(int j=0; j<num_r_values; j++)
	{

		while(count<removed.size() && *iter2 < r[j]*r[j])
		{
			count++;
			iter2++;
		}
		Removed_array[i][j] = count;
	}

	std::map<Site, int>::iterator iter3;

	for(iter3 = chem_level_list.begin(); iter3 != chem_level_list.end(); iter3++)
	{
		if(iter3->second < chem_level_cutoff)
		{
			chem_level_array[i][iter3->second]++;
		}
	}

	std::deque<boost::tuple<int, int, long int> >::iterator burst_iter = burst_list.begin();
	std::deque<boost::tuple<int, int, long int> >::iterator burst_list_end = burst_list.end();

	int burst_x;
	int burst_y;
	long int burst_size;

	while(burst_iter != burst_list_end)
	{
		burst_x = burst_iter->get<0>();
		burst_y = burst_iter->get<1>();
		burst_size = burst_iter->get<2>();

		burst_array.push_back(boost::make_tuple(i, burst_x, burst_y, burst_size));

		burst_iter++;
	}
}
	iterator end(){ return futures.end(); }
Beispiel #18
0
void write_runs_to_file(void)
{
	std::ofstream toFile1("cluster_masses.txt", std::ios::trunc);
	toFile1 << num_runs << "\t" << num_r_values << "\t" << N << "\n";
	toFile1 << "Cluster mass as a function of radius" << "\n";

	for(int j=0; j< num_r_values; j++)
	{
		toFile1 << r[j] << "\t";
	}
	toFile1 << "\n";

	for(int j=0; j< num_runs; j++)
	{
		for(int k=0; k< num_r_values; k++)
		{
			toFile1 << M_array[j][k] << "\t";
		}
		toFile1 << "\n";
	}

	toFile1.close();

	std::ofstream toFile2("removed_masses.txt", std::ios::trunc);
	toFile2 << num_runs << "\t" << num_r_values << "\t" << N << "\n";
	toFile2 << "Mass of removed bonds as a function of radius" << "\n";

	for(int j=0; j< num_r_values; j++)
	{
		toFile2 << r[j] << "\t";
	}
	toFile2 << "\n";

	for(int j=0; j< num_runs; j++)
	{
		for(int k=0; k< num_r_values; k++)
		{
			toFile2 << Removed_array[j][k] << "\t";
		}
		toFile2 << "\n";
	}

	toFile2.close();

	std::ofstream toFile3("both_masses.txt", std::ios::trunc);
	toFile3 << num_runs << "\t" << num_r_values << "\t" << N << "\n";
	toFile3 << "Mass of cluster and removed bonds as a function of radius" << "\n";

	for(int j=0; j< num_r_values; j++)
	{
		toFile3 << r[j] << "\t";
	}
	toFile3 << "\n";

	for(int j=0; j< num_runs; j++)
	{
		for(int k=0; k< num_r_values; k++)
		{
			toFile3 << Both_array[j][k] << "\t";
		}
		toFile3 << "\n";
	}

	toFile3.close();

	std::ofstream toFile4("burst_sizes.txt", std::ios::trunc);
	toFile4 << num_runs << "\t" << N << "\t" << cutoff << "\t" << burst_counts.size() << "\n";
	toFile4 << "Counts of burst masses" << "\n";

	std::map<long int, long int>::iterator iter3;

	for(iter3 = burst_counts.begin(); iter3 != burst_counts.end(); iter3++)
	{
		toFile4 << iter3->first << "\t" << iter3->second << "\n";
	}

	toFile4.close();

	std::ofstream toFile5("chem_levels.txt", std::ios::trunc);
	toFile5 << num_runs << "\t" << N << "\t" << chem_level_cutoff << "\n";
	toFile5 << "Counts of chemical level styles" << "\n";

	for(int j=0; j < num_runs; j++)
	{
		for(int k=0; k<chem_level_cutoff; k++)
		{
			toFile5 << chem_level_array[j][k] << "\t";
		}
		toFile5 << "\n";
	}

	toFile5.close();

	std::ofstream toFile6("bursts.txt", std::ios::trunc);
		toFile6 << burst_array.size() << "\n";
		toFile6 << "Burst hypocenters and size for: anisotropy= " << anisotropy << "\n";
		std::deque<boost::tuple<int, int, int, long int> >::iterator burst_iter = burst_array.begin();
		std::deque<boost::tuple<int, int, int, long int> >::iterator burst_list_end = burst_array.end();

		while(burst_iter != burst_list_end)
		{
			toFile6 << burst_iter->get<0>() << "\t";
			toFile6 << burst_iter->get<1>() << "\t";
			toFile6 << burst_iter->get<2>() << "\t";
			toFile6 << burst_iter->get<3>() << "\n";

			burst_iter++;
		}

		burst_list.clear();
		toFile6.close();
}
Beispiel #19
0
void CWizSync::onDocumentGetList(const std::deque<WIZDOCUMENTDATABASE>& arrayRet)
{
    CWizApi::onDocumentGetList(arrayRet);

    m_arrayAllDocumentsNeedToBeDownloaded.insert(m_arrayAllDocumentsNeedToBeDownloaded.end(), arrayRet.begin(), arrayRet.end());

    if (arrayRet.size() < getCountPerPage()) {
        onDownloadDocumentsSimpleInfoCompleted();
    } else {
        downloadNextDocumentsSimpleInfo(WizObjectsGetMaxVersion<WIZDOCUMENTDATABASE>(arrayRet));
    }
}
Beispiel #20
0
void pump()
{
	if(boost::this_thread::get_id() != main_thread) {
		// Can only call this on the main thread!
		return;
	}
	SDL_PumpEvents();
	peek_for_resize();
	pump_info info;

	//used to keep track of double click events
	static int last_mouse_down = -1;
	static int last_click_x = -1, last_click_y = -1;

	SDL_Event temp_event;
	int poll_count = 0;
	int begin_ignoring = 0;
	std::vector< SDL_Event > events;
	while(SDL_PollEvent(&temp_event)) {
		++poll_count;
		peek_for_resize();

		if(!begin_ignoring && temp_event.type == SDL_WINDOWEVENT
				&& (temp_event.window.event == SDL_WINDOWEVENT_ENTER
						|| temp_event.window.event == SDL_WINDOWEVENT_FOCUS_GAINED))
		{
			begin_ignoring = poll_count;
		} else if(begin_ignoring > 0 && is_input(temp_event)) {
			//ignore user input events that occurred after the window was activated
			continue;
		}
		events.push_back(temp_event);
	}

	std::vector<SDL_Event>::iterator ev_it = events.begin();
	for(int i=1; i < begin_ignoring; ++i){
		if(is_input(*ev_it)) {
			//ignore user input events that occurred before the window was activated
			ev_it = events.erase(ev_it);
		} else {
			++ev_it;
		}
	}

	std::vector<SDL_Event>::iterator ev_end = events.end();
	bool resize_found = false;
	for(ev_it = events.begin(); ev_it != ev_end; ++ev_it){
		SDL_Event &event = *ev_it;
		if (event.type == SDL_WINDOWEVENT &&
				event.window.event == SDL_WINDOWEVENT_RESIZED) {
			resize_found = true;
			last_resize_event = event;
			last_resize_event_used = false;

		}
	}
	// remove all inputs, draw events and only keep the last of the resize events
	// This will turn horrible after ~38 days when the Uint32 wraps.
	if (resize_found || SDL_GetTicks() <= last_resize_event.window.timestamp + resize_timeout) {
		events.erase(std::remove_if(events.begin(), events.end(), remove_on_resize), events.end());
	} else if(SDL_GetTicks() > last_resize_event.window.timestamp + resize_timeout && !last_resize_event_used) {
		events.insert(events.begin(), last_resize_event);
		last_resize_event_used = true;
	}

	ev_end = events.end();

	for(ev_it = events.begin(); ev_it != ev_end; ++ev_it){
		for (context& c : event_contexts)
		{
			c.add_staging_handlers();
		}

		SDL_Event &event = *ev_it;
		switch(event.type) {

			case SDL_WINDOWEVENT:
				switch(event.window.event) {
					case SDL_WINDOWEVENT_ENTER:
					case SDL_WINDOWEVENT_FOCUS_GAINED:
						cursor::set_focus(1);
						break;

					case SDL_WINDOWEVENT_LEAVE:
					case SDL_WINDOWEVENT_FOCUS_LOST:
						cursor::set_focus(1);
						break;

					case SDL_WINDOWEVENT_RESIZED:
						info.resize_dimensions.first = event.window.data1;
						info.resize_dimensions.second = event.window.data2;
						break;
				}
				//make sure this runs in it's own scope.
				{
					flip_locker flip_lock(CVideo::get_singleton());
					for( std::deque<context>::iterator i = event_contexts.begin() ; i != event_contexts.end(); ++i) {
						const handler_list& event_handlers = (*i).handlers;
						for(auto handler : event_handlers) {
							handler->handle_window_event(event);
						}
					}
					const handler_list& event_handlers = event_contexts.front().handlers;
					for(auto handler : event_handlers) {
						handler->handle_window_event(event);
					}
				}

				//This event was just distributed, don't re-distribute.
				continue;

			case SDL_MOUSEMOTION: {
				//always make sure a cursor is displayed if the
				//mouse moves or if the user clicks
				cursor::set_focus(true);
				raise_help_string_event(event.motion.x,event.motion.y);
				break;
			}

			case SDL_MOUSEBUTTONDOWN: {
				//always make sure a cursor is displayed if the
				//mouse moves or if the user clicks
				cursor::set_focus(true);
				if(event.button.button == SDL_BUTTON_LEFT) {
					static const int DoubleClickTime = 500;
					static const int DoubleClickMaxMove = 3;
					if(last_mouse_down >= 0 && info.ticks() - last_mouse_down < DoubleClickTime &&
					   abs(event.button.x - last_click_x) < DoubleClickMaxMove &&
					   abs(event.button.y - last_click_y) < DoubleClickMaxMove) {
						SDL_UserEvent user_event;
						user_event.type = DOUBLE_CLICK_EVENT;
						user_event.code = 0;
						user_event.data1 = reinterpret_cast<void*>(event.button.x);
						user_event.data2 = reinterpret_cast<void*>(event.button.y);
						::SDL_PushEvent(reinterpret_cast<SDL_Event*>(&user_event));
					}
					last_mouse_down = info.ticks();
					last_click_x = event.button.x;
					last_click_y = event.button.y;
				}
				break;
			}
			case DRAW_ALL_EVENT:
			{
				flip_locker flip_lock(CVideo::get_singleton());
				/* iterate backwards as the most recent things will be at the top */
				for( std::deque<context>::iterator i = event_contexts.begin() ; i != event_contexts.end(); ++i) {
					handler_list& event_handlers = (*i).handlers;
					for( handler_list::iterator i1 = event_handlers.begin(); i1 != event_handlers.end(); ++i1) {
						(*i1)->handle_event(event);
					}
				}
				continue; //do not do further handling here
			}

#ifndef __APPLE__
			case SDL_KEYDOWN: {
				if(event.key.keysym.sym == SDLK_F4 && (event.key.keysym.mod == KMOD_RALT || event.key.keysym.mod == KMOD_LALT)) {
					quit_confirmation::quit_to_desktop();
					continue; // this event is already handled
				}
				break;
			}
#endif

#if defined(_X11) && !defined(__APPLE__)
			case SDL_SYSWMEVENT: {
				//clipboard support for X11
				desktop::clipboard::handle_system_event(event);
				break;
			}
#endif

#if defined _WIN32
			case SDL_SYSWMEVENT: {
				windows_tray_notification::handle_system_event(event);
				break;
			}
#endif

			case SDL_QUIT: {
				quit_confirmation::quit_to_desktop();
				continue; //this event is already handled.
			}
		}

		const handler_list& event_handlers = event_contexts.front().handlers;
		for(auto handler : event_handlers) {
			handler->handle_event(event);
		}

		if(event_contexts.empty() == false) {

			const handler_list& event_handlers = event_contexts.back().handlers;

			//events may cause more event handlers to be added and/or removed,
			//so we must use indexes instead of iterators here.
			for(auto handler : event_handlers) {
				handler->handle_event(event);
			}
		}

	}

	//inform the pump monitors that an events::pump() has occurred
	for(size_t i1 = 0, i2 = pump_monitors.size(); i1 != i2 && i1 < pump_monitors.size(); ++i1) {
		pump_monitors[i1]->process(info);
	}
}
Beispiel #21
0
  ///Method to remove a symbol
  bool remove_symbol(const char* symbol_name) {
    for( typename std::deque<std::pair<std::string, T> >::iterator it = symbols.begin() ; it != symbols.end() ; it++ ){
      if( it->first.compare(symbol_name) == 0 ){
	symbols.erase(it);
	return true;
      }
    }
    return false;
  }
Beispiel #22
0
// =====================================================================================
//  TEX_InitFromWad
// =====================================================================================
bool            TEX_InitFromWad()
{
    int             i, j;
    wadinfo_t       wadinfo;
    char            szTmpWad[1024]; // arbitrary, but needs to be large.
    char*           pszWadFile;
    const char*     pszWadroot;
    wadpath_t*      currentwad;

    Log("\n"); // looks cleaner

    szTmpWad[0] = 0;
    pszWadroot = getenv("WADROOT");

#ifdef HLCSG_AUTOWAD
    autowad_UpdateUsedWads();
#endif

    // for eachwadpath
    for (i = 0; i < g_iNumWadPaths; i++)
    {
        FILE*           texfile;                           // temporary used in this loop
        bool            bExcludeThisWad = false;

        currentwad = g_pWadPaths[i];
        pszWadFile = currentwad->path;


#ifdef HLCSG_AUTOWAD
        #ifdef _DEBUG
        Log("[dbg] Attempting to parse wad: '%s'\n", pszWadFile);
        #endif

        if (g_bWadAutoDetect && !currentwad->usedtextures)
            continue;

        #ifdef _DEBUG
        Log("[dbg] Parsing wad\n");
        #endif
#endif

        texfiles[nTexFiles] = fopen(pszWadFile, "rb");

        #ifdef SYSTEM_WIN32
        if (!texfiles[nTexFiles])
        {
            // cant find it, maybe this wad file has a hard code drive
            if (pszWadFile[1] == ':')
            {
                pszWadFile += 2;                           // skip past the drive
                texfiles[nTexFiles] = fopen(pszWadFile, "rb");
            }
        }
        #endif

        if (!texfiles[nTexFiles] && pszWadroot)
        {
            char            szTmp[_MAX_PATH];
            char            szFile[_MAX_PATH];
            char            szSubdir[_MAX_PATH];

            ExtractFile(pszWadFile, szFile);

            ExtractFilePath(pszWadFile, szTmp);
            ExtractFile(szTmp, szSubdir);

            // szSubdir will have a trailing separator
            safe_snprintf(szTmp, _MAX_PATH, "%s" SYSTEM_SLASH_STR "%s%s", pszWadroot, szSubdir, szFile);
            texfiles[nTexFiles] = fopen(szTmp, "rb");

            #ifdef SYSTEM_POSIX
            if (!texfiles[nTexFiles])
            {
                // if we cant find it, Convert to lower case and try again
                strlwr(szTmp);
                texfiles[nTexFiles] = fopen(szTmp, "rb");
            }
            #endif
        }

        if (!texfiles[nTexFiles])
        {
            // still cant find it, error out
            Fatal(assume_COULD_NOT_FIND_WAD, "Could not open wad file %s", pszWadFile);
            continue;
        }

        // look and see if we're supposed to include the textures from this WAD in the bsp.
        WadInclude_i it;
        for (it = g_WadInclude.begin(); it != g_WadInclude.end(); it++)
        {
            if (stristr(pszWadFile, it->c_str()))
            {
                Log("Including Wadfile: %s\n", pszWadFile);
                bExcludeThisWad = true;             // wadincluding this one
                s_WadIncludeMap[nTexFiles] = true;
                break;
            }
        }

        if (!bExcludeThisWad)
        {
            Log("Using Wadfile: %s\n", pszWadFile);
            safe_snprintf(szTmpWad, 1024, "%s%s;", szTmpWad, pszWadFile);
        }

        // temp assignment to make things cleaner:
        texfile = texfiles[nTexFiles];

        // read in this wadfiles information
        SafeRead(texfile, &wadinfo, sizeof(wadinfo));

        // make sure its a valid format
        if (strncmp(wadinfo.identification, "WAD2", 4) && strncmp(wadinfo.identification, "WAD3", 4))
        {
            Log(" - ");
            Error("%s isn't a Wadfile!", pszWadFile);
        }

        wadinfo.numlumps        = LittleLong(wadinfo.numlumps);
        wadinfo.infotableofs    = LittleLong(wadinfo.infotableofs);

        // read in lump
        if (fseek(texfile, wadinfo.infotableofs, SEEK_SET))
            Warning("fseek to %d in wadfile %s failed\n", wadinfo.infotableofs, pszWadFile);

        // memalloc for this lump
        lumpinfo = (lumpinfo_t*)realloc(lumpinfo, (nTexLumps + wadinfo.numlumps) * sizeof(lumpinfo_t));

        // for each texlump
        for (j = 0; j < wadinfo.numlumps; j++, nTexLumps++)
        {
            SafeRead(texfile, &lumpinfo[nTexLumps], (sizeof(lumpinfo_t) - sizeof(int)) );  // iTexFile is NOT read from file

            if (!TerminatedString(lumpinfo[nTexLumps].name, MAXWADNAME))
            {
                lumpinfo[nTexLumps].name[MAXWADNAME - 1] = 0;
                Log(" - ");
                Warning("Unterminated texture name : wad[%s] texture[%d] name[%s]\n", pszWadFile, nTexLumps, lumpinfo[nTexLumps].name);
            }

            CleanupName(lumpinfo[nTexLumps].name, lumpinfo[nTexLumps].name);

            lumpinfo[nTexLumps].filepos = LittleLong(lumpinfo[nTexLumps].filepos);
            lumpinfo[nTexLumps].disksize = LittleLong(lumpinfo[nTexLumps].disksize);
            lumpinfo[nTexLumps].iTexFile = nTexFiles;

            if (lumpinfo[nTexLumps].disksize > MAX_TEXTURE_SIZE)
            {
                Log(" - ");
                Warning("Larger than expected texture (%d bytes): '%s'",
                    lumpinfo[nTexLumps].disksize, lumpinfo[nTexLumps].name);
            }

        }

        // AJM: this feature is dependant on autowad. :(
        // CONSIDER: making it standard?
#ifdef HLCSG_AUTOWAD
        {
            double percused = ((float)(currentwad->usedtextures) / (float)(g_numUsedTextures)) * 100;
            Log(" - Contains %i used texture%s, %2.2f percent of map (%d textures in wad)\n",
                currentwad->usedtextures, currentwad->usedtextures == 1 ? "" : "s", percused, wadinfo.numlumps);
        }
#endif

        nTexFiles++;
        hlassume(nTexFiles < MAX_TEXFILES, assume_MAX_TEXFILES);
    }

    //Log("num of used textures: %i\n", g_numUsedTextures);

    // AJM: Tommy suggested i add this warning message in, and  it certianly doesnt
    //  hurt to be cautious. Especially one of the possible side effects he mentioned was svc_bad
    if (nTexFiles > 8)
    {
        Log("\n");
        Warning("More than 8 wadfiles are in use. (%i)\n"
                "This may be harmless, and if no strange side effects are occurring, then\n"
                "it can safely be ignored. However, if your map starts exhibiting strange\n"
                "or obscure errors, consider this as suspect.\n"
                , nTexFiles);
    }

    // sort texlumps in memory by name
    qsort((void*)lumpinfo, (size_t) nTexLumps, sizeof(lumpinfo[0]), lump_sorter_by_name);

    SetKeyValue(&g_entities[0], "wad", szTmpWad);

    Log("\n");
    CheckFatal();
    return true;
}