text
stringlengths
8
6.88M
/**************************************************************************** ** Copyright (C) 2017 Olaf Japp ** ** This file is part of FlatSiteBuilder. ** ** FlatSiteBuilder is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation, either version 3 of the License, or ** (at your option) any later version. ** ** FlatSiteBuilder is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with FlatSiteBuilder. If not, see <http://www.gnu.org/licenses/>. ** ****************************************************************************/ #include "undoableeditor.h" #include <QUndoCommand> #include <QHBoxLayout> #include <QGridLayout> #include <QFileInfo> #include <QDir> UndoableEditor::UndoableEditor() { m_filename = ""; m_undoStack = new QUndoStack; m_undo = new FlatButton(":/images/undo_normal.png", ":/images/undo_hover.png", "", ":/images/undo_disabled.png"); m_redo = new FlatButton(":/images/redo_normal.png", ":/images/redo_hover.png", "", ":/images/redo_disabled.png"); m_undo->setToolTip("Undo"); m_redo->setToolTip("Redo"); m_undo->setEnabled(false); m_redo->setEnabled(false); QHBoxLayout *hbox = new QHBoxLayout(); hbox->addStretch(0); hbox->addWidget(m_undo); hbox->addWidget(m_redo); m_titleLabel = new QLabel(); QFont fnt = m_titleLabel->font(); fnt.setPointSize(20); fnt.setBold(true); m_titleLabel->setFont(fnt); m_layout = new QGridLayout; m_layout->addWidget(m_titleLabel, 0, 0); m_layout->addLayout(hbox, 0, 2); setLayout(m_layout); connect(m_redo, SIGNAL(clicked()), this, SLOT(redo())); connect(m_undo, SIGNAL(clicked()), this, SLOT(undo())); connect(m_undoStack, SIGNAL(canUndoChanged(bool)), this, SLOT(canUndoChanged(bool))); connect(m_undoStack, SIGNAL(canRedoChanged(bool)), this, SLOT(canRedoChanged(bool))); connect(m_undoStack, SIGNAL(undoTextChanged(QString)), this, SLOT(undoTextChanged(QString))); connect(m_undoStack, SIGNAL(redoTextChanged(QString)), this, SLOT(redoTextChanged(QString))); } UndoableEditor::~UndoableEditor() { disconnect(m_undoStack, SIGNAL(canUndoChanged(bool)), this, SLOT(canUndoChanged(bool))); disconnect(m_undoStack, SIGNAL(canRedoChanged(bool)), this, SLOT(canRedoChanged(bool))); disconnect(m_undoStack, SIGNAL(undoTextChanged(QString)), this, SLOT(undoTextChanged(QString))); disconnect(m_undoStack, SIGNAL(redoTextChanged(QString)), this, SLOT(redoTextChanged(QString))); delete m_undoStack; } void UndoableEditor::contentChanged(QString text) { QUndoCommand *changeCommand = new ChangeFileCommand(this, m_filename, text); m_undoStack->push(changeCommand); } int fileVersionNumber = 0; ChangeFileCommand::ChangeFileCommand(UndoableEditor *editor, QString filename, QString text, QUndoCommand *parent) : QUndoCommand(parent) { fileVersionNumber++; m_editor = editor; m_filename = filename; setText(text); QFileInfo info(filename); QString dir = info.dir().dirName(); QString file = info.fileName(); m_undoFilename = QDir::tempPath() + "/FlatSiteBuilder/" + dir + "/" + file + "." + QString::number(fileVersionNumber) + ".undo"; m_redoFilename = QDir::tempPath() + "/FlatSiteBuilder/" + dir + "/" + file + "." + QString::number(fileVersionNumber) + ".redo"; } void ChangeFileCommand::undo() { QFile dest(m_filename); if(dest.exists()) dest.remove(); QFile::copy(m_undoFilename, m_filename); m_editor->load(); } void ChangeFileCommand::redo() { QFile redo(m_redoFilename); if(redo.exists()) { QFile dest(m_filename); if(dest.exists()) dest.remove(); QFile::copy(m_redoFilename, m_filename); m_editor->load(); } else { QFile::copy(m_filename, m_undoFilename); m_editor->save(); QFile::copy(m_filename, m_redoFilename); } }
#include<iostream> #include<vector> #include<algorithm> using namespace std; class Solution { public: vector<int> findDisappearedNumbers(vector<int>& nums) { //基本思想:哈希表HashMap,利用nums数组的下标作为哈希表的映射,如果该数存在,则对应下标的元素为负。这样就不用申请额外空间标记该数存在并且不改变下标元素值 vector<int> res; for(int i=0;i<nums.size();i++) { if(nums[abs(nums[i])-1]<0) continue; nums[abs(nums[i])-1]=-nums[abs(nums[i])-1]; } for(int i=0;i<nums.size();i++) if(nums[i]>0) res.push_back(i+1); return res; } }; int main() { vector<int> nums={1,2,2,3,3,4,4}; Solution solute; vector<int> res=solute.findDisappearedNumbers(nums); for_each(res.begin(),res.end(),[](int v){cout<<v<<endl;}); return 0; }
#include<bits/stdc++.h> using namespace std; template<typename V> class Mapnode{ public: string key; V value; Mapnode* next; Mapnode(string key,V value){ this -> key = key; this -> value = value; this -> next = NULL; } ~Mapnode(){ delete next; } }; template<typename V> class Ourmap{ Mapnode<V>** buckets; int count; int numBuckets; public: Ourmap(){ count = 0; numBuckets = 5; buckets = new Mapnode<V>*[numBuckets]; for(int i=0;i<numBuckets;i++){ //Initialising the bucket array with NULL values. buckets[i] = NULL; } } ~Ourmap(){ for(int i=0;i<numBuckets;i++){ delete buckets[i]; } delete [] buckets; } int size(){ return count; } V getValue(string key){ //Function which takes key and gives value. int bucketIndex = getBucketIndex(key); Mapnode<V>* head = buckets[bucketIndex]; while(head != NULL){ if(head->key == key){ //If key found then return it's value. return head -> value; } head = head -> next; } return 0; //If key not found then return 0(default value). } private: int getBucketIndex(string key){ int hashcode = 0; int currentCoeff = 1; for(int i=key.length()-1;i>=0;i--){ hashcode = hashcode + (key[i] * currentCoeff); hashcode = hashcode % numBuckets; //To be safer,if hashcode comes out of range. currentCoeff = currentCoeff * 37; currentCoeff = currentCoeff % numBuckets; //To be safer,if currentCoeff comes out of range. } return hashcode % numBuckets; } public: double getLoadFactor(){ return (1.0 * count)/numBuckets; } void rehash(){ Mapnode<V>** temp = buckets; buckets = new Mapnode<V>*[2 * numBuckets]; for(int i=0;i<numBuckets;i++){ buckets[i] = NULL; } int oldBucketCount = numBuckets; numBuckets = numBuckets * 2; count = 0; for(int i=0;i<oldBucketCount;i++){ Mapnode<V>* head = temp[i]; while(head != NULL){ string key = head -> key; V value = head -> value; insert(key,value); head = head -> next; } } for(int i=0;i<oldBucketCount;i++){ Mapnode<V>* head = temp[i]; delete head; } delete [] temp; } void insert(string key,V value){ //Function which takes key and value for insertion. int bucketIndex = getBucketIndex(key); Mapnode<V>* head = buckets[bucketIndex]; while(head != NULL){ //Traverse the linked list till end to check the key already exists or not. if(head->key == key){ head -> value = value; return; } head = head -> next; } head = buckets[bucketIndex]; //Re-initialization of head because after while loop head becomes NULL. //If key is not found. Mapnode<V>* newNode = new Mapnode<V>(key,value); newNode -> next = head; buckets[bucketIndex] = newNode; count++; double loadFactor = (1.0 * count)/numBuckets; if(loadFactor > 0.7){ rehash(); } } V remove(string key){ //Function which takes key and removes that key,gives corresponding key value. int bucketIndex = getBucketIndex(key); Mapnode<V>* head = buckets[bucketIndex]; Mapnode<V>* prev = NULL; while(head != NULL){ if(head->key == key){ if(prev == NULL){ //If the key is found in the beginning. buckets[bucketIndex] = head -> next; }else{ prev -> next = head -> next; //If the key is found at the middle. } V prevValue = head -> value; //Store prevValue of deleting node and return it. head -> next = NULL; delete head; count--; //Decrement the counter after deletion of every node. return prevValue; } prev = head; head = head -> next; } return 0; //If the removing key is not present in the list then return 0(default value). } }; int main(){ Ourmap<int> m; for(int i=0;i<10;i++){ char c = '0' + i; string key = "abc"; key = key + c; int value = i + 1; m.insert(key,value); cout << m.getLoadFactor() << endl; } m.remove("abc2"); for(int i=0;i<10;i++){ char c = '0' + i; string key = "abc"; key = key + c; cout << key << " : " << m.getValue(key) << endl; } cout << m.size() << endl; return 0; }
#include <cstdio> #include <iostream> #include <vector> #include <string> #include <stack> #include <unordered_map> #include <unordered_set> #include <queue> #include <algorithm> #define INT_MAX 0x7fffffff #define INT_MIN 0x80000000 using namespace std; vector<int> findSubstring(string S, vector<string> &L){ vector<int> res; if(L.size()==0) return res; int oneLength = L[0].length(); unordered_map<string,int> mymap; int count = L.size(); for(auto x : L) mymap[x] ++; for(int i=0;i+count*oneLength-1<S.length();i++){ unordered_map<string,int> tester; int j = 0; while(j<count){ string str = S.substr(i+j*oneLength,oneLength); if(mymap.find(str) == mymap.end()) break; else{ tester[str]++; if(tester[str]>mymap[str]) break; } j++; } if(j==count) res.push_back(i); } return res; } int main(){ string S,s; cin >> S; vector<string> L; while(cin >> s) L.push_back(s); vector<int> res = findSubstring(S,L); for(auto x : res) cout << x << " "; }
/** \file BHandSupervisoryRealTime.cpp \brief Contains the implementation of a class for the BarrettHand Supervisory and RealTime modules. The BarrettHand API provides high-level control functions for the Barrett Hand that operates under in a supervisory mode or under a real time mode. This module needs to be initialized with a call to #InitSoftware or #Init. If the API has been compiled to support serial communication then low-level access of the serial port methods that are used internally are exposed. These serial port methods may be used to support building a custom software interface to the BarrettHand. Barrett uses these methods to provide a bootloader for uploading new firmware outside the API. Supervisory mode is the mode that the hand starts in after initialization. There are several useful commands such as open and close commands that will open and close fingers on the BarrettHand. The Supervisory and RealTime modules contained here use the POCO C++ Foundation library for cross-platform multithreading. RealTime mode allows control loops to be formed so that control and feedback data may be exchanged with the hand. This mode is used to control the hand directly. */ #include "BHandSupervisoryRealTime.h" #include "BHand.h" #ifdef BH8_280_HARDWARE #include "BHandCANDriver.h" // Include headers for puck communication with the BarrettHand #endif #ifdef BH8_262_HARDWARE #include "BHandSerialDriver.h" // Include header for serial communication with the BarrettHand #include "BHandBH8_262.h" #endif #include "bhand_parse.h" /////////////////////////////////////////////////////////////////////////// // Public Methods (SupervisoryRealtime Constructor/Deconstructor) /////////////////////////////////////////////////////////////////////////// BHandSupervisoryRealtime::BHandSupervisoryRealtime(BHand *bhand, int priority) : syncMode(BHMODE_SYNC), requestTimeout(INFINITE), pCallback(NULL), m_initialized(false), m_bhand(bhand), m_driver(NULL), m_requestPending(), m_requestComplete(false), m_request(0), m_comErr(0) { createThread(priority); } BHandSupervisoryRealtime::~BHandSupervisoryRealtime() { while (ComIsPending()); // Ask thread to stop syncMode = BHMODE_ASYNCWAIT; ComRequest(BHREQ_EXIT); // Wait for thread to complete execution for up to 1000 milliseconds m_thread.tryJoin(1000); // Close communication interface if (m_driver != NULL) { m_driver->Close(); delete m_driver; } } /////////////////////////////////////////////////////////////////////////// // Public Methods (SupervisoryRealtime Initialization) /////////////////////////////////////////////////////////////////////////// /** Initialize this BHand instance. The InitSoftware method will initialize communication with the BarrettHand. The BarrettHand API needs to have the Supervisory and RealTime modules initialized as well as having the means to communicate with the hand prior to using Supervisory or RealTime methods. This method will initialize the Supervisory and RealTime modules given that the parameters are set correctly and serial communication with the hand is established. If this method successfully establishes communication with the hand then a low-level thread is started for executing high-level BarrettHand Supervisory commands. Both reset and init hand commands will also be issued. \param port The comport to use for communication (1 for "COM1" in Windows or "/dev/ttyS0" in Linux) \param priority The thread priority for the communication thread \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::InitSoftware(int port, int priority) { // Set hardware description before initialization int hwIndex = BHandHardware::getBHandHardwareIndex("BH8-262"); if (hwIndex < 0) { //printf("\n\nThe API has not been compiled to include target hand.\n"); return BHERR_NOTINITIALIZED; } m_bhand->setHardwareDesc(hwIndex); // BarrettHand API is compiled with BH8-262 support // so initialize for serial communication return Init(port, priority, BH_SERIAL_COMMUNICATION); } /** Initialize this BHand instance. This method will need to be called to initialize the hand for CAN or serial communication. Before Init is called, setHardwareDesc should be called to set the hardware description so that the API knows what hand it will be communicating with. This method will attempt to reset the hand and will report an error if there is a problem. Users may run initialize as a non-blocking call by passing true to the async parameter. This is for advanced applications that need to not block if there is a timeout or problem attempting to reset the hand. Note that all supervisory commands will be run asynchronously until the mode is switched. \param port The comport to use for communication (1 for "COM1" in Windows or "/dev/ttyS0" in Linux) \param priority The thread priority for the communication thread \param async Will set the blocking/non-blocking behavior of Init, default value is false \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::Init(int port, int priority, BHCommunication comm, bool async) { // Check to make sure software has not already been initialized if (m_initialized) return BHERR_BHANDEXISTS; /////////////////////////////////////////////////////////////////////////// // Initialize BarrettHand the Device Driver (CAN or serial) /////////////////////////////////////////////////////////////////////////// //printf("Init 1( port = %d\n", port); if (m_driver != NULL) { // Cleanup driver created previously m_driver->Close(); delete m_driver; m_driver = NULL; } switch (comm) { #ifdef BH8_280_HARDWARE case BH_CAN_COMMUNICATION: { m_driver = new BHandCANDriver(m_bhand, this); break; } #endif #ifdef BH8_262_HARDWARE case BH_SERIAL_COMMUNICATION: { m_driver = new BHandSerialDriver(m_bhand, this, port); break; } #endif default: { // Return if communication with the BarrettHand is not supported return BHERR_NOTINITIALIZED; } } //printf("Init 2( port = %d\n", port); /////////////////////////////////////////////////////////////////////////// // Set device driver used for the Supervisory and RealTime module /////////////////////////////////////////////////////////////////////////// m_bhand->setDeviceDriver(m_driver); /////////////////////////////////////////////////////////////////////////// // Initialize device driver /////////////////////////////////////////////////////////////////////////// int result; if ((result = m_driver->Initialize())) { m_driver->Close(); m_comErr = result; return result; // Driver did not initialize } //printf("Init before set timeouts\n"); #ifdef BH8_262_HARDWARE // Replace timeouts with more reasonable ones to achieve a faster // timeout if there is no response from the hand after sending a Reset command if (comm == BH_SERIAL_COMMUNICATION && (result = ComSetTimeouts(50, 2000, 50, 2000)) > 0) { m_driver->Close(); m_comErr = result; return result; } #endif //printf("Init after set timeouts\n"); // Set asynchronous mode if requested (more advanced) if (async) setSyncMode(BHMODE_ASYNCWAIT); /////////////////////////////////////////////////////////////////////////// // Send Reset command and store if a response is received /////////////////////////////////////////////////////////////////////////// //printf("Init wait for response\n"); bool receivedResponse; result = Reset(&receivedResponse); #ifdef BH8_262_HARDWARE // Restore default timeouts (set in ComInitialize) if (!async && comm == BH_SERIAL_COMMUNICATION && (result = ComSetTimeouts(50, 15000, 50, 5000)) > 0) { m_driver->Close(); m_comErr = result; return result; } #endif // Set initialized flag m_initialized = receivedResponse; /*if (async) { m_initialized = true; printf("Init m_initialized = %d receivedResponse = %d\n", m_initialized, receivedResponse); return 0; } else { m_initialized = receivedResponse; printf("Init m_initialized = %d receivedResponse = %d\n", m_initialized, receivedResponse); }*/ //printf("Init received\n"); // Return an error if there was no response received after sending a reset return receivedResponse ? 0 : BHERR_READCOM; } /////////////////////////////////////////////////////////////////////////// // Private methods (Misc.) /////////////////////////////////////////////////////////////////////////// bool BHandSupervisoryRealtime::driverIsOpen() { return m_driver != NULL && m_driver->IsOpen(); } bool BHandSupervisoryRealtime::serialDriverIsOpen() { return driverIsOpen() && m_driver->getComm() == BH_SERIAL_COMMUNICATION; } void BHandSupervisoryRealtime::createThread(int priority) { // Initialize variables for thread m_requestComplete.set(); m_request = 0; // Create thread for asynchronous communication m_thread.setName("BHand Async"); switch (priority) { case THREAD_PRIORITY_TIME_CRITICAL: { m_thread.setPriority(Poco::Thread::PRIO_HIGHEST); break; } case THREAD_PRIORITY_HIGHEST: { m_thread.setPriority(Poco::Thread::PRIO_HIGHEST); break; } case THREAD_PRIORITY_ABOVE_NORMAL: { m_thread.setPriority(Poco::Thread::PRIO_HIGH); break; } case THREAD_PRIORITY_NORMAL: { m_thread.setPriority(Poco::Thread::PRIO_NORMAL); break; } case THREAD_PRIORITY_BELOW_NORMAL: { m_thread.setPriority(Poco::Thread::PRIO_LOW); break; } case THREAD_PRIORITY_LOWEST: { m_thread.setPriority(Poco::Thread::PRIO_LOWEST); break; } case THREAD_PRIORITY_IDLE: { m_thread.setPriority(Poco::Thread::PRIO_LOWEST); break; } default: { m_thread.setPriority(Poco::Thread::PRIO_HIGHEST); break; } } m_thread.start(*this); // Note that POCO does not have any way that would allow for detecting if // the thread was not created or if setting the thread priority failed. // So BHERR_THREADSTART and BHERR_THREADPRIORITY are never returned anymore. } /////////////////////////////////////////////////////////////////////////// // Methods used to validate calls to commands before they are made /////////////////////////////////////////////////////////////////////////// int BHandSupervisoryRealtime::validate(BHMotors motors, const char *propertyName, int value) { // Check if there are motor properties to validate if (!motors) return 0; //printf("validate(%d, %s, %d)", motors, propertyName, value); // Get property that may be used to validate input BHandHardware *hw = m_bhand->getHardwareDesc(); BHandProperty *p = hw->getBHandProperty(propertyName); // Make sure that this property may be a motor property if (p->getNumExtendedAttributes() != 4) return BHERR_OUTOFRANGE; for (unsigned int i = 0; i < 4; i++) // handle more motors if ((motors >> i) & 1) { int minValue = p->getMinValue(i); int maxValue = p->getMaxValue(i); //printf("validate %s check range %d minValue = %d maxValue = %d\n", propertyName, i, minValue, maxValue); // Validate value is in property range if (value < minValue || value > maxValue) return BHERR_OUTOFRANGE; } return 0; } int BHandSupervisoryRealtime::validate(const char *propertyName, int value) { // Get property that may be used to validate input BHandHardware *hw = m_bhand->getHardwareDesc(); BHandProperty *p = hw->getBHandProperty(propertyName); // Make sure that this property may be a global property if (p->getNumExtendedAttributes() != 1) return BHERR_OUTOFRANGE; int minValue = p->getMinValue(); int maxValue = p->getMaxValue(); // Validate value is in property range if (value < minValue || value > maxValue) return BHERR_OUTOFRANGE; return 0; } /////////////////////////////////////////////////////////////////////////// // Public Methods (Control Over Execution) /////////////////////////////////////////////////////////////////////////// /** Sends a request to the low-level communication thread. The request must be BHREQ_EXIT, BHREQ_REALTIME, BHREQ_SUPERVISE, or BHREQ_CLEAR. \param requestNumber One of the request constants listed above \retval int Returns 0 on success or an error code on failure */ int BHandSupervisoryRealtime::ComRequest(int requestNumber) { // Wait for the request handler thread to be ready to accept a request if (syncMode == BHMODE_ASYNCNOW) { // in immediate async mode, so throw an error if the request handler is busy if (!m_requestComplete.tryWait(0)) return BHERR_NOTCOMPLETED; } else { if (requestTimeout < INFINITE) m_requestComplete.wait(requestTimeout); else { m_requestComplete.wait(); } } // return immediately if (syncMode == BHMODE_RETURN) { // call callback anyway m_comErr = 0; if (pCallback) (*(pCallback))(getBHand()); return 0; } // clear request complete event m_requestComplete.reset(); // send request m_request = requestNumber; m_requestPending.set(); // wait for completion in sync mode if (syncMode == BHMODE_SYNC) return ComWaitForCompletion(requestTimeout); else return BHERR_PENDING; } /** Waits for low-level communication thread to complete processing. Blocks until the communication thread completes processing in the given amount of time. It will return 0, a positive hand error code, or a negative timeout error code. \param timeout Number of milliseconds to wait for completion (may be INFINITE) \retval int Returns 0, a positive hand error code, or BHERR_TIMEOUT if there is a timeout */ int BHandSupervisoryRealtime::ComWaitForCompletion(unsigned int timeout) { if (timeout < INFINITE) { bool wait = m_requestComplete.tryWait(timeout); if (wait) return m_comErr; else return BHERR_TIMEOUT; } else m_requestComplete.wait(); return m_comErr; } /** Checks for a low-level pending communication request \retval bool Returns true if a communication request is pending and false otherwise */ bool BHandSupervisoryRealtime::ComIsPending() { return !m_requestComplete.tryWait(0); } /** Checks the low-level thread for communication errors Communication errors are set to zero before communication begins with the low-level thread and is set after completion to the value that would be returned by the Supervisory command if run synchronously. Use this to get the last error, which is the only method available to access the error code in asynchronous mode. Call this after ComIsPending() returns false or the application receives a callback on a method that the supervisory command has executed. \retval int Returns the most recent communication error */ int BHandSupervisoryRealtime::ComGetError() { return m_comErr; } /** Obtain command results after the supervisory command has finished running The last command run should be a supervisory command that returns a result. Ensure that the command has finished running. Use ComIsPending() or received the finished command event through a callback method. Usually, a cast is needed to receive useful information from the result returned as appropriate. \retval BHandSupervisoryResult Pointer to most recent result */ BHandSupervisoryResult * BHandSupervisoryRealtime::GetResult() { return m_driver->GetResult(); } // A macro to end thread processing and invoke callback function #define THREADEND(err) \ { \ m_comErr = (err); \ if (pCallback) \ (*(pCallback))(m_bhand); \ break; \ } /////////////////////////////////////////////////////////////////////////// // Private method (required to be implemented to be Runnable) /////////////////////////////////////////////////////////////////////////// /** The low-level communication thread for the BarrettHand. This thread waits for low-level communication requests and may make calls that block until they are finished. Blocking calls may take quite awhile to complete so this thread waits for them and then handles making calls to the BarrettHand driver one at a time. Requests are signalled using ComRequest. \internal */ void BHandSupervisoryRealtime::run() { int result; // Loop forever - user must ask thread to exit while (1) { // Signal that the request is complete m_requestComplete.set(); // Now wait for a request m_requestPending.wait(); // event is auto reset m_comErr = 0; // Check to see if the driver ready to process Supervisory or RealTime requests if (!driverIsOpen() && (m_request == BHREQ_REALTIME || m_request == BHREQ_SUPERVISE)) continue; // handle all requests switch (m_request) { case BHREQ_EXIT: { // Set request complete m_requestComplete.set(); //m_comPending = false; return; } case BHREQ_REALTIME: { // loop mode command result = m_driver->ExecuteRealtimeCall(); THREADEND(result); } case BHREQ_SUPERVISE: { // Supervisory mode command result = m_driver->ExecuteSupervisoryCall(); // Note that 280 commands still exist to return results in asynchonous mode // This will need to get deleted within this class later THREADEND(result); } case BHREQ_CLEAR: { #ifdef BH8_262_HARDWARE // Clear com port buffers (will have no effect if not using the serial driver) if (!ComClear()) THREADEND(BHERR_CLEARBUFFER) #endif THREADEND(0) } default: { } } } } /////////////////////////////////////////////////////////////////////////////// // Methods in Serial Communication Module /////////////////////////////////////////////////////////////////////////////// #ifdef BH8_262_HARDWARE /** Initializes serial communication. This method is used internally by InitSoftware. \param comport Com port number (1 for "COM1" in Windows or "/dev/ttyS0" in Linux) \param priority The thread priority parameter is not used anymore \retval int Returns 0 on success or an error code on failure */ int BHandSupervisoryRealtime::ComInitialize(int comport, int priority) { //if (m_driver != NULL) return (m_driver != NULL && m_driver->getComm() == BH_SERIAL_COMMUNICATION) ? ((BHandSerialDriver *)m_driver)->ComInitialize(comport) : BHERR_OPENCOMMPORT; /*else { printf("BHandSupervisoryRealtime::ComInitialize(%d ... new case for driver being NULL\n", comport); // Open serial port communication with hand m_driver = new BHandSerialDriver(m_bhand, this, comport); m_bhand->setDeviceDriver(m_driver); //printf("m_driver->getComm() == BH_SERIAL_COMMUNICATION = %d", m_driver->getComm() == BH_SERIAL_COMMUNICATION); return (m_driver != NULL && m_driver->getComm() == BH_SERIAL_COMMUNICATION) ? ((BHandSerialDriver *)m_driver)->ComInitialize(comport) : BHERR_OPENCOMMPORT; }*/ } /** Opens serial communication port. This is provided to support serial communication with the BarrettHand. A user may choose to write their own application that uses the serial port using only the serial communication provided in a BHand instance. \param comport Com port number (1 for "COM1" in Windows or "/dev/ttyS0" in Linux) \param baudrate The desired baud rate \retval int Returns 0 on success or an error code on failure */ int BHandSupervisoryRealtime::ComOpen(int comport, int baudrate) { // Check to make sure software has not already been initialized if (m_initialized || m_driver != NULL) { printf("BHandSupervisoryRealtime: m_initialized || m_driver != NULL\n"); if (m_driver != NULL && m_driver->getComm() == BH_SERIAL_COMMUNICATION) { printf("For the first time - using serial driver that already exists.\n"); return ((BHandSerialDriver *)m_driver)->ComOpen(comport, baudrate); } else return BHERR_BHANDEXISTS; } printf("BHandSupervisoryRealtime::ComOpen\n"); if (m_driver != NULL) printf("m_driver != NULL\n"); else printf("m_driver = NULL\n"); // Open serial port communication with hand m_driver = new BHandSerialDriver(m_bhand, this, comport); m_bhand->setDeviceDriver(m_driver); //printf("m_driver->getComm() == BH_SERIAL_COMMUNICATION = %d", m_driver->getComm() == BH_SERIAL_COMMUNICATION); return (m_driver != NULL && m_driver->getComm() == BH_SERIAL_COMMUNICATION) ? ((BHandSerialDriver *)m_driver)->ComOpen(comport, baudrate) : BHERR_OPENCOMMPORT; } /** Close serial port communication. Will close the serial port if it is opened. */ void BHandSupervisoryRealtime::ComClose() { if (serialDriverIsOpen()) { ((BHandSerialDriver *)m_driver)->ComClose(); if (m_driver != NULL) { delete m_driver; m_driver = NULL; } m_initialized = false; } } /** Useful for determining if the com port is opened. \retval bool Returns true if opened and false if not opened */ bool BHandSupervisoryRealtime::ComIsOpen() { return serialDriverIsOpen() ? ((BHandSerialDriver *)m_driver)->ComIsOpen() : false; } /** Clears the serial port input and output buffers. Will always clear the input buffer and will also clear the output buffer by default. Clearing the output buffer takes longer since the serial port needs to be reopened. \param rxOnly Clear only the receive buffer \retval bool Returns true on success or false if there is a problem. */ bool BHandSupervisoryRealtime::ComClear(bool rxOnly) { return serialDriverIsOpen() ? ((BHandSerialDriver *)m_driver)->ComClear(rxOnly) : false; } /** Reads bytes from serial port input buffer. If the serial port is opened then this method will transfer rxNumBytes from the input buffer to the given buffer. It will block forever until the number of requested bytes have been received. \param rxBuf Pointer to a receive buffer that bytes will be transferred to \param rxNumBytes Number of bytes to receive from the input buffer \retval int Returns 0 on success and BHERR_READCOM if there is a problem. */ int BHandSupervisoryRealtime::ComRead(char* rxBuf, int rxNumBytes) { return serialDriverIsOpen() ? ((BHandSerialDriver *)m_driver)->ComRead(rxBuf, rxNumBytes) : BHERR_OPENCOMMPORT; } /** Writes bytes to the serial port output buffer. If the serial port is opened then this method will transfer txNumBytes to the output buffer from the given buffer. It will block forever until the number of requested bytes have been transmitted. \param txBuf Pointer to a transmit buffer that bytes will be transferred from \param txNumBytes Number of bytes to transfer to the output buffer \retval int Returns 0 on success and BHERR_WRITECOM if there is a problem. */ int BHandSupervisoryRealtime::ComWrite(const char* txBuf, int txNumBytes) { return serialDriverIsOpen() ? ((BHandSerialDriver *)m_driver)->ComWrite(txBuf, txNumBytes) : BHERR_OPENCOMMPORT; } /** Registers a callback function to be called periodically by the BHandCANDriver The method will be called periodically while movement commands are running and with the Supervisory Delay command. This method can be helpful for polling property values with the RTUpdate get property method. This method is okay to execute during one of the supervisory events described above. \param waitCallbackFunc Method signature must be: void waitFunc(BHand *bh) */ void BHandSupervisoryRealtime::SetWaitCallbackFunc(BHCallback waitCallbackFunc) { if (driverIsOpen()) m_driver->SetWaitCallbackFunc(waitCallbackFunc); } /** Sets timeout parameters for serial communication. Both timeout constants are in milliseconds. Each read and write call to the serial functions ComRead and ComWrite will end after the calculated timeout period. Timeout periods for reads and writes are computed as the sum of the read/write constant and read/write multiplier multiplied by the number of bytes to transmit or receive. A computed timeout value of zero disables the respective timeout, essentially making the timeout infinite. Example: \code // Set timeout parameters // read interval of 999 is ignored // read multiplier of 50 // read constant of 15000 // write multiplier of 50 // write constant of 5000 err = bh.ComSetTimeouts(999, 50, 15000, 50, 5000); \endcode It is recommended to remain at the default values unless shorter or longer timeouts are required in your application. Even at the slowest possible baud rate of 600 baud, the communications will not timeout under normal circumstances. \param readInterval Ignored \param readMultiplier Average time per character \param readConstant Constant for the entire transaction \param writeMultiplier Average time per character \param writeConstant Constant for the entire transaction \retval int Returns 0 on success and BHERR_SETCOMMTIMEOUT on failure */ int BHandSupervisoryRealtime::ComSetTimeouts(unsigned int readInterval, unsigned int readMultiplier, unsigned int readConstant, unsigned int writeMultiplier, unsigned int writeConstant) { return ComSetTimeouts(readMultiplier, readConstant, writeMultiplier, writeConstant); } /** Sets timeout parameters for serial communication. Both timeout constants are in milliseconds. Each read and write call to the serial functions ComRead and ComWrite will end after the calculated timeout period. Timeout periods for reads and writes are computed as the sum of the read/write constant and read/write multiplier multiplied by the number of bytes to transmit or receive. A computed timeout value of zero disables the respective timeout, essentially making the timeout infinite. Example: \code // Set timeout parameters // read multiplier of 50 // read constant of 15000 // write multiplier of 50 // write constant of 5000 err = bh.ComSetTimeouts(50, 15000, 50, 5000); \endcode It is recommended to remain at the default values unless shorter or longer timeouts are required in your application. Even at the slowest possible baud rate of 600 baud, the communications will not timeout under normal circumstances. \param readMultiplier Average time per character \param readConstant Constant for the entire transaction \param writeMultiplier Average time per character \param writeConstant Constant for the entire transaction \retval int Returns 0 on success and BHERR_SETCOMMTIMEOUT on failure */ int BHandSupervisoryRealtime::ComSetTimeouts(unsigned int readMultiplier, unsigned int readConstant, unsigned int writeMultiplier, unsigned int writeConstant) { return serialDriverIsOpen() ? ((BHandSerialDriver *)m_driver)->ComSetTimeouts(readMultiplier, readConstant, writeMultiplier, writeConstant) : BHERR_OPENCOMMPORT; } /** Sets the baud rate for serial communication. This method may also be called after ComOpen to set the baud rate. The BarrettHand will only work with the standard baud rates up to 38400. More baud rates are possible but are not supported in the BarrettHand. Users should also look at the Baud command if interested in changing the baud rate used by the hand. \param baudrate The requested baud rate (possible values are 600, 1200, 2400, 4800, 9600, 19200, 38400) \retval int Returns 0 on success and BHERR_SETCOMMSTATE on failure */ int BHandSupervisoryRealtime::ComSetBaudrate(int baudrate) { return serialDriverIsOpen() ? ((BHandSerialDriver *)m_driver)->ComSetBaudrate(baudrate) : BHERR_OPENCOMMPORT; } #endif /////////////////////////////////////////////////////////////////////////////// // Methods in Supervisory Module /////////////////////////////////////////////////////////////////////////////// /** Sends the "Hand Initialize" command to the hand. The purpose of this command is to determine encoder and motor alignment for commutation. It moves all fingers and spread to open positions. Example: \code // Initializes all finger motors char motor[2] = "G"; err = bh.InitHand(motor); \endcode InitHand() needs to be called after the hand has been reset. This command must be run before any other motor commands, once the hand is turned on. \param motor Specifies which motors to initialize \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::InitHand(const char *motor) { return driverIsOpen() ? m_driver->InitHand(motor) : BHERR_OPENCOMMPORT; } /** Sends the "Reset" command to the hand. Resets the firmware loop in the BarrettHand and sets the baud rate to the default baud rate of 9600 bps unless it is set differently with the BHandSerialDriver::SetDefaultBaud method. Example: \code // resets the hand err = bh.Reset(); \endcode After resetting the BarrettHand you will need to call InitHand() before issuing any motion commands. \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::Reset(bool *responseReceived) { return driverIsOpen() ? m_driver->Reset(responseReceived) : BHERR_OPENCOMMPORT; } /** Sends the "Close" supervisory command to the hand. Commands the selected motor(s) to move finger(s) in the close direction with a velocity ramp-down to target limit, CT. Example: \code // closes grasp char motor[4] = "123"; err = bh.Close(motor); \endcode Finger(s) close until the joint stop(s) are reached, the close target is reached, or an obstacle is encountered. \param motor Specifies which motors will be closed \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::Close(const char *motor) { return driverIsOpen() ? m_driver->Close(motor) : BHERR_OPENCOMMPORT; } /** Sends the "Open" supervisory command to the hand. Commands the selected motor(s) to move finger(s) in the open direction with a velocity ramp-down at target limit, OT. Example: \code // Opens the spread char motor[2] = "S"; err = bh.Open(motor); \endcode Finger(s) open until the open target is reached or an obstacle is encountered. The motor argument passed to the function needs to be a pointer to a string. \param motor Specifies which motors will be opened \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::Open(const char *motor) { return driverIsOpen() ? m_driver->Open(motor) : BHERR_OPENCOMMPORT; } /** Sends the "Goto Default" supervisory command to the hand. Moves all motors to default positions defined by the default property DP. Example: \code // move grasp to default positions char result; err = bh.GoToDefault(motor); \endcode The motor argument passed to the function needs to be a pointer to a string. \param motor Specifies which motors will be moved \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::GoToDefault(const char* motor) { return driverIsOpen() ? m_driver->GoToDefault(motor) : BHERR_OPENCOMMPORT; } /** Sends the "GoTo Different Position" supervisory command to the hand. Moves all motors to specified encoder positions. Example: \code // moves finger F1 to 2000, finger F2 to 3000, finger F3 to 4000, and spread to 1000 err = bh.GoToDifferentPositions(2000, 3000, 4000, 1000); \endcode Encoder positions will be validated before setting "DP" property and going to the desired encoder positions. \param value1 Specifies the encoder position for motor 1 \param value2 Specifies the encoder position for motor 2 \param value3 Specifies the encoder position for motor 3 \param value4 Specifies the encoder position for motor 4 \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::GoToDifferentPositions(int value1, int value2, int value3, int value4) { if (!driverIsOpen()) return BHERR_OPENCOMMPORT; if (validate(1, "DP", value1)) return BHERR_OUTOFRANGE; if (validate(2, "DP", value2)) return BHERR_OUTOFRANGE; if (validate(4, "DP", value3)) return BHERR_OUTOFRANGE; if (validate(8, "DP", value4)) return BHERR_OUTOFRANGE; // Fill desired encoder positions in array int encoderPositions[4]; encoderPositions[0] = value1; encoderPositions[1] = value2; encoderPositions[2] = value3; encoderPositions[3] = value4; return m_driver->GoToDifferentPositions(encoderPositions, 4); } /** Sends the "GoTo Home" supervisory command to the hand. Moves the specified motors to position 0. If any fingers are sent home then all fingers will be sent home. Spread is sent home last and only if it is commanded to return to the home posiiton. Example: \code // moves all motors to the home position err = bh.GoToHome(); \endcode \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::GoToHome(const char *motor) { return driverIsOpen() ? m_driver->GoToHome(motor) : BHERR_OPENCOMMPORT; } /** Sends the "GoTo Position" supervisory command to the hand. Moves motors to specified encoder position. Example: \code // moves finger F3 to position 10000 char motor[2] = "3"; err = bh.GoToPosition(motor, 10000); \endcode Encoder position will be validated to be in the range of the "DP" property for each included motor. \param motor Specifies which motors will be moved to the encoder position \param value Specifies the encoder position to move to \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::GoToPosition(const char *motor, int value) { if (!driverIsOpen()) return BHERR_OPENCOMMPORT; BHMotors bhMotors = toBHMotors(motor); if (validate(bhMotors, "DP", value)) return BHERR_OUTOFRANGE; return m_driver->GoToPosition(motor, value); } /** Sends the "Step Close" supervisory command to the hand. Incrementally closes the specified motors. The property DS contains the default increment size that will be used. Example: \code // step close finger F2 1500 encoder counts char motor[2] = "2"; err = bh.StepClose(motor, 1500); \endcode Step size will be validated to be in the range of the "DS" property for each included motor. \param motor Specifies which motors will be closed \param stepAmount Specifies the step size amount in encoder ticks \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::StepClose(const char *motor, int stepAmount) { if (!driverIsOpen()) return BHERR_OPENCOMMPORT; BHMotors bhMotors = toBHMotors(motor); if (validate(bhMotors, "DS", stepAmount)) return BHERR_OUTOFRANGE; return m_driver->StepClose(motor, true, stepAmount); } /** Sends the "Step Close" supervisory command to the hand. Incrementally closes the specified motors. The property DS contains the default increment size that will be used. Example: \code // step close finger F2 1500 encoder counts char motor[2] = "2"; err = bh.StepClose(motor, 1500); \endcode \param motor Specifies which motors will be closed \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::StepClose(const char *motor) { if (!driverIsOpen()) return BHERR_OPENCOMMPORT; return m_driver->StepClose(motor); } /** Sends the "Step Open" supervisory command to the hand. Incrementally opens the specified motors. The property DS contains the default increment size that will be used. Example: \code // step open the grasp 2000 encoder counts char motor[2] = "G"; err = bh.StepOpen(motor, 2000); \endcode Step size will be validated to be in the range of the "DS" property for each included motor. \param motor Specifies which motors will be opened \param stepAmount Specifies the step size amount in encoder ticks \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::StepOpen(const char *motor, int stepAmount) { if (!driverIsOpen()) return BHERR_OPENCOMMPORT; BHMotors bhMotors = toBHMotors(motor); if (validate(bhMotors, "DS", stepAmount)) return BHERR_OUTOFRANGE; return m_driver->StepOpen(motor, true, stepAmount); } /** Sends the "Step Open" supervisory command to the hand. Incrementally opens the specified motors. The DS property contains the default increment size that will be used. Example: \code // step open finger F2 by DP encoder counts char motor[2] = "2"; err = bh.StepOpen(motor); \endcode \param motor Specifies which motors will be opened \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::StepOpen(const char *motor) { if (!driverIsOpen()) return BHERR_OPENCOMMPORT; return m_driver->StepOpen(motor); } /** Sends the "Torque Close" supervisory command to the hand. Commands velocity of selected motor(s) in the direction that closes the finger(s) with control of motor torque at stall. Example: \code // closes grasp with torque control char motor[4] = "123"; err = bh.TorqueClose(motor); \endcode \param motor Specifies which motors will be closed with torque control \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::TorqueClose(const char *motor) { return driverIsOpen() ? m_driver->TorqueClose(motor) : BHERR_OPENCOMMPORT; } /** Sends the "Torque Open" supervisory command to the hand. Commands velocity of selected motor(s) in the direction that opens the finger(s) with control of motor torque at stall. Example: \code // opens grasp with torque control char motor[4] = "123"; err = bh.TorqueOpen(motor); \endcode \param motor Specifies which motors will be opened with torque control \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::TorqueOpen(const char *motor) { return driverIsOpen() ? m_driver->TorqueOpen(motor) : BHERR_OPENCOMMPORT; } /////////////////////////////////////////////////////////////////////////// // More methods in Supervisory Module (Property Get/Set) /////////////////////////////////////////////////////////////////////////// /** Sends the "Get" command to the hand. Gets motor properties. Example: \code // gets the maximum close velocity for finger F1 and stores it in result char motor[2] = "1"; char property[4] = "MCV"; int result; err = bh.Get(motor, property, &result); \endcode Refer to the BH8-Series User Manual or the BHControl GUI for a list of motor properties and their functions. Verify that the size of the result variable can hold all values returned. For example, if you request the values for motors F1, F2, and F3, make sure you pass a pointer to an array with at least 3 valid locations. \param motor Specifies which motor's property to get \param propertyName Specifies which motor property you want to get \param result Specifies a pointer to where the result(s) will be stored \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::Get(const char *motor, const char *propertyName, int *result) { if (!driverIsOpen()) return BHERR_OPENCOMMPORT; // Get value(s) for properties int r; if ((r = m_driver->Get(motor, propertyName, result))) return r; // Validate values before returning? return 0; } /** Sends the "Set" command to the hand. Sets motor properties. Example: \code // set finger F1 maximum close velocity to 20 char motor[2] = "1"; char property[4] = "MCV"; err = bh.Set(motor, property, 20); \endcode Refer to the BH8-Series User Manual or the BHControl GUI for a list of motor properties and their functions. Set validates desired property value first. \param motor Specifies which motor's properties to set \param propertyName Specifies which motor property will be set \param value Specifies the desired value of the property \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::Set(const char *motor, const char *propertyName, int value) { if (!driverIsOpen()) return BHERR_OPENCOMMPORT; //if (validate(toBHMotors(motor), propertyName, value)) // return BHERR_OUTOFRANGE; return m_driver->Set(motor, propertyName, value); } /** Sends the "PGet" command to the hand. Gets the value of a global property. Example: \code // get over temperature fault value char property[6] = "OTEMP"; int result; err = bh.PGet(property, &result); \endcode Refer to the BH8-Series User Manual or the BHControl GUI for a list of motor properties and their functions. \param propertyName Specifies which global property to get \param result Specifies a pointer to where the result will be stored \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::PGet(const char *propertyName, int *result) { if (!driverIsOpen()) return BHERR_OPENCOMMPORT; // Get value for property int r; if ((r = m_driver->PGet(propertyName, result))) return r; return 0; } /** Sends the "PSet" command to the hand. Sets the value of a global property. Example: \code // set over temperature fault to 585 (58.5 degrees Celsius) char property[6] = "OTEMP"; err = bh.PSet(property, 585); \endcode Refer to the BH8-Series User Manual or the BHControl GUI for a list of motor properties and their functions. PSet validates desired property value first. \param propertyName Specifies which global property will be set \param value Specifies the desired value of the property \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::PSet(const char *propertyName, int value) { if (!driverIsOpen()) return BHERR_OPENCOMMPORT; if (validate(propertyName, value)) return BHERR_OUTOFRANGE; return m_driver->PSet(propertyName, value); } /** Sends the "Default" command to the hand. Loads factory default motor properties from EEPROM into active property list. Example: \code // loads factory default properties for the grasp char motor[2] = "G"; err = bh.Default(motor); \endcode This command only changes the active properties, to write the properties to EEPROM use Save(). The motor argument passed to the function needs to be a pointer to a string. \param motor Specifies which motor's default properties to load \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::Default(const char* motor) { return driverIsOpen() ? m_driver->Default(motor) : BHERR_OPENCOMMPORT; } /** Sends the "Load" command to the hand. Loads the saved motor properties from EEPROM into active property list. Example: \code // loads previously saved properties for the grasp char motor[2] = "G"; err = bh.Load(motor); \endcode The motor argument passed to the function needs to be a pointer to a string. All of the settable firmware properties will be loaded into RAM. \param motor Specifies which motor's properties to load \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::Load(const char* motor) { return driverIsOpen() ? m_driver->Load(motor) : BHERR_OPENCOMMPORT; } /** Sends the "Save" command to the hand. Saves present motor properties from the active properties list to EEPROM. These values can be loaded later. Storing the values in EEPROM allows you to reset the BarrettHand and retain preferred motor properties. Example: \code // saves the grasp motor properties char motor[2] = "G"; err = bh.Save(motor); \endcode The properties can be recalled into the active properties list by using the function Load(). The motor argument passed to the function needs to be a pointer to a string. However, this command should not be performed more than 5,000 times or the Hand electronics may need repair. \param motor Specifies which motor's properties to save \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::Save(const char *motor) { return driverIsOpen() ? m_driver->Save(motor) : BHERR_OPENCOMMPORT; } /** Sends the "Temperature" request command to the hand. Returns temperature from the BarrettHand. For the 262 hand, this is CPU temperature and for the 280 hand it is the maximum temperature read from any of the Pucks. Example: \code // stores the temperature in result int result; err = bh.Temperature(&result); \endcode \param result A pointer to where the temperature value will be stored (in degrees Celsius) \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::Temperature(int *result) { return driverIsOpen() ? m_driver->Temperature(result) : BHERR_OPENCOMMPORT; } /////////////////////////////////////////////////////////////////////////// // More methods in Supervisory Module (Misc.) /////////////////////////////////////////////////////////////////////////// void allocate(COMMAND_RESULT *cResult) { if (cResult) { // Allocatate space for string in command result cResult->result = new char[MAX_COMMAND_RESULT_LENGTH]; cResult->result[0] = 0; } } /** Sends a command to the hand and is able to receive a response. Send an ASCII character string to the BarrettHand. The hand is expected to respond in Supervisory mode. If the receive buffer is supplied, the function will copy the hand response into the buffer. If not and you are using serial, you can obtain the hand response using the command Response(). Example: \code // gets maximum close velocity of motor F3 and stores // the resultant string value in receive char command[10] = "3FGET MCV"; char receive[10]; err = bh.Command(command, receive); \endcode This function can be used to implement a simple terminal control. The command argument passed to the function needs to be a pointer to a string. The receive buffer for the response must be allocated by the user and be large enough to hold the response for the sent command. \param send String to send to the BarrettHand (any variation of letters and numbers) \param receive Pointer to a buffer where the response will be stored \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::Command(const char *send, char *receive) { if (!driverIsOpen()) return BHERR_OPENCOMMPORT; #ifdef BH8_262_HARDWARE BHandHardware *hw = m_bhand->getHardwareDesc(); // If 262 then send commands directly to the hand and ignore validating command parameters if (strcmp(hw->getModelNumber(), BHAND_BH8_262_MODEL_NUM) == 0) return m_driver->Command(send, receive); #endif // Hand must be a 280 //printf("Command(%s)\n", send); if (receive != NULL) *receive = 0; // NULL terminate receive buffer // Cannot send a command if it is too long if (strlen(send) + 1 >= MAX_CMD_LEN) { //printf("Command very long...\n"); // Then send the command directly return m_driver->Command(send, receive); } //printf("Command NULL terminated receive buffer\n"); // Local storage for command and command result COMMAND command; COMMAND_RESULT command_result; // Initialize variables for result COMMAND_RESULT *cResult = &command_result; cResult->result = NULL; // Copy send string into command buffer strcpy(command.command, send); //printf("Command parseInput(COMMAND(%s))\n", command.command); // Parse command (with code from btclient\src\btdiag that needs to be merged with Puck code) parseInput(&command, cResult); // Copy the results of parsing command to local variables int cmd = command_result.command; // parsed command BHMotors bhMotors = command_result.bhMotors; // optional parsed motors included //int puckProperty = command_result.p; // optional parsed property bool valueIncluded = command_result.valueIncluded; // optional parsed value included for commands such as step open/close int value = command_result.value; // optional parsed value //if (cResult->result != NULL) // printf("Command parseInput: %s\n", cResult->result); //else // printf("Command parseInput:\n"); //printf(" cmd = %d\n", cmd); //printf(" bhMotors = %d\n", bhMotors); //printf(" puckProperty = %d\n", puckProperty); //printf(" valueIncluded = %d\n", valueIncluded); //printf(" value = %d\n", value); // Create for motor string for commands char motors[10]; toMotorChar(bhMotors, motors); //printf("Command after toMotorChar(%d) returned %s\n", bhMotors, motors); // Call methods in hand driver switch (cmd) { // Init, Calibration, Reset, etc. case CMD_HI: { return InitHand(motors); } case CMD_RESET: { bool reset; return Reset(&reset); } // Movement commands case CMD_C: { return Close(motors); } case CMD_O: { return Open(motors); } case CMD_M: { return valueIncluded ? GoToPosition(motors, value) : GoToDefault(motors); } case CMD_HOME: { return GoToHome(motors); } case CMD_IC: { return valueIncluded ? StepClose(motors, value) : StepClose(motors); } case CMD_IO: { return valueIncluded ? StepOpen(motors, value) : StepOpen(motors); } case CMD_TC: { return TorqueClose(motors); break; } case CMD_TO: { return TorqueOpen(motors); break; } // Motor and global property Get/Set commands case CMD_SET: { return Set(motors, command_result.propertyName, value); } // FSET, PSET case CMD_GET: { // Check if this is a global property unsigned int nResults = countMotors(bhMotors); //p->getNumExtendedAttributes(); //printf("Command Get nResults = %d\n", nResults); // Allocate space for result(s) int *results = new int[nResults]; //printf(" In command calling Get(%s, %s, results)\n", motors, propName); //printf("Command Get multiple\n"); Get(motors, command_result.propertyName, results); // If return results immediately then create string containing results char *resultString = receive; char propValueString[64]; for (unsigned int i = 0; i < nResults; i++) { sprintf(propValueString, "%d ", results[i]); strcat(resultString, propValueString); } // Remove space character at the end of string if (strlen(resultString) > 0) resultString[strlen(resultString) - 1] = 0; //printf("Command Get results concatenated: %s\n", resultString); // Free space allocated for result(s) delete[] results; return 0; } // FGET, PGET case CMD_LOAD: { return Load(motors); } // FLOAD, PLOAD case CMD_SAVE: { return Save(motors); } // FSAVE, PSAVE case CMD_DEF: { return Default(motors); } // FDEF, PDEF // FLIST, FLISTV // PLIST, and PLISTV case CMD_T: { return StopMotor(motors); } // RealTime commands case CMD_LOOP: { return RTStart(motors); } default: { // Drop this command - don't try to handle it return BHERR_NOTCOMPLETED; } /* // Administrative Commands case CMD_HELP: { break; } // TODO: set the appropriate help string for "pucks in hand" case CMD_ERR: { break; } // TODO: Handle this command case CMD_VERS: { break; } // TODO: Handle this command // Advanced Commands // A?, FLISTA, FLISTAV, PLISTA, PLISTAV */ } } /** Sends the "Delay" command to the hand. Insert a delay into sequence of commands. Example: \code // Inserts a delay of 3 seconds unsigned int time = 3000; err = bh.Delay(time); \endcode \param msec The desired delay in units of milliseconds \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::Delay(unsigned int msec) { if (!driverIsOpen()) return BHERR_OPENCOMMPORT; // Just in case the user cast a negative number to an int if (((int)msec) <= 0) return BHERR_OUTOFRANGE; return m_driver->Delay(msec); } /** Sends the "Stop Motor" command to the hand. Stops actuating motors specified. Example: \code // stops actuating the spread motor char motor[2] = "S"; err = bh.StopMotor(motor); \endcode Use StopMotor() command, when possible, to reduce the amount of heat generated by the motor. \param motor Specifies which motors will be terminated \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::StopMotor(const char *motor) { return driverIsOpen() ? m_driver->StopMotor(motor) : BHERR_OPENCOMMPORT; } #ifdef BH8_262_HARDWARE /** Gets a pointer to the receive buffer for the hand. Provides read access to the receive buffer. The buffer will contain the response for the last command sent to the BarrettHand. \retval const char * Returns a pointer to the receive buffer */ const char* BHandSupervisoryRealtime::Response() { return serialDriverIsOpen() ? ((BHandSerialDriver *)m_driver)->Response() : NULL; } /** Gets a pointer to the transmit buffer for the hand. Provides read access to the transmit buffer. \retval const char * Returns a pointer to the transmit buffer */ const char* BHandSupervisoryRealtime::Buffer() { return serialDriverIsOpen() ? ((BHandSerialDriver *)m_driver)->Response() : NULL; } #endif /** Sends "Baud" command to the Barrett Hand. Changes the baud rate of both the associated hand and the COM port on the host PC to the new value. The possible values are the standard baud rates up to 38400. Example: \code // sets hand and serial port to 9600 baud unsigned int baudrate = 9600; err = bh.Baud(baudrate); \endcode The baud rate of the hand is reset to the default baud rate by issuing the Reset() command. Baud rate can be saved between resets by executing the "PSAVE" command after the Baud command. Examples and demos work only with the hand starting up at 9600 bps so saving higher baud rates should only be done by experienced users. \param newbaud The desired baud rate should be stored in this variable \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::Baud(unsigned int newbaud) { return driverIsOpen() ? m_driver->Baud(newbaud) : BHERR_OPENCOMMPORT; } /////////////////////////////////////////////////////////////////////////////// // RealTime mode commands /////////////////////////////////////////////////////////////////////////////// /** Sends "Start" RealTime Mode Command to the Barrett Hand. Call this function after desired loop mode properties have been set and you are ready to enter RealTime control. Only one active motor control mode may be active or RTStart may return an error (e.g. don't try to control motor torques and velocities at the same time). Example: \code // Enter motor F2 into RealTime control char motor[2] = "2"; err = bh.RTStart(motor); \endcode The motor argument passed to the function needs to be a pointer to a string. Motor protection is an optional argument that is used to set the desired motor protection level for the 280 hand only. The default value is BHMotorTSTOPProtect. This will protect motors from overheating and damage if a motor comes to a stop after TSTOP milliseconds. The motor mode will be returned to idle mode to protect the motor so RTAbort and RTStart will need to be called again to regain control of the stopped motor(s). Another option available is to set the motorProtection argument to BHMotorTorqueLimitProtect. This will limit the maximum torque to motors to a safe amount during RTUpdate calls. It is important that RTUpdate is called frequently or a stalled motor may not have its torque limited. If a user program is not calling RTUpdate then motors may overheat and be damaged. \param motor Determines which motors will be controlled in RealTime \param motorProtection See above for detailed description \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::RTStart(const char *motor, BHMotorProtection motorProtection) { return driverIsOpen() ? m_driver->RTStart(motor, motorProtection) : BHERR_OPENCOMMPORT; } /** Sends "Update" RealTime Mode Command to the Barrett Hand. This command is used to trigger the sending and receiving of data between the host PC and the Hand. Example: \code // Set Velocity to 30 and read position for motor 2, stop when position > 3000 char motor[2] = "2"; char parameter[2] = "P"; int pos[1]; err = bh.RTSetFlags(motor, TRUE, 1, FALSE, FALSE, 1, FALSE, TRUE, FALSE, 1, TRUE, FALSE); err = bh.Get(motor, parameter, pos); err = bh.RTStart(motor); while (pos[1] < 3000) { err = bh.RTSetVelocity(`2`, 30); err = bh.RTUpdate(TRUE, TRUE); pos = bh.RTGetPosition(`2`); } \endcode \param control Indicates if control data should be sent \param feedback Indicates if feedback data should be received \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::RTUpdate(bool control, bool feedback) { return driverIsOpen() ? m_driver->RTUpdate(control, feedback) : BHERR_OPENCOMMPORT; } /** Sends "Abort" RealTime Mode Command to the Barrett Hand. Ends RealTime mode and returns to Supervisory mode. Example: \code // Ends RealTime control err = bh.RTAbort(); \endcode \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::RTAbort() { return driverIsOpen() ? m_driver->RTAbort() : BHERR_OPENCOMMPORT; } /** This method will "Update" Puck properties while in RealTime Mode. This command will efficiently request property values from the given Pucks and wait until the properties have been read and stored in the array passed to this method. It is provided to be able to read properties in between calls to RTUpdate(bool, bool). Example: \code // Set Velocity to 30 and read position for motor F2, stop when position > 3000 char motors[2] = "G"; char prop[] = "JP"; int jointPositions[4]; // must be of the number of motors in the hand ... while (1) { ... err = bh.RTUpdate(TRUE, TRUE); err = bh.RTUpdate(motors, prop, jointPositions); } \endcode The size of the array passed into this method must be equal to the number of motors in the hand. Ensure that the array is large enough to hold values for each motor of the hand even if not all motor property values are read. \param motor Determines which motor properties to retrieve in RealTime mode \param property The name of the Puck 2 property \param values Pointer to an array that will contain retrieved results \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::RTUpdate(const char *motor, const char *property, int *values) { return driverIsOpen() ? m_driver->RTUpdate(motor, property, values) : BHERR_OPENCOMMPORT; } /** Sends "Set Flags" RealTime Mode Command to the Barrett Hand. Sets the nine of the parameters relevant for RealTime mode, for the specified motors. See BH8-Series User Manual for a list of relevant RealTime Parameters and their functions. Example: \code // Prepares flags and variables to send control velocity // and receive absolute position to/from motor F2 bool control_velocity_flag = TRUE, control_propgain_flag = FALSE, feedback_velocity_flag = FALSE, feedback_strain_flag = FALSE, feedback_position_flag = TRUE, feedback_deltapos_flag = FALSE; int control_velocity_coefficient = 1; int feedback_velocity_coefficient = 1; int feedback_delta_position_coefficient = 1; char motor[2] = "2"; err = bh.RTSetFlags(motor, control_velocity_flag, control_velocity_coefficient, control_propgain_flag, feedback_velocity_flag, feedback_velocity_coefficient, feedback_strain_flag, feedback_position_flag, feedback_deltapos_flag, feedback_delta_position_coefficient); \endcode This function is provided for convenience, the same effect can be achieved with multiple calls to the Set() function. However, RTSetFlags can only define some of the parameters that can be defined with Set(). The motor argument passed to the function needs to be a pointer to a string. \param motor Determines which motor parameters will be set \param LCV Loop Control Velocity Flag \param LCVC Loop Control Velocity Coefficient \param LCPG Loop Control Proportional Gain Flag \param LFV Loop Feedback Velocity Flag \param LFVC Loop Feedback Velocity Coefficient \param LFS Loop Feedback Stain Flag \param LFAP Loop Feedback Absolute Position Flag \param LFDP Loop Feedback Delta Position Flag \param LFDPC Loop Feedback Delta Position Coefficient \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::RTSetFlags(const char *motor, bool LCV, int LCVC, bool LCPG, bool LFV, int LFVC, bool LFS, bool LFAP, bool LFDP, int LFDPC) { /* if (!driverIsOpen) return BHERR_OPENCOMMPORT; // Validate input parameters if (validate("LCVC", LCVC)) return BHERR_OUTOFRANGE; if (validate("LFVC", LFVC)) return BHERR_OUTOFRANGE; if (validate("LFDPC", LFDPC)) return BHERR_OUTOFRANGE; // Call method provided by driver return m_driver->RTSetFlags(motor, LCV, LCVC, LCPG, LFV, LFVC, LFS, LFAP, LFDP, LFDPC); */ return driverIsOpen() ? m_driver->RTSetFlags(motor, LCV, LCVC, LCPG, LFV, LFVC, LFS, LFAP, LFDP, LFDPC) : BHERR_OPENCOMMPORT; } /** Sends "Set Flags" RealTime Mode Command to the Barrett Hand. Sets the fourteen of the parameters relevant for RealTime mode, for the specified motors. See BH8-Series User Manual for a list of relevant RealTime Parameters and their functions. Example: \code // Prepares flags and variables to send control velocity // and receive absolute position and temperature to/from motor F2 bool control_velocity_flag = TRUE, control_propgain_flag = FALSE, control_torque_flag = FALSE, feedback_velocity_flag = FALSE, feedback_strain_flag = FALSE, feedback_position_flag = TRUE, feedback_deltapos_flag = FALSE, feedback_breakaway_position_flag = FALSE, feedback_analog_input_flag = FALSE, feedback_delta_position_discard_flag = FALSE, feedback_temperature = TRUE; int control_velocity_coefficient = 1; int feedback_velocity_coefficient = 1; int feedback_delta_position_coefficient = 1; char motor[2] = "2"; err = bh.RTSetFlags(motor, control_velocity_flag, control_velocity_coefficient, control_propgain_flag, control_torque_flag, feedback_velocity_flag, feedback_velocity_coefficient, feedback_strain_flag, feedback_position_flag, feedback_deltapos_flag, feedback_delta_position_coefficient, feedback_breakaway_position_flag, feedback_analog_input_flag, feedback_delta_position_discard_flag, feedback_temperature); \endcode This function is provided for convenience, the same effect can be achieved with multiple calls to the Set() function. However, RTSetFlags can only define some of the parameters that can be defined with Set(). The motor argument passed to the function needs to be a pointer to a string. \param motor Determines which motor parameters will be set \param LCV Loop Control Velocity Flag \param LCVC Loop Control Velocity Coefficient \param LCPG Loop Control Proportional Gain Flag \param LCT Loop Control Torque Flag \param LFV Loop Feedback Velocity Flag \param LFVC Loop Feedback Velocity Coefficient \param LFS Loop Feedback Stain Flag \param LFAP Loop Feedback Absolute Position Flag \param LFDP Loop Feedback Delta Position Flag \param LFDPC Loop Feedback Delta Position Coefficient \param LFBP Loop Feedback Breakaway Position Flag \param LFAIN Loop Feedback Analog Input Flag \param LFDPD Loop Feedback Delta Position Discard Flag \param LFT Loop Feedback Temperature Flag \retval int Returns 0 on success and a BHERR error code on failure */ int BHandSupervisoryRealtime::RTSetFlags(const char *motor, bool LCV, int LCVC, bool LCPG, bool LCT, bool LFV, int LFVC, bool LFS, bool LFAP, bool LFDP, int LFDPC, bool LFBP, bool LFAIN, bool LFDPD, bool LFT) { return driverIsOpen() ? m_driver->RTSetFlags(motor, LCV, LCVC, LCPG, LCT, LFV, LFVC, LFS, LFAP, LFDP, LFDPC, LFBP, LFAIN, LFDPD, LFT) : BHERR_OPENCOMMPORT; } /** Gets RealTime velocity feedback for the desired motor. Example: \code // Get velocity feedback of motor F1 char velocity = bh.RTGetVelocity(`1`); \endcode BH8-262 velocity feedback is divided by the loop feedback velocity coefficient (LFVC) before it is sent by the hand. This value can be set with the RTSetFlags method. The returned velocity units are encoder ticks per 10 milliseconds and will be scaled accordingly with a LFVC greater than 1. BH8-280 velocity feedback is in encoder ticks per millisecond. Velocity feedback with this method will be clipped to limit the range to be from -127 to 127. The loop feedback velocity (LFV) flag must be set to receive velocity feedback. Only one motor velocity can be retrieved at a time. \param motor Determines which motor velocity will be retrieved \retval int Returns the velocity for the specified motor */ char BHandSupervisoryRealtime::RTGetVelocity(const char motor) { return driverIsOpen() ? m_driver->RTGetVelocity(motor) : 0; } /** Gets RealTime strain gauge feedback for the desired motor. Example: \code // Gets strain gauge value for motor 3 unsigned char strain = bh.RTGetStrain(`3`); \endcode This method may only return 8-bit values so it will scale strain readings to be from 0 to 255. Better resolution can be achieved for BH8-280 users by calling RTUpdate with the "SG" property name passed as a parameter. The loop feedback strain (LFS) flag must be set to receive strain gauge feedback if using just the RTUpdate(bool, bool) method. Only one motor strain gauge reading can be retrieved at a time. \param motor Determines which finger strain gauge values will be retrieved \retval unsigned char Returns the strain gauge value for the specified motor */ unsigned char BHandSupervisoryRealtime::RTGetStrain(const char motor) { return driverIsOpen() ? m_driver->RTGetStrain(motor) : 0; } /** Gets RealTime absolute position feedback for the desired motor. Example: \code // Gets absolute position for motor 1 unsigned char position = bh.RTGetPosition(`1`); \endcode The loop feedback absolute position (LFAP) flag must be set to receive absolute position feedback. The hand also needs to be intialized with the HI command. Only one motor position can be retrieved at a time. \param motor Determines which motor's absolute position will be retrieved \retval int Returns the absolute position of the motor */ int BHandSupervisoryRealtime::RTGetPosition(const char motor) { return driverIsOpen() ? m_driver->RTGetPosition(motor) : 0; } /** Gets RealTime temperature feedback from the Barrett Hand. Example: \code // Get temperature int handtemperature = bh.RTGetTemp(); \endcode The global loop feedback temperature (LFT) flag must be set to receive temperature feedback. BH8-262 temperature is returned as stated in the user manual. BH8-280 temperature will return the maximum of the present TEMP readings from the Pucks. \retval int Returns the temperature value */ int BHandSupervisoryRealtime::RTGetTemp() { return driverIsOpen() ? m_driver->RTGetTemp() : 0; } /** Gets RealTime analog input feedback from the Barrett Hand. Example: \code // Get analog input value for finger F1 int analog1 = bh.RTGetAIN(`1`); \endcode The loop feedback analog input (LFAIN) flag must be set to receive analog input feedback. This is will only work on the BH8-262 hand. \param motor Determines which motor's analog value will be retrieved \retval unsigned char Returns the analog input value for the specified motor */ unsigned char BHandSupervisoryRealtime::RTGetAIN(const char motor) { return driverIsOpen() ? m_driver->RTGetAIN(motor) : 0; } /** Gets RealTime delta position value feedback for the specified motor. Example: \code // Get delta position value for finger F1 int deltaposition1 = bh.RTGetDeltaPos(`1`); \endcode The loop feedback delta position (LFDP) flag must be set to receive delta position feedback. Delta position is the change in position from the last reported position and is limited to one signed byte. The present position is read and compared to the last reported position. The difference is divided by the RealTime variable LFDPC, clipped to a single signed byte, and then sent to the host. The value sent to the host should then be multiplied by LFDPC and added to the last reported position. Example (with LFDPC set to 2): What will delta position feedback look like if last reported position was 1500 and the position jumps to 2000? The first feedback block will include the delta position value 127. This value should be multiplied by LFDPC on the host machine resulting in 254. The hand will internally update the reported position to 1754. The next feedback block will include the delta position 123, which should be multiplied by LFDPC resulting in 246. The reported position will be updated to 2000. Subsequent feedback blocks will include the delta position value 0 (until the next position change). Delta position feedback is only implemented on the BH8-262 hand in order to increase the servo rate. Only one motor delta position can be retrieved at a time. \param motor Determines which motor's delta position value will be retrieved \retval char Returns the delta position value for the specified motor */ char BHandSupervisoryRealtime::RTGetDeltaPos(const char motor) { return driverIsOpen() ? m_driver->RTGetDeltaPos(motor) : 0; } /** Gets RealTime breakaway position feedback from the Barrett Hand. Example: // Get breakaway position of finger 1 int bp = bh.RTGetBreakawayPosition(`1`); \endcode The loop feedback breakaway position flag must be set to receive the breakaway positions. Open, toque open, and hand initialize commands will reset the breakaway detected (BD) flag and clear the breakaway position (BP). Initialization hit count (IHIT) is used to get a consistent origin for finger motors and thus a consistent breakaway force. Initialization Offset affects the force required to cause breakaway. Properties that affect the breakaway position are the breakaway detection acceleration threshold (BDAT). Breakaway stop (BS) flag is used to stop a finger motor as soon as breakaway is detected. The user is refered to the BH8-262 user manual for information concerning breakaway. Only one motor breakaway position can be retrieved at a time. */ int BHandSupervisoryRealtime::RTGetBreakawayPosition(const char motor) { return driverIsOpen() ? m_driver->RTGetBreakawayPosition(motor) : 0; } void BHandSupervisoryRealtime::RTGetPPS(const char motor, int *pps, int ppsElements) { if (driverIsOpen()) m_driver->RTGetPPS(motor, pps, ppsElements); } /** Sets RealTime control velocity reference for the desired motor. Example: \code // Set control velocity references for motors F1, F2, and F3 to 50 err = bh.RTSetVelocity(`1`, 50); err = bh.RTSetVelocity(`2`, 50); err = bh.RTSetVelocity(`3`, 50); \endcode The loop control velocity (LCV) flag must be set to send velocity references to the hand. BH8-280 Puck motor controllers implement velocity mode on top of a position controller updated at a kilohertz. Velocity references in units of encoder ticks/ms are added to the present commanded position each servo cycle. KP, KI, and KD affect both position and velocity PID gains. BH8-262 motor controllers responds by applying motor torque according to the following equation in the HCTL-1100 datasheet: MCn = (K/4) * Yn Where K depends on the loop control proportional gain (LCPG) flag. If LCPG is set then K is set with RTSetGain, otherwise K is equal to the value of the "FPG" property. Yn is the velocity error and equals: Loop Control Velocity Reference * Loop Control Velocity Coefficient - Actual Velocity In proportional velocity control mode, the HCTL-1100 tries to match the desired motor control reference velocities by applying motor torques proportional to the velocity error. The proportional gain "K" may be set at runtime. The actual velocity is in units of encoder ticks per 10 milliseconds. The motor will not actually be sent this control velocity reference until RTUpdate() is called. Only one motor velocity reference can be set at a time. \param motor Determines which motor velocity reference will be set \param velocity Desired control velocity for the specified motor \retval int Returns 0 on success and BHERR_MOTORINACTIVE if motor is inactive */ int BHandSupervisoryRealtime::RTSetVelocity(const char motor, int velocity) { return driverIsOpen() ? m_driver->RTSetVelocity(motor, velocity) : 0; } /** Sets RealTime control torque for the desired motor. Example: \code // Set control torque parameters of motors F1, F2, and F3 to 50 err = bh.RTSetTorque(`1`, 50); err = bh.RTSetTorque(`2`, 50); err = bh.RTSetTorque(`3`, 50); \endcode The loop control torque (LCT) flag needs to be set to send 16-bit torque references to the hand. BH8-262 motor torque references will be used in position mode to apply motor torques. The desired motor torque will be added to the present motor encoder position and be submitted as the commanded position. The BH8-280 will control motor currents directly by using the desired torque reference. The motor will not actually be set to this control torque until RTUpdate() is called. Only one motor control torque can be set at a time. \param motor Determines which motor torque will be set \param torque Desired control velocity for the specified motor \retval int Returns 0 on success and BHERR_MOTORINACTIVE if motor is inactive */ int BHandSupervisoryRealtime::RTSetTorque(const char motor, int torque) { return driverIsOpen() ? m_driver->RTSetTorque(motor, torque) : 0; } /** Sets RealTime control proportional gain for the desired motor. Example: \code // Set gain parameters of motors 1 and 2 to 150 err = bh.RTSetGain(`1`, 150); err = bh.RTSetGain(`2`, 150); \endcode This method should only be used for the BH8-262 hand. The loop control proportional gain (LCPG) flags must be set to send proportional gains to the hand. The gains for the motors will not actually be set until RTUpdate() is called. In RealTime control, the motors are controlled using a proportional velocity mode. The proportional gain affects the motor command according to the Velocity Control equations. See RTSetVelocity method for more information. \param motor Determines which motor gain will be set \param gain Desired proportional gain for the specified motor \retval int Returns 0 on success and BHERR_MOTORINACTIVE if motor is inactive */ int BHandSupervisoryRealtime::RTSetGain(const char motor, int gain) { return driverIsOpen() ? m_driver->RTSetGain(motor, gain) : 0; } /** Sets RealTime position reference for the desired motor. Example: \code // Set positions of F3 and spread to be in the center position err = bh.RTSetPosition(`3`, -100000); err = bh.RTSetPosition(`S`, -18000); \endcode RealTime position control is only possible with the 280 hand. The loop control position (LCP) flag needs to be set to send desired position references to the hand. The new reference positions will not actually be set until RTUpdate() is called. Only one motor control position reference can be set at a time. \param motor Determines which motor position will be set \param position Desired position for the specified motor \retval int Returns 0 on success and BHERR_MOTORINACTIVE if motor is inactive */ int BHandSupervisoryRealtime::RTSetPosition(const char motor, int position) { return driverIsOpen() ? m_driver->RTSetPosition(motor, position) : 0; }
// Created on: 1994-05-02 // Created by: Christian CAILLET // Copyright (c) 1994-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IFSelect_AppliedModifiers_HeaderFile #define _IFSelect_AppliedModifiers_HeaderFile #include <Standard.hxx> #include <IFSelect_SequenceOfGeneralModifier.hxx> #include <Interface_IntList.hxx> #include <Standard_Integer.hxx> #include <Standard_Transient.hxx> #include <TColStd_HSequenceOfInteger.hxx> class IFSelect_GeneralModifier; class IFSelect_AppliedModifiers; DEFINE_STANDARD_HANDLE(IFSelect_AppliedModifiers, Standard_Transient) //! This class allows to memorize and access to the modifiers //! which are to be applied to a file. To each modifier, is bound //! a list of integers (optional) : if this list is absent, //! the modifier applies to all the file. Else, it applies to the //! entities designated by these numbers in the produced file. //! //! To record a modifier, and a possible list of entity numbers to be applied on: //! AddModif (amodifier); //! loop on AddNum (anumber); //! //! To query it, Count gives the count of recorded modifiers, then for each one: //! Item (numodif, amodifier, entcount); //! IsForAll () -> can be called, if True, applies on the whole file //! //! for (i = 1; i <= entcount; i ++) //! nument = ItemNum (i); -> return an entity number class IFSelect_AppliedModifiers : public Standard_Transient { public: //! Creates an AppliedModifiers, ready to record up to <nbmax> //! modifiers, on a model of <nbent> entities Standard_EXPORT IFSelect_AppliedModifiers(const Standard_Integer nbmax, const Standard_Integer nbent); //! Records a modifier. By default, it is to apply on all a //! produced file. Further calls to AddNum will restrict this. //! Returns True if done, False if too many modifiers are already //! recorded Standard_EXPORT Standard_Boolean AddModif (const Handle(IFSelect_GeneralModifier)& modif); //! Adds a number of entity of the output file to be applied on. //! If a sequence of AddNum is called after AddModif, this //! Modifier will be applied on the list of designated entities. //! Else, it will be applied on all the file //! Returns True if done, False if no modifier has yet been added Standard_EXPORT Standard_Boolean AddNum (const Standard_Integer nument); //! Returns the count of recorded modifiers Standard_EXPORT Standard_Integer Count() const; //! Returns the description for applied modifier n0 <num> : //! the modifier itself, and the count of entities to be applied //! on. If no specific list of number has been defined, returns //! the total count of entities of the file //! If this count is zero, then the modifier applies to all //! the file (see below). Else, the numbers are then queried by //! calls to ItemNum between 1 and <entcount> //! Returns True if OK, False if <num> is out of range Standard_EXPORT Standard_Boolean Item (const Standard_Integer num, Handle(IFSelect_GeneralModifier)& modif, Standard_Integer& entcount); //! Returns a numero of entity to be applied on, given its rank //! in the list. If no list is defined (i.e. for all the file), //! returns <nument> itself, to give all the entities of the file //! Returns 0 if <nument> out of range Standard_EXPORT Standard_Integer ItemNum (const Standard_Integer nument) const; //! Returns the list of entities to be applied on (see Item) //! as a HSequence (IsForAll produces the complete list of all //! the entity numbers of the file Standard_EXPORT Handle(TColStd_HSequenceOfInteger) ItemList() const; //! Returns True if the applied modifier queried by last call to //! Item is to be applied to all the produced file. //! Else, <entcount> returned by Item gives the count of entity //! numbers, each one is queried by ItemNum Standard_EXPORT Standard_Boolean IsForAll() const; DEFINE_STANDARD_RTTIEXT(IFSelect_AppliedModifiers,Standard_Transient) private: IFSelect_SequenceOfGeneralModifier themodifs; Interface_IntList thelists; Standard_Integer thenbent; Standard_Integer theentcnt; }; #endif // _IFSelect_AppliedModifiers_HeaderFile
#include <iostream> std::string getBinaryRep(int); std::string evil(int); std::string evil(int n) { int oneCount = 0; std::string binaryRepresentation = getBinaryRep(n); for (int i = 0; i < binaryRepresentation.length(); i++) { if (binaryRepresentation[i] == '1') { oneCount += 1; } } return oneCount % 2 == 1 ? "It's Odious!" : "It's Evil!"; } std::string getBinaryRep(int num) { std::string binaryRep; while (num != 0) { binaryRep = (num % 2 == 0 ? "0" : "1") + binaryRep; num /= 2; } return binaryRep; } int main (int argc, const char *argv[]) { std::cout << getBinaryRep(5) << "\n"; }
#include <iostream> #include <algorithm> using namespace std; int test(int k, int n) { int apt[k+1][n]; for(int i=0; i<=k; i++) { for(int j=0; j<n; j++) { int under, left; under = i > 0 ? apt[i-1][j] : 1; left = j > 0 ? apt[i][j - 1] : 0; apt[i][j] = under + left; } } return apt[k][n-1]; } int main() { int T; cin >> T; while(T--) { int k, n; cin >> k >> n; cout << test(k, n) << endl; } }
#include "stdio.h" int main(){ int n; long long fn[80]; fn[0] = fn[1] = 1; for(int i = 2;i < 52; i++){ fn[i] = fn[i - 1] + fn[i - 2]; } while(~scanf("%d", &n)){ printf("%lld\n",fn[n]); } return 0; }
#include "platform/i_platform.h" #include "target_repo.h" #include "wall_target.h" #include "ctf_soldier_spawn_target.h" #include "../ctf_program_state.h" #include "pickup_target.h" #include "flag_spawn_target.h" #include "soldier_spawn_target.h" using platform::AutoId; namespace map { DefaultTarget const TargetRepo::mDefault = DefaultTarget(-1); TargetRepo::TargetRepo() : Repository<ITarget>( mDefault ) , mTargetFactory( TargetFactory::Get() ) { Init(); } void TargetRepo::Init() { using boost::filesystem::path; Filesys& FSys = Filesys::Get(); PathVect_t Paths; FSys.GetFileNames( Paths, "actors" ); for (auto const& Path : Paths) { if (Path.extension().string() != ".target") { continue; } AutoFile JsonFile = FSys.Open( Path ); if (!JsonFile.get()) { continue; } JsonReader Reader( *JsonFile ); if (!Reader.IsValid()) { continue; } Json::Value Root = Reader.GetRoot(); if (!Root.isArray()) { continue; } for (auto& Desc : Root) { try { AddTargetFromOneDesc( Desc ); } catch (std::exception const& err) { L1( "Exception caught while parsing %s : %s", Path.generic_string().c_str(), err.what() ); } } } } void TargetRepo::AddTargetFromOneDesc( Json::Value& TargetDesc ) { std::string target_name; if (!Json::GetStr( TargetDesc["target_name"], target_name )) { return; } std::string name; if (!Json::GetStr( TargetDesc["name"], name )) { return; } int32_t target_autoid = AutoId( target_name ); int32_t autoid = AutoId( name ); auto target = mTargetFactory( target_autoid ); const Json::Value& setters = TargetDesc["setters"]; if (target->Load( setters )) { mElements.insert( autoid, target.release() ); } } void DefaultTarget::Update( double DeltaTime ) { } DefaultTarget::DefaultTarget(int32_t) : ITarget( -1 ) { } void DefaultTarget::PutTarget( glm::vec2 position ) { } bool DefaultTarget::Load( const Json::Value& ) { return true; } } // namespace map
#include<SoftwareSerial.h> SoftwareSerial gsm(8,9); String incomingch; int flag=0; void setup() { Serial.begin(9600); gsm.begin(9600); pinMode(8,OUTPUT); pinMode(11,OUTPUT); } void check_incoming() { if(gsm.available()) { incomingch = gsm.read(); } } void loop() { check_incoming(); if(incomingch =="RING") { delay(5000); if(authorised no.) //checking for authorised no. { gsm.write("ATA\r\n"); // call recieved successfully delay(500); //play recording: /* welcome to arduino home security please enter the password*/ digitalWrite(8,HIGH); delay(300); digitalWrite(8,LOW); check_code() // func for checking the code using the num pad (freqency) flag is ref variable if(flag==1); { /* open servo motor, lock */ digitalWrite(11,HIGH); //Should specify the angle delay(500); } } else //if not authorised { gsm.write("ATH"); } } }
#include "CTSTracker.h" using namespace CTS; void setup() { begin(); } void loop() { }
#ifndef __VIVADO_SYNTH__ #include <fstream> using namespace std; // Debug utility ofstream* global_debug_handle; #endif //__VIVADO_SYNTH__ #include "mp_2_opt_compute_units.h" #include "hw_classes.h" struct in_in_update_0_write0_merged_banks_2_cache { // RAM Box: {[0, 126], [0, 127], [0, 31]} // Capacity: 65 // # of read delays: 2 hw_uint<32> f0; fifo<hw_uint<32> , 63> f1; hw_uint<32> f2; inline hw_uint<32> peek_0() { return f0; } inline hw_uint<32> peek_63() { #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ return f1.back(); } inline hw_uint<32> peek_64() { return f2; } inline void push(const hw_uint<32> value) { #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ // cap: 1 reading from capacity: 63 f2 = f1.back(); #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ // cap: 63 reading from capacity: 1 f1.push(f0); // cap: 1 f0 = value; } }; struct in_in_update_0_write1_merged_banks_2_cache { // RAM Box: {[1, 127], [0, 127], [0, 31]} // Capacity: 65 // # of read delays: 2 hw_uint<32> f0; fifo<hw_uint<32> , 63> f1; hw_uint<32> f2; inline hw_uint<32> peek_0() { return f0; } inline hw_uint<32> peek_63() { #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ return f1.back(); } inline hw_uint<32> peek_64() { return f2; } inline void push(const hw_uint<32> value) { #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ // cap: 1 reading from capacity: 63 f2 = f1.back(); #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ // cap: 63 reading from capacity: 1 f1.push(f0); // cap: 1 f0 = value; } }; struct in_cache { in_in_update_0_write0_merged_banks_2_cache in_in_update_0_write0_merged_banks_2; in_in_update_0_write1_merged_banks_2_cache in_in_update_0_write1_merged_banks_2; }; inline void in_in_update_0_write0_write(hw_uint<32> & in_in_update_0_write0, in_cache& in, int d0, int d1, int d2) { in.in_in_update_0_write0_merged_banks_2.push(in_in_update_0_write0); } inline void in_in_update_0_write1_write(hw_uint<32> & in_in_update_0_write1, in_cache& in, int d0, int d1, int d2) { in.in_in_update_0_write1_merged_banks_2.push(in_in_update_0_write1); } inline hw_uint<32> mp_2_rd0_select(in_cache& in, int d0, int d1, int d2) { #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ // mp_2_rd0 read pattern: { mp_2_update_0[d0, d1, d2] -> in[2d0, 2d1, d2] : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 31 } // Read schedule : { mp_2_update_0[d0, d1, d2] -> [d2, 1 + 2d1, d0, 2] : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 31 } // Write schedule: { in_update_0[d0, d1, d2] -> [d2, d1, d0, 1] : 0 <= d0 <= 63 and 0 <= d1 <= 127 and 0 <= d2 <= 31 } // DD fold: { mp_2_update_0[d0, d1, d2] -> 64 : 0 < d0 <= 62 and 0 <= d1 <= 63 and 0 <= d2 <= 31; mp_2_update_0[d0, d1, d2] -> (1 + d0) : d0 = 63 and 0 <= d1 <= 63 and 0 <= d2 <= 31; mp_2_update_0[d0, d1, d2] -> 64 : d0 = 0 and 0 <= d1 <= 63 and 0 <= d2 <= 31 } auto value_in_in_update_0_write0 = in.in_in_update_0_write0_merged_banks_2.peek_64(); return value_in_in_update_0_write0; #ifndef __VIVADO_SYNTH__ cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << " d2 = " << d2 << endl; assert(false); return 0; #endif //__VIVADO_SYNTH__ } inline hw_uint<32> mp_2_rd1_select(in_cache& in, int d0, int d1, int d2) { #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ // mp_2_rd1 read pattern: { mp_2_update_0[d0, d1, d2] -> in[2d0, 1 + 2d1, d2] : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 31 } // Read schedule : { mp_2_update_0[d0, d1, d2] -> [d2, 1 + 2d1, d0, 2] : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 31 } // Write schedule: { in_update_0[d0, d1, d2] -> [d2, d1, d0, 1] : 0 <= d0 <= 63 and 0 <= d1 <= 127 and 0 <= d2 <= 31 } // DD fold: { } auto value_in_in_update_0_write0 = in.in_in_update_0_write0_merged_banks_2.peek_0(); return value_in_in_update_0_write0; #ifndef __VIVADO_SYNTH__ cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << " d2 = " << d2 << endl; assert(false); return 0; #endif //__VIVADO_SYNTH__ } inline hw_uint<32> mp_2_rd2_select(in_cache& in, int d0, int d1, int d2) { #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ // mp_2_rd2 read pattern: { mp_2_update_0[d0, d1, d2] -> in[1 + 2d0, 2d1, d2] : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 31 } // Read schedule : { mp_2_update_0[d0, d1, d2] -> [d2, 1 + 2d1, d0, 2] : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 31 } // Write schedule: { in_update_0[d0, d1, d2] -> [d2, d1, d0, 1] : 0 <= d0 <= 63 and 0 <= d1 <= 127 and 0 <= d2 <= 31 } // DD fold: { mp_2_update_0[d0, d1, d2] -> 64 : 0 < d0 <= 62 and 0 <= d1 <= 63 and 0 <= d2 <= 31; mp_2_update_0[d0, d1, d2] -> (1 + d0) : d0 = 63 and 0 <= d1 <= 63 and 0 <= d2 <= 31; mp_2_update_0[d0, d1, d2] -> 64 : d0 = 0 and 0 <= d1 <= 63 and 0 <= d2 <= 31 } auto value_in_in_update_0_write1 = in.in_in_update_0_write1_merged_banks_2.peek_64(); return value_in_in_update_0_write1; #ifndef __VIVADO_SYNTH__ cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << " d2 = " << d2 << endl; assert(false); return 0; #endif //__VIVADO_SYNTH__ } inline hw_uint<32> mp_2_rd3_select(in_cache& in, int d0, int d1, int d2) { #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ // mp_2_rd3 read pattern: { mp_2_update_0[d0, d1, d2] -> in[1 + 2d0, 1 + 2d1, d2] : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 31 } // Read schedule : { mp_2_update_0[d0, d1, d2] -> [d2, 1 + 2d1, d0, 2] : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 31 } // Write schedule: { in_update_0[d0, d1, d2] -> [d2, d1, d0, 1] : 0 <= d0 <= 63 and 0 <= d1 <= 127 and 0 <= d2 <= 31 } // DD fold: { } auto value_in_in_update_0_write1 = in.in_in_update_0_write1_merged_banks_2.peek_0(); return value_in_in_update_0_write1; #ifndef __VIVADO_SYNTH__ cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << " d2 = " << d2 << endl; assert(false); return 0; #endif //__VIVADO_SYNTH__ } // # of bundles = 2 // in_update_0_write // in_in_update_0_write0 // in_in_update_0_write1 inline void in_in_update_0_write_bundle_write(hw_uint<64>& in_update_0_write, in_cache& in, int d0, int d1, int d2) { hw_uint<32> in_in_update_0_write0_res = in_update_0_write.extract<0, 31>(); in_in_update_0_write0_write(in_in_update_0_write0_res, in, d0, d1, d2); hw_uint<32> in_in_update_0_write1_res = in_update_0_write.extract<32, 63>(); in_in_update_0_write1_write(in_in_update_0_write1_res, in, d0, d1, d2); } // mp_2_update_0_read // mp_2_rd0 // mp_2_rd1 // mp_2_rd2 // mp_2_rd3 inline hw_uint<128> in_mp_2_update_0_read_bundle_read(in_cache& in, int d0, int d1, int d2) { // # of ports in bundle: 4 // mp_2_rd0 // mp_2_rd1 // mp_2_rd2 // mp_2_rd3 hw_uint<128> result; hw_uint<32> mp_2_rd0_res = mp_2_rd0_select(in, d0, d1, d2); set_at<0, 128>(result, mp_2_rd0_res); hw_uint<32> mp_2_rd1_res = mp_2_rd1_select(in, d0, d1, d2); set_at<32, 128>(result, mp_2_rd1_res); hw_uint<32> mp_2_rd2_res = mp_2_rd2_select(in, d0, d1, d2); set_at<64, 128>(result, mp_2_rd2_res); hw_uint<32> mp_2_rd3_res = mp_2_rd3_select(in, d0, d1, d2); set_at<96, 128>(result, mp_2_rd3_res); return result; } // Operation logic inline void in_update_0(HWStream<hw_uint<64> >& /* buffer_args num ports = 2 */in_oc, in_cache& in, int d0, int d1, int d2) { // Consume: in_oc auto in_oc_0_c__0_value = in_oc.read(); auto compute_result = id_unrolled_2(in_oc_0_c__0_value); // Produce: in in_in_update_0_write_bundle_write(compute_result, in, d0, d1, d2); #ifndef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ } inline void mp_2_update_0(in_cache& in, HWStream<hw_uint<32> >& /* buffer_args num ports = 1 */mp_2, int d0, int d1, int d2) { // Consume: in auto in_0_c__0_value = in_mp_2_update_0_read_bundle_read(in/* source_delay */, d0, d1, d2); #ifndef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ auto compute_result = max_pool_2x2_unrolled_1(in_0_c__0_value); // Produce: mp_2 mp_2.write(compute_result); #ifndef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ } // Driver function void mp_2_opt(HWStream<hw_uint<64> >& /* get_args num ports = 2 */in_oc, HWStream<hw_uint<32> >& /* get_args num ports = 1 */mp_2, int num_epochs) { #ifndef __VIVADO_SYNTH__ ofstream debug_file("mp_2_opt_debug.csv"); global_debug_handle = &debug_file; #endif //__VIVADO_SYNTH__ in_cache in; #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ #ifdef __VIVADO_SYNTH__ #pragma HLS inline recursive #endif // __VIVADO_SYNTH__ for (int epoch = 0; epoch < num_epochs; epoch++) { // Schedules... // in_oc_update_0 -> [1*d2*1*1 + 1*0,1*d1*1*1 + 1*0,1*d0*1*1 + 1*0,1*0] // in_update_0 -> [1*d2*1*1 + 1*0,1*d1*1*1 + 1*0,1*d0*1*1 + 1*0,1*1] // mp_2_update_0 -> [1*d2*1*1 + 1*0,1*d1*1*2 + 1*1,1*d0*1*1 + 1*0,1*2] for (int c0 = 0; c0 <= 31; c0++) { for (int c1 = 0; c1 <= 127; c1++) { for (int c2 = 0; c2 <= 63; c2++) { #ifdef __VIVADO_SYNTH__ #pragma HLS pipeline II=1 #endif // __VIVADO_SYNTH__ if ((0 <= c2 && c2 <= 63) && ((c2 - 0) % 1 == 0) && (0 <= c1 && c1 <= 127) && ((c1 - 0) % 1 == 0) && (0 <= c0 && c0 <= 31) && ((c0 - 0) % 1 == 0)) { in_update_0(in_oc, in, (c2 - 0) / 1, (c1 - 0) / 1, (c0 - 0) / 1); } if ((0 <= c2 && c2 <= 63) && ((c2 - 0) % 1 == 0) && (1 <= c1 && c1 <= 127) && ((c1 - 1) % 2 == 0) && (0 <= c0 && c0 <= 31) && ((c0 - 0) % 1 == 0)) { mp_2_update_0(in, mp_2, (c2 - 0) / 1, (c1 - 1) / 2, (c0 - 0) / 1); } } } } } #ifndef __VIVADO_SYNTH__ debug_file.close(); #endif //__VIVADO_SYNTH__ } void mp_2_opt(HWStream<hw_uint<64> >& /* get_args num ports = 2 */in_oc, HWStream<hw_uint<32> >& /* get_args num ports = 1 */mp_2) { mp_2_opt(in_oc, mp_2, 1); } #ifdef __VIVADO_SYNTH__ #include "mp_2_opt.h" const int in_update_0_read_num_transfers = 262144; const int mp_2_update_0_write_num_transfers = 131072; extern "C" { static void read_in_update_0_read(hw_uint<64>* input, HWStream<hw_uint<64> >& v, const int size) { hw_uint<64> burst_reg; int num_transfers = in_update_0_read_num_transfers*size; for (int i = 0; i < num_transfers; i++) { #pragma HLS pipeline II=1 burst_reg = input[i]; v.write(burst_reg); } } static void write_mp_2_update_0_write(hw_uint<32>* output, HWStream<hw_uint<32> >& v, const int size) { hw_uint<32> burst_reg; int num_transfers = mp_2_update_0_write_num_transfers*size; for (int i = 0; i < num_transfers; i++) { #pragma HLS pipeline II=1 burst_reg = v.read(); output[i] = burst_reg; } } void mp_2_opt_accel(hw_uint<64>* in_update_0_read, hw_uint<32>* mp_2_update_0_write, const int size) { #pragma HLS dataflow #pragma HLS INTERFACE m_axi port = in_update_0_read offset = slave depth = 65536 bundle = gmem0 #pragma HLS INTERFACE m_axi port = mp_2_update_0_write offset = slave depth = 65536 bundle = gmem1 #pragma HLS INTERFACE s_axilite port = in_update_0_read bundle = control #pragma HLS INTERFACE s_axilite port = mp_2_update_0_write bundle = control #pragma HLS INTERFACE s_axilite port = size bundle = control #pragma HLS INTERFACE s_axilite port = return bundle = control static HWStream<hw_uint<64> > in_update_0_read_channel; static HWStream<hw_uint<32> > mp_2_update_0_write_channel; read_in_update_0_read(in_update_0_read, in_update_0_read_channel, size); mp_2_opt(in_update_0_read_channel, mp_2_update_0_write_channel, size); write_mp_2_update_0_write(mp_2_update_0_write, mp_2_update_0_write_channel, size); } } #endif //__VIVADO_SYNTH__
#include "CGetDrawGold.h" #include "json/json.h" #include "Logger.h" #include "Util.h" #include "threadres.h" #include "CConfig.h" #include "SqlLogic.h" #include "RedisLogic.h" #include "Helper.h" //#include "RedisAccess.h" int CGetDrawGold::do_request(const Json::Value& root, char *client_ip, HttpResult& out) { //Json::FastWriter jWriter; //Json::Value ret; int uid, productid; try { uid = root["mid"].asInt(); productid = root["productid"].asInt(); } catch (...) { out["msg"] = "参数不正确"; //out = jWriter.write(ret); return status_param_error; } if (uid < 1) { out["msg"] = "参数不正确"; return status_param_error; } CAutoUserDoing userDoing(uid); if (userDoing.IsDoing()) { out["msg"] = "您操作太快了,请休息一会!"; return status_ok; } RedisAccess* redisAccess = ThreadResource::getInstance().getRedisConnMgr()->minfo(); if (!redisAccess) { LOGGER(E_LOG_ERROR) << "minfo redis is null, it did not be initted when server starting!"; return -1; } string value; int timestamp = Helper::strtotime(Util::formatGMTTime_Date() + " 00:00:00"); bool reply = redisAccess->GET(StrFormatA("Draw|%d|%d", uid,timestamp).c_str(),value); if (reply || value != "") { out["result"] = 0; out["msg"] = "你今天已经抽过了"; LOGGER(E_LOG_WARNING) << "你今天已经抽过了"; return status_ok; } //判断设备 std::string devno; if (!SqlLogic::getDeviceNoByMid(uid, devno)) { //out = writer.write(info); out["result"] = 0; out["msg"] = "设备错误"; return status_ok; } bool reply1 = redisAccess->GET(StrFormatA("Draw|%s|%d", devno.c_str(),timestamp).c_str(),value); if (reply1 || value != "") { out["result"] = 0; out["msg"] = "今天该设备已经抽过了"; LOGGER(E_LOG_WARNING) << "你今天该设备已经抽过了"; return status_ok; } Json::Value userInfo; if(SqlLogic::getOneById(userInfo, uid)) { //RedisLogic::addWin(userInfo, 300 , MONEY_RECEIVE_BENEFITS, 1, "抽奖领取救济金"); //身上的金额加上保险柜的余额 int all_money = Json::SafeConverToInt32(userInfo["money"]) + Json::SafeConverToInt32(userInfo["freezemoney"]); if (all_money < 0) { LOGGER(E_LOG_WARNING) << "User Moeny Is:" << all_money; //这个用户有问题,直接返回吧 return status_ok; } if(all_money >= 200) { out["result"] = 0; out["msg"] = "你的金钱太多"; return status_ok; } //抽奖概率 int num = rand()%10000; int drawMoney = 0; int DrawResult = 0; if(num < 288) { DrawResult = 1; drawMoney = 500; } else if(num >= 288 && num < 1288) { DrawResult = 2; drawMoney = 400; } else if(num >= 1288 && num < 3288) { DrawResult = 3; drawMoney = 300; } else if(num >= 3288 && num < 6288) { DrawResult = 4; drawMoney = 200; } else { DrawResult = 5; drawMoney = 100; } RedisLogic::addWin(userInfo, drawMoney, MONEY_RECEIVE_BENEFITS, 0, "抽奖领取救济金"); redisAccess->CommandV("set Draw|%s|%d %d",devno.c_str(),timestamp,1); redisAccess->CommandV("set Draw|%d|%d %d",uid,timestamp,1); out["DrawResult"] = DrawResult; out["CurGold"] = all_money + drawMoney; out["result"] = 1; out["msg"] = ""; } return status_ok; }
#include <iostream> #include <cmath> #include <cstdio> #include <cstdlib> #include <vector> #include <unistd.h> #include "TFile.h" #include "TTree.h" #include "TH1.h" #include "TH2.h" #include "TGraphAsymmErrors.h" #include "TVectorT.h" #include "Nuclear_Info.h" #include "Cross_Sections.h" #include "fiducials.h" #include "helpers.h" #include "AccMap.h" using namespace std; const double pmiss_cut=0.4; const double pmiss_lo=0.5; const double pmiss_md=0.6; const double pmiss_hi=0.7; const double Ebeam=eg2beam; const double sCutOff=0; const double sigmaCM=0.143; const double Estar=0.03; const double acc_thresh=0.0; const bool bin_center = false; int main(int argc, char ** argv) { if (argc < 5) { cerr << "Wrong number of arguments. Instead try:\n" << " make_hists /path/to/1p/file /path/to/2p/file /path/to/map/file /path/to/output/file\n\n"; exit(-1); } TFile * f1p = new TFile(argv[1]); TFile * f2p = new TFile(argv[2]); TFile * fo = new TFile(argv[4],"RECREATE"); Cross_Sections myCS(cc1,kelly); bool doSWeight = false; bool doCut = true; bool doOtherCut = true; bool doGaps = true; bool lc_weight = false; int c; while((c=getopt (argc-4, &argv[4], "SCOgl")) != -1) switch(c) { case 'S': doSWeight = true; break; case 'C': doCut = false; break; case 'O': doOtherCut = false; break; case 'g': doGaps = false; break; case 'l': lc_weight = true; break; case '?': return -1; default: abort(); } // Attempt to pull the acceptance ratio from 1p file, if we had a simulation file. TGraphAsymmErrors * rec_p_rat = NULL; TGraphAsymmErrors * rec_p_rat_coarse = NULL; rec_p_rat = (TGraphAsymmErrors*) f1p->Get("rec_p_rat"); rec_p_rat_coarse = (TGraphAsymmErrors*) f1p->Get("rec_p_rat_coarse"); if (rec_p_rat) { fo->cd(); rec_p_rat->Write(); rec_p_rat_coarse->Write(); } // We'll need to get acceptance maps in order to do a fiducial cut on minimum acceptance AccMap proton_map(argv[3], "p"); // Create some directories so that the output file isn't so crowded in a browser TDirectory * dir_by_sec = fo->mkdir("by_sec"); TDirectory * dir_sub_bins = fo->mkdir("sub_bins"); fo->cd(); // Let's create a vector of all the histogram pointers so we can loop over them, save hassles vector<TH1*> h1p_list; vector<TH1*> h2p_list; // Create histograms TH1D * h1p_QSq = new TH1D("ep_QSq","ep;QSq [GeV^2];Counts",36,1.,5.); h1p_list.push_back(h1p_QSq); TH1D * h1p_xB = new TH1D("ep_xB" ,"ep;xB;Counts",40,1.2,2.); h1p_list.push_back(h1p_xB ); TH1D * h1p_Pm = new TH1D("ep_Pm" ,"ep;pMiss [GeV];Counts",30,0.4,1.0); h1p_list.push_back(h1p_Pm ); TH1D * h1p_Pm_coarse = new TH1D("ep_Pm_coarse" ,"ep;pMiss [GeV];Counts",9,coarse_bin_edges_new); h1p_list.push_back(h1p_Pm_coarse); TH1D * h1p_Pmq = new TH1D("ep_Pmq","ep;Theta_Pmq [deg];Counts",40,100.,180.); h1p_list.push_back(h1p_Pmq); TH1D * h1p_cPmq = new TH1D("ep_cPmq","ep;cos(Theta_Pmq);Counts",40,-1.,0.); h1p_list.push_back(h1p_cPmq); TH1D * h1p_phi1 = new TH1D("ep_phi1","ep;Phi_1 [deg];Counts",60,-30.,330.); h1p_list.push_back(h1p_phi1); TH1D * h1p_phie = new TH1D("ep_phie","ep;Phi_e [deg];Counts",60,-30.,330.); h1p_list.push_back(h1p_phie); TH1D * h1p_theta1 = new TH1D("ep_theta1","ep;Theta_1 [deg];Counts",60,10.,130.); h1p_list.push_back(h1p_theta1); TH1D * h1p_thetae = new TH1D("ep_thetae","ep;Theta_e [deg];Counts",60,10.,40.); h1p_list.push_back(h1p_thetae); TH1D * h1p_mome = new TH1D("ep_mome","ep;Mom_e [GeV/c];Counts",40,3.0,5.0); h1p_list.push_back(h1p_mome); TH1D * h1p_mom1 = new TH1D("ep_mom1","ep;Mom_1 [GeV/c];Counts",40,0.4,2.4); h1p_list.push_back(h1p_mom1); TH1D * h1p_alphaq = new TH1D("ep_alphaq","ep;alphaq;Counts",30,-1.5,-0.5); h1p_list.push_back(h1p_alphaq); TH1D * h1p_alphaLead = new TH1D("ep_alphaLead","ep;alphaLead;Counts",30,0.1,0.6); h1p_list.push_back(h1p_alphaLead); TH1D * h1p_alphaM = new TH1D("ep_alphaM","ep;alphaM;Counts",30,1.1,1.7); h1p_list.push_back(h1p_alphaM); TH1D * h1p_km = new TH1D("ep_km" ,"epp;kmiss [GeV];Counts",30,0.2,0.8); h1p_list.push_back(h1p_km); TH1D * h1p_dE1 = new TH1D("ep_dE1","ep;dE1;Counts",40,-0.2,1); h1p_list.push_back(h1p_dE1); TH1D * h1p_rE1 = new TH1D("ep_rE1","ep;rE1;Counts",40,0,1); h1p_list.push_back(h1p_rE1); TH2D * h1p_pmiss_Emiss = new TH2D("ep_pmiss_Emiss","ep;pmiss [GeV];Emiss [GeV];Counts",24,0.4,1.0,20,-0.2,0.6); h1p_list.push_back(h1p_pmiss_Emiss); TH2D * h1p_pmiss_E1 = new TH2D("ep_pmiss_E1","ep;pmiss [GeV];E1 [GeV];Counts",24,0.4,1.0,25,0.5,1.0); h1p_list.push_back(h1p_pmiss_E1); TH2D * h1p_Emiss_by_sector = new TH2D("ep_Emiss_sec","ep;Electron Sector;Emiss [GeV];Counts",6,-0.5,5.5,40,-0.2,0.6); h1p_list.push_back(h1p_Emiss_by_sector); TH2D * h1p_pmiss_epsilon = new TH2D("ep_pmiss_epsilon","pmiss_epsilon;pmiss;epsilon;Counts",24,0.4,1.0,25,0.5,1.0); h1p_list.push_back(h1p_pmiss_epsilon); TH1D * h2p_QSq = new TH1D("epp_QSq","epp;QSq [GeV^2];Counts",30,1.,4.); h2p_list.push_back(h2p_QSq); TH1D * h2p_xB = new TH1D("epp_xB" ,"epp;xB;Counts",26,1.2,2.5); h2p_list.push_back(h2p_xB ); TH1D * h2p_Pm = new TH1D("epp_Pm" ,"epp;pMiss [GeV];Counts",30,0.4,1.0); h2p_list.push_back(h2p_Pm ); TH1D * h2p_Pm_clas = new TH1D("epp_Pm_clas" ,"epp;pMiss [GeV];Counts",18,0.4,1.0); h2p_Pm_clas->Sumw2(); TH1D * h2p_Pm_coarse = new TH1D("epp_Pm_coarse" ,"epp;pMiss [GeV];Counts",9,coarse_bin_edges_new); h2p_list.push_back(h2p_Pm_coarse); TH1D * h2p_Pmq = new TH1D("epp_Pmq","epp;Theta_Pmq [deg];Counts",20,100.,180.); h2p_list.push_back(h2p_Pmq); TH1D * h2p_cPmq = new TH1D("epp_cPmq","epp;cos(Theta_Pmq);Counts",20,-1.,0.); h2p_list.push_back(h2p_cPmq); TH1D * h2p_Pmr = new TH1D("epp_Pmr","epp;Theta_Pmr [deg];Counts",20,100.,180.); h2p_list.push_back(h2p_Pmr); TH1D * h2p_cPmr = new TH1D("epp_cPmr","epp;cos(Theta_Pmr);Counts",20,-1.,0.); h2p_list.push_back(h2p_cPmr); TH1D * h2p_phi1 = new TH1D("epp_phi1","epp;Phi_1 [deg];Counts",60,-30.,330.); h2p_list.push_back(h2p_phi1); TH1D * h2p_phi2 = new TH1D("epp_phi2","epp;Phi_2 [deg];Counts",60,-30.,330.); h2p_list.push_back(h2p_phi2); TH1D * h2p_phie = new TH1D("epp_phie","epp;Phi_e [deg];Counts",60,-30.,330.); h2p_list.push_back(h2p_phie); TH1D * h2p_thetae = new TH1D("epp_thetae","epp;Theta_e [deg];Counts",30,10.,40.); h2p_list.push_back(h2p_thetae); TH1D * h2p_mome = new TH1D("epp_mome","epp;Mom_e [GeV/c];Counts",40,3.0,5.0); h2p_list.push_back(h2p_mome); TH1D * h2p_theta1 = new TH1D("epp_theta1","epp;Theta_1 [deg];Counts",30,10.,130.); h2p_list.push_back(h2p_theta1); TH1D * h2p_theta2 = new TH1D("epp_theta2","epp;Theta_2 [deg];Counts",30,10.,130.); h2p_list.push_back(h2p_theta2); TH1D * h2p_mom2 = new TH1D("epp_mom2","epp;Recoil Mom [GeV/c];Counts",17,0.35,1.2); h2p_list.push_back(h2p_mom2); TH1D * h2p_mom1 = new TH1D("epp_mom1","epp;Mom_1 [GeV/c];Counts",40,0.4,2.4); h2p_list.push_back(h2p_mom1); TH1D * h2p_momdiff = new TH1D("epp_momdiff","epp;Delta_mom [GeV/c];Counts",40,0.0,2.0); h2p_list.push_back(h2p_momdiff); TH1D * h2p_alphaq = new TH1D("epp_alphaq","ep;alphaq;Counts",30,-1.5,-0.5); h2p_list.push_back(h2p_alphaq); TH1D * h2p_alphaLead = new TH1D("epp_alphaLead","ep;alphaLead;Counts",30,0.1,0.6); h2p_list.push_back(h2p_alphaLead); TH1D * h2p_alphaM = new TH1D("epp_alphaM","ep;alphaM;Counts",30,1.1,1.7); h2p_list.push_back(h2p_alphaM); TH1D * h2p_km = new TH1D("epp_km" ,"epp;kmiss [GeV];Counts",30,0.2,0.8); h2p_list.push_back(h2p_km); TH1D * h2p_alphaRec = new TH1D("epp_alphaRec","ep;alphaRec;Counts",30,0.4,1.3); h2p_list.push_back(h2p_alphaRec); TH1D * h2p_alphaD = new TH1D("epp_alphaD","ep;alphaD;Counts",30,1.6,2.6); h2p_list.push_back(h2p_alphaD); TH1D * h2p_dE1 = new TH1D("epp_dE1","epp;dE1;Counts",40,-0.2,1); h2p_list.push_back(h2p_dE1); TH1D * h2p_rE1 = new TH1D("epp_rE1","epp;rE1;Counts",40,0,1); h2p_list.push_back(h2p_rE1); TH2D * h2p_pmiss_E1 = new TH2D("epp_pmiss_E1","epp;pmiss [GeV];E1 [GeV];Counts",24,0.4,1.0,25,0.5,1.0); h2p_list.push_back(h2p_pmiss_E1); TH2D * h2p_pmiss_appEstar = new TH2D("epp_pmiss_appEstar","epp;pmiss [GeV];Apparent Estar [GeV];Counts",24,0.4,1.0,20,-0.2,0.8); h2p_list.push_back(h2p_pmiss_appEstar); TH2D * h2p_pmiss_epsilon = new TH2D("epp_pmiss_epsilon","pmiss_epsilon;pmiss;epsilon;Counts",24,0.4,1.0,25,0.5,1.0); h2p_list.push_back(h2p_pmiss_epsilon); TH2D * h1p_pmiss_QSq = new TH2D("ep_pmiss_QSq","pmiss_epsilon;pmiss;Q^2;Counts",24,0.4,1.0,30,1.,4.); h1p_list.push_back(h1p_pmiss_QSq); TH2D * h2p_pmiss_QSq = new TH2D("epp_pmiss_QSq","pmiss_epsilon;pmiss;Q^2;Counts",24,0.4,1.0,30,1.,4.); h2p_list.push_back(h2p_pmiss_QSq); TH2D * h1p_pmiss_mom1 = new TH2D("ep_pmiss_mom1","pmiss_epsilon;pmiss;pLead;Counts",24,0.4,1.0,40,0.4,2.4); h1p_list.push_back(h1p_pmiss_mom1); TH2D * h2p_pmiss_mom1 = new TH2D("epp_pmiss_mom1","pmiss_epsilon;pmiss;pLead;Counts",24,0.4,1.0,40,0.4,2.4); h2p_list.push_back(h2p_pmiss_mom1); TH2D * h2p_pmiss_mom2 = new TH2D("epp_pmiss_mom2","pmiss_epsilon;pmiss;pRec;Counts",24,0.4,1.0,17,0.35,1.2); h2p_list.push_back(h2p_pmiss_mom2); TH2D * h2p_pmiss_momrat = new TH2D("epp_pmiss_momrat","pmiss_epsilon;pmiss;pLead/pRec;Counts",24,0.4,1.0,30,1.,4.); h2p_list.push_back(h2p_pmiss_momrat); TH2D * h2p_pmiss_momdiff = new TH2D("epp_pmiss_momdiff","pmiss_epsilon;pmiss;pLead-pRec;Counts",24,0.4,1.0,40,0.,2.); h2p_list.push_back(h2p_pmiss_momdiff); TH2D * h2p_pRec_epsilon = new TH2D("epp_pRec_epsilon","pRec_epsilon;pRec;epsilon;Counts",20,0.3,1.2,20,0.2,1.2); h2p_list.push_back(h2p_pRec_epsilon); TH1D * h2p_pRec_epsilon_mean = new TH1D("epp_pRec_epsilon_mean","pRec_epsilon_mean;pRec;epsilon_mean;Counts",20,0.3,1.2); h2p_pRec_epsilon_mean->Sumw2(); TH1D * h2p_pRec_epsilon_std = new TH1D("epp_pRec_epsilon_std","pRec_epsilon_std;pRec;epsilon_std;Counts",20,0.3,1.2); h2p_pRec_epsilon_std->Sumw2(); TH2D * h2p_pRec_eMiss = new TH2D("epp_pRec_eMiss","pRec_eMiss;pRec;eMiss;Counts",10,0.35,0.9,10,0,0.5); h2p_list.push_back(h2p_pRec_eMiss); TH1D * h2p_pRec_eMiss_mean = new TH1D("epp_pRec_eMiss_mean","pRec_eMiss_mean;pRec;eMiss_mean;Counts",20,0.3,1.2); h2p_pRec_eMiss_mean->Sumw2(); TH1D * h2p_pRec_eMiss_std = new TH1D("epp_pRec_eMiss_std","pRec_eMiss_std;pRec;eMiss_std;Counts",20,0.3,1.2); h2p_pRec_eMiss_std->Sumw2(); TH1D * h2p_pRecError = new TH1D("epp_pRecError","epp;pRecError;Counts",40,-1,1); h2p_pRecError->Sumw2(); TH2D * pp_to_p_2d = new TH2D("pp_to_p_2d","2d ratio;pmiss [GeV];E1 [GeV];pp/p",28,0.35,1.0,20,0.5,0.9); TH1D * h1p_Emiss = new TH1D("ep_Emiss","ep;Emiss [GeV];Counts",40,-0.2,0.6); h1p_list.push_back(h1p_Emiss); TH1D * h1p_Emiss_fine = new TH1D("ep_Emiss_fine","ep;Emiss [GeV];Counts",160,-0.2,0.6); h1p_list.push_back(h1p_Emiss_fine); TH1D * h1p_e1 = new TH1D("ep_e1","ep;e1 [GeV];Counts",160,0.5,1.0); h1p_list.push_back(h1p_e1); TH1D * h1p_emiss = new TH1D("ep_emiss","ep;emiss [GeV];Counts",160,0.0,0.5); h1p_list.push_back(h1p_emiss); TH1D * h2p_Emiss = new TH1D("epp_Emiss","epp;Emiss [GeV];Counts",40,-0.2,0.6); h2p_list.push_back(h2p_Emiss); TH1D * h2p_Emiss_fine = new TH1D("epp_Emiss_fine","epp;Emiss [GeV];Counts",160,-0.2,0.6); h2p_list.push_back(h2p_Emiss_fine); TH1D * h2p_e1 = new TH1D("epp_e1","epp;e1 [GeV];Counts",160,0.5,1.0); h2p_list.push_back(h2p_e1); TH1D * h2p_emiss = new TH1D("epp_emiss","epp;emiss [GeV];Counts",160,0.0,1.5); h2p_list.push_back(h2p_emiss); TH1D * h2p_k = new TH1D("epp_k" ,"epp;k [GeV];Counts",30,0.2,0.8); h2p_list.push_back(h2p_k); TH2D * h2p_pmiss_k = new TH2D("epp_pmiss_k","pmiss_k;pmiss;k;Counts",24,0.4,1.0,30,0.2,0.8); h2p_list.push_back(h2p_pmiss_k); TH2D * h2p_prec_k = new TH2D("epp_prec_k","prec_k;prec;k;Counts",20,0.35,1.15,30,0.2,0.8); h2p_list.push_back(h2p_prec_k); TH1D * h2p_rat1 = new TH1D("epp_rat1","Eq. (53);JIF/LF;Counts",20,0.9,1.3); h2p_list.push_back(h2p_rat1); TH1D * h2p_rat2 = new TH1D("epp_rat2","rat2;rat2;Counts",20,0.8,1.6); h2p_list.push_back(h2p_rat2); //The first element is pmiss bin, second is xB bin, third is QSq bin TH1D * h1p_Emiss_split[4][3][3]; TH1D * h1p_Emiss_fine_split[4][3][3]; TH1D * h1p_e1_split[4][3][3]; TH1D * h1p_emiss_split[4][3][3]; TH1D * h1p_Pmq_split[4][3][3]; TH1D * h1p_Pmzq_split[4][3][3]; TH1D * h1p_PmTq_split[4][3][3]; TH1D * h1p_dE1_split[4][3][3]; TH1D * h1p_rE1_split[4][3][3]; TH1D * h2p_Emiss_split[4][3][3]; TH1D * h2p_Emiss_fine_split[4][3][3]; TH1D * h2p_e1_split[4][3][3]; TH1D * h2p_emiss_split[4][3][3]; TH1D * h2p_Pmq_split[4][3][3]; TH1D * h2p_Pmzq_split[4][3][3]; TH1D * h2p_PmTq_split[4][3][3]; TH1D * h2p_dE1_split[4][3][3]; TH1D * h2p_rE1_split[4][3][3]; TH1D * h2p_Pcmzq_split[4][3][3]; TH1D * h2p_Pcmn1q_split[4][3][3]; TH1D * h2p_Pcmn2q_split[4][3][3]; TH1D * h2p_PcmTq_split[4][3][3]; TH1D * h2p_Pcmzm_split[4][3][3]; TH1D * h2p_Pcmn1m_split[4][3][3]; TH1D * h2p_Pcmn2m_split[4][3][3]; TH1D * h2p_PcmTm_split[4][3][3]; TH1D * h2p_alphaD_split[4][3][3]; //dir_sub_bins->cd(); for (int i=0 ; i<4 ; i++) { for(int j=0; j<3 ; j++){ for(int k=0; k<3; k++){ char temp[100]; sprintf(temp,"ep_Emiss_%d_%d_%d",i,j,k); h1p_Emiss_split[i][j][k] = new TH1D(temp,"ep;Emiss [GeV];Counts",40,-0.2,0.6); h1p_list.push_back(h1p_Emiss_split[i][j][k]); sprintf(temp,"ep_Emiss_fine_%d_%d_%d",i,j,k); h1p_Emiss_fine_split[i][j][k] = new TH1D(temp,"ep;Emiss [GeV];Counts",160,-0.2,0.6); h1p_list.push_back(h1p_Emiss_fine_split[i][j][k]); sprintf(temp,"ep_e1_%d_%d_%d",i,j,k); h1p_e1_split[i][j][k] = new TH1D(temp,"ep;e1 [GeV];Counts",120,0.4,1.0); h1p_list.push_back(h1p_e1_split[i][j][k]); sprintf(temp,"ep_emiss_%d_%d_%d",i,j,k); h1p_emiss_split[i][j][k] = new TH1D(temp,"ep;emiss [GeV];Counts",120,-0.1,0.5); h1p_list.push_back(h1p_emiss_split[i][j][k]); sprintf(temp,"ep_Pmq_%d_%d_%d",i,j,k); h1p_Pmq_split[i][j][k] = new TH1D(temp,"ep;Pmq [GeV];Counts",20,100.,180.); h1p_list.push_back(h1p_Pmq_split[i][j][k]); sprintf(temp,"ep_Pmzq_%d_%d_%d",i,j,k); h1p_Pmzq_split[i][j][k] = new TH1D(temp,"ep;Pmzq [GeV];Counts",30,-1.0,0.0); h1p_list.push_back(h1p_Pmzq_split[i][j][k]); sprintf(temp,"ep_PmTq_%d_%d_%d",i,j,k); h1p_PmTq_split[i][j][k] = new TH1D(temp,"ep;PmTq [GeV];Counts",30,0.0,1.0); h1p_list.push_back(h1p_PmTq_split[i][j][k]); sprintf(temp,"ep_dE1_%d_%d_%d",i,j,k); h1p_dE1_split[i][j][k] = new TH1D(temp,"ep;dE1 [GeV];Counts",40,-0.2,1); h1p_list.push_back(h1p_dE1_split[i][j][k]); sprintf(temp,"ep_rE1_%d_%d_%d",i,j,k); h1p_rE1_split[i][j][k] = new TH1D(temp,"ep;rE1;Counts",40,0,1); h1p_list.push_back(h1p_rE1_split[i][j][k]); sprintf(temp,"epp_Emiss_%d_%d_%d",i,j,k); h2p_Emiss_split[i][j][k] = new TH1D(temp,"epp;Emiss [GeV];Counts",20,-0.2,0.6); h2p_list.push_back(h2p_Emiss_split[i][j][k]); sprintf(temp,"epp_Emiss_fine_%d_%d_%d",i,j,k); h2p_Emiss_fine_split[i][j][k] = new TH1D(temp,"epp;Emiss [GeV];Counts",80,-0.2,0.6); h2p_list.push_back(h2p_Emiss_fine_split[i][j][k]); sprintf(temp,"epp_e1_%d_%d_%d",i,j,k); h2p_e1_split[i][j][k] = new TH1D(temp,"epp;e1 [GeV];Counts",60,0.4,1.0); h2p_list.push_back(h2p_e1_split[i][j][k]); sprintf(temp,"epp_emiss_%d_%d_%d",i,j,k); h2p_emiss_split[i][j][k] = new TH1D(temp,"epp;emiss [GeV];Counts",60,-0.1,0.5); h2p_list.push_back(h2p_emiss_split[i][j][k]); sprintf(temp,"epp_Pmq_%d_%d_%d",i,j,k); h2p_Pmq_split[i][j][k] = new TH1D(temp,"epp;Pmq [GeV];Counts",20,100.,180.); h2p_list.push_back(h2p_Pmq_split[i][j][k]); sprintf(temp,"epp_Pmzq_%d_%d_%d",i,j,k); h2p_Pmzq_split[i][j][k] = new TH1D(temp,"epp;Pmzq [GeV];Counts",30,-1.0,0.0); h2p_list.push_back(h2p_Pmzq_split[i][j][k]); sprintf(temp,"epp_PmTq_%d_%d_%d",i,j,k); h2p_PmTq_split[i][j][k] = new TH1D(temp,"epp;PmTq [GeV];Counts",30,0.0,1.0); h2p_list.push_back(h2p_PmTq_split[i][j][k]); sprintf(temp,"epp_dE1_%d_%d_%d",i,j,k); h2p_dE1_split[i][j][k] = new TH1D(temp,"epp;dE1 [GeV];Counts",40,-0.2,1); h2p_list.push_back(h2p_dE1_split[i][j][k]); sprintf(temp,"epp_rE1_%d_%d_%d",i,j,k); h2p_rE1_split[i][j][k] = new TH1D(temp,"epp;rE1;Counts",40,0,1); h2p_list.push_back(h2p_rE1_split[i][j][k]); sprintf(temp,"epp_Pcmzq_%d_%d_%d",i,j,k); h2p_Pcmzq_split[i][j][k] = new TH1D(temp,"epp;Pcmzq [GeV];Counts",30,-1.0,1.0); h2p_list.push_back(h2p_Pcmzq_split[i][j][k]); sprintf(temp,"epp_PcmTq_%d_%d_%d",i,j,k); h2p_PcmTq_split[i][j][k] = new TH1D(temp,"epp;PcmTq [GeV];Counts",30,0.0,1.0); h2p_list.push_back(h2p_PcmTq_split[i][j][k]); sprintf(temp,"epp_Pcmn1q_%d_%d_%d",i,j,k); h2p_Pcmn1q_split[i][j][k] = new TH1D(temp,"epp;Pcmn1q [GeV];Counts",30,-1.0,1.0); h2p_list.push_back(h2p_Pcmn1q_split[i][j][k]); sprintf(temp,"epp_Pcmn2q_%d_%d_%d",i,j,k); h2p_Pcmn2q_split[i][j][k] = new TH1D(temp,"epp;Pcmn2q [GeV];Counts",30,-1.0,1.0); h2p_list.push_back(h2p_Pcmn2q_split[i][j][k]); sprintf(temp,"epp_Pcmzm_%d_%d_%d",i,j,k); h2p_Pcmzm_split[i][j][k] = new TH1D(temp,"epp;Pcmzm [GeV];Counts",30,-1.0,1.0); h2p_list.push_back(h2p_Pcmzm_split[i][j][k]); sprintf(temp,"epp_PcmTm_%d_%d_%d",i,j,k); h2p_PcmTm_split[i][j][k] = new TH1D(temp,"epp;PcmTm [GeV];Counts",30,0.0,1.0); h2p_list.push_back(h2p_PcmTm_split[i][j][k]); sprintf(temp,"epp_Pcmn1m_%d_%d_%d",i,j,k); h2p_Pcmn1m_split[i][j][k] = new TH1D(temp,"epp;Pcmn1m [GeV];Counts",30,-1.0,1.0); h2p_list.push_back(h2p_Pcmn1m_split[i][j][k]); sprintf(temp,"epp_Pcmn2m_%d_%d_%d",i,j,k); h2p_Pcmn2m_split[i][j][k] = new TH1D(temp,"epp;Pcmn2m [GeV];Counts",30,-1.0,1.0); h2p_list.push_back(h2p_Pcmn2m_split[i][j][k]); sprintf(temp,"epp_alphaD_%d_%d_%d",i,j,k); h2p_alphaD_split[i][j][k] = new TH1D(temp,"epp;alphaD;Counts",30,1.6,2.6); h2p_list.push_back(h2p_alphaD_split[i][j][k]); } } } dir_by_sec->cd(); TH1D * h1p_thetae_bySec[6]; TH1D * h1p_theta1_bySec[6]; TH1D * h2p_theta1_bySec[6]; TH1D * h2p_theta2_bySec[6]; for (int i=0 ; i<6 ; i++) { char temp[100]; sprintf(temp,"ep_theta1_%d",i); h1p_theta1_bySec[i] = new TH1D(temp,"ep;Theta [deg];Counts",60,10.,130.); h1p_list.push_back(h1p_theta1_bySec[i]); sprintf(temp,"ep_thetae_%d",i); h1p_thetae_bySec[i] = new TH1D(temp,"ep;Theta [deg];Counts",60,10.,40.); h1p_list.push_back(h1p_thetae_bySec[i]); sprintf(temp,"epp_theta1_%d",i); h2p_theta1_bySec[i] = new TH1D(temp,"epp;Theta [deg];Counts",60,10.,130.); h2p_list.push_back(h2p_theta1_bySec[i]); sprintf(temp,"epp_theta2_%d",i); h2p_theta2_bySec[i] = new TH1D(temp,"epp;Theta [deg];Counts",60,10.,130.); h2p_list.push_back(h2p_theta2_bySec[i]); } fo->cd(); // Now that all histograms have been defined, set them to Sumw2 for (int i=0 ; i<h1p_list.size() ; i++) h1p_list[i]->Sumw2(); for (int i=0 ; i<h2p_list.size() ; i++) h2p_list[i]->Sumw2(); // For data and bin-centering TH1D * h1p_Pm_30bin = new TH1D("ep_Pm_30bin" ,"ep;pMiss [GeV];Counts",30,0.4,1.0); h1p_Pm_30bin->Sumw2(); TH1D * h2p_Pm_30bin = new TH1D("epp_Pm_30bin" ,"epp;pMiss [GeV];Counts",30,0.4,1.0); h2p_Pm_30bin->Sumw2(); TH1D * h1p_Pm_30bin_bins = new TH1D("ep_Pm_30bin_bins" ,"ep;pMiss [GeV];Sum pMiss [GeV]",30,0.4,1.0); TH1D * h2p_Pm_30bin_bins = new TH1D("epp_Pm_30bin_bins" ,"epp;pMiss [GeV];Sum pMiss [GeV]",30,0.4,1.0); TH1D * h1p_Pm_coarse_bins = new TH1D("ep_Pm_coarse_bins" ,"ep;pMiss [GeV];Sum pMiss [GeV]",9,coarse_bin_edges_new); TH1D * h2p_Pm_coarse_bins = new TH1D("epp_Pm_coarse_bins" ,"epp;pMiss [GeV];Sum pMiss [GeV]",9,coarse_bin_edges_new); // pp2p graphs TGraphAsymmErrors * pp_to_p = new TGraphAsymmErrors(); pp_to_p->SetName("pp_to_p"); pp_to_p->SetTitle("pp_to_p;p_miss [GeV];pp_to_p ratio"); TGraphAsymmErrors * pp_to_p_coarse = new TGraphAsymmErrors(); pp_to_p_coarse->SetName("pp_to_p_coarse"); pp_to_p_coarse->SetTitle("pp_to_p;p_miss [GeV];pp_to_p ratio"); // Loop over 1p tree cerr << " Looping over 1p tree...\n"; TTree * t1p = (TTree*)f1p->Get("T"); Float_t Xb, Q2, Pmiss_size[2], Pp[2][3], Rp[2][3], Pp_size[2], Pmiss_q_angle[2], Pe[3], q[3]; Double_t weight = 1.; bool resetto1 = false; t1p->SetBranchAddress("Pmiss_q_angle",Pmiss_q_angle); t1p->SetBranchAddress("Xb",&Xb); t1p->SetBranchAddress("Q2",&Q2); t1p->SetBranchAddress("Pmiss_size",Pmiss_size); t1p->SetBranchAddress("Pp_size",Pp_size); t1p->SetBranchAddress("Rp",Rp); t1p->SetBranchAddress("Pp",Pp); t1p->SetBranchAddress("Pe",Pe); t1p->SetBranchAddress("q",q); // See if there is a weight branch TBranch * weight_branch = t1p->GetBranch("weight"); if (weight_branch) { if (lc_weight) t1p->SetBranchAddress("lcweight",&weight); else t1p->SetBranchAddress("weight",&weight); } else resetto1 = true; for (int event =0 ; event < t1p->GetEntries() ; event++) { t1p->GetEvent(event); if(resetto1) weight = 1; TVector3 ve(Pe[0],Pe[1],Pe[2]); TVector3 vp(Pp[0][0],Pp[0][1],Pp[0][2]); if (doOtherCut) { // Do necessary cuts if (fabs(Rp[0][2]+22.25)>2.25) continue; if (Pp_size[0]>2.4) continue; if (Pmiss_size[0]<pmiss_cut) continue; } if (doCut){ // Apply fiducial cuts if (!accept_electron(ve)) continue; if (doGaps) { if (!accept_proton(vp)) continue; } else { if (!accept_proton_simple(vp)) continue; } // Apply an additional fiducial cut that the map acc must be > acc_thresh if ( proton_map.accept(vp) < acc_thresh) continue; } // Sector-specific theta1 cuts double phi1_deg = vp.Phi() * 180./M_PI; if (phi1_deg < -30.) phi1_deg += 360.; int sector = clas_sector(phi1_deg); double theta1_deg = vp.Theta() * 180./M_PI; // A few more vectors TVector3 vq(q[0],q[1],q[2]); TVector3 vqUnit = vq.Unit(); TVector3 vm = vp - vq; double omega = Q2/(2.*mN*Xb); //Do spectral function weight if (doSWeight){ double factorS = omega * myCS.sigma_eN(Ebeam,ve,vp,true) / (2 * Ebeam * ve.Mag() * Xb); if (factorS>sCutOff){ weight = weight / factorS; } else weight=0; } h1p_QSq->Fill(Q2,weight); h1p_xB ->Fill(Xb,weight); h1p_Pm ->Fill(Pmiss_size[0],weight); h1p_Pm_30bin ->Fill(Pmiss_size[0],weight); h1p_Pm_30bin_bins ->Fill(Pmiss_size[0],weight*Pmiss_size[0]); h1p_Pm_coarse->Fill(Pmiss_size[0],weight); h1p_Pm_coarse_bins->Fill(Pmiss_size[0],weight*Pmiss_size[0]); h1p_Pmq->Fill(Pmiss_q_angle[0],weight); h1p_cPmq->Fill(cos(Pmiss_q_angle[0]*M_PI/180.),weight); // Kinematic variables we need double Ep = sqrt(Pp_size[0]*Pp_size[0] + mN*mN); double Emiss = -m_12C + mN + sqrt( sq(omega + m_12C - Ep) - (Pmiss_size[0]*Pmiss_size[0])); double epsilon = Ep - omega; double dE1 = sqrt(vm.Mag2()+sq(mN)) - epsilon; double rE1 = epsilon/sqrt(vm.Mag2()+sq(mN)); //Let's calculate light cone variables double alphaq= (omega - vq.Mag()) / mN; double alphaLead = (Ep - vp.Dot(vqUnit)) / mN; double alphaM = alphaLead - alphaq; TVector3 vm_perp = vm - vm.Dot(vqUnit)*vqUnit; double kmSq = (sq(mN) + vm_perp.Mag2())/(alphaM*(2-alphaM))-sq(mN); double km = sqrt(kmSq); h1p_alphaq->Fill(alphaq,weight); h1p_alphaLead->Fill(alphaLead,weight); h1p_alphaM->Fill(alphaM,weight); h1p_km->Fill(km,weight); h1p_dE1->Fill(dE1,weight); h1p_rE1->Fill(rE1,weight); // Let's make a sanitized phi and sector double phie_deg = ve.Phi() * 180./M_PI; if (phie_deg < -30.) phie_deg += 360.; int sec_e = clas_sector(phie_deg); double thetae_deg = ve.Theta() * 180./M_PI; h1p_phie->Fill(phie_deg,weight); h1p_thetae->Fill(thetae_deg,weight); h1p_thetae_bySec[sec_e]->Fill(thetae_deg,weight); h1p_mome->Fill(ve.Mag(),weight); h1p_phi1->Fill(phi1_deg,weight); h1p_theta1->Fill(theta1_deg,weight); h1p_theta1_bySec[sector]->Fill(theta1_deg,weight); h1p_mom1->Fill(Pp_size[0],weight); // Let's figure out missing energy! h1p_Emiss->Fill(Emiss,weight); h1p_Emiss_fine->Fill(Emiss,weight); h1p_e1->Fill(epsilon,weight); h1p_emiss->Fill(mN-epsilon,weight); h1p_pmiss_Emiss->Fill(Pmiss_size[0],Emiss,weight); h1p_Emiss_by_sector->Fill(sec_e,Emiss); //Pmiss splits int Pmiss_region_p; if (Pmiss_size[0] < pmiss_lo) Pmiss_region_p = 0; else if (Pmiss_size[0] < pmiss_md) Pmiss_region_p = 1; else if (Pmiss_size[0] < pmiss_hi) Pmiss_region_p = 2; else Pmiss_region_p = 3; int xB_region_p; if (Xb < 1.4) xB_region_p = 1; else xB_region_p = 2; int QSq_region_p; if (Q2 < 2) QSq_region_p = 1; else QSq_region_p = 2; for(int j=0; j<=xB_region_p; j=j+xB_region_p){ for(int k=0; k<=QSq_region_p; k=k+QSq_region_p){ h1p_Emiss_split[Pmiss_region_p][j][k]->Fill(Emiss,weight); h1p_Emiss_fine_split[Pmiss_region_p][j][k]->Fill(Emiss,weight); h1p_e1_split[Pmiss_region_p][j][k]->Fill(epsilon,weight); h1p_emiss_split[Pmiss_region_p][j][k]->Fill(mN-epsilon,weight); h1p_Pmq_split[Pmiss_region_p][j][k]->Fill(Pmiss_q_angle[0],weight); h1p_Pmzq_split[Pmiss_region_p][j][k]->Fill(vm.Dot(vqUnit),weight); h1p_PmTq_split[Pmiss_region_p][j][k]->Fill(vm.Perp(vqUnit),weight); h1p_dE1_split[Pmiss_region_p][j][k]->Fill(dE1,weight); h1p_rE1_split[Pmiss_region_p][j][k]->Fill(rE1,weight); } } h1p_pmiss_E1->Fill(Pmiss_size[0],epsilon,weight); h1p_pmiss_epsilon->Fill(Pmiss_size[0],epsilon,weight); h1p_pmiss_QSq->Fill(Pmiss_size[0],Q2,weight); h1p_pmiss_mom1->Fill(Pmiss_size[0],Pp_size[0],weight); } // Loop over 2p tree cerr << " Looping over 2p tree...\n"; TTree * t2p = (TTree*)f2p->Get("T"); t2p->SetBranchAddress("Pmiss_q_angle",Pmiss_q_angle); t2p->SetBranchAddress("Xb",&Xb); t2p->SetBranchAddress("Q2",&Q2); t2p->SetBranchAddress("Pmiss_size",Pmiss_size); t2p->SetBranchAddress("Pp_size",Pp_size); t2p->SetBranchAddress("Rp",Rp); t2p->SetBranchAddress("Pp",Pp); t2p->SetBranchAddress("Pe",Pe); t2p->SetBranchAddress("q",q); // See if there is a weight branch weight=1.; resetto1 = false; weight_branch = t2p->GetBranch("weight"); if (weight_branch) { if (lc_weight) t2p->SetBranchAddress("lcweight",&weight); else t2p->SetBranchAddress("weight",&weight); } else resetto1 = true; for (int event =0 ; event < t2p->GetEntries() ; event++) { t2p->GetEvent(event); if(resetto1) weight = 1; TVector3 ve(Pe[0],Pe[1],Pe[2]); TVector3 vlead(Pp[0][0],Pp[0][1],Pp[0][2]); if(doOtherCut){ // Do necessary cuts if (fabs(Rp[0][2]+22.25)>2.25) continue; if (Pp_size[0]>2.4) continue; if (Pmiss_size[0]<pmiss_cut) continue; } if(doCut){ // Apply fiducial cuts if (!accept_electron(ve)) continue; if (doGaps) { if (!accept_proton(vlead)) continue; } else { if (!accept_proton_simple(vlead)) continue; } // Apply an additional fiducial cut that the map acc must be > acc_thresh if ( proton_map.accept(vlead) < acc_thresh) continue; } // Sector-specific theta1 cuts double phi1_deg = vlead.Phi() * 180./M_PI; if (phi1_deg < -30.) phi1_deg += 360.; int sector = clas_sector(phi1_deg); double theta1_deg = vlead.Theta() * 180./M_PI; // A few more vectors TVector3 vq(q[0],q[1],q[2]); TVector3 vqUnit = vq.Unit(); TVector3 nUnit = vqUnit.Orthogonal().Unit(); TVector3 vmiss = vlead - vq; TVector3 vmUnit = vmiss.Unit(); TVector3 nmUnit = vmUnit.Orthogonal().Unit(); TVector3 vrec(Pp[1][0],Pp[1][1],Pp[1][2]); double omega = Q2/(2.*mN*Xb); //Do spectral function weight if (doSWeight){ double factorS = omega * myCS.sigma_eN(Ebeam,ve,vlead,true) / (2 * Ebeam * ve.Mag() * Xb); if (factorS>sCutOff){ weight = weight / factorS; } else weight=0; } h1p_QSq->Fill(Q2,weight); h1p_xB ->Fill(Xb,weight); h1p_Pm ->Fill(Pmiss_size[0],weight); h1p_Pm_30bin ->Fill(Pmiss_size[0],weight); h1p_Pm_30bin_bins ->Fill(Pmiss_size[0],weight*Pmiss_size[0]); h1p_Pm_coarse->Fill(Pmiss_size[0],weight); h1p_Pm_coarse_bins->Fill(Pmiss_size[0],weight*Pmiss_size[0]); h1p_Pmq->Fill(Pmiss_q_angle[0],weight); h1p_cPmq->Fill(cos(Pmiss_q_angle[0]*M_PI/180.),weight); // Kinematic variables we need double Elead = sqrt(Pp_size[0]*Pp_size[0] + mN*mN); double Emiss = -m_12C + mN + sqrt( sq(omega + m_12C - Elead) - (Pmiss_size[0]*Pmiss_size[0])); double epsilon = Elead - omega; double dE1 = sqrt(vmiss.Mag2()+sq(mN)) - epsilon; double rE1 = epsilon/sqrt(vmiss.Mag2()+sq(mN)); // Calculate the expected recoil momentum double TCM = (3/20) * sq(sigmaCM) / mN; double p2Calc = sqrt( sq( (m_12C-(m_10B+Estar)) - epsilon - TCM ) - sq(mN)); double p2CalcError = (p2Calc - vrec.Mag()) / vrec.Mag(); h2p_pRecError->Fill(p2CalcError,weight); // Let's calculate light cone variables double alphaq= (omega - vq.Mag()) / mN; double alphaLead = (Elead - vlead.Dot(vqUnit)) / mN; double alphaM = alphaLead - alphaq; TVector3 vmiss_perp = vmiss - vmiss.Dot(vqUnit)*vqUnit; double kmSq = (sq(mN) + vmiss_perp.Mag2())/(alphaM*(2-alphaM))-sq(mN); double km = sqrt(kmSq); h1p_alphaq->Fill(alphaq,weight); h1p_alphaLead->Fill(alphaLead,weight); h1p_alphaM->Fill(alphaM,weight); h1p_dE1->Fill(dE1,weight); h1p_rE1->Fill(rE1,weight); h1p_km->Fill(km,weight); // Let's make a sanitized phi and sector double phie_deg = ve.Phi() * 180./M_PI; if (phie_deg < -30.) phie_deg += 360.; int sec_e = clas_sector(phie_deg); double thetae_deg = ve.Theta() * 180./M_PI; h1p_phie->Fill(phie_deg,weight); h1p_thetae->Fill(thetae_deg,weight); h1p_thetae_bySec[sec_e]->Fill(thetae_deg,weight); h1p_mome->Fill(ve.Mag(),weight); h1p_phi1->Fill(phi1_deg,weight); h1p_theta1->Fill(theta1_deg,weight); h1p_theta1_bySec[sector]->Fill(theta1_deg,weight); h1p_mom1->Fill(Pp_size[0],weight); h1p_Emiss->Fill(Emiss,weight); h1p_Emiss_fine->Fill(Emiss,weight); h1p_e1->Fill(epsilon,weight); h1p_emiss->Fill(mN-epsilon,weight); h1p_pmiss_Emiss->Fill(Pmiss_size[0],Emiss,weight); h1p_pmiss_E1->Fill(Pmiss_size[0],epsilon,weight); h1p_Emiss_by_sector->Fill(sec_e,Emiss); //Look at kinematic regions int Pmiss_region_pp; if (Pmiss_size[0] < pmiss_lo) Pmiss_region_pp = 0; else if (Pmiss_size[0] < pmiss_md) Pmiss_region_pp = 1; else if (Pmiss_size[0] < pmiss_hi) Pmiss_region_pp = 2; else Pmiss_region_pp = 3; int xB_region_pp; if (Xb < 1.4) xB_region_pp = 1; else xB_region_pp = 2; int QSq_region_pp; if (Q2 < 2) QSq_region_pp = 1; else QSq_region_pp = 2; for(int j=0; j<=xB_region_pp; j=j+xB_region_pp){ for(int k=0; k<=QSq_region_pp; k=k+QSq_region_pp){ h1p_Emiss_split[Pmiss_region_pp][j][k]->Fill(Emiss,weight); h1p_Emiss_fine_split[Pmiss_region_pp][j][k]->Fill(Emiss,weight); h1p_e1_split[Pmiss_region_pp][j][k]->Fill(epsilon,weight); h1p_emiss_split[Pmiss_region_pp][j][k]->Fill(mN-epsilon,weight); h1p_Pmq_split[Pmiss_region_pp][j][k]->Fill(Pmiss_q_angle[0],weight); h1p_Pmzq_split[Pmiss_region_pp][j][k]->Fill(vmiss.Dot(vqUnit),weight); h1p_PmTq_split[Pmiss_region_pp][j][k]->Fill(vmiss.Perp(vqUnit),weight); h1p_dE1_split[Pmiss_region_pp][j][k]->Fill(dE1,weight); h1p_rE1_split[Pmiss_region_pp][j][k]->Fill(rE1,weight); } } h1p_pmiss_epsilon->Fill(Pmiss_size[0],epsilon,weight); h1p_pmiss_QSq->Fill(Pmiss_size[0],Q2,weight); h1p_pmiss_mom1->Fill(Pmiss_size[0],Pp_size[0],weight); if(doOtherCut){ // Make a check on the recoils if (fabs(Rp[1][2]+22.25)>2.25) continue; if (Pp_size[1] < 0.35) continue; } if(doCut){ if (doGaps) { if (!accept_proton(vrec)) continue; } else { if (!accept_proton_simple(vrec)) continue; } // Apply an additional fiducial cut that the map acc must be > acc_thresh if ( proton_map.accept(vrec) < acc_thresh) continue; } double Erec = sqrt(vrec.Mag2() + mN*mN); TVector3 vcm = vmiss + vrec; // Find final light cone variables double alphaRec = (Erec - vrec.Dot(vqUnit))/mN; double alphaD = alphaM + alphaRec; double alphaRel = 2*alphaRec/alphaD; TVector3 vrec_perp = vrec - vrec.Dot(vqUnit)*vqUnit; TVector3 k_perp = alphaM/alphaD*vrec_perp - alphaRec/alphaD*vmiss_perp; double kSq = (sq(mN) + k_perp.Mag2())/(alphaRel*(2-alphaRel))-sq(mN); double k = sqrt(kSq); h2p_QSq->Fill(Q2,weight); h2p_xB ->Fill(Xb,weight); h2p_Pm ->Fill(Pmiss_size[0],weight); h2p_Pm_30bin ->Fill(Pmiss_size[0],weight); h2p_Pm_30bin_bins ->Fill(Pmiss_size[0],Pmiss_size[0]*weight); h2p_Pm_clas ->Fill(Pmiss_size[0],weight); h2p_Pm_coarse->Fill(Pmiss_size[0],weight); h2p_Pm_coarse_bins->Fill(Pmiss_size[0],weight*Pmiss_size[0]); h2p_Pmq->Fill(Pmiss_q_angle[0],weight); h2p_Pmr->Fill(vmiss.Angle(vrec)*180./M_PI,weight); h2p_cPmq->Fill(cos(Pmiss_q_angle[0]*M_PI/180.),weight); h2p_cPmr->Fill(cos(vmiss.Angle(vrec)),weight); h2p_alphaq->Fill(alphaq,weight); h2p_alphaLead->Fill(alphaLead,weight); h2p_alphaM->Fill(alphaM,weight); h2p_dE1->Fill(dE1,weight); h2p_rE1->Fill(rE1,weight); h2p_km->Fill(km,weight); h2p_alphaRec->Fill(alphaRec,weight); h2p_alphaD->Fill(alphaD,weight); h2p_phie->Fill(phie_deg,weight); h2p_thetae->Fill(thetae_deg,weight); h2p_mome->Fill(ve.Mag(),weight); h2p_phi1->Fill(phi1_deg,weight); h2p_theta1->Fill(theta1_deg,weight); h2p_theta1_bySec[sector]->Fill(theta1_deg,weight); h2p_mom1->Fill(Pp_size[0],weight); h2p_k->Fill(k,weight); h2p_Emiss->Fill(Emiss,weight); h2p_Emiss_fine->Fill(Emiss,weight); h2p_e1->Fill(epsilon,weight); h2p_emiss->Fill(mN-epsilon,weight); h2p_pmiss_E1->Fill(Pmiss_size[0],epsilon,weight); h2p_pmiss_epsilon->Fill(Pmiss_size[0],epsilon,weight); h2p_pRec_epsilon->Fill(Pp_size[1],epsilon,weight); h2p_pRec_eMiss->Fill(Pp_size[1],Emiss,weight); //Do Pmiss splits for(int j=0; j<=xB_region_pp; j=j+xB_region_pp){ for(int k=0; k<=QSq_region_pp; k=k+QSq_region_pp){ h2p_Emiss_split[Pmiss_region_pp][j][k]->Fill(Emiss,weight); h2p_Emiss_fine_split[Pmiss_region_pp][j][k]->Fill(Emiss,weight); h2p_e1_split[Pmiss_region_pp][j][k]->Fill(epsilon,weight); h2p_emiss_split[Pmiss_region_pp][j][k]->Fill(mN-epsilon,weight); h2p_Pmq_split[Pmiss_region_pp][j][k]->Fill(Pmiss_q_angle[0],weight); h2p_Pmzq_split[Pmiss_region_pp][j][k]->Fill(vmiss.Dot(vqUnit),weight); h2p_PmTq_split[Pmiss_region_pp][j][k]->Fill(vmiss.Perp(vqUnit),weight); h2p_dE1_split[Pmiss_region_pp][j][k]->Fill(dE1,weight); h2p_rE1_split[Pmiss_region_pp][j][k]->Fill(rE1,weight); h2p_Pcmzq_split[Pmiss_region_pp][j][k]->Fill(vcm.Dot(vqUnit),weight); h2p_Pcmn1q_split[Pmiss_region_pp][j][k]->Fill(vcm.Dot(nUnit),weight); h2p_Pcmn2q_split[Pmiss_region_pp][j][k]->Fill(vcm.Dot(vqUnit.Cross(nUnit)),weight); h2p_PcmTq_split[Pmiss_region_pp][j][k]->Fill(vcm.Perp(vqUnit),weight); h2p_Pcmzm_split[Pmiss_region_pp][j][k]->Fill(vcm.Dot(vmUnit),weight); h2p_Pcmn1m_split[Pmiss_region_pp][j][k]->Fill(vcm.Dot(nmUnit),weight); h2p_Pcmn2m_split[Pmiss_region_pp][j][k]->Fill(vcm.Dot(vmUnit.Cross(nmUnit)),weight); h2p_PcmTm_split[Pmiss_region_pp][j][k]->Fill(vcm.Perp(vmUnit),weight); h2p_alphaD_split[Pmiss_region_pp][j][k]->Fill(alphaD,weight); } } // Let's make a sanitized phi and sector double phi2_deg = vrec.Phi() * 180./M_PI; if (phi2_deg < -30.) phi2_deg += 360.; int sector2 = clas_sector(phi2_deg); double theta2_deg = vrec.Theta() * 180./M_PI; h2p_phi2->Fill(phi2_deg,weight); h2p_theta2->Fill(theta2_deg,weight); h2p_theta2_bySec[sector2]->Fill(theta2_deg,weight); h2p_mom2->Fill(Pp_size[1],weight); h2p_pmiss_QSq->Fill(Pmiss_size[0],Q2,weight); h2p_pmiss_mom1->Fill(Pmiss_size[0],Pp_size[0],weight); h2p_pmiss_mom2->Fill(Pmiss_size[0],Pp_size[1],weight); h2p_pmiss_k->Fill(Pmiss_size[0],k,weight); h2p_prec_k->Fill(Pp_size[1],k,weight); h2p_pmiss_momrat->Fill(Pmiss_size[0],Pp_size[0]/Pp_size[1],weight); double xlc = 0.5 + 0.5*sqrt(kSq - k_perp.Mag2())/sqrt(kSq + mN*mN); h2p_rat1->Fill(sqrt(1/(2*mN)*sqrt((k_perp.Mag2() + mN*mN)/(xlc*(1-xlc)))),weight); h2p_rat2->Fill(2/(8*mN*mN*mN)*xlc*(1-xlc)/(1-abs(1-2*xlc)) *sqrt((k_perp.Mag2() + mN*mN)/(xlc*(1-xlc))) *((k_perp.Mag2() + mN*mN)/(xlc*(1-xlc))+4*mN*mN -sqrt((k_perp.Mag2() + mN*mN)/(xlc*(1-xlc))) * sqrt((k_perp.Mag2() + mN*mN)/(xlc*(1-xlc))-4*mN*mN)),weight); TVector3 vdiff = vlead - vrec; h2p_momdiff->Fill(vdiff.Mag(),weight); h2p_pmiss_momdiff->Fill(Pmiss_size[0],vdiff.Mag(),weight); // Histogram for the "apparent E*" double apparent_Estar = sqrt(sq(sqrt(sq(m_10B) + vcm.Mag2()) + Erec) -vlead.Mag2()) - m_11B; h2p_pmiss_appEstar->Fill(Pmiss_size[0],apparent_Estar,weight); } for( int i = 0; i < h2p_pRec_epsilon->GetNbinsX(); i++){ TH1D * h2p_pRec_epsilon_Proj = h2p_pRec_epsilon->ProjectionY("pRec_epsilon_Proj",i,i+1); h2p_pRec_epsilon_mean->Fill(h2p_pRec_epsilon->GetXaxis()->GetBinCenter(i+1),h2p_pRec_epsilon_Proj->GetMean()); h2p_pRec_epsilon_std->Fill(h2p_pRec_epsilon->GetXaxis()->GetBinCenter(i+1),h2p_pRec_epsilon_Proj->GetStdDev()); } for( int i = 0; i < h2p_pRec_eMiss->GetNbinsX(); i++){ TH1D * h2p_pRec_eMiss_Proj = h2p_pRec_eMiss->ProjectionY("pRec_eMiss_Proj",i,i+1); h2p_pRec_eMiss_mean->Fill(h2p_pRec_eMiss->GetXaxis()->GetBinCenter(i+1),h2p_pRec_eMiss_Proj->GetMean()); h2p_pRec_eMiss_std->Fill(h2p_pRec_eMiss->GetXaxis()->GetBinCenter(i+1),h2p_pRec_eMiss_Proj->GetStdDev()); } f1p->Close(); f2p->Close(); // Do the bin centering TGraphAsymmErrors * g1p_Pm = new TGraphAsymmErrors(30); g1p_Pm->SetName("ep_Pm_graph"); g1p_Pm->SetTitle("ep;p_miss [GeV];Counts"); for (int i=1 ; i<= 30 ; i++) { // e'p double sumN = h1p_Pm_30bin->GetBinContent(i); double sumPm = h1p_Pm_30bin_bins->GetBinContent(i); double avgPm = h1p_Pm_30bin->GetBinLowEdge(i) + 0.5 *h1p_Pm_30bin->GetBinWidth(i); if (sumN > 0) avgPm = (sumPm/sumN); h1p_Pm_30bin_bins->SetBinContent(i,avgPm); // Fill out the TGraph g1p_Pm->SetPoint(i-1,avgPm,sumN); g1p_Pm->SetPointError(i-1,avgPm - h1p_Pm_30bin->GetBinLowEdge(i), h1p_Pm_30bin->GetBinLowEdge(i) + h1p_Pm_30bin->GetBinWidth(i) - avgPm, h1p_Pm_30bin->GetBinError(i), h1p_Pm_30bin->GetBinError(i)); } g1p_Pm->Write(); TGraphAsymmErrors * g2p_Pm = new TGraphAsymmErrors(24); g2p_Pm->SetName("epp_Pm_graph"); g2p_Pm->SetTitle("epp;p_miss [GeV];Counts"); // The binning is non-uniform, so we have to be careful const int startBins[24]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,23,25,27}; const int stopBins[24] ={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,22,24,26,30}; for (int i=0 ; i< 24 ; i++) { // e'pp double sumN = h2p_Pm_30bin->Integral(startBins[i],stopBins[i]); double sumPm = h2p_Pm_30bin_bins->Integral(startBins[i],stopBins[i]); double avgPm = 0.5*(h2p_Pm_30bin->GetBinLowEdge(startBins[i]) + h2p_Pm_30bin->GetXaxis()->GetBinUpEdge(stopBins[i])); if (sumN > 0) avgPm = (sumPm / sumN); cerr << avgPm << "\n"; double binScale = (0.02)/(h2p_Pm_30bin->GetXaxis()->GetBinUpEdge(stopBins[i]) - h2p_Pm_30bin->GetBinLowEdge(startBins[i])); g2p_Pm->SetPoint(i,avgPm,sumN * binScale); g2p_Pm->SetPointError(i,avgPm - h2p_Pm_30bin->GetBinLowEdge(startBins[i]), h2p_Pm_30bin->GetXaxis()->GetBinUpEdge(stopBins[i]) -avgPm, binScale * sqrt(sumN),binScale * sqrt(sumN)); } g2p_Pm->Write(); cerr << "The ep and epp integrals are: " << h1p_Pm->Integral() << " " << h2p_Pm->Integral() << "\n"; cerr << "Broken down by pmiss range...\n\n"; for (int j=1 ; j<=30 ; j+=1) { cerr << h1p_Pm->GetBinCenter(j) << " " << h1p_Pm->GetBinContent(j) << " " << h2p_Pm->GetBinContent(j) << "\n"; } cerr << "\n\n"; // pp-to-p, including bin centering pp_to_p->BayesDivide(h2p_Pm,h1p_Pm); pp_to_p_coarse->BayesDivide(h2p_Pm_coarse,h1p_Pm_coarse); if (bin_center) { for (int j=1 ; j<=9 ; j++) { double sumPm = h1p_Pm_coarse_bins->GetBinContent(j); double sumN = h1p_Pm_coarse->GetBinContent(j); double avgPm = sumPm / sumN; double pp2p = pp_to_p_coarse->GetY()[j-1]; pp_to_p_coarse->SetPoint(j-1,avgPm,pp2p); pp_to_p_coarse->SetPointEXlow(j-1,avgPm - h1p_Pm_coarse->GetBinLowEdge(j)); pp_to_p_coarse->SetPointEXhigh(j-1,h1p_Pm_coarse->GetXaxis()->GetBinUpEdge(j) - avgPm); cerr << avgPm << " " << h1p_Pm_coarse->GetBinContent(j) << " & " << h2p_Pm_coarse->GetBinContent(j) << " & " << pp_to_p_coarse->GetY()[j-1] << " & \n"; } cerr << "\n\n"; } // 2d pp-to-p for (int binX=1 ; binX<=pp_to_p_2d->GetNbinsX() ; binX++) for (int binY=1 ; binY<=pp_to_p_2d->GetNbinsY() ; binY++) { double N_pp = h2p_pmiss_E1->GetBinContent(binX,binY); double N_p = h1p_pmiss_E1->GetBinContent(binX,binY); double ratio = 0.; if (N_p >0) ratio = N_pp / N_p; pp_to_p_2d->SetBinContent(binX,binY,ratio); } // Write out fo -> cd(); pp_to_p->Write(); pp_to_p_coarse->Write(); pp_to_p_2d->Write(); const double data_ep = 5604.; const double data_ep_cor = 6077.; const double data_epp = 364.; const double pnorm = data_ep/h1p_Pm->Integral(); const double ppnorm = pnorm;//data_epp/h2p_Pm->Integral(); h2p_pRecError->Scale(data_epp/h2p_Pm->Integral()); // Including a factor if we want to rescale data to match epp luminosity const double renorm = data_epp/h2p_Pm->Integral()/(data_ep/h1p_Pm->Integral()); TVectorT<double> renorm_factor(1); renorm_factor[0] = renorm; renorm_factor.Write("factor"); h2p_Pm_clas->Scale(data_epp/h2p_Pm->Integral()); // scale all the histograms for (int i=0 ; i<h1p_list.size() ; i++) h1p_list[i]->Scale(pnorm); for (int i=0 ; i<h2p_list.size() ; i++) h2p_list[i]->Scale(ppnorm); // Write all the histograms and close the file. fo->Write(); fo->Close(); return 0; }
//////////////////////////////////////////////////////////////////////////////// // rovioSpeak.cpp // Mario Chirinos Colunga // Oscar Sanchez Sioridia // Áurea - Desarrollo Tecnológico // http://www.aurea-dt.com // 18 Dic 2010 - 26 Jun 2013 //------------------------------------------------------------------------------ // Notes: // send rovio audio using espeak and culr // //////////////////////////////////////////////////////////////////////////////// #include "rovioSpeak.h" #include <iostream> #include <sstream> #include <string.h> using namespace std; //------------------------------------------------------------------------------ rovioSpeak::rovioSpeak(const char *_uri) { cout << "rovioSpeak("<< _uri <<")" << endl; sampleRate = espeak_Initialize(AUDIO_OUTPUT_RETRIEVAL, 500, NULL, 1); espeak_SetVoiceByName("default"); espeak_SetSynthCallback(SynthCallback); stringstream ss; ss << "http://" << _uri << "/GetAudio.cgi" << endl; getline(ss, audiouri); rovioSR= 8000; audioBufferLength=0; audioBuffer=NULL; cout << audiouri << endl; // curl_global_init(CURL_GLOBAL_ALL); } //------------------------------------------------------------------------------ rovioSpeak::~rovioSpeak() { espeak_Terminate(); } //------------------------------------------------------------------------------ void rovioSpeak::speak(const char* text) { cout << "speak(" << text << ")" << endl; string str = text; // unsigned int* unique_identifier; espeak_Synth(str.c_str(), str.size(), 0, POS_CHARACTER, 0, espeakCHARS_AUTO, NULL, this); espeak_Synchronize( ); } //------------------------------------------------------------------------------ int rovioSpeak::SynthCallback(short int *wav, int numsamples, espeak_EVENT *events) { cout << "int rovioSpeak::SynthCallback(short int *wav, "<< numsamples<< ", " << events->type << ")"<< endl; if(events->type==6) { cout << "End of message" << endl; ((rovioSpeak*)events->user_data)->sendBuffer(); return 0; } if(numsamples <= 0) { cout << "no audio" << endl; return 0; } int newLenght = numsamples; short int *newBuffer = new short int[newLenght]; newLenght=((rovioSpeak*)events->user_data)->scaleBuffer(wav, numsamples, newBuffer); string audiouri = ((rovioSpeak*)events->user_data)->audiouri; int bufferLength = newLenght*sizeof(short); ((rovioSpeak*)events->user_data)->mergeAudioBuffers((unsigned char*)newBuffer, bufferLength); delete []newBuffer; return 0; } //------------------------------------------------------------------------------ void rovioSpeak::mergeAudioBuffers(unsigned char* buffer, unsigned int bufferLength) { if(audioBuffer!=NULL) { unsigned char* audioTemp = new unsigned char [audioBufferLength]; memcpy(audioTemp, audioBuffer,audioBufferLength); delete []audioBuffer; audioBuffer = new unsigned char [audioBufferLength+bufferLength]; memcpy(audioBuffer, audioTemp, audioBufferLength); memcpy(audioBuffer+audioBufferLength, buffer, bufferLength); audioBufferLength+=bufferLength; delete []audioTemp; } else { cout << audioBufferLength << ", " << bufferLength << endl; audioBuffer = new unsigned char [audioBufferLength+bufferLength]; memcpy(audioBuffer+audioBufferLength, buffer, bufferLength); audioBufferLength+=bufferLength; } } //------------------------------------------------------------------------------ void rovioSpeak::sendBuffer() { sendBuffer(audioBuffer, audioBufferLength); delete []audioBuffer; audioBuffer = NULL; audioBufferLength = 0; } //------------------------------------------------------------------------------ void rovioSpeak::sendBuffer(unsigned char *buffer, unsigned int bufferLength) const { CURL* ctx = curl_easy_init(); cout << rovioSR << endl; cout << audiouri << endl; curl_easy_setopt(ctx, CURLOPT_URL, audiouri.c_str()); curl_easy_setopt(ctx, CURLOPT_POST,true); curl_easy_setopt(ctx, CURLOPT_POSTFIELDSIZE, bufferLength); curl_easy_setopt(ctx, CURLOPT_POSTFIELDS, buffer); struct curl_slist *headers = NULL; headers = curl_slist_append(headers, "Content-Type: multipart/form-data"); curl_easy_setopt(ctx, CURLOPT_HTTPHEADER, headers); CURLcode ret = curl_easy_perform(ctx); curl_slist_free_all(headers); curl_easy_cleanup(ctx); } //------------------------------------------------------------------------------ int rovioSpeak::scaleBuffer(short int *wavIn, int nSamplesIn, short int *wavOut) const { int newLenght = nSamplesIn*rovioSR/sampleRate; cout << nSamplesIn<<"*"<< rovioSR <<"/" << sampleRate << "=" << newLenght << endl; int delta = nSamplesIn/newLenght; for(int i=0; i<nSamplesIn; i+=delta) { *wavOut=wavIn[i]; *wavOut++; } return newLenght; } //------------------------------------------------------------------------------
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * LispC Parsing * 1) tokenize into vector of string * 2) parse into expressions * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #pragma once #include <set> #include <string> #include <vector> #include "Expression.h" #include "ListExpression.h" #include "SymbolExpression.h" #include "NumberExpression.h" namespace lispc { Expression* parse(std::string& program); std::vector<std::string> tokenize(std::string& program); Expression* read_from_tokens(std::vector<std::string> tokens); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2008 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * @author Alexander Remen */ #include "core/pch.h" #include "adjunct/desktop_util/resources/ResourceDefines.h" /* static */ StartupType& StartupType::GetInstance() { static StartupType s_startup_type; return s_startup_type; } /* static */ RegionInfo& RegionInfo::GetInstance() { static RegionInfo s_region_info; return s_region_info; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-1999 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #include "modules/dom/src/domenvironmentimpl.h" #include "modules/dom/src/domglobaldata.h" #include "modules/dom/src/domcore/domconfiguration.h" #include "modules/util/str.h" #include "modules/util/tempbuf.h" class DOM_DOMConfiguration_Parameter : public Link { public: DOM_DOMConfiguration_Parameter(DOM_DOMConfiguration::CheckParameterValue *check) : name(NULL), check(check) { } ~DOM_DOMConfiguration_Parameter() { OP_DELETEA(name); } char *name; DOM_DOMConfiguration::CheckParameterValue *check; }; #ifdef DOM_NO_COMPLEX_GLOBALS # define DOM_STATIC_PARAMETERS_START() void DOM_configurationParameters_Init(DOM_GlobalData *global_data) { DOM_DOMConfiguration_StaticParameter *parameters = global_data->configurationParameters; # define DOM_STATIC_PARAMETERS_ITEM(name_, initial_, check_) parameters->name = name_; parameters->initial = initial_; parameters->check = check_; ++parameters; # define DOM_STATIC_PARAMETERS_END() parameters->name = NULL; } #else // DOM_NO_COMPLEX_GLOBALS # define DOM_STATIC_PARAMETERS_START() const DOM_DOMConfiguration_StaticParameter g_DOM_configurationParameters[] = { # define DOM_STATIC_PARAMETERS_ITEM(name_, initial_, check_) { name_, initial_, check_ }, # define DOM_STATIC_PARAMETERS_END() { 0, 0, 0 } }; #endif // DOM_NO_COMPLEX_GLOBALS DOM_STATIC_PARAMETERS_START() DOM_STATIC_PARAMETERS_ITEM("canonical-form", "false", DOM_DOMConfiguration::acceptFalse) DOM_STATIC_PARAMETERS_ITEM("cdata-sections", "true", DOM_DOMConfiguration::acceptTrue) DOM_STATIC_PARAMETERS_ITEM("check-character-normalization", "false", DOM_DOMConfiguration::acceptFalse) DOM_STATIC_PARAMETERS_ITEM("comments", "true", DOM_DOMConfiguration::acceptTrue) DOM_STATIC_PARAMETERS_ITEM("datatype-normalization", "false", DOM_DOMConfiguration::acceptFalse) DOM_STATIC_PARAMETERS_ITEM("entities", "false", DOM_DOMConfiguration::acceptFalse) DOM_STATIC_PARAMETERS_ITEM("error-handler", "null", DOM_DOMConfiguration::acceptObject) DOM_STATIC_PARAMETERS_ITEM("infoset", "false", DOM_DOMConfiguration::acceptFalse) DOM_STATIC_PARAMETERS_ITEM("namespaces", "true", DOM_DOMConfiguration::acceptTrue) DOM_STATIC_PARAMETERS_ITEM("namespace-declarations", "true", DOM_DOMConfiguration::acceptTrue) DOM_STATIC_PARAMETERS_ITEM("normalize-characters", "false", DOM_DOMConfiguration::acceptFalse) DOM_STATIC_PARAMETERS_ITEM("schema-location", "null", DOM_DOMConfiguration::acceptNothing) DOM_STATIC_PARAMETERS_ITEM("schema-type", "null", DOM_DOMConfiguration::acceptNothing) DOM_STATIC_PARAMETERS_ITEM("split-cdata-sections", "false", DOM_DOMConfiguration::acceptFalse) DOM_STATIC_PARAMETERS_ITEM("validate", "false", DOM_DOMConfiguration::acceptFalse) DOM_STATIC_PARAMETERS_ITEM("validate-if-schema", "false", DOM_DOMConfiguration::acceptFalse) DOM_STATIC_PARAMETERS_ITEM("well-formed", "true", DOM_DOMConfiguration::acceptTrue) DOM_STATIC_PARAMETERS_ITEM("element-content-whitespace", "true", DOM_DOMConfiguration::acceptTrue) DOM_STATIC_PARAMETERS_END() /* static */ OP_STATUS DOM_DOMConfiguration::Make(DOM_DOMConfiguration *&configuration, DOM_EnvironmentImpl *environment) { DOM_Runtime *runtime = environment->GetDOMRuntime(); RETURN_IF_ERROR(DOMSetObjectRuntime(configuration = OP_NEW(DOM_DOMConfiguration, ()), runtime, runtime->GetPrototype(DOM_Runtime::DOMCONFIGURATION_PROTOTYPE), "DOMConfiguration")); RETURN_IF_ERROR(DOMSetObjectRuntime(configuration->parameter_values = OP_NEW(DOM_Object, ()), runtime)); const DOM_DOMConfiguration_StaticParameter *parameters = g_DOM_configurationParameters; while (parameters->name) { const char *initial = parameters->initial; ES_Value value; if (op_strcmp("true", initial) == 0) DOMSetBoolean(&value, TRUE); else if (op_strcmp("false", initial) == 0) DOMSetBoolean(&value, FALSE); else if (op_strcmp("null", initial) == 0) DOMSetNull(&value); RETURN_IF_ERROR(configuration->AddParameter(parameters->name, &value, parameters->check)); ++parameters; } return OpStatus::OK; } DOM_DOMConfiguration::~DOM_DOMConfiguration() { parameters.Clear(); } OP_STATUS DOM_DOMConfiguration::AddParameter(const char *name, ES_Value *value, DOM_DOMConfiguration::CheckParameterValue *check) { TempBuffer buffer; RETURN_IF_ERROR(buffer.Append(name)); DOM_DOMConfiguration_Parameter *parameter = OP_NEW(DOM_DOMConfiguration_Parameter, (check)); if (!parameter) return OpStatus::ERR_NO_MEMORY; if (OpStatus::IsMemoryError(SetStr(parameter->name, name)) || value->type != VALUE_NULL && OpStatus::IsMemoryError(parameter_values->Put(buffer.GetStorage(), *value))) { OP_DELETE(parameter); return OpStatus::ERR_NO_MEMORY; } parameter->Into(&parameters); return OpStatus::OK; } OP_STATUS DOM_DOMConfiguration::GetParameter(const uni_char *name, ES_Value *value) { OP_BOOLEAN result = parameter_values->Get(name, value); if (OpStatus::IsError(result)) return result; else if (result != OpBoolean::IS_TRUE) return OpStatus::ERR; else return OpStatus::OK; } /* virtual */ ES_GetState DOM_DOMConfiguration::GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime) { if (property_name == OP_ATOM_parameterNames) { ES_GetState state = DOMSetPrivate(value, DOM_PRIVATE_parameterNames); if (state == GET_FAILED) { DOM_DOMStringList *stringlist; GET_FAILED_IF_ERROR(DOM_DOMStringList::Make(stringlist, this, this, static_cast<DOM_Runtime *>(origining_runtime))); GET_FAILED_IF_ERROR(PutPrivate(DOM_PRIVATE_parameterNames, *stringlist)); DOMSetObject(value, stringlist); return GET_SUCCESS; } return state; } else return GET_FAILED; } /* virtual */ ES_PutState DOM_DOMConfiguration::PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime) { if (property_name == OP_ATOM_parameterNames) return PUT_READ_ONLY; else return PUT_FAILED; } /* virtual */ void DOM_DOMConfiguration::GCTrace() { GCMark(parameter_values); } /* virtual */ unsigned DOM_DOMConfiguration::StringList_length() { return parameters.Cardinal(); } /* virtual */ OP_STATUS DOM_DOMConfiguration::StringList_item(int index, const uni_char *&name) { for (DOM_DOMConfiguration_Parameter *parameter = (DOM_DOMConfiguration_Parameter *) parameters.First(); parameter; parameter = (DOM_DOMConfiguration_Parameter *) parameter->Suc()) if (index == 0) { TempBuffer *buffer = GetEmptyTempBuf(); RETURN_IF_ERROR(buffer->Append(parameter->name)); name = buffer->GetStorage(); return OpStatus::OK; } else --index; return OpStatus::ERR; } /* virtual */ BOOL DOM_DOMConfiguration::StringList_contains(const uni_char *string) { for (DOM_DOMConfiguration_Parameter *parameter = (DOM_DOMConfiguration_Parameter *) parameters.First(); parameter; parameter = (DOM_DOMConfiguration_Parameter *) parameter->Suc()) if (uni_str_eq(string, parameter->name)) return TRUE; return FALSE; } /* static */ int DOM_DOMConfiguration::accessParameter(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value *return_value, DOM_Runtime *origining_runtime, int data) { DOM_THIS_OBJECT(configuration, DOM_TYPE_DOMCONFIGURATION, DOM_DOMConfiguration); DOM_CHECK_ARGUMENTS("s"); const uni_char *name = argv[0].value.string; DOM_DOMConfiguration_Parameter *parameter; for (parameter = (DOM_DOMConfiguration_Parameter *) configuration->parameters.First(); parameter && !uni_str_eq(name, parameter->name); parameter = (DOM_DOMConfiguration_Parameter *) parameter->Suc()) { // Loop until we find the right parameter } if (data == 0) { if (parameter) { OP_STATUS result = configuration->GetParameter(name, return_value); if (result == OpStatus::ERR_NO_MEMORY) return ES_NO_MEMORY; else if (result != OpStatus::OK) DOMSetNull(return_value); return ES_VALUE; } else return DOM_CALL_DOMEXCEPTION(NOT_FOUND_ERR); } else { DOMException code = parameter ? parameter->check(parameter->name, &argv[1]) : NOT_FOUND_ERR; if (data == 1) { if (code == DOMEXCEPTION_NO_ERR) { OP_STATUS status; if (argv[1].type == VALUE_NULL || argv[1].type == VALUE_UNDEFINED) status = configuration->parameter_values->Delete(name); else status = configuration->parameter_values->Put(name, argv[1]); CALL_FAILED_IF_ERROR(status); return ES_FAILED; } else return configuration->CallDOMException(code, return_value); } else { DOMSetBoolean(return_value, code == DOMEXCEPTION_NO_ERR); return ES_VALUE; } } } DOM_Object::DOMException DOM_DOMConfiguration::acceptTrue(const char *, ES_Value *value) { if (value->type == VALUE_BOOLEAN) if (value->value.boolean == TRUE) return DOM_Object::DOMEXCEPTION_NO_ERR; else return DOM_Object::NOT_SUPPORTED_ERR; else return DOM_Object::TYPE_MISMATCH_ERR; } DOM_Object::DOMException DOM_DOMConfiguration::acceptFalse(const char *, ES_Value *value) { if (value->type == VALUE_BOOLEAN) if (value->value.boolean == FALSE) return DOM_Object::DOMEXCEPTION_NO_ERR; else return DOM_Object::NOT_SUPPORTED_ERR; else return DOM_Object::TYPE_MISMATCH_ERR; } DOM_Object::DOMException DOM_DOMConfiguration::acceptBoolean(const char *, ES_Value *value) { if (value->type == VALUE_BOOLEAN) return DOM_Object::DOMEXCEPTION_NO_ERR; else return DOM_Object::TYPE_MISMATCH_ERR; } DOM_Object::DOMException DOM_DOMConfiguration::acceptNull(const char *, ES_Value *value) { if (value->type == VALUE_NULL) return DOM_Object::DOMEXCEPTION_NO_ERR; else if (value->type == VALUE_OBJECT) return DOM_Object::NOT_SUPPORTED_ERR; else return DOM_Object::TYPE_MISMATCH_ERR; } DOM_Object::DOMException DOM_DOMConfiguration::acceptObject(const char *, ES_Value *value) { if (value->type == VALUE_NULL || value->type == VALUE_OBJECT) return DOM_Object::DOMEXCEPTION_NO_ERR; else return DOM_Object::TYPE_MISMATCH_ERR; } DOM_Object::DOMException DOM_DOMConfiguration::acceptNothing(const char *, ES_Value *value) { if (value->type == VALUE_NULL) return DOM_Object::DOMEXCEPTION_NO_ERR; else return DOM_Object::NOT_SUPPORTED_ERR; } #include "modules/dom/src/domglobaldata.h" DOM_FUNCTIONS_WITH_DATA_START(DOM_DOMConfiguration) DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_DOMConfiguration, DOM_DOMConfiguration::accessParameter, 0, "getParameter", "s-") DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_DOMConfiguration, DOM_DOMConfiguration::accessParameter, 1, "setParameter", "s-") DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_DOMConfiguration, DOM_DOMConfiguration::accessParameter, 2, "canSetParameter", "s-") DOM_FUNCTIONS_WITH_DATA_END(DOM_DOMConfiguration)
/* * TreeLib * A library for manipulating phylogenetic trees. * Copyright (C) 2001 Roderic D. M. Page <r.page@bio.gla.ac.uk> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307, USA. */ // $Id: profile.h,v 1.21 2002/03/19 09:26:23 rdmp1c Exp $ /** * @file profile.h * * Storage of trees * */ #ifndef PROFILE_H #define PROFILE_H #ifdef __BORLANDC__ // Undefine __MINMAX_DEFINED so that min and max are correctly defined #ifdef __MINMAX_DEFINED #undef __MINMAX_DEFINED #endif // Ignore "Cannot create precompiled header: code in header" message // generated when compiling string.cc #pragma warn -pch #endif #include "TreeLib.h" #include "gtree.h" #include "treereader.h" #include "treewriter.h" /* // NCL includes #include "nexusdefs.h" #include "xnexus.h" #include "nexustoken.h" #include "nexus.h" #include "taxablock.h" #include "assumptionsblock.h" #include "treesblock.h" #include "discretedatum.h" #include "discretematrix.h" #include "charactersblock.h" #include "datablock.h" */ #if USE_VC2 #include "VMsg.h" #endif #if USE_WXWINDOWS #include "wx/wx.h" #endif #if (__BORLANDC__ < 0x0550) #include <time.h> #else #include <ctime> #endif /** *@typedef map <std::string, int, less<std::string> > LabelMap; */ typedef map <std::string, int, less<std::string> > LabelMap; /** * @class Profile * Encapsulates reading and storing a set of trees. * */ template <class T> class Profile { public: /** * A map between leaf labels in the profile and a unique integer index */ LabelMap Labels; /** * For each leaf label the number of trees in the profile that have the corresponding leaf */ LabelMap LabelFreq; /** * Constructor */ Profile () {}; /** * Destructor */ virtual ~Profile () {}; /** * @brief The ith tree in the profile * * @param i the index of the tree in the range 0 - (n-1) * @return The tree */ virtual T GetIthTree (int i) { return Trees[i]; }; /** * @brief The name of the ith tree in the profile * * @param i the index of the tree in the range 0 - (n-1) * @return The tree */ virtual std::string GetIthTreeName (int i) { return Trees[i].GetName(); }; /** * @return The number of labels in the profile */ virtual int GetNumLabels () { return Labels.size(); }; /** * @return The number of trees in the profile */ virtual int GetNumTrees () { return Trees.size(); }; /** * @brief The index of a leaf label * @param s A leaf label * @return The index of the leaf label */ virtual int GetIndexOfLabel (string s); /** * @brief The unique index of a leaf label * @param i A leaf index * @return The ith leaf label * @sa Profile::GetIndexOfLabel */ virtual std::string GetLabelFromIndex (int i) { return LabelIndex[i]; }; /** * @brief Assign a unique integer index to each leaf label in the profile */ virtual void MakeLabelList (); /** * @brief Count the number of trees each leaf label occurs in */ virtual void MakeLabelFreqList (); /** * @brief Read a NEXUS file and store the trees in Profile::trees. * If a TAXA block is * present then the leaf labels are stored in Labels in the same order as in * the TAXA block, otherwise Profile::MakeLabelList is called to assign a unique integer * index to each label. * * @param f input stream in NEXUS format * @return true if sucessful */ //virtual bool ReadNEXUS (istream &f); /** * @brief Read a PHYLIP tree file and store the trees in Profile::trees. * * @param f input stream in PHYLIP format * @return true if sucessful */ virtual bool ReadPHYLIP (istream &f); /** * @brief Read a set of trees from an input stream * At present only PHYLIP and NEXUS formats are supported * @param f input stream * @return true if successful */ virtual bool ReadTrees (istream &f); /** * @brief Output leaf labels. * * @param f output stream */ virtual void ShowLabelList (ostream &f); /** * @brief Output trees as dendrograms. * * @param f output stream */ virtual void ShowTrees (ostream &f); /** * @brief Write a set of trees to an output stream * @param f output stream * @param format file format to use (at present nexus only) * @return true if successful */ virtual bool WriteTrees (ostream &f, const int format = 0, const char *endOfLine = "\n"); protected: /** * The trees * */ vector <T> Trees; /** * The leaf labels stored as a vector so they can be accessed by an index value * */ vector <string> LabelIndex; }; //------------------------------------------------------------------------------ template <class T> int Profile<T>::GetIndexOfLabel (string s) { return Labels[s]; } //------------------------------------------------------------------------------ template <class T> void Profile<T>::MakeLabelList () { for (int i = 0; i < Trees.size(); i++) { T t = Trees[i]; t.MakeNodeList(); for (int j = 0; j < t.GetNumLeaves(); j++) { string s = t[j]->GetLabel(); if (Labels.find (s) == Labels.end ()) { int index = Labels.size(); // cout << "Labels.size() = " << Labels.size(); Labels[s] = index; LabelIndex.push_back (s); // cout << "Labels[s] =" << Labels[s] << endl; } } } /* cout << endl << "Number of labels = " << Labels.size() << endl; LabelMap::iterator it = Labels.begin(); LabelMap::iterator end = Labels.end(); while (it != end) { cout << (*it).first << " - " << (*it).second << endl; it++; }*/ } //------------------------------------------------------------------------------ template <class T> void Profile<T>::ShowLabelList (ostream &f) { f << endl << "Number of labels = " << Labels.size() << endl; LabelMap::iterator it = Labels.begin(); LabelMap::iterator end = Labels.end(); while (it != end) { f << (*it).first << " - " << (*it).second << endl; it++; } f << endl; } //------------------------------------------------------------------------------ template <class T> void Profile<T>::MakeLabelFreqList () { // cout << "MakeLabelListFreq" << endl; for (int i = 0; i < Trees.size(); i++) { T t = Trees[i]; t.MakeNodeList(); for (int j = 0; j < t.GetNumLeaves(); j++) { string s = t[j]->GetLabel(); LabelMap::iterator there = LabelFreq.find (s); if (there == Labels.end ()) { LabelFreq[s] = 1; } else { LabelFreq[s] += 1; } } } /* cout << "Frequency of labels" << endl; LabelMap::iterator it = LabelFreq.begin(); LabelMap::iterator end = LabelFreq.end(); while (it != end) { cout << (*it).first << " - " << (*it).second << endl; it++; }*/ } /** * @class MyNexus * Extends Nexus class to output progress to cout * */ /* class MyNexus : public Nexus { public: MyNexus () : Nexus() { isOK = true; }; #if (USE_VC2 || USE_WXWINDOWS) #if USE_VC2 virtual void EnteringBlock( nxsstring blockName ) { } virtual void ExitingBlock( nxsstring blockName ) { }; virtual void SkippingBlock( nxsstring blockName ) { }; virtual void SkippingDisabledBlock( nxsstring blockName ) { }; virtual void ExecuteStarting() { }; virtual void ExecuteStopping() { }; virtual void OutputComment( nxsstring comment ) {}; virtual void NexusError( nxsstring& msg, streampos pos, long line, long col ) { char buf[256]; sprintf (buf,"%s at line %d, column %d", msg.c_str(), line, col); Message (MSG_ERROR, "Error reading NEXUS file", buf); isOK = false; }; #endif #if USE_WXWINDOWS #if 1 virtual void EnteringBlock( nxsstring blockName ) { } virtual void ExitingBlock( nxsstring blockName ) { }; virtual void SkippingBlock( nxsstring blockName ) { }; virtual void SkippingDisabledBlock( nxsstring blockName ) { }; virtual void ExecuteStarting() { }; virtual void ExecuteStopping() { }; #else // debugging NEXUS reader virtual void EnteringBlock( nxsstring blockName ) { wxLogMessage ("Entering %s block", blockName.c_str()); } virtual void ExitingBlock( nxsstring blockName ) { wxLogMessage ("Exiting %s block", blockName.c_str()); }; virtual void SkippingBlock( nxsstring blockName ) { wxLogWarning ("Skipping %s block", blockName.c_str()); }; virtual void SkippingDisabledBlock( nxsstring blockName ) { wxLogWarning ("Skipping disabled %s block", blockName.c_str()); }; virtual void ExecuteStarting() { wxLogMessage ("Starting to execute NEXUS file"); }; virtual void ExecuteStopping() { wxLogMessage ("Finished executing NEXUS file"); }; #endif virtual void OutputComment( nxsstring comment ) { cout << comment << endl;}; virtual void NexusError( nxsstring& msg, streampos pos, long line, long col ) { wxLogError ("%s at line %d, column %d", msg.c_str(), line, col); isOK = false; }; #endif #else virtual void EnteringBlock( nxsstring blockName ) { cout << " Entering " << blockName << " block..."; }; virtual void ExitingBlock( nxsstring blockName ) { cout << "done" << endl; }; virtual void SkippingBlock( nxsstring blockName ) { cout << " (Skipping " << blockName << " block)" << endl; }; virtual void SkippingDisabledBlock( nxsstring blockName ) { cout << " (Skipping disabled " << blockName << " block)" << endl; }; virtual void ExecuteStarting() { cout << "Starting to execute NEXUS file" << endl; }; virtual void ExecuteStopping() { cout << "Finished executing NEXUS file" << endl; }; virtual void OutputComment( nxsstring comment ) { cout << comment << endl;}; virtual void NexusError( nxsstring& msg, streampos pos, long line, long col ) { cerr << "Error: " << msg << " line " << line << ", col " << col << endl; isOK = false; }; #endif bool GetIsOK () { return isOK; }; protected: bool isOK; }; //------------------------------------------------------------------------------ template <class T> bool Profile<T>::ReadNEXUS (istream &f) { bool result = false; TaxaBlock* taxa; DataBlock *data; CharactersBlock *characters; AssumptionsBlock *assumptions; TreesBlock *trees; taxa = new TaxaBlock(); assumptions = new AssumptionsBlock (*taxa); data = new DataBlock (*taxa, *assumptions); characters = new CharactersBlock (*taxa, *assumptions); trees = new TreesBlock (*taxa); MyNexus nexus; nexus.Add( taxa ); nexus.Add( data ); nexus.Add( characters ); nexus.Add( trees ); // Set to binary to handle Mac and Unix files #ifdef __MWERKS__ #elif __BORLANDC__ f.setf (ios::binary); #elif __GNUC__ #if __GNUC__ < 3 f.setf (ios::binary); #endif #endif NexusToken token (f); try { nexus.Execute (token); } catch (XNexus x) { cout << x.msg << " (line " << x.line << ", column " << x.col << ")" << endl; } if (nexus.GetIsOK() && (trees->GetNumTrees() > 0)) { // Display information about the trees #if (USE_WXWINDOWS || USE_VC2) #else trees->Report (cout); cout << endl; #endif // Store the trees themselves int i = 0; int error = 0; while ((i < trees->GetNumTrees()) && (error == 0)) { T t; std::string tstr; // if (trees->HasTranslationTable()) // tstr = trees->GetTranslatedTreeDescription (i); // else tstr = trees->GetTreeDescription (i); tstr += ";"; error = t.Parse (tstr.c_str()); if (error == 0) { t.SetName (trees->GetTreeName (i)); t.SetRooted (trees->IsRootedTree (i)); t.SetWeight (trees->GetTreeWeight (i)); if (trees->HasTranslationTable()) { t.MakeNodeList(); for (int k = 0; k < t.GetNumLeaves (); k++) { std::string skey = t[k]->GetLabel(); if (skey != "") { nxsstring svalue = trees->GetTranslatedLabel(skey); if (svalue != "") t[k]->SetLabel (svalue); } } } Trees.push_back (t); } else { #if USE_WXWINDOWS wxLogError ( "Error in description of tree %d: %s", (i+1), t.GetErrorMsg().c_str()); #elif USE_VC2 char buf[256]; sprintf (buf, "Reading tree %d: %s", (i+1), t.GetErrorMsg().c_str()); Message (MSG_ERROR, "Error in tree description", buf); #else cerr << "Error in tree description " << (i + 1) << t.GetErrorMsg() << endl; #endif return false; } i++; } // Assign each label a unique index if (taxa->GetNumTaxonLabels() == 0) { // No taxa block in NEXUS file MakeLabelList (); } else { // Store the labels in the same order encountered in the // NEXUS file for (int i = 0; i < taxa->GetNumTaxonLabels (); i++) { Labels[taxa->GetTaxonLabel (i)] = i; LabelIndex.push_back (taxa->GetTaxonLabel (i)); } } result = true; } return result; } */ //------------------------------------------------------------------------------ template <class T> bool Profile<T>::ReadTrees (istream &f) { bool result = false; char ch = (char)f.peek (); // if (ch == '#') // result = ReadNEXUS (f); // else if (strchr ("([", ch)) result = ReadPHYLIP (f); return result; } //------------------------------------------------------------------------------ template <class T> bool Profile<T>::ReadPHYLIP (istream &f) { Tokeniser p (f); PHYLIPReader tr (p); bool ok = true; while (ok) { T t; try { ok = tr.Read (&t); } catch (XTokeniser x) { #if USE_WXWINDOWS wxLogError ("%s at line %d, column %d", x.msg.c_str(), x.line, x.col); #elif USE_VC2 char buf[256]; sprintf (buf, "%s at line %d, column %d", x.msg.c_str(), x.line, x.col); Message (MSG_ERROR, "Error reading tree file", buf); #else cerr << x.msg << " (line " << x.line << ", column " << x.col << ")" << endl; #endif return false; } if (ok) Trees.push_back (t); } bool result = (Trees.size() > 0); if (result) { // Build a list of labels in the profile, such that each label // is assigned a unique index MakeLabelList (); } return result; } //------------------------------------------------------------------------------ template <class T> void Profile<T>::ShowTrees (ostream &f) { cout << "ShowTrees" << endl; for (int i = 0; i < Trees.size(); i++) { T t = Trees[i]; t.Update (); t.Draw (f); } } //------------------------------------------------------------------------------ template <class T> bool Profile<T>::WriteTrees (ostream &f, const int format, const char *endOfLine) { bool result = true; // Simple nexus tree file f << "#nexus" << endOfLine; f << endOfLine; f << "begin trees;"; // Date the file f << " [Treefile written "; time_t timer = time(NULL); struct tm* tblock = localtime(&timer); char time_buf[64]; strncpy (time_buf, asctime(tblock), sizeof (time_buf)); char *q = strrchr (time_buf, '\n'); if (q) *q = '\0'; f << time_buf << "]" << endOfLine; for (int i = 0; i < Trees.size(); i++) { T t = Trees[i]; f << "\ttree "; if (t.GetName() != "") f << NEXUSString (t.GetName()); else f << "tree_" << (i+1); f << " = "; if (t.IsRooted()) f << "[&R] "; else f << "[&U] "; // Tree NewickTreeWriter tw (&t); tw.SetStream (&f); tw.Write(); f << endOfLine; // f << t << endOfLine; } f << "end;" << endOfLine; return true; } #if __BORLANDC__ // Redefine __MINMAX_DEFINED so Windows header files compile #ifndef __MINMAX_DEFINED #define __MINMAX_DEFINED #endif #endif #endif
#include <bits/stdc++.h> using namespace std; #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) #define MAXN 30000 #define INF 0x3f3f3f3f #define DEVIATION 0.00000005 typedef long long LL; struct disjoint { int p[MAXN+10]; void init(){ memset(p,-1,sizeof(p)); } int find(int k){ return p[k]<0 ? k : (p[k]=find(p[k])); } void uni(int a, int b){ a = find(a), b = find(b); p[a] += p[b]; p[b] = a; } bool isGroup(int a, int b){ return find(a) == find(b); } int siz(int k){ return ( -p[find(k)] ); } }D; int main(int argc, char const *argv[]) { int kase; scanf("%d",&kase); int N,M,a,b; while( kase-- ){ scanf("%d %d",&N,&M); D.init(); int ans = 1; for(int i = 0 ; i < M ; i++ ){ scanf("%d %d",&a,&b); if( !D.isGroup(a,b) ) D.uni(a,b); ans = max(ans,D.siz(a)); } printf("%d\n",ans); } return 0; }
/* This file is part of the VRender library. Copyright (C) 2005 Cyril Soler (Cyril.Soler@imag.fr) Version 1.0.0, released on June 27, 2005. http://artis.imag.fr/Members/Cyril.Soler/VRender VRender is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. VRender is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VRender; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */ /**************************************************************************** Copyright (C) 2002-2014 Gilles Debunne. All rights reserved. This file is part of the QGLViewer library version 2.6.3. http://www.libqglviewer.com - contact@libqglviewer.com This file may be used under the terms of the GNU General Public License versions 2.0 or 3.0 as published by the Free Software Foundation and appearing in the LICENSE file included in the packaging of this file. In addition, as a special exception, Gilles Debunne gives you certain additional rights, described in the file GPL_EXCEPTION in this package. libQGLViewer uses dual licensing. Commercial/proprietary software must purchase a libQGLViewer Commercial License. This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. *****************************************************************************/ #include <math.h> #include <assert.h> #include "Primitive.h" #include "Types.h" using namespace vrender ; using namespace std ; Point::Point(const Feedback3DColor& f) : _position_and_color(f) { } const Vector3& Point::vertex(size_t) const { return _position_and_color.pos() ; } const Feedback3DColor& Point::sommet3DColor(size_t) const { return _position_and_color ; } const Feedback3DColor& Segment::sommet3DColor(size_t i) const { return ( (i&1)==0 )?P1:P2 ; } AxisAlignedBox_xyz Point::bbox() const { return AxisAlignedBox_xyz(_position_and_color.pos(),_position_and_color.pos()) ; } const Vector3& Segment::vertex(size_t i) const { return ( (i&1)==0 )?P1.pos():P2.pos() ; } AxisAlignedBox_xyz Segment::bbox() const { AxisAlignedBox_xyz B(P1.pos()); B.include(P2.pos()) ; return B ; } const Feedback3DColor& Polygone::sommet3DColor(size_t i) const { return _vertices[i % nbVertices()] ; } const Vector3& Polygone::vertex(size_t i) const { return _vertices[i % nbVertices()].pos() ; } Polygone::Polygone(const vector<Feedback3DColor>& fc) : _vertices(fc) { initNormal() ; for(size_t i=0;i<fc.size();i++) _bbox.include(fc[i].pos()) ; } AxisAlignedBox_xyz Polygone::bbox() const { return _bbox ; } double Polygone::equation(const Vector3& v) const { return v * _normal - _c ; } void Polygone::initNormal() { FLOAT anglemax = 0.0 ; Vector3 normalmax = Vector3(0.0,0.0,0.0) ; FLOAT v12norm = (vertex(1)-vertex(0)).norm() ; for(size_t i=0;i<nbVertices();i++) { Vector3 v1(vertex(i)) ; Vector3 v2(vertex(i+1)); Vector3 v3(vertex(i+2)) ; Vector3 normal_tmp((v3-v2)^(v1-v2)) ; FLOAT v32norm = (v3-v2).norm() ; if(normal_tmp.z() > 0) normal_tmp *= -1.0 ; if((v32norm > 0.0)&&(v12norm > 0.0)) { double anglemaxtmp = normal_tmp.norm()/v32norm/v12norm ; if(anglemaxtmp > anglemax) { anglemax = anglemaxtmp ; normalmax = normal_tmp ; } } v12norm = v32norm ; if(anglemax > FLAT_POLYGON_EPS) // slight optimization break ; } if(normalmax.infNorm() != 0.0) _normal = NVector3(normalmax) ; anglefactor = anglemax ; _c = _normal*vertex(0) ; } std::ostream& vrender::operator<<(std::ostream& o,const Feedback3DColor& f) { o << "(" << f.pos() << ") + (" << f.red() << "," << f.green() << "," << f.blue() << "," << f.alpha() << ")" << endl ; return o ; }
#include "Boss.h" vector<RECT> Boss::LoadRECT(BossState::StateName state) { vector<RECT> listSourceRect; RECT rect; switch (state) { case BossState::StandHuman: rect.left = 8; rect.top = 9; rect.right = rect.left + 64; rect.bottom = rect.top + 70; listSourceRect.push_back(rect); rect.left = 80; rect.top = 10; rect.right = rect.left + 57; rect.bottom = rect.top + 69; listSourceRect.push_back(rect); rect.left = 144; rect.top = 11; rect.right = rect.left + 55; rect.bottom = rect.top + 68; listSourceRect.push_back(rect); rect.left = 208; rect.top = 12; rect.right = rect.left + 51; rect.bottom = rect.top + 67; listSourceRect.push_back(rect); rect.left = 272; rect.top = 11; rect.right = rect.left + 64; rect.bottom = rect.top + 68; listSourceRect.push_back(rect); break; case BossState::StandSnake: rect.left = 240; rect.top = 104; rect.right = rect.left + 71; rect.bottom = rect.top + 71; listSourceRect.push_back(rect); rect.left = 320; rect.top = 92; rect.right = rect.left + 68; rect.bottom = rect.top + 83; listSourceRect.push_back(rect); rect.left = 400; rect.top = 93; rect.right = rect.left + 68; rect.bottom = rect.top + 82; listSourceRect.push_back(rect); rect.left = 480; rect.top = 94; rect.right = rect.left + 69; rect.bottom = rect.top + 81; listSourceRect.push_back(rect); rect.left = 560; rect.top = 94; rect.right = rect.left + 69; rect.bottom = rect.top + 81; listSourceRect.push_back(rect); rect.left = 644; rect.top = 93; rect.right = rect.left + 63; rect.bottom = rect.top + 83; listSourceRect.push_back(rect); break; case BossState::Magnet: rect.left = 8; rect.top = 9; rect.right = rect.left + 64; rect.bottom = rect.top + 70; listSourceRect.push_back(rect); rect.left = 80; rect.top = 10; rect.right = rect.left + 57; rect.bottom = rect.top + 69; listSourceRect.push_back(rect); rect.left = 144; rect.top = 11; rect.right = rect.left + 55; rect.bottom = rect.top + 68; listSourceRect.push_back(rect); rect.left = 208; rect.top = 12; rect.right = rect.left + 51; rect.bottom = rect.top + 67; listSourceRect.push_back(rect); rect.left = 272; rect.top = 11; rect.right = rect.left + 64; rect.bottom = rect.top + 68; listSourceRect.push_back(rect); rect.left = 344; rect.top = 11; rect.right = rect.left + 82; rect.bottom = rect.top + 68; listSourceRect.push_back(rect); rect.left = 440; rect.top = 11; rect.right = rect.left + 85; rect.bottom = rect.top + 68; listSourceRect.push_back(rect); rect.left = 536; rect.top = 11; rect.right = rect.left + 68; rect.bottom = rect.top + 68; listSourceRect.push_back(rect); break; case BossState::FightingSnake: rect.left = 320; rect.top = 92; rect.right = rect.left + 68; rect.bottom = rect.top + 83; listSourceRect.push_back(rect); rect.left = 400; rect.top = 93; rect.right = rect.left + 68; rect.bottom = rect.top + 82; listSourceRect.push_back(rect); rect.left = 480; rect.top = 94; rect.right = rect.left + 69; rect.bottom = rect.top + 81; listSourceRect.push_back(rect); rect.left = 560; rect.top = 94; rect.right = rect.left + 69; rect.bottom = rect.top + 81; listSourceRect.push_back(rect); rect.left = 644; rect.top = 93; rect.right = rect.left + 63; rect.bottom = rect.top + 83; listSourceRect.push_back(rect); rect.left = 716; rect.top = 95; rect.right = rect.left + 64; rect.bottom = rect.top + 81; listSourceRect.push_back(rect); rect.left = 788; rect.top = 116; rect.right = rect.left + 71; rect.bottom = rect.top + 60; listSourceRect.push_back(rect); rect.left = 8; rect.top = 118; rect.right = rect.left + 70; rect.bottom = rect.top + 57; listSourceRect.push_back(rect); rect.left = 88; rect.top = 112; rect.right = rect.left + 64; rect.bottom = rect.top + 63; listSourceRect.push_back(rect); rect.left = 160; rect.top = 104; rect.right = rect.left + 67; rect.bottom = rect.top + 71; listSourceRect.push_back(rect); rect.left = 240; rect.top = 104; rect.right = rect.left + 71; rect.bottom = rect.top + 71; listSourceRect.push_back(rect); break; case BossState::Die: break; } return listSourceRect; } vector<RECT> Boss::LoadRectFire() { vector<RECT> listSourceRect; RECT rect; rect.left = 14; rect.top = 193; rect.right = rect.left + 24; rect.bottom = rect.top + 46; listSourceRect.push_back(rect); rect.left = 46; rect.top = 187; rect.right = rect.left + 21; rect.bottom = rect.top + 52; listSourceRect.push_back(rect); rect.left = 78; rect.top = 193; rect.right = rect.left + 24; rect.bottom = rect.top + 46; listSourceRect.push_back(rect); rect.left = 110; rect.top = 190; rect.right = rect.left + 27; rect.bottom = rect.top + 49; listSourceRect.push_back(rect); rect.left = 150; rect.top = 194; rect.right = rect.left + 35; rect.bottom = rect.top + 45; listSourceRect.push_back(rect); return listSourceRect; } Boss::Boss(Player* player, D3DXVECTOR3 pos) { SetPosition(pos); mPlayer = player; mAnimationStandHuman = new Animation("Resources/jafar.png", 5, LoadRECT(BossState::StandHuman), (float)1 / 0.15, D3DXVECTOR2(0.5, 1), D3DCOLOR_XRGB(186, 254, 202),Entity::jafar); mAnimationMagnet = new Animation("Resources/jafar.png", 8, LoadRECT(BossState::Magnet), (float)1 / 0.15, D3DXVECTOR2(0.5, 1), D3DCOLOR_XRGB(186, 254, 202), Entity::jafar); mAnimationFightingSnake = new Animation("Resources/jafar.png", 11, LoadRECT(BossState::FightingSnake), (float)1 / 0.25, D3DXVECTOR2(0.5, 1), D3DCOLOR_XRGB(186, 254, 202), Entity::jafar); mAnimationStandSnake = new Animation("Resources/jafar.png", 6, LoadRECT(BossState::StandSnake), (float)1 / 0.15, D3DXVECTOR2(0.5, 1), D3DCOLOR_XRGB(186, 254, 202), Entity::jafar); mAnimationFire1 = new Animation("Resources/jafar.png", 5, LoadRectFire(), (float)1 / 0.15, D3DXVECTOR2(0.5, 1), D3DCOLOR_XRGB(186, 254, 202), Entity::jafar); mAnimationFire2 = new Animation("Resources/jafar.png", 5, LoadRectFire(), (float)1 / 0.15, D3DXVECTOR2(0.5, 1), D3DCOLOR_XRGB(186, 254, 202), Entity::jafar); mAnimationFire3 = new Animation("Resources/jafar.png", 5, LoadRectFire(), (float)1 / 0.15, D3DXVECTOR2(0.5, 1), D3DCOLOR_XRGB(186, 254, 202), Entity::jafar); mAnimationFire1->SetScale(D3DXVECTOR2(1, 1.5)); mAnimationFire2->SetScale(D3DXVECTOR2(1, 1.5)); mAnimationFire3->SetScale(D3DXVECTOR2(1, 1)); mAnimationFire1->SetPosition(GetPosition().x - 30, GetPosition().y); mAnimationFire2->SetPosition(GetPosition().x + 30, GetPosition().y); mAnimationFire3->SetPosition(GetPosition()); RECT rect; rect.left = 198; rect.top = 226; rect.right = rect.left + 27; rect.bottom = rect.top + 13; star1 = new Sprite("Resources/jafar.png", rect, 0, 0, D3DCOLOR_XRGB(186, 254, 202),D3DXVECTOR2(0.5,0.5),GameGlobal::mJafartexture); rect.left = 238; rect.top = 224; rect.right = rect.left + 23; rect.bottom = rect.top + 15; star2 = new Sprite("Resources/jafar.png", rect, 0, 0, D3DCOLOR_XRGB(186, 254, 202), D3DXVECTOR2(0.5, 0.5), GameGlobal::mJafartexture); rect.left = 270; rect.top = 225; rect.right = rect.left + 25; rect.bottom = rect.top + 14; star3 = new Sprite("Resources/jafar.png", rect, 0, 0, D3DCOLOR_XRGB(186, 254, 202), D3DXVECTOR2(0.5, 0.5), GameGlobal::mJafartexture); this->mData = new BossData(); this->mData->boss = this; SetState(new BossSummon(mData)); rect.left = 0; rect.top = 0; rect.right = rect.left + 173; rect.bottom = rect.top + 105; arg = new Sprite("Resources/arg.png", rect, 0, 0, D3DCOLOR_XRGB(255, 0, 255), D3DXVECTOR2(0.5, 0.5)); arg->SetScale(D3DXVECTOR2(0.5, 0.5)); arg->SetPosition(350, 180); rect.left = 0; rect.top = 0; rect.right = 76; rect.bottom = 12; hp_green = new Sprite("Resources/hp_green.png", rect); hp_green->SetPosition(GetPosition().x, GetPosition().y - 120); hp_yellow = new Sprite("Resources/hp_yellow.png", rect); hp_yellow->SetPosition(GetPosition().x, GetPosition().y - 120); hp_red = new Sprite("Resources/hp_red.png", rect); hp_red->SetPosition(GetPosition().x, GetPosition().y - 120); hp_white = new Sprite("Resources/hp_white.png", rect); hp_white->SetPosition(GetPosition().x, GetPosition().y - 120); listAmmo.push_back(new FireAmmo(D3DXVECTOR2(GetPosition().x, GetPosition().y))); listAmmo.push_back(new FireAmmo(D3DXVECTOR2(GetPosition().x, GetPosition().y))); listAmmo.push_back(new FireAmmo(D3DXVECTOR2(GetPosition().x, GetPosition().y))); listMeteor.push_back(new Apple(Entity::Meteor)); lastTimeCreateMeteor = GetTickCount(); } Boss::~Boss() { } void Boss::Update() { if (GetTickCount() - lastTimeCreateMeteor >= 3500 && listMeteor.size() <2) { listMeteor.push_back(new Apple(Entity::Meteor)); lastTimeCreateMeteor = GetTickCount(); } if(mCurrentState==BossState::MeteorSummon || mCurrentState == BossState::StandHuman || mCurrentState == BossState::Magnet) for (int i = 0; i < listMeteor.size(); i++) { if (listMeteor.at(i)->GetCurrentState() == AppleState::NONE) { int left = mPlayer->GetPosition().x - 100; int right = mPlayer->GetPosition().x + 100; int a = rand() % (right-left +1) + left; listMeteor.at(i)->SetPosition(a, 50); listMeteor.at(i)->SetState(AppleState::Flying); } else listMeteor.at(i)->Update(1); } if (mData->boss->mPlayer->GetPosition().x < mData->boss->GetPosition().x) Reverse = true; else if (mData->boss->mPlayer->GetPosition().x > mData->boss->GetPosition().x) Reverse = false; if (BossAttacked) { if ((GetTickCount() - lastTimeBossAttacked) / 1000.0f >= 0.7f) BossAttacked = false; } if (HPCount < 22 && HPCount > 12 && mCurrentState != BossState::StandHuman && mCurrentState != BossState::Magnet) { SetState(new BossMagnetState(mData)); return; } if (HPCount == 12 && mCurrentState != BossState::FightingSnake && mCurrentState != BossState::StandSnake) { SetState(new BossFightingSnake(mData)); return; } if (mCurrentState == BossState::FightingSnake || mCurrentState == BossState::StandSnake) { mAnimationFire1->Update(1); mAnimationFire2->Update(1); mAnimationFire3->Update(1); } mCurrentAnimation->Update(1); if (this->mData->state) { this->mData->state->Update(); } for (int i = 0; i < listAmmo.size(); i++) { listAmmo.at(i)->Update(); } int temp; if (HPCount >= 22 && HPCount <= 30) temp = 30 - HPCount; else if (HPCount > 12 && HPCount <= 21) temp = 21 - HPCount; else if (HPCount >= 2 && HPCount <= 12) temp = 12 - HPCount; else return; RECT rect{ 0,0,(float)(9 - temp)* (76 / 9.0f),12 }; hp_yellow->SetSourceRect(rect); hp_green->SetSourceRect(rect); hp_red->SetSourceRect(rect); } void Boss::DrawStar(D3DXVECTOR2 transform) { //srand(time(NULL)); for (int i = 0; i < starPos.size(); i++) { int a = rand() % 3 + 1; if(a==1) star1->Draw(D3DXVECTOR3(starPos.at(i).x, starPos.at(i).y - a*4, 0), RECT(), D3DXVECTOR2(), transform); if (a == 2) star2->Draw(D3DXVECTOR3(starPos.at(i).x, starPos.at(i).y +a*4, 0), RECT(), D3DXVECTOR2(), transform); if (a == 3) star3->Draw(D3DXVECTOR3(starPos.at(i).x, starPos.at(i).y -a*4, 0), RECT(), D3DXVECTOR2(), transform); } } void Boss::Draw(D3DXVECTOR2 transform) { if (mCurrentState == BossState::FightingSnake || mCurrentState == BossState::StandSnake) { mAnimationFire1->Draw(D3DXVECTOR3(), RECT(), D3DXVECTOR2(), transform); mAnimationFire2->Draw(D3DXVECTOR3(), RECT(), D3DXVECTOR2(), transform); } mCurrentAnimation->GetSprite()->FlipVertical(Reverse); mCurrentAnimation->SetPosition(GetPosition()); mCurrentAnimation->Draw(D3DXVECTOR3(), RECT(), D3DXVECTOR2(), transform); if(mCurrentState==BossState::Magnet && mCurrentAnimation->GetCurrentFrame()==6) DrawStar(transform); if (BossAttacked) arg->Draw(D3DXVECTOR3(), RECT(), D3DXVECTOR2(), transform); if (mCurrentState == BossState::FightingSnake || mCurrentState == BossState::StandSnake) mAnimationFire3->Draw(D3DXVECTOR3(), RECT(), D3DXVECTOR2(), transform); for (int i = 0; i < listAmmo.size(); i++) { listAmmo.at(i)->Draw(transform); } hp_white->Draw(D3DXVECTOR3(), RECT(), D3DXVECTOR2(), transform); if(HPCount >= 22 && HPCount <= 30) hp_green->Draw(D3DXVECTOR3(), RECT(), D3DXVECTOR2(),transform, 0, D3DXVECTOR2(0, 0.5)); else if(HPCount > 12 && HPCount <= 21) hp_yellow->Draw(D3DXVECTOR3(), RECT(), D3DXVECTOR2(), transform, 0, D3DXVECTOR2(0, 0.5)); else if (HPCount >= 1 && HPCount <= 12) hp_red->Draw(D3DXVECTOR3(), RECT(), D3DXVECTOR2(), transform, 0, D3DXVECTOR2(0, 0.5)); if (mCurrentState == BossState::MeteorSummon || mCurrentState == BossState::StandHuman || mCurrentState == BossState::Magnet) for (int i = 0; i < listMeteor.size(); i++) { if (listMeteor.at(i)->GetCurrentState() != AppleState::NONE) listMeteor.at(i)->Draw(D3DXVECTOR3(), RECT(), D3DXVECTOR2(), transform); } } void Boss::OnCollision(Entity *impactor, Entity::CollisionReturn data, Entity::SideCollisions side) { if (impactor->Tag == Entity::AppleThrow) { HPCount--; lastTimeBossAttacked = GetTickCount(); BossAttacked = true; } } void Boss::SetState(BossState *newState) { delete this->mData->state; this->mData->state = newState; this->changeAnimation(newState->GetState()); mCurrentState = newState->GetState(); } void Boss::changeAnimation(BossState::StateName state) { switch (state) { case BossState::MeteorSummon: mCurrentAnimation = mAnimationStandHuman; break; case BossState::None: mCurrentAnimation = nullptr; break; case BossState::StandHuman: mCurrentAnimation = mAnimationStandHuman; break; case BossState::StandSnake: mCurrentAnimation = mAnimationStandSnake; break; case BossState::Magnet: mCurrentAnimation = mAnimationMagnet; break; case BossState::FightingSnake: mCurrentAnimation = mAnimationFightingSnake; break; } this->width = mCurrentAnimation->GetSprite()->GetWidth(); this->height = mCurrentAnimation->GetSprite()->GetHeight(); } Animation* Boss::GetCurrentAnimation() { return mCurrentAnimation; } RECT Boss::GetBound() { RECT rect; rect.left = this->posX - mCurrentAnimation->GetSprite()->GetWidth() / 2; rect.right = rect.left + mCurrentAnimation->GetSprite()->GetWidth(); rect.top = this->posY - mCurrentAnimation->GetSprite()->GetHeight(); //Chú ý đoạn này rect.bottom = this->posY; float cWidth = this->posX; float cHeight = this->posY - mCurrentAnimation->GetSprite()->GetHeight() / 2; SetCenter(D3DXVECTOR2(cWidth, cHeight)); return rect; }
#include "OpCode.hpp" /* #include "Runtime.hpp" #include "DictionaryWord.hpp" #include "CountedString.hpp" #include "StructuredMemory.hpp" #include "Builder.hpp" #include <string> #include <iostream> #include "TermialIO.hpp" int digitValue(int base, char c) { if (c >= '0' && c <= '9') { if (c - '0' < base) { return c - '0'; } else { return -1; } } else if (c >= 'a' && c <= 'z') { if (c - 'a' < base - 10) { return c - 'a' + 10; } else { return -1; } } else { return -1; } } OpCode::OpCode(OpCode::Code codeIn) : code(codeIn) { } OpCode::operator std::string() const { return toString(); } std::string OpCode::toString() const { static const std::string names[] = { "(colon)", "(semicolon)", "(constant)", "(variable)", "abort", ",", "(lit)", "rot", "drop", "dup", "swap", "+", "=", "@", "!", "(0branch)", "(branh)", "execute", "exit", "count", ">number", "accept", "word", "emit", "find", ";", ":", "create", "constant" }; return names[code]; } void OpCode::execute(Runtime* runtime, DictionaryWord* currentWord) { switch (code) { case DoColon: { runtime->pushReturn(runtime->getInstructionPointer()); runtime->setInstructionPointer(&(currentWord->data[0].w)); break; } case DoSemicolon: runtime->setInstructionPointer(runtime->popReturn()); break; case Constant: case DoConstant: runtime->pushData(currentWord->data[0]); break; case DoVariable: runtime->pushData(&currentWord->data[0]); break; case Abort: runtime->abort(); break; case Comma: { Builder(runtime).compileReference(runtime->popData()); break; } case Lit: runtime->pushData(runtime->consumeNextInstruction()); break; case Rot: { long temp = runtime->peekData(2); runtime->pokeData(2, runtime->peekData(1)); runtime->pokeData(1, runtime->peekData(0)); runtime->pokeData(0, temp); break; } case Drop: runtime->popData(); break; case Dup: runtime->pushData(runtime->tos()); break; case Swap: { long temp = runtime->tos(); runtime->pokeData(0, runtime->peekData(1)); runtime->pokeData(1, temp); break; } case Plus: runtime->pushData(runtime->popData().l + runtime->popData().l); break; case Equals: runtime->pushData(runtime->popData().l == runtime->popData().l); break; case At: runtime->pushData(*((Num*)runtime->popData().ptr)); break; case Put: { Num* addr = (Num*)runtime->popData().ptr; *addr = runtime->popData().l; break; } case ZeroBranch: { IPtr destination = (IPtr)runtime->consumeNextInstruction(); if (runtime->popData() == 0) { runtime->setInstructionPointer(destination); } break; } case Branch: runtime->setInstructionPointer((IPtr)runtime->consumeNextInstruction()); break; case Execute: runtime->pushReturn(runtime->getInstructionPointer()); runtime->setInstructionPointer((IPtr)runtime->popData().w); break; case Exit: runtime->setInstructionPointer(runtime->popReturn()); break; case Count: { // ( addr -- addr2 len ) // dup 1 + swap c@ char* addr = runtime->popData(); runtime->pushData(addr + 1); runtime->pushData(*addr); break; } case ToNumber: { //( ud1 c-addr1 u1 -- ud2 c-addr2 u2 ) //>number - ( double addr len -- double2 addr2-zero ) if successful, or // ( double addr len -- long addr2-nonzero ) on error. int len = runtime->popData(); char* addr = runtime->popData(); Num dval = runtime->popData(); int base = runtime->getNumberBase(); bool done = false; while (len > 0 && !done) { int val = digitValue(base, *addr); if (val >= 0) { dval = dval * base + val; len = len - 1; addr = addr + 1; } else { done = true; } } runtime->pushData(dval); runtime->pushData(addr); runtime->pushData(len); break; } case Accept: { //( addr len -- len2 ) int maxLen = runtime->popData(); char* addr = (char*)runtime->popData(); long ndx; do { char c = runtime->read(); for (ndx = 0; ndx < maxLen && c != '\n'; ndx++) { addr[ndx] = c; c = runtime->read(); } } while (ndx == 0); //skip empty lines // if (ndx >= maxLen) { // hey jf - this overflowed the input buffer // do you want to print a message on the // terminal and flush the remaining input? // } runtime->pushData(ndx); break; } case Word: { // ( char -- addr ) char* pad = (char*)runtime->getDictionaryPtr(); char delimeter = runtime->popData(); std::string nameIn = Builder(runtime).getNextInputWord(delimeter); CountedString::fromCString(nameIn, pad, padLength); runtime->pushData(pad); break; } case Emit: // ( char -- ) runtime->emit((char)runtime->popData()); break; case Find: { // addr -- addr2 flag look up word in the dictionary // find looks in the Forth dictionary for a word with the name given in the // counted string at addr. One of the following will be returned: // flag = 0, addr2 = counted string --> word was not found // flag = 1, addr2 = call address --> word is immediate // flag = -1, addr2 = call address --> word is not immediate char* stringAddr = runtime->popData(); DictionaryWord* thisWordAddr = runtime->getLastWordPtr(); bool done = false; while (thisWordAddr != 0 && !done) { char* thisWordNameAddr = thisWordAddr->name; if (CountedString::compare(stringAddr, thisWordNameAddr) != 0) { thisWordAddr = thisWordAddr->previous; } else { done = true; } } if (thisWordAddr != 0) { runtime->pushData(thisWordAddr); runtime->pushData(thisWordAddr->flags & DictionaryWord::IMMEDIATE_MASK); } else { runtime->pushData(stringAddr); runtime->pushData(0L); } break; } case SemiColon: runtime->setInstructionPointer(runtime->popReturn()); break; case Colon: { // compiling word assert(runtime->getCompilerFlags() == 0); // set state to compile runtime->setCompilerFlags(-1); Builder(runtime).createWord(OpCode::Colon); break; } case Create: { // -- create a new word -- Builder(runtime).createWord(OpCode::Colon); break; } default: { break; } } } */
/* Crayfish - A collection of tools for TUFLOW and other hydraulic modelling packages Copyright (C) 2016 Lutra Consulting info at lutraconsulting dot co dot uk Lutra Consulting 23 Chestnut Close Burgess Hill West Sussex RH15 8HN This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "crayfish_colormap.h" #include <QPainter> #include <QPixmap> void ColorMap::dump() const { qDebug("COLOR RAMP: items %d", items.count()); for (int i = 0; i < items.count(); ++i) { qDebug("%d: %f -- %08x", i, items[i].value, items[i].color); } } QRgb ColorMap::valueDiscrete(double v) const { if (items.count() == 0) return qRgba(0,0,0,0); int currentIdx = items.count() / 2; // TODO: keep last used index while (currentIdx >= 0 && currentIdx < items.count()) { // Start searching from the last index - assumtion is that neighboring pixels tend to be similar values const Item& currentItem = items.value(currentIdx); bool valueVeryClose = qAbs(v - currentItem.value) < 0.0000001; if (currentIdx != 0 && v <= items.at(currentIdx-1).value) { currentIdx--; } else if (v <= currentItem.value || valueVeryClose) { if (clipLow && currentIdx == 0 && v < currentItem.value) return qRgba(0,0,0,0); // clipped - transparent return qRgba( qRed(currentItem.color), qGreen(currentItem.color), qBlue(currentItem.color), qAlpha(currentItem.color) * alpha / 255); } else { // Search deeper into the color ramp list currentIdx++; } } if (clipHigh) return qRgba(0,0,0,0); // clipped - transparent const Item& lastItem = items[items.count()-1]; return qRgba( qRed(lastItem.color), qGreen(lastItem.color), qBlue(lastItem.color), qAlpha(lastItem.color) * alpha / 255); } QRgb ColorMap::valueLinear(double v) const { // interpolate int currentIdx = items.count() / 2; // TODO: keep last used index while (currentIdx >= 0 && currentIdx < items.count()) { const Item& currentItem = items[currentIdx]; bool valueVeryClose = qAbs(v - currentItem.value) < 0.0000001; if (currentIdx > 0 && v <= items[currentIdx-1].value) { currentIdx--; } else if (currentIdx > 0 && (v <= currentItem.value || valueVeryClose)) { // we are at the right interval const Item& prevItem = items[currentIdx-1]; double scale = (v - prevItem.value) / (currentItem.value - prevItem.value); int vR = (int)((double) qRed(prevItem.color) + ((double)(qRed(currentItem.color) - qRed(prevItem.color) ) * scale) + 0.5); int vG = (int)((double) qGreen(prevItem.color) + ((double)(qGreen(currentItem.color) - qGreen(prevItem.color)) * scale) + 0.5); int vB = (int)((double) qBlue(prevItem.color) + ((double)(qBlue(currentItem.color) - qBlue(prevItem.color) ) * scale) + 0.5); int vA = (int)((double) qAlpha(prevItem.color) + ((double)(qAlpha(currentItem.color) - qAlpha(prevItem.color)) * scale) + 0.5); return qRgba(vR, vG, vB, vA * alpha / 255); } else if ((currentIdx == 0 && ( ( !clipLow && v <= currentItem.value ) || valueVeryClose ) ) || (currentIdx == items.count()-1 && ( ( !clipHigh && v >= currentItem.value ) || valueVeryClose ) ) ) { // outside of the range return qRgba( qRed(currentItem.color), qGreen(currentItem.color), qBlue(currentItem.color), qAlpha(currentItem.color) * alpha / 255); } else if (v > currentItem.value) { currentIdx++; } else { return qRgba(0,0,0,0); // transparent pixel } } return qRgba(0,0,0,0); // transparent pixel } QRgb ColorMap::value(double v) const { return method == Linear ? valueLinear(v) : valueDiscrete(v); } QPixmap ColorMap::previewPixmap(const QSize& size, double vMin, double vMax) { QPixmap pix(size); pix.fill(Qt::white); QPainter p(&pix); if (items.count() == 0) { p.drawLine(0,0,size.width()-1,size.height()-1); p.drawLine(0,size.height()-1,size.width()-1,0); } else { for (int i = 0; i < size.width(); ++i) { double v = vMin + (vMax-vMin) * i / (size.width()-1); p.setPen(QColor(value(v))); p.drawLine(i,0,i,size.height()-1); } } p.end(); return pix; } ColorMap ColorMap::defaultColorMap(double vMin, double vMax) { ColorMap map; map.items.append(Item(vMin, qRgb(0,0,255))); // blue map.items.append(Item(vMin*0.75+vMax*0.25, qRgb(0,255,255))); // cyan map.items.append(Item(vMin*0.50+vMax*0.50, qRgb(0,255,0))); // green map.items.append(Item(vMin*0.25+vMax*0.75, qRgb(255,255,0))); // yellow map.items.append(Item(vMax, qRgb(255,0,0))); // red return map; }
#ifndef __ModuleKatana_H__ #define __ModuleKatana_H__ #include "Module.h" #include "Animation.h" #include "p2Point.h" #include "ModuleInput.h" //#include "SDL_mixer\include\SDL_mixer.h" struct SDL_Texture; struct Collider; struct Mix_Chunk; enum player_state { SPAWN_PLAYER, IDLE, BACKWARD, GO_BACKWARD, BACK_IDLE, SPIN, DEATH, POST_DEATH }; class ModuleKatana : public Module { public: ModuleKatana(); ~ModuleKatana(); bool Start(); update_status Update(); bool CleanUp(); //void OnCollision(Collider* c1, Collider* c2); private: void CheckState(); void PerformActions(); public: Mix_Chunk* basicsound = nullptr; int aux = 0; int aux1 = 0; int alpha_player = 255; Collider* coll = nullptr; Collider* hitbox = nullptr; SDL_Texture* graphics = nullptr; SDL_Texture* player_death = nullptr; Animation* current_animation = nullptr; Animation idle; Animation backward; Animation intermediate; Animation intermediate_return; Animation spin; Animation spin_circle; Animation death_circle; SDL_Rect death; fPoint position; fPoint aux_spin; fPoint aux_death; bool destroyed = false; bool check_death = false, check_spawn = true; bool fire_rate = false; player_state state = IDLE; bool time = true; bool blink = true; int time_on_entry = 0; int current_time = 0; int blink_on_entry = 0; int blink_time = 0; int fire_rate_timer = 0; float speed; bool input = true; bool spin_pos = false; bool death_pos = false; bool explosion = false; int current_bullet_time = 0; int bullet_on_entry = 0; int power_up = 0; }; #endif
#pragma once #ifndef WIMGUI_MESH_PAINTER_H #define WIMGUI_MESH_PAINTER_H #include <vector> #include <string> #include <fstream> #include <memory> #define GLM_FORCE_RADIANS #pragma warning(push, 0) #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/transform.hpp> #include <glm/mat4x4.hpp> #include <glm/gtc/type_ptr.hpp> #pragma warning(pop) #define IMGUI_DEFINE_MATH_OPERATORS #include "../imgui/imgui.h" #include "../imgui/imgui_internal.h" #include <GL/gl3w.h> #include "../painter3d.h" #include "gl_mesh.h" #include "boat.h" namespace wimgui { typedef std::vector<glm::vec3> vertex_array_type; class mesh_painter: public painter3d { private: GLuint vertex_buffer; GLuint vertex_array; GLuint normal_buffer; mesh_program program; public: mesh_painter() { init_painter(); } GLuint get_vertex_buffer() { return vertex_buffer; } GLuint get_vertex_array() { return vertex_array; } mesh_program* get_program() { return &program; } virtual void clear() override; virtual void gl_paint(view3d& view) override; virtual void draw() override {}; void init_painter(); }; } #endif
/**素数环问题*/ #include <iostream> #include <cstdio> #include <cmath> #include<cstring> using namespace std; int judge[25],ar[25]; int n; /**素数判断*/ int prime(int sum) { if(sum < 2) return 0; for(int i=2; i<=sqrt(sum); i++) { if(sum % i == 0) return 0; } return 1; } void dfs(int p)//第p位置应放什么书 { if(p==n&&prime(ar[p]+ar[1])) { for(int i=1; i<n; i++) { printf("%d ",ar[i]); } printf("%d\n",ar[n]); } if(p==n) return; for(int j=2; j<=n; j++) { if(!judge[j] && prime(ar[p]+j)) { ar[p+1] = j; judge[j] = 1; dfs(p+1); judge[j] = 0; } } } int main() { int s=0; while(~scanf("%d",&n))//-1取反是0,或者scanf("%d",&n)!=EOF,直接写scanf时间超限 { s++; memset(judge,0,sizeof(judge)); judge[1] = 1; ar[1] = 1; printf("Case %d:\n",s); dfs(1); printf("\n"); } return 0; }
#include ".\graphics.h" #include "Variables.h" #include "Camera.h" #include "console.h" #include "SDL_image.h" extern Camera *camera; extern gamevars *vars; extern Console *console; #pragma comment(lib,"sdl.lib") #pragma comment(lib,"sdlmain.lib") #pragma comment(lib,"sdl_image.lib") #pragma comment(lib,"opengl32.lib") PFNGLMULTITEXCOORD2FARBPROC glMultiTexCoord2fARB = NULL; PFNGLACTIVETEXTUREARBPROC glActiveTextureARB = NULL; PFNGLCLIENTACTIVETEXTUREARBPROC glClientActiveTextureARB= NULL; void DrawCube(Vector pos, Vector scale) { glPushMatrix(); glTranslatef(pos.x,pos.y,pos.z); glScalef(scale.x/2,scale.y/2,scale.z/2); glBegin(GL_QUADS); // top glTexCoord2f(1.0f,1.0f); glVertex3f( 1.0f, 1.0f,-1.0f); glTexCoord2f(0.0f,1.0f); glVertex3f(-1.0f, 1.0f,-1.0f); glTexCoord2f(0.0f,0.0f); glVertex3f(-1.0f, 1.0f, 1.0f); glTexCoord2f(1.0f,0.0f); glVertex3f( 1.0f, 1.0f, 1.0f); // bottom glTexCoord2f(1.0f,1.0f); glVertex3f( 1.0f,-1.0f, 1.0f); glTexCoord2f(0.0f,1.0f); glVertex3f(-1.0f,-1.0f, 1.0f); glTexCoord2f(0.0f,0.0f); glVertex3f(-1.0f,-1.0f,-1.0f); glTexCoord2f(1.0f,0.0f); glVertex3f( 1.0f,-1.0f,-1.0f); // back glTexCoord2f(0.0f,0.0f); glVertex3f( 1.0f, 1.0f, 1.0f); glTexCoord2f(1.0f,0.0f); glVertex3f(-1.0f, 1.0f, 1.0f); glTexCoord2f(1.0f,1.0f); glVertex3f(-1.0f,-1.0f, 1.0f); glTexCoord2f(0.0f,1.0f); glVertex3f( 1.0f,-1.0f, 1.0f); // front glTexCoord2f(1.0f,1.0f); glVertex3f( 1.0f,-1.0f,-1.0f); glTexCoord2f(0.0f,1.0f); glVertex3f(-1.0f,-1.0f,-1.0f); glTexCoord2f(0.0f,0.0f); glVertex3f(-1.0f, 1.0f,-1.0f); glTexCoord2f(1.0f,0.0f); glVertex3f( 1.0f, 1.0f,-1.0f); // left glTexCoord2f(0.0f,0.0f); glVertex3f(-1.0f, 1.0f, 1.0f); glTexCoord2f(1.0f,0.0f); glVertex3f(-1.0f, 1.0f,-1.0f); glTexCoord2f(1.0f,1.0f); glVertex3f(-1.0f,-1.0f,-1.0f); glTexCoord2f(0.0f,1.0f); glVertex3f(-1.0f,-1.0f, 1.0f); //right glTexCoord2f(0.0f,0.0f); glVertex3f( 1.0f, 1.0f,-1.0f); glTexCoord2f(1.0f,0.0f); glVertex3f( 1.0f, 1.0f, 1.0f); glTexCoord2f(1.0f,1.0f); glVertex3f( 1.0f,-1.0f, 1.0f); glTexCoord2f(0.0f,1.0f); glVertex3f( 1.0f,-1.0f,-1.0f); glEnd(); glPopMatrix(); } void DrawQuad(Vector pos, Vector scale) { glPushMatrix(); glTranslatef(pos.x,pos.y,pos.z); glScalef(scale.x/2,scale.y/2,scale.z/2); glBegin(GL_QUADS); // top glTexCoord2f(1.0f,1.0f); glVertex3f( 1.0f, 1.0f,-1.0f); glTexCoord2f(0.0f,1.0f); glVertex3f(-1.0f, 1.0f,-1.0f); glTexCoord2f(0.0f,0.0f); glVertex3f(-1.0f, 1.0f, 1.0f); glTexCoord2f(1.0f,0.0f); glVertex3f( 1.0f, 1.0f, 1.0f); glEnd(); glPopMatrix(); } int skybox; void DrawSkybox() { glPushMatrix(); glLoadIdentity(); glScalef(10,10,10); glRotatef(camera->GetRotation().x,1,0,0); glRotatef(camera->GetRotation().y,0,1,0); glRotatef(camera->GetRotation().z,0,0,1); glDisable(GL_BLEND); glDisable(GL_DEPTH_TEST); glDepthMask(0); glBindTexture(GL_TEXTURE_2D,skybox); glColor4f(1,1,1,1); glBegin(GL_QUADS); // top glTexCoord2f(0.249f,0.249f); glVertex3f( 1.0f, 1.0f,-1.0f); glTexCoord2f(0.001f,0.249f); glVertex3f(-1.0f, 1.0f,-1.0f); glTexCoord2f(0.001f,0.001f); glVertex3f(-1.0f, 1.0f, 1.0f); glTexCoord2f(0.249f,0.001f); glVertex3f( 1.0f, 1.0f, 1.0f); // bottom glTexCoord2f(0.249f,0.749f); glVertex3f( 1.0f,-1.0f, 1.0f); glTexCoord2f(0.001f,0.749f); glVertex3f(-1.0f,-1.0f, 1.0f); glTexCoord2f(0.001f,0.501f); glVertex3f(-1.0f,-1.0f,-1.0f); glTexCoord2f(0.249f,0.501f); glVertex3f( 1.0f,-1.0f,-1.0f); // back glTexCoord2f(0.501f,0.251f); glVertex3f( 1.0f, 1.0f, 1.0f); glTexCoord2f(0.749f,0.251f); glVertex3f(-1.0f, 1.0f, 1.0f); glTexCoord2f(0.749f,0.499f); glVertex3f(-1.0f,-1.0f, 1.0f); glTexCoord2f(0.501f,0.499f); glVertex3f( 1.0f,-1.0f, 1.0f); // front glTexCoord2f(0.249f,0.499f); glVertex3f( 1.0f,-1.0f,-1.0f); glTexCoord2f(0.001f,0.499f); glVertex3f(-1.0f,-1.0f,-1.0f); glTexCoord2f(0.001f,0.251f); glVertex3f(-1.0f, 1.0f,-1.0f); glTexCoord2f(0.249f,0.251f); glVertex3f( 1.0f, 1.0f,-1.0f); // left glTexCoord2f(0.751f,0.251f); glVertex3f(-1.0f, 1.0f, 1.0f); glTexCoord2f(0.999f,0.251f); glVertex3f(-1.0f, 1.0f,-1.0f); glTexCoord2f(0.999f,0.499f); glVertex3f(-1.0f,-1.0f,-1.0f); glTexCoord2f(0.751f,0.499f); glVertex3f(-1.0f,-1.0f, 1.0f); //right glTexCoord2f(0.251f,0.251f); glVertex3f( 1.0f, 1.0f,-1.0f); glTexCoord2f(0.499f,0.251f); glVertex3f( 1.0f, 1.0f, 1.0f); glTexCoord2f(0.499f,0.499f); glVertex3f( 1.0f,-1.0f, 1.0f); glTexCoord2f(0.251f,0.499f); glVertex3f( 1.0f,-1.0f,-1.0f); glEnd(); glDepthMask(1); glEnable(GL_DEPTH_TEST); glPopMatrix(); } /* void setShaders() { char *vs,*fs; v = glCreateShader(GL_VERTEX_SHADER); vs = textFileRead("toon.vert"); const char * vv = vs; glShaderSource(v, 1, &vv,NULL); free(vs); glCompileShader(v); f = glCreateShader(GL_FRAGMENT_SHADER); fs = textFileRead("toon.frag"); const char * ff = fs; glShaderSource(f, 1, &ff,NULL); free(fs); glCompileShader(f); p = glCreateProgram(); glAttachShader(p,v); glAttachShader(p,f); glLinkProgram(p); glUseProgram(p); } */ Graphics::Graphics(void) { } Graphics::~Graphics(void) { } #define GL_FOG_COORDINATE_SOURCE_EXT 0x8450 #define GL_FOG_COORDINATE_EXT 0x8451 typedef void (APIENTRY * PFNGLFOGCOORDFEXTPROC) (GLfloat coord); PFNGLFOGCOORDFEXTPROC glFogCoordfEXT = NULL; bool Graphics::init() { SDL_Init(SDL_INIT_EVERYTHING); SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 ); /* Fetch the video info */ const SDL_VideoInfo *videoInfo = SDL_GetVideoInfo( ); if ( !videoInfo ) { fprintf( stderr, "Video query failed: %s\n", SDL_GetError( ) ); return false; } int videoFlags = SDL_OPENGL | SDL_GL_DOUBLEBUFFER | SDL_HWPALETTE | SDL_RESIZABLE; if (vars->getIntValue("screen_fullscreen") == 1) { videoFlags |= SDL_FULLSCREEN; } videoFlags |= ( videoInfo->hw_available )?SDL_HWSURFACE:SDL_SWSURFACE; if ( videoInfo->blit_hw ) videoFlags |= SDL_HWACCEL; SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); /* Verify there is a surface */ if (!SDL_SetVideoMode(vars->getIntValue("screen_width"), vars->getIntValue("screen_height"), 24, videoFlags)) { fprintf( stderr, "Video mode set failed: %s\n", SDL_GetError( ) ); return false; } SDL_WM_SetCaption("MOTORS Engine", NULL ); glClearColor(0.8f,0.8f,0.8f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); glShadeModel(GL_SMOOTH); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glClearDepth(9999.0f); glEnable(GL_TEXTURE_2D); glMultiTexCoord2fARB = (PFNGLMULTITEXCOORD2FARBPROC) wglGetProcAddress("glMultiTexCoord2fARB"); glActiveTextureARB = (PFNGLACTIVETEXTUREARBPROC) wglGetProcAddress("glActiveTextureARB"); glClientActiveTextureARB= (PFNGLCLIENTACTIVETEXTUREARBPROC) wglGetProcAddress("glClientActiveTextureARB"); glFogCoordfEXT = (PFNGLFOGCOORDFEXTPROC) wglGetProcAddress("glFogCoordfEXT"); GLfloat fogColor[4]= {0.8f, 0.8f, 0.8f, 1}; glFogi(GL_FOG_MODE, GL_EXP2); // Fog Mode glFogfv(GL_FOG_COLOR, fogColor); // Set Fog Color glFogf(GL_FOG_DENSITY, 0.005f); // How Dense Will The Fog Be glHint(GL_FOG_HINT, GL_NICEST); // Fog Hint Value glFogf(GL_FOG_START, 200.0f); // Fog Start Depth glFogf(GL_FOG_END, 300.0f); // Fog End Depth glEnable(GL_FOG); // SDL_ShowCursor(0); // SDL_WM_GrabInput(SDL_GRAB_ON); text.init(); skybox = LoadTexture("data/topographical/skybox.JPG"); console->Printf("Finished renderer initialization"); return true; } void Graphics::pause() { } bool Graphics::stop() { SDL_Quit(); console->Printf("Renderer shutdown complete"); return true; } void Graphics::run() { SDL_GL_SwapBuffers(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); DrawSkybox(); glLoadIdentity(); // glScalef(0.001f,0.001f,0.001f); } int Graphics::LoadTexture(const char *filename) { GLuint texture; SDL_Surface* imageFile = IMG_Load(filename); if (!imageFile) { console->Printf("IMG_Load(%s) failed. reason: %s", filename,IMG_GetError()); return -1; } glPixelStorei(GL_UNPACK_ALIGNMENT,4); glGenTextures(1,&texture); glBindTexture(GL_TEXTURE_2D,texture); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER, GL_LINEAR); gluBuild2DMipmaps(GL_TEXTURE_2D,3,imageFile->w, imageFile->h, GL_RGB, GL_UNSIGNED_BYTE,imageFile->pixels); SDL_FreeSurface(imageFile); return (int)texture; }
#pragma once #include "../../framework.h" #include "../gl_command.h" namespace glmock { // // http://www.opengl.org/sdk/docs/man3/xhtml/glDeleteTextures.xml class GLGetError : public IReturns<GLenum>, public GLCommand { public: GLGetError(); virtual ~GLGetError(); public: virtual void Returns(GLenum returns); public: // GLenum Eval(); private: GLenum mReturns; }; }
#include <thread> #include <vector> #include <iostream> #include "common/thread/thread_instance.h" #include "common/thread/thread.h" #include "common/thread/lock.h" #include "common/thread/lock_guard.h" #include <gtest/gtest.h> namespace common { class A { public: int64_t a_; }; MutexLock m; std::vector<std::shared_ptr<A> > as; void* GetInstance(void* arg) { ThreadInstance<A>::instance()->a_ = Threading::GetTid(); { LockGuard<MutexLock> guard(&m); as.push_back(ThreadInstance<A>::instance()); } return nullptr; } TEST(ThreadInstanceTest, InstanceTest) { ThreadInstance<A>::instance()->a_ = Threading::GetTid(); const size_t thread_num = 3; for (size_t i = 0; i < thread_num; i++) { pthread_t tid = 0; pthread_create(&tid, nullptr, GetInstance, nullptr); } sleep(1); EXPECT_EQ(Threading::GetTid(), ThreadInstance<A>::instance()->a_); EXPECT_EQ(thread_num + 1, ThreadInstance<A>::instances().size()); for (auto& tid: as) { EXPECT_TRUE(ThreadInstance<A>::instances().count(tid) > 0); std::cout << tid->a_ << std::endl; } for (auto& a: ThreadInstance<A>::instances()) { std::cout << a->a_ << std::endl; } } class B { public: int32_t b_; }; TEST(ThreadInstanceTest, SetInstanceTest) { std::shared_ptr<B> inst = std::make_shared<B>(); EXPECT_TRUE(ThreadInstance<B>::set_instance(inst)); EXPECT_EQ(inst.get(), ThreadInstance<B>::instance().get()); EXPECT_FALSE(ThreadInstance<B>::set_instance(inst)); } }
#ifndef Q53_H #define Q53_H #include<iostream> #include<stdlib.h> #include<stack> #include<queue> #include<stdio.h> #include<string.h> using namespace std; /* 5.3-综合题02:设计一个算法,判断一个无向图是否为一颗树 */ #define INF_MAX 999999 const int vexNum = 9; bool visits[vexNum]; typedef struct ENode { int adjvex; // 邻接顶点 int weight; struct ENode *next; } ENode; typedef struct VNode { int in; int data; ENode *firstEdge; } VNode, ADJList[vexNum]; typedef struct { int vertexNum, edgeNum; // 顶点数 char vexs[vexNum]; ADJList adjList; } graphQ53, *GraphQ53; int FirstNeighbor(graphQ53 &G, int v); void DFS(graphQ53 &G, int v, int &VNum, int &ENum, bool visited[vexNum]); bool isTree(graphQ53 g); // bug void hw02(); /* 5.3-综合题03:邻接表:深度优先搜索非递归 */ #define MAX03 9 #define INF03 99999 typedef struct ENode03 { int adjvex = -1; int weight = -1; struct ENode03 *next = nullptr; } ENode03; typedef struct VNode03 { int vex = -1; int in = 0; ENode03 *firstEdge = nullptr; } VNode03, AdjList03[MAX03]; typedef struct { AdjList03 adjList; int vexNum; int edgeNum; int visited[MAX03]; } Graph03; // void CreateGraph03(Graph03 *g); Graph03* CreateGraph03(); void DFS03(Graph03 *g, int vexId); void hw03(); /* 5.3-综合题04:邻接表(有向图):分别用深度优先和广度优先判断是否右 Vi 到 Vj 的路径 (i != j) */ #define MAX04 9 #define INF04 99999 typedef struct ENode04 { int adjvex = -1; int weight = -1; struct ENode04 *next = nullptr; } ENode04; typedef struct VNode04 { int vex = -1; int in = 0, out = 0; ENode04 *firstEdge = nullptr; } VNode04, AdjList04[MAX04]; typedef struct { AdjList04 adjList; int vexNum; int edgeNum; int visited[MAX04]; } Graph04; Graph04* CreateGraph04(); bool findPathByBFS(Graph04 *g, int &vexIdStart, int &vexIdEnd); bool findPathByDFS(Graph04 *g, int &vexIdStart, int &vexIdEnd); void hw04(); #endif
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- // // Copyright (C) 2003-2007 Opera Software AS. All rights reserved. // // This file is part of the Opera web browser. It may not be distributed // under any circumstances. // // // #ifndef WINDOWS_LAUNCH_PI_H #define WINDOWS_LAUNCH_PI_H #include "adjunct/desktop_pi/launch_pi.h" class WindowsLaunchPI : public LaunchPI { public: WindowsLaunchPI(); virtual ~WindowsLaunchPI() {} static LaunchPI* Create(); /* * Executes a program with the given parameters * * @param exe_name Full path of file to read in UTF16 * @param cmd_line Command line to pass to the application UTF8 * * @return BOOL, TRUE if it succeded */ virtual BOOL Launch(const uni_char *exe_name, int argc, const char* const* argv); /* * Executes a program with the given parameters. Function is synchronous. * * @param exe_name Full path of file to read in UTF16 * @param cmd_line Command line to pass to the application UTF8 * * @return BOOL, TRUE if program succeeded with return code as 0 */ BOOL LaunchAndWait(const uni_char *exe_name, int argc, const char* const* argv); /** * Verify signature of executable */ virtual BOOL VerifyExecutable(const uni_char *executable, const uni_char* vendor_name = NULL); /* * For an argument passed (from the argv array given to Launch), * quote it if it contains a space * and escapes all " characters * * @param arg Argument to escape and test * * @return char*, Pointer to a string containing the escaped argument */ char* EscapeAndQuoteArg(const char* arg); /* * For a list of arguments passed, builds the corresponding command line * with the help of EscapeAndQuoteArg */ uni_char* ArgCat(int argc, const char* const* argv); }; #endif // WINDOWS_LAUNCH_PI_H
#pragma once #include "bricks/core/autopointer.h" #include "bricks/audio/miditypes.h" namespace Bricks { namespace IO { class Stream; class StreamReader; } } namespace Bricks { template<typename T> class ReturnPointer; } namespace Bricks { namespace Audio { class MidiReader : public Object { protected: AutoPointer<IO::StreamReader> reader; MidiType::Enum midiType; AutoPointer<MidiTimeDivision> division; u16 trackCount; u16 trackIndex; u32 trackSize; u64 trackPosition; u8 previousIdentifier; static const u32 MagicHeader1 = 0x4D546864; static const u32 MagicHeader2 = 0x00000006; static const u32 MagicTrackHeader = 0x4D54726B; void ReadTrack(); public: MidiReader(IO::Stream* stream); ~MidiReader(); bool EndOfFile() const; bool EndOfTrack() const; void NextTrack(); void SeekTrack(u32 index); ReturnPointer<IO::Stream> GetTrackStream(); ReturnPointer<MidiEvent> ReadEvent(); MidiTimeDivision* GetDivision() const { return division; } MidiType::Enum GetMidiType() const { return midiType; } u16 GetTrackCount() const { return trackCount; } u16 GetCurrentTrack() const { return trackIndex; } }; } }
#include <iostream> #include <string> #include "CarInsoles.hpp" #pragma warning (disable:4996) CarInsoles::CarInsoles(): material(materials::carpets) { this->product_name = product::carInsoles; } CarInsoles::CarInsoles(const std::string& mark, const double& price, const unsigned int& count, const materials& material): Product(mark, price, count) { this->material = material; this->product_name = product::carInsoles; } void CarInsoles::set_material(const CarInsoles::materials& material) { this->material = material; } CarInsoles::materials CarInsoles::get_material()const { return this->material; } product CarInsoles::get_product_name()const { return product::carInsoles; } void CarInsoles::print()const { Product::print(); std::cout << "Material: "; switch (CarInsoles::get_material()) { case 0: std::cout << "Carpets" << '\n'; break; case 1: std::cout << "Rubber" << '\n'; break; default: break; } }
#include "rectangle.h" #include <iostream> #include <stdexcept> using namespace std; Rectangle::Rectangle(float new_height, float new_width) : Shape("Rectangle", "Red"){ width = new_width; height = new_height; if(area() == 0){ throw domain_error("Invalid constructor argument"); } } float Rectangle::area(){ return width * height; } void Rectangle::print_shape_info(){ cout << endl << "Testing rectangle object attributes." << endl; cout << endl << "\tExpected: \tActual:" << endl; cout << "\tName: Rectangle\tName: " << get_name() << endl; cout << "\tColour: Red \tColour: " << get_colour() << endl; cout << "\tHeigth: 2 \tHeigth: " << get_height() << endl; cout << "\tWidth: 3 \tWidth: " << get_width() << endl; cout << "\tArea: 6 \tArea: " << area() << endl; } float Rectangle::get_width(){ return width; } float Rectangle::get_height(){ return height; } void Rectangle::set_width(float new_width){ width = new_width; } void Rectangle::set_height(float new_height){ height = new_height; } bool Rectangle::operator>(Rectangle & r2){ return area() > r2.area(); } bool Rectangle::operator<(Rectangle & r2){ return area() < r2.area(); }
#pragma once #include "ParallelPrimeFinder.h" class SieveParAlternative2 : public ParallelPrimeFinder { // Inherited via ParallelPrimeFinder virtual std::string name() override; virtual int* find(int min, int max, int* size) override; };
/* playing_screen.hpp Purpose: Handle all the logic of the main gameplay (e.g. collisions, enemies, items, etc). @author Jeremy Elkayam */ #pragma once #include <memory> #include <iostream> #include <list> #include <random> #include <chrono> #include <algorithm> #include <stdexcept> #include "player.hpp" #include "enemy.hpp" #include "potion.hpp" #include "screen.hpp" #include "end_screen.hpp" #include "playing_screen.hpp" #include "resource_manager.hpp" #include "hud.hpp" #include "bomb.hpp" using std::cout; using std::endl; using std::list; using std::shared_ptr; using std::mt19937; using std::uniform_real_distribution; using std::min; using std::logic_error; class PlayingScreen : public Screen { private: const game_options opts; const vector<sf::Color> explosion_colors { sf::Color::White, sf::Color::Yellow, sf::Color::White, sf::Color::Cyan, sf::Color::White, sf::Color::Red, sf::Color::White, sf::Color::Green }; //that's all the speccy colors. so if we want to do more, we'll have to //repeat colors. Dim colors can help. const vector<sf::Color> player_colors { sf::Color::Cyan, sf::Color::Magenta, sf::Color::Yellow, sf::Color::Green, sf::Color::Blue, sf::Color::White, sf::Color::Red, sf::Color::Cyan }; vector<postmortem_info> dead_players_info; sf::Sprite background, foreground; sf::Sound kill_sound,start_sound; sf::RectangleShape field_fill; HUD hud; list<Player> players; list<Enemy> enemies; //A list of the potions. //Currently we only have one potion on the game board at a time. //But if I add multiplayer or something, it might be nice to put out a few potions at once. list<Potion> potions; SpecialItem ring; Bomb bomb; const float base_speed, color_change_interval; const unsigned int base_heal, base_dmg; float time_since_last_enemy_spawn,time_since_last_potion_spawn,total_time_elapsed, last_color_change; unsigned long color_change_index; /* * Generate a random location that is within the confines of the game board and is * also at least threshold units away from the player. * * @param threshold the minimum number of units away that the coordinates can be generated. */ sf::Vector2f random_distant_location(float threshold); float spawn_interval(float min, float max, float time_limit, bool countingUp); bool can_spawn_enemy(); void spawn_enemies(); /* * Update every enemy stored in the class, including movement, hit detection, and * steering. * * @param s_elapsed The time in seconds elapsed since the last loop. */ void update_enemies(float s_elapsed); bool can_spawn_potion(); void spawn_potion(); /* * Update every potion stored in the class, including despawning if necessary. * * @param s_elapsed The time in seconds elapsed since the last loop. */ void update_potions(float s_elapsed); mt19937 randy; const float field_width,field_height; uniform_real_distribution<float>width_dist,height_dist,time_dist; void draw_gameplay(sf::RenderWindow &window, ColorGrid &color_grid); void explode(); void spawn_if_able(SpecialItem &item); public: /* Constructor for the PlayingScreen class. Sets up the initial values for PlayingScreen. */ PlayingScreen(TextLoader &a_text_loader, ResourceManager &a_resource_manager, InputManager &an_input_manager, game_options game_opts); void update(float s_elapsed) override; void set_player_sword(bool active){players.front().set_sword(active);} bool go_to_next() override {return players.empty();} void draw(sf::RenderWindow &window, ColorGrid &color_grid) override; unique_ptr<Screen> next_screen() override; };
#include <maya/MGlobal.h> #include <maya/MPxCommand.h> #include <maya/MFnPlugin.h> #include <maya/MString.h> #include <maya/MArgList.h> #include <maya/MObject.h> #include "third_class.h" #define __VENDOR "kingmax_res@163.com | 184327932@qq.com | iJasonLee@WeChat" #define __VERSION "2018.07.25.01" namespace NeoBards { class FirstClass : public MPxCommand { public: FirstClass(); ~FirstClass(); MStatus doIt(const MArgList&); static void* creator(); private: }; FirstClass::FirstClass() { MGlobal::displayInfo("constructor"); } FirstClass::~FirstClass() { MGlobal::displayInfo("deConstructor"); } MStatus FirstClass::doIt(const MArgList &) { MGlobal::displayInfo("doIt"); return MStatus(); } void * FirstClass::creator() { return new FirstClass(); } ////////////////////////////////////////////////////////////////////////// class SecondClass : public MPxCommand { public: SecondClass() {}; ~SecondClass() {}; MStatus doIt(const MArgList& args); static void* creator(); protected: private: }; MStatus SecondClass::doIt(const MArgList& args) { MGlobal::displayInfo("second class doIt"); return MS::kSuccess; } void* SecondClass::creator() { return new SecondClass(); } ////////////////////////////////////////////////////////////////////////// } MStatus NeoBards::ThirdClass::doIt(const MArgList& args) { MGlobal::displayInfo("third class doIt"); return MS::kSuccess; } void* NeoBards::ThirdClass::creator() { return new ThirdClass(); } MStatus initializePlugin(MObject obj) { MFnPlugin plugin(obj, __VENDOR, __VERSION); MStatus status; status = plugin.registerCommand("mCmd1", NeoBards::FirstClass::creator); if (!status) { status.perror("register mCmd1 failed"); } status = plugin.registerCommand("mCmd2", NeoBards::SecondClass::creator); if (!status) { status.perror("register mCmd2 failed"); } status = plugin.registerCommand("mCmd3", NeoBards::ThirdClass::creator); if (!status) { status.perror("register mCmd3 failed"); } return MS::kSuccess; } MStatus uninitializePlugin(MObject obj) { MFnPlugin plugin(obj, __VENDOR, __VERSION); MStatus status; plugin.deregisterCommand("mCmd1"); plugin.deregisterCommand("mCmd2"); status = plugin.deregisterCommand("mCmd3"); if (!status) { status.perror("deregister mCmd3 failed"); } return MS::kSuccess; }
/* * Copyright (C) 20182-2021 David C. Harrison. All right reserved. * * You may not use, distribute, publish, or modify this code without * the express written permission of the copyright holder. */ // Citation: // String Sort Method: https://www.geeksforgeeks.org/sort-an-array-of-strings-lexicographically-based-on-prefix/ // Compare() : https://stackoverflow.com/questions/19588809/sort-array-of-integers-lexicographically-c // Threads: https://stackoverflow.com/questions/54551371/creating-thread-inside-a-for-loop-c #include <iostream> #include <string> #include <thread> #include <bits/stdc++.h> #include "radix.h" using namespace std; bool Compare(string a, string b) { unsigned int i = 0, j = 0; while(i < a.size() && j < b.size()) { if(a[i] - '0' != b[j] - '0') return (a[i] - '0' < b[j] - '0'); i++, j++; } return (a.size() < b.size()); } // Lexicographically sort the unsigned ints in list vector void LexNumbers(vector<unsigned int> &list) { vector<string> strList; vector<unsigned int> sorted; // Convert to string for (unsigned int i = 0; i < list.size(); i++) { strList.emplace_back(to_string(list.at(i))); } sort(strList.begin(), strList.end(), Compare); for (unsigned int i = 0; i < list.size(); i++) { sorted.emplace_back(stoull(strList.at(i))); } list = sorted; } void joinThreads(std::vector<std::thread> &Threads) { for(auto& t: Threads) { // Sync threads t.join(); } } void RadixSort::msd(vector<reference_wrapper<vector<unsigned int>>> &lists, const unsigned int cores) { std::vector<std::thread> Threads; for (std::vector<unsigned int> &list : lists) { Threads.emplace_back([&](){ LexNumbers(list); }); if (Threads.size() == lists.size()) { break; } if (Threads.size() == cores) { joinThreads(Threads); Threads.clear(); } } joinThreads(Threads); }
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); public: void setupConnects(); public slots: void handlePrevButtonClicked(); void handlePlayButtonClicked(); void handleNextButtonClicked(); void handleProgressSliderMoved(int pos); void handleVolumeDialMoved(int pos); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
/** * @author: aaditkamat * @date: 31/12/2018 */ #include <string> #include <iostream> #include <algorithm> using namespace std; int ind(char m, char n) { return m == n ? 0 : 1; } int dist(string first, string second) { int firstLength = first.length(), secondLength = second.length(); int m[firstLength + 1][secondLength + 1]; for (int i = 1; i <= firstLength; i++) { m[i][0] = i; } for (int i = 0; i <= secondLength; i++) { m[0][i] = i; } for (int i = 1; i <= firstLength; i++) { for (int j = 1; j <= secondLength; j++) { int values[] = { m[i - 1][j] + 1, m[i][j - 1] + 1, m[i - 1][j - 1] + ind(first[i - 1], second[j - 1])}; m[i][j] = *min_element(begin(values), end(values)); } } return m[firstLength][secondLength]; } int main() { string first, second; cout << "Enter two strings: " << endl; getline(cin, first); getline(cin, second); cout << "The Levenshtein distance between \"" << first << "\" and \"" << second << "\" is: " << dist(first, second) << endl; }
#pragma once /* =========================================================================== Copyright (C) 2017 waYne (CAM) =========================================================================== */ #pragma once #ifndef ELYSIUM_CORE_MATH_NUMERICS_QUATERNIONDOUBLE #define ELYSIUM_CORE_MATH_NUMERICS_QUATERNIONDOUBLE #ifndef ELYSIUM_CORE_EXPORT #include "../../../Core/01-Shared/Elysium.Core/Export.hpp" #endif #ifndef ELYSIUM_CORE_MATH_NUMERICS_QUATERNIONTEMPLATE #include "QuaternionTemplate.hpp" #endif namespace Elysium { namespace Core { namespace Math { namespace Numerics { class EXPORT QuaternionDouble : public QuaternionTemplate<double> { public: // constructors & destructor QuaternionDouble(double ValueX, double ValueY, double ValueZ, double ValueW); ~QuaternionDouble(); // static constructors static QuaternionDouble Identity(); }; } } } } #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2012 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * @author Cihat Imamoglu (cihati) */ #ifndef QUICK_BUTTON_STRIP_H #define QUICK_BUTTON_STRIP_H #include "adjunct/quick_toolkit/widgets/QuickWidget.h" #include "modules/widgets/OpWidget.h" class QuickStackLayout; /** @brief Represents the group of buttons that normally appear at the bottom of a dialog * A button strip consists of two content areas - a primary group, where buttons that * close the dialog are usually displayed (OK, Cancel, etc) and a secondary group * where other controls that refer to the whole dialog can be placed */ class QuickButtonStrip : public QuickWidget { IMPLEMENT_TYPEDOBJECT(QuickWidget); public: enum Order { SYSTEM, ///< order of widgets in primary group decided by system we're running on NORMAL, ///< widgets in primary group are displayed in the order they were inserted REVERSE ///< widgets in primary group are displayed in reverse order }; /** Constructor * @param order Order of widgets in the primary group, use this to reverse buttons * where necessary (eg. Mac, sometimes Unix GTK) */ QuickButtonStrip(Order order = SYSTEM); virtual ~QuickButtonStrip(); OP_STATUS Init(); /** Inserts a widget into the primary area of the button strip (usually displayed on the right) * @param widget Widget to insert (takes ownership) */ OP_STATUS InsertIntoPrimaryContent(QuickWidget* widget); /** Content to use in the secondary area of the button strip (usually displayed on the left) * @param widget Content to use (takes ownership) */ OP_STATUS SetSecondaryContent(QuickWidget* widget); // Overriding QuickWidget virtual BOOL HeightDependsOnWidth() { return FALSE; } virtual OP_STATUS Layout(const OpRect& rect); virtual void SetParentOpWidget(class OpWidget* parent); virtual void Show(); virtual void Hide(); virtual BOOL IsVisible(); virtual void SetEnabled(BOOL enabled); virtual void SetContainer(QuickWidgetContainer* container); protected: virtual unsigned GetDefaultMinimumWidth(); virtual unsigned GetDefaultMinimumHeight(unsigned width); virtual unsigned GetDefaultNominalWidth() { return GetMinimumWidth(); } virtual unsigned GetDefaultNominalHeight(unsigned width) { return GetMinimumHeight(width); } virtual unsigned GetDefaultPreferredWidth(); virtual unsigned GetDefaultPreferredHeight(unsigned width); virtual void GetDefaultMargins(WidgetSizes::Margins& margins); private: const Order m_order; QuickStackLayout* m_content; QuickStackLayout* m_primary; }; #endif //QUICK_BUTTON_STRIP_H
class BrowserHistory { public: vector<string> vec; int idx = 0; BrowserHistory(string homepage) { vec.push_back(homepage); } void visit(string url) { if (idx + 1 < vec.size()) { vec.resize(idx + 1); vec.shrink_to_fit(); } vec.push_back(url); ++idx; } string back(int steps) { idx = max(idx - steps, 0); return vec[idx]; } string forward(int steps) { idx = min(idx + steps, (int) vec.size() - 1); return vec[idx]; } }; /** * Your BrowserHistory object will be instantiated and called as such: * BrowserHistory* obj = new BrowserHistory(homepage); * obj->visit(url); * string param_2 = obj->back(steps); * string param_3 = obj->forward(steps); */
#ifndef BLACKJACK_H #define BLACKJACK_H #include "main/minigame.h" #include "mini/BlackJack/blackjacktile.h" #include "mini/BlackJack/about_blackjack.h" #include <QDialog> #include <QAbstractButton> #define num2 3 namespace Ui { class BlackJack; } class BlackJack : public QDialog, public Minigame { Q_OBJECT public: explicit BlackJack(QWidget *parent = 0); ~BlackJack(); private slots: void on_b_about_clicked(); void on_b_ok_clicked(); void on_Hit_Button_clicked(); void on_Draw_Button_clicked(); void setBustUser(); void setBustAI(); private: Ui::BlackJack* ui; BlackJackTile* tile[num2]; void configureGame(int); void configureAIGame(int); void disableGame(); void setWin(); void setLose(); void quit(); void printOutput(int); }; #endif // MINIROLLCHANCE_H
/** Underscore @file /.../Source/Kabuki_SDK-Impl/_Id/EmailAddress.h @author Cale McCollough <http://calemccollough.github.io> @copyright Copyright © 2016 Cale McCollough @license http://www.apache.org/licenses/LICENSE-2.0 */ #include "_Id/EmailAddress.h" using namespace _Id; EmailAddress::EmailAddress (const string& S) { } /** Sets the email address to a string. */ bool EmailAddress::SetAddress (const string& S) { invalid = false; if (String.IsNullOrEmpty(S)) return false; /// Use IdnMapping class to convert Unicode domain names. try { S = Regex.Replace(a, @"(@)(.+)$", this.DomainMapper, RegexOptions.None, TimeSpan.FromMilliseconds(200)); } catch (RegexMatchTimeoutException) { return false; } if (invalid) return false; // Return true if a is in valid e-mail format. try { return Regex.IsMatch(a, @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" + @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)); } catch (RegexMatchTimeoutException) { return false; } } string& EmailAddress::GetAddress () { return address; } void EmailAddress::SetAddress (const String& S) {address = S;} string EmailAddress::DomainMapper(Match match) { // IdnMapping class with default property values. IdnMapping idn = new IdnMapping(); string domainName = match.Groups[2].Value; try { domainName = idn.GetAscii(domainName); } catch (ArgumentException) { invalid = true; } return match.Groups[1].Value + domainName; }
// codecmanager.cc // 5/21/2015 jichi #include "qtembedplugin/codecmanager.h" #include "qtembedplugin/pluginmanager.h" #include <QtCore/QTextCodec> #include <boost/assign/list_of.hpp> #include <boost/foreach.hpp> #include <vector> #include <unordered_map> //#define DEBUG "embedplugin::codecmanager" //#include "sakurakit/skdebug.h" //#include <QDebug> using namespace boost::assign; // Helper functions namespace { // unnamed // Return if two code names are equal. Normalize to lowercase and replace '_' by '-'. inline char _normalize_codec_char(char ch) { if (ch == '_') ch = '-'; else if ('A' <= ch && ch <= 'Z') ch += 'a' - 'A'; return ch; } inline bool eqcodec(const char *x, const char *y) { if (x == y) return true; if (!x || !y) return false; for (;; x++, y++) { if (_normalize_codec_char(*x) != _normalize_codec_char(*y)) return false; if (*x == 0) return true; } } } // unnamed namespace QTEMBEDPLUGIN_BEGIN_NAMESPACE /** Private class */ class CodecManagerPrivate { enum CodecPlugin { JP = 0, KO, CN, TW, CodecPluginCount }; public: typedef std::vector<const char *> CodecNameList; static CodecNameList pluginNames[]; static const char *pluginFiles[]; PluginManager *plugin; std::unordered_map<const char *, QTextCodec *> codecs; QTextCodec *createForName(const char *name) { if (plugin) for (int pluginIndex = 0; pluginIndex < CodecPluginCount; pluginIndex++) BOOST_FOREACH(const char* key, pluginNames[pluginIndex]) if (eqcodec(name, key)) // case-insensitive if (QObject* p = plugin->loadPlugin(pluginFiles[pluginIndex])) return nullptr;//static_cast<QTextCodec *>p->createForName(key); return nullptr; } }; const char *CodecManagerPrivate::pluginFiles[] = { "plugins/codecs/qjpcodecs4.dll", // JP "plugins/codecs/qkrcodecs4.dll", // KR "plugins/codecs/qcncodecs4.dll", // CN "plugins/codecs/qtwcodecs4.dll", // TW }; CodecManagerPrivate::CodecNameList CodecManagerPrivate::pluginNames[] = { list_of("EUC-JP")("ISO-2022-JP")("Shift_JIS"), // JP list_of("EUC-KR")("cp949"), // KO list_of("GB18030")("GBK")("GB2312"), // CN list_of("Big5")("Big5-HKSCS"), // TW }; /** Public class */ // - Construction - CodecManager::CodecManager(PluginManager *plugin) : d_(new D) { d_->plugin = plugin ? plugin : PluginManager::globalInstance(); } CodecManager::~CodecManager() { delete d_; } CodecManager *CodecManager::globalInstance() { static Self g; return &g; } QTextCodec *CodecManager::codecForName(const char *name) { auto it = d_->codecs.find(name); if (it != d_->codecs.end()) return it->second; return ( d_->codecs[name] = d_->createForName(name) ); } QTEMBEDPLUGIN_END_NAMESPACE // EOF
#pragma once #include "SDL.h" #include "GameState.h" class GameSetupState : public GameState { public: void init(Game* game); void pause(); void resume(); void clean(Game* game); void handleEvents(Game* game); void draw(Game* game); void update(Game* game); static GameSetupState* Instance() { return &mGameSetupState; } protected: GameSetupState() {} private: static GameSetupState mGameSetupState; static SDL_Renderer* renderer; static std::vector<bool> players; //holds player before the game starts static std::vector<int> ages; //holds player ages static std::vector<int> strategies; static bool mapLoaded; static void handleMapPicker(Game* game); static void handlePlayerPicker(Game* game); static void handleGameStart(Game* game); static bool initMapLoader(Game* game); static void setupPlayers(Game* game); static void assignCoins(Game* game); };
#include "Arduino.h" #include "PD443X.h" int _Adr0; int _Adr1; int _Adr2; int _CE; int _WR; int _RST; int _latch; int _clock; int _data; PD443X::PD443X(int Adr0,int Adr1,int Adr2,int CE,int RST,int WR,int latch,int clock,int data) { _Adr0 = Adr0; _Adr1 = Adr1; _Adr2 = Adr2; _CE = CE; _RST = RST; _WR = WR; _latch = latch; _clock = clock; _data = data; pinMode(Adr0,OUTPUT); pinMode(Adr1,OUTPUT); pinMode(Adr2,OUTPUT); pinMode(CE ,OUTPUT); pinMode(RST ,OUTPUT); pinMode(WR ,OUTPUT); pinMode(latch,OUTPUT); pinMode(clock,OUTPUT); pinMode(data ,OUTPUT); } void PD443X::SendByte(char a,byte column) { digitalWrite(_WR,LOW); digitalWrite(_CE,LOW); digitalWrite(_Adr2,HIGH); digitalWrite(_Adr0, column >> 0& B1); digitalWrite(_Adr1, column >> 1& B1); digitalWrite(_latch,LOW); shiftOut(_data,_clock,MSBFIRST,a); digitalWrite(_latch,HIGH); digitalWrite(_WR,HIGH); digitalWrite(_CE,HIGH); digitalWrite(_Adr2,LOW); } void PD443X::ClrDisp() { digitalWrite(_WR,LOW); digitalWrite(_CE,LOW); digitalWrite(_Adr2,LOW); digitalWrite(_latch,LOW); shiftOut(_data,_clock,MSBFIRST,0x80); digitalWrite(_latch,HIGH); digitalWrite(_WR,HIGH); digitalWrite(_CE,HIGH); digitalWrite(_Adr2,HIGH); } void PD443X::SendStringScroll(String text ,int Speed) { ClrDisp(); text=" "+text+" "; int l = text.length()+1; byte b[1]; text.getBytes(b,l); for(int i=0;i < l-4;i++) { SendByte(b[0+i],3); SendByte(b[1+i],2); SendByte(b[3+i],1); SendByte(b[4+i],0); delay(Speed); } ClrDisp(); } void PD443X::SetBrigthness(int B) // B need to be 0,1,2 or 3 only { digitalWrite(_WR,LOW); digitalWrite(_CE,LOW); digitalWrite(_Adr2,LOW); digitalWrite(_latch,LOW); shiftOut(_data,_clock,MSBFIRST,B); digitalWrite(_latch,HIGH); digitalWrite(_WR,HIGH); digitalWrite(_CE,HIGH); digitalWrite(_Adr2,LOW); } void PD443X::CtrlWord(char X) { digitalWrite(_WR,LOW); digitalWrite(_CE,LOW); digitalWrite(_Adr2,LOW); digitalWrite(_latch,LOW); shiftOut(_data,_clock,MSBFIRST,X); digitalWrite(_latch,HIGH); digitalWrite(_WR,HIGH); digitalWrite(_CE,HIGH); digitalWrite(_Adr2,LOW); } void PD443X::LampTest(int tog) { if (tog == 1){ digitalWrite(_WR,LOW); digitalWrite(_CE,LOW); digitalWrite(_Adr2,LOW); digitalWrite(_latch,LOW); shiftOut(_data,_clock,MSBFIRST,0x40); digitalWrite(_latch,HIGH); digitalWrite(_WR,HIGH); digitalWrite(_CE,HIGH); digitalWrite(_Adr2,LOW); }else if(tog == 0){ ClrDisp(); }else if (tog != 1 && tog != 0){ //Do nothing... } }
// Created on: 2013-12-20 // Created by: Denis BOGOLEPOV // Copyright (c) 2013-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _BVH_TreeBase_Header #define _BVH_TreeBase_Header #include <BVH_Box.hxx> template<class T, int N> class BVH_Builder; //! A non-template class for using as base for BVH_TreeBase //! (just to have a named base class). class BVH_TreeBaseTransient : public Standard_Transient { DEFINE_STANDARD_RTTIEXT(BVH_TreeBaseTransient, Standard_Transient) protected: BVH_TreeBaseTransient() {} //! Dumps the content of me into the stream virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const { (void)theOStream; (void)theDepth; } //! Dumps the content of me into the stream virtual void DumpNode (const int theNodeIndex, Standard_OStream& theOStream, Standard_Integer theDepth) const { (void)theNodeIndex; (void)theOStream; (void)theDepth; } }; //! Stores parameters of bounding volume hierarchy (BVH). //! Bounding volume hierarchy (BVH) organizes geometric objects in //! the tree based on spatial relationships. Each node in the tree //! contains an axis-aligned bounding box of all the objects below //! it. Bounding volume hierarchies are used in many algorithms to //! support efficient operations on the sets of geometric objects, //! such as collision detection, ray-tracing, searching of nearest //! objects, and view frustum culling. template<class T, int N> class BVH_TreeBase : public BVH_TreeBaseTransient { friend class BVH_Builder<T, N>; public: //! @name custom data types typedef typename BVH_Box<T, N>::BVH_VecNt BVH_VecNt; public: //! @name general methods //! Creates new empty BVH tree. BVH_TreeBase() : myDepth (0) { } //! Releases resources of BVH tree. virtual ~BVH_TreeBase() {} //! Returns depth (height) of BVH tree. int Depth() const { return myDepth; } //! Returns total number of BVH tree nodes. int Length() const { return BVH::Array<int, 4>::Size (myNodeInfoBuffer); } public: //! @name methods for accessing individual nodes //! Returns minimum point of the given node. BVH_VecNt& MinPoint (const int theNodeIndex) { return BVH::Array<T, N>::ChangeValue (myMinPointBuffer, theNodeIndex); } //! Returns maximum point of the given node. BVH_VecNt& MaxPoint (const int theNodeIndex) { return BVH::Array<T, N>::ChangeValue (myMaxPointBuffer, theNodeIndex); } //! Returns minimum point of the given node. const BVH_VecNt& MinPoint (const int theNodeIndex) const { return BVH::Array<T, N>::Value (myMinPointBuffer, theNodeIndex); } //! Returns maximum point of the given node. const BVH_VecNt& MaxPoint (const int theNodeIndex) const { return BVH::Array<T, N>::Value (myMaxPointBuffer, theNodeIndex); } //! Returns index of first primitive of the given leaf node. int& BegPrimitive (const int theNodeIndex) { return BVH::Array<int, 4>::ChangeValue (myNodeInfoBuffer, theNodeIndex).y(); } //! Returns index of last primitive of the given leaf node. int& EndPrimitive (const int theNodeIndex) { return BVH::Array<int, 4>::ChangeValue (myNodeInfoBuffer, theNodeIndex).z(); } //! Returns index of first primitive of the given leaf node. int BegPrimitive (const int theNodeIndex) const { return BVH::Array<int, 4>::Value (myNodeInfoBuffer, theNodeIndex).y(); } //! Returns index of last primitive of the given leaf node. int EndPrimitive (const int theNodeIndex) const { return BVH::Array<int, 4>::Value (myNodeInfoBuffer, theNodeIndex).z(); } //! Returns number of primitives in the given leaf node. int NbPrimitives (const int theNodeIndex) const { return EndPrimitive (theNodeIndex) - BegPrimitive (theNodeIndex) + 1; } //! Returns level (depth) of the given node. int& Level (const int theNodeIndex) { return BVH::Array<int, 4>::ChangeValue (myNodeInfoBuffer, theNodeIndex).w(); } //! Returns level (depth) of the given node. int Level (const int theNodeIndex) const { return BVH::Array<int, 4>::Value (myNodeInfoBuffer, theNodeIndex).w(); } //! Checks whether the given node is outer. bool IsOuter (const int theNodeIndex) const { return BVH::Array<int, 4>::Value (myNodeInfoBuffer, theNodeIndex).x() != 0; } public: //! @name methods for accessing serialized tree data //! Returns array of node data records. BVH_Array4i& NodeInfoBuffer() { return myNodeInfoBuffer; } //! Returns array of node data records. const BVH_Array4i& NodeInfoBuffer() const { return myNodeInfoBuffer; } //! Returns array of node minimum points. typename BVH::ArrayType<T, N>::Type& MinPointBuffer() { return myMinPointBuffer; } //! Returns array of node maximum points. typename BVH::ArrayType<T, N>::Type& MaxPointBuffer() { return myMaxPointBuffer; } //! Returns array of node minimum points. const typename BVH::ArrayType<T, N>::Type& MinPointBuffer() const { return myMinPointBuffer; } //! Returns array of node maximum points. const typename BVH::ArrayType<T, N>::Type& MaxPointBuffer() const { return myMaxPointBuffer; } //! Dumps the content of me into the stream virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const Standard_OVERRIDE { OCCT_DUMP_TRANSIENT_CLASS_BEGIN (theOStream) OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myDepth) OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, Length()) for (Standard_Integer aNodeIdx = 0; aNodeIdx < Length(); ++aNodeIdx) { DumpNode (aNodeIdx, theOStream, theDepth); } } //! Dumps the content of node into the stream virtual void DumpNode (const int theNodeIndex, Standard_OStream& theOStream, Standard_Integer theDepth) const Standard_OVERRIDE { OCCT_DUMP_CLASS_BEGIN (theOStream, BVH_TreeNode) OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, theNodeIndex) Bnd_Box aBndBox = BVH::ToBndBox (MinPoint (theNodeIndex), MaxPoint (theNodeIndex)); Bnd_Box* aPointer = &aBndBox; OCCT_DUMP_FIELD_VALUES_DUMPED (theOStream, theDepth, aPointer) OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, BegPrimitive (theNodeIndex)) OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, EndPrimitive (theNodeIndex)) OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, Level (theNodeIndex)) OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, IsOuter (theNodeIndex)) } public: //! @name protected fields //! Array of node data records. BVH_Array4i myNodeInfoBuffer; //! Array of node minimum points. typename BVH::ArrayType<T, N>::Type myMinPointBuffer; //! Array of node maximum points. typename BVH::ArrayType<T, N>::Type myMaxPointBuffer; //! Current depth of BVH tree (set by builder). int myDepth; }; //! Type corresponding to quad BVH. struct BVH_QuadTree { }; //! Type corresponding to binary BVH. struct BVH_BinaryTree { }; //! BVH tree with given arity (2 or 4). template<class T, int N, class Arity = BVH_BinaryTree> class BVH_Tree { // Invalid type }; #endif // _BVH_TreeBase_Header
//Pie //UVA12097 /* 題目描述: 現在有一些不同半徑的蛋糕,每個厚度都是 1,現在有 F 個朋友和自己要去分, 而每個人所得到的蛋糕塊的體積要一樣,但分的時候只能來自於一塊蛋糕, 不可由來自不同蛋糕的小蛋糕構成。 題目解法: 二分答案,然後去除每塊蛋糕取整數,得到該蛋糕可以分出幾份。 */ #include<iostream> #include<algorithm> #include<iomanip> #include<cstdio> #include<cmath> using namespace std; const int maxn = 10000 + 5; const double pi = acos(-1.0); //数學中arccos(-1)=圆周率pi int T; int n, f; int x; double maxf; double Pie[maxn]; bool judge(double area) { int sum = 0; for (int i = 0; i < n; i++) sum += floor(Pie[i] / area); return sum >= f + 1; } int main() { cin >> T; while(T--) { maxf = -1.0; cin >> n >> f; for (int i = 0; i < n; i++) { cin >> x; Pie[i] = pi*x*x; maxf = max(maxf, Pie[i]); } double l = 0, r = maxf; while (r - l > 1e-4) { double mid = (r + l) / 2.0; if (judge(mid))l = mid; else r = mid; } printf("%.4f\n", l); } return 0; }
#include<iostream> using namespace std; int Merge(int array[] , int p , int q , int r){ int left_size , right_size , i , j , k; left_size = q - p + 1; // array kiri right_size = r - q ; // array kanan int L[left_size] , R[right_size]; for(i = 0 ; i < left_size ; i++) { L[i] = array[p+i] ; // bagian kiri } for(j = 0 ; j < right_size ; j++) { R[j] = array[q+j+1]; // bagian kanan } i = 0,j = 0 ; // perbandingan untuk gabung for(k = p ; i < left_size && j < right_size ; k++) { if(L[i] < R[j]) { array[k] = L[i++]; } else { array[k] = R[j++]; } } while(i < left_size) { array[k++] = L[i++]; } while(j < right_size) { array[k++] = R[j++]; } } // merge sort int MergeSort(int array[],int p,int r){ int q; if(p < r){ q = (p + r) /2; MergeSort(array , p , q); MergeSort(array , q+1 , r); Merge(array , p , q , r); } } int main() { int n ; cout << "Jumlah Array : "; cin >> n; int array[n] , i; for(i = 0 ; i < n ; i++){ cout << "Input array ke - " << i+1 << " : "; cin >> array[i]; } MergeSort(array , 0 , n-1); cout << "Merge Sort Sukses !!" << endl ; for(i = 0 ; i < n ; i++) { cout << array[i] << " "; } return 0; }
//Gvector.cpp #include <vector> #include "Gvector.h" using namespace std; Gvector::Gvector(){ nx = 0; ny = 0; vect = new complex<double>[0]; } Gvector :: Gvector(int nnx, int nny, complex<double> val){ nx = nnx; ny = nny; vect = new complex<double>[nnx*nny]; for (int i=0 ; i<nx*ny ; i++) { vect[i] = val; } } Gvector :: Gvector(int nnx, int nny){ nx = nnx; ny = nny; vect = new complex<double>[nnx*nny]; for (int i=0 ; i<nx*ny ; i++) { complex<double> val(0.0); vect[i] = val; } } Gvector :: Gvector(const Gvector &v){ nx = v.nx; ny = v.ny; vect = new complex<double>[nx*ny]; if (nx*ny == 0) return; for (int i = 0 ; i<nx*ny ; i++) { vect[i] = v.vect[i]; } } int Gvector::size() const{ return nx*ny; } int Gvector::getNX() const{ return nx; } int Gvector::getNY() const{ return ny; } complex<double> Gvector::getvect() const{ return *vect; } void Gvector::fillRandomly(){ srand(time(NULL)); for (int i = 0; i < nx*ny; i++){ vect[i] = (complex<double>)rand()/(complex<double>)RAND_MAX; } } void Gvector::transpose(){ //if (nx > ny){ vector<int> checker(nx*ny, false); complex<double> Cow(0,0); Gvector CS(nx, ny, Cow); CS.nx = ny; CS.ny = nx; for(int i = 0; i<nx; i++){ for(int j = 0; j<ny; j++){ if(!checker[i*ny + j]){ complex<double> x1 = (*this)(i,j); x1.imag(-x1.imag()); CS(j,i) = x1; } } } for(int i = 0; i<nx*ny; i++){ vect[i] = CS(i); } nx = CS.nx; ny = CS.ny; } void Gvector::display(std::ostream& str) const{ for (int i = 0 ; i<nx ; i++) { for (int j = 0 ; j<ny ; j++) { str << std::fixed; str << std::setprecision(3); str << vect[i*ny + j].real() << "+%i*" << vect[i*ny + j].imag() <<"||"; } str<<"\n"; } } void Gvector::fft(){ int n = nx*ny; if (n <= 1){return;} complex<double> t; const double pi = std::acos(-1); const std::complex<double> i(0, 1); Gvector even; even = Gvector(1, n/2 + n%2); Gvector odd; odd = Gvector(1, n/2); for (int i = 0; i < n/2; i++){ even(i) = vect[2*i]; odd(i) = vect[2*i+1]; } odd.fft(); even.fft(); for (int k = 0; k<n/2; k++){ t = odd(k); t*=exp(-2.0*i*pi*(double)k/(double)n); vect[k] = even(k)+t; vect[k+n/2] = even(k)-t; } } void Gvector::ifft(){ int n = nx*ny; if (n <= 1){return;} for(int i = 0; i<n; i++){ vect[i].imag(-1*vect[i].imag()); } fft(); for(int i = 0; i<n; i++){ vect[i].imag(-1*vect[i].imag()); vect[i]/=n; } } Gvector :: ~Gvector(){ nx = 0; ny = 0; delete [] vect; } complex<double>& Gvector::operator()(int i){ assert(i>=0); assert(i<nx*ny); return vect[i]; } complex<double> & Gvector::operator()(int i) const{ assert(i>=0); assert(i<nx*ny); return vect[i]; } complex<double>& Gvector::operator()(int i, int j){ assert(i>=0); assert(j>=0); assert(i<nx); assert(j<ny); return vect[i*ny + j]; } complex<double> & Gvector::operator()(int i, int j) const{ assert(i>=0); assert(j>=0); assert(i<nx); assert(j<ny); return vect[i*ny + j]; } Gvector & Gvector::operator=(Gvector const & A){ nx = A.nx; ny = A.ny; vect = new complex<double>[nx*ny]; memcpy(vect, A.vect, nx*ny*sizeof(complex<double>)); return *this; } Gvector & Gvector::operator-(){ Gvector *aux = new Gvector(nx, ny); for (int i = 0; i < nx*ny; i++){ aux->vect[i] = -vect[i]; } return(*aux); } Gvector & Gvector::operator+= (Gvector const &Dv){ if (nx*ny != Dv.nx*Dv.ny){ exit(-1); } Gvector &D = *this; for (int i = 0; i < nx*ny; i++){ D(i) += Dv(i); } return D; } Gvector & Gvector::operator-= (Gvector const &Dv){ if (nx*ny != Dv.nx*ny){ exit(-1); } Gvector &D = *this; for (int i = 0; i < nx*ny; i++){ D(i) -= Dv(i); } return D; } Gvector & Gvector::operator+= (complex<double> d){ Gvector &D = *this; for (int i = 0; i < nx*ny; i++){ D(i) += d; } return D; } Gvector & Gvector::operator-= (complex<double> d){ Gvector &D = *this; for (int i = 0; i < nx*ny; i++){ D(i) -= d; } return D; } Gvector & Gvector::operator*= (complex<double> d){ Gvector &D = *this; for (int i = 0; i < nx*ny; i++){ D(i) *= d; } return D; } Gvector & Gvector::operator/= (complex<double> d){ Gvector &D = *this; for (int i = 0; i < nx*ny; i++){ D(i) /= d; } return D; } bool Gvector::operator== (Gvector const &Dv){ if (nx*ny != Dv.nx*ny){ return(false); } for (int i = 0; i < nx*ny; i++){ if (Dv(i) != vect[i]){ return(false); } } return true; } bool Gvector::operator!= (Gvector const &Dv){ return !(*this == Dv); } Gvector & operator+ (Gvector const & A, Gvector const & B){ Gvector *aux = new Gvector(A); *aux+= B; return(*aux); } Gvector & operator- (Gvector const & A, Gvector const & B){ Gvector *aux = new Gvector(A); *aux-= B; return(*aux); } Gvector & operator+ (Gvector const & A, complex<double> d){ Gvector *aux = new Gvector(A); *aux+= d; return(*aux); } Gvector & operator- (Gvector const & A, complex<double> d){ Gvector *aux = new Gvector(A); *aux-= d; return(*aux); } Gvector & operator* (Gvector const & A, complex<double> d){ Gvector *aux = new Gvector(A); *aux*= d; return(*aux); } Gvector & operator* (complex<double> d, Gvector const & A){ Gvector *aux = new Gvector(A); *aux*= d; return(*aux); } Gvector & operator/ (Gvector const & A, complex<double> d){ Gvector *aux = new Gvector(A); *aux/= d; return(*aux); } ostream & operator << (ostream & out, Gvector const & Dv){ out << "#Gvector : "; Dv.display(out); return out; } istream & operator >>(istream & in, Gvector const & Dv){ for (int i=0; i< Dv.size(); i++){ in >> Dv(i); } return in; }
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Components/ActorComponent.h" #include "ObjectInfo.generated.h" UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) ) class FPS_TEST_5_API UObjectInfo : public UActorComponent { GENERATED_BODY() public: // Sets default values for this component's properties UObjectInfo(); // Object Name UPROPERTY(EditAnywhere) FString Name; // Object Description UPROPERTY(EditAnywhere) FString Description; // Object ID used to define it UPROPERTY(EditAnywhere) FString ObjectId; // 3D String Mesh used for 3D render UPROPERTY(EditAnywhere) FString MeshReference; // 2D Image used for inventory/equiped item UPROPERTY(EditAnywhere) FString ImageReference; // Character that owns the object UPROPERTY(VisibleAnywhere) AActor* Player; virtual void UtilityFunction(); };
#include <iostream> #include "ABB.h" using namespace std; int main() { ABB A; int e,n; cout << "Ingresa n: "; cin >> n; for(int i=0;i<n;i++){ cout << "Ingresa el valor entero: "; cin >> e; A.inserta(e); } A.entreorden(); A.preorden(); A.postorden(); return 0; }
#ifdef IS_LIB # ifdef _WIN32 __declspec(dllexport) # endif int internal_empty_1() { return 0; } #else # ifdef _WIN32 __declspec(dllexport) # endif int empty_1() { return 0; } #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** Copyright (C) 1995-2007 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef VEGATRANSFORM_H #define VEGATRANSFORM_H #ifdef VEGA_SUPPORT #include "modules/libvega/vegafixpoint.h" enum VEGATransformClass { // These are the 'basic' features VEGA_XFRMCLS_TRANSLATION = 0x01, VEGA_XFRMCLS_SCALE = 0x02, VEGA_XFRMCLS_SKEW = 0x04, // These are 'additional' features that further specialize the // above 'basic' features VEGA_XFRMCLS_INT_TRANSLATION = 0x08, VEGA_XFRMCLS_POS_SCALE = 0x10 }; /** A transform is used to transform an x and a y value. When a transform is * created its values are undefined. * The transform is row based (row major). */ class VEGATransform { public: /** Load the identity matrix. */ void loadIdentity(); /** Load a scale matrix. The x and y value will be multiplied by the * factors. * @param xscale the factor to multiply the x coordinate with. * @param yscale the factor to multiply the y coordinate with. */ void loadScale(VEGA_FIX xscale, VEGA_FIX yscale); /** Load a translate matrix. The translation values will be added to * the coordinate. * @param xtrans the translation of the x coordinate. * @param ytrans the translation of the y coordinate. */ void loadTranslate(VEGA_FIX xtrans, VEGA_FIX ytrans); /** Load a rotation matrix. The coordinates will be rotated around * the origin counter-clockwise by the amount specified. * @param angle the angle to rotate be specified in degrees. */ void loadRotate(VEGA_FIX angle); /** Multiply with a different transform. The transform you multiply with * (not this transform but "the other" will be applied first when * transforming using this transform. * @param other the transform to multiply with. */ void multiply(const VEGATransform &other); /** Invert the transform. * @returns false if no inverse exists, true otherwise. */ bool invert(); /** Apply this transform to a coordinate. * @param x the x coord. * @param y the y coord. */ void apply(VEGA_FIX &x, VEGA_FIX &y) const; /** Apply this transform to a vector. * @param x the x coord. * @param y the y coord. */ void applyVector(VEGA_FIX &x, VEGA_FIX &y) const; /** Copy the values of a transform to this transform. * @param other the transform to copy. */ void copy(const VEGATransform &other); /** [] operator used to access (read-write) the values of the matrix. */ VEGA_FIX &operator[](int index){return matrix[index];} /** [] operator used to access (read-only) the values of the matrix. */ VEGA_FIX operator[](int index) const {return matrix[index];} /** Perform a classification of the transform, using the classes * defined by VEGATransformClass. * @returns A bitmask with the * applicable classes set. */ unsigned classify() const; /** Checks if the transform is composed of an integral translation only. */ bool isIntegralTranslation() const { return classify() == (VEGA_XFRMCLS_TRANSLATION | VEGA_XFRMCLS_INT_TRANSLATION | VEGA_XFRMCLS_POS_SCALE); } /** Checks if the transform is a rotation n*(pi/2) or a x/y-flip, has * x/y-scale = 1 and if any translation can be represented by integers. */ bool isAlignedAndNonscaled() const; /** Checks if the transform consists of scaling and translation only. */ bool isScaleAndTranslateOnly() const; private: VEGA_FIX matrix[6]; }; #if defined(VEGA_3DDEVICE) || defined(CANVAS3D_SUPPORT) /** A 3-dimensional transform used by the 3d device. This can be used to build * world transforms to apply to 3d rendering. */ class VEGATransform3d { public: /** Load the identity matrix. */ void loadIdentity(); /** Load a scale matrix. The x and y value will be multiplied by the * factors. * @param xscale the factor to multiply the x coordinate with. * @param yscale the factor to multiply the y coordinate with. */ void loadScale(VEGA_FIX xscale, VEGA_FIX yscale, VEGA_FIX zscale); /** Load a translate matrix. The translation values will be added to * the coordinate. * @param xtrans the translation of the x coordinate. * @param ytrans the translation of the y coordinate. */ void loadTranslate(VEGA_FIX xtrans, VEGA_FIX ytrans, VEGA_FIX ztrans); /** Load a rotation matrix. The coordinates will be rotated around * the origin counter-clockwise by the amount specified. * @param angle the angle to rotate be specified in degrees. */ void loadRotateX(VEGA_FIX angle); void loadRotateY(VEGA_FIX angle); void loadRotateZ(VEGA_FIX angle); /** Multiply with a different transform. The transform you multiply with * (not this transform but "the other" will be applied first when * transforming using this transform. * @param other the transform to multiply with. */ void multiply(const VEGATransform3d &other); /** Copy the values of a transform to this transform and optionally transpose it. * @param other the transform to copy. * @param transpose set to true to transpose the copy. */ void copy(const VEGATransform3d& other, bool transpose = false); /** Copy a 2d transform to this 3d transform. * @param 2d transform to copy. */ void copy(const VEGATransform& other); /** [] operator used to access (read-write) the values of the matrix. */ VEGA_FIX &operator[](int index){return matrix[index];} /** [] operator used to access (read-only) the values of the matrix. */ const VEGA_FIX &operator[](int index) const {return matrix[index];} private: VEGA_FIX matrix[16]; }; #endif // VEGA_3DDEVICE || CANVAS3D_SUPPORT #endif // VEGA_SUPPORT #endif // VEGATRANSFORM_H
#include "EnemyLogicCalculator.h" #include "Core.h" EnemyLogicCalculator::EnemyLogicCalculator(): m_collidingWithPlayer(false) { } EnemyLogicCalculator::~EnemyLogicCalculator() { //not responsible to free any element } void EnemyLogicCalculator::init(LevelModel* levelModel, AvatarModel* avatarModel ) { m_avatarModel = avatarModel; m_levelModel = levelModel; } bool EnemyLogicCalculator::isPlayerCloseAndVisible() { float distanceToPlayer = std::sqrtf( (m_levelModel->getPlayerModel()->getTerrainPosition()[0]-m_avatarModel->getTerrainPosition()[0])*(m_levelModel->getPlayerModel()->getTerrainPosition()[0]-m_avatarModel->getTerrainPosition()[0]) + (m_levelModel->getPlayerModel()->getTerrainPosition()[1]-m_avatarModel->getTerrainPosition()[1])*(m_levelModel->getPlayerModel()->getTerrainPosition()[1]-m_avatarModel->getTerrainPosition()[1]) ); //check if distance is close enough this value should become a constant somewhere or depend on the type of enemy //TO_DO if(distanceToPlayer < 40) { //if close enough check for visibility if(isPlayerVisible()) { return true; } else { return false; } } else { return false; } } bool EnemyLogicCalculator::isPlayerVisible() { float playerX = m_levelModel->getPlayerModel()->getTerrainPosition()[0]*PIXELS_PER_METER/m_levelModel->getTileSetTileWidth(); float playerY = m_levelModel->getPlayerModel()->getTerrainPosition()[1]*PIXELS_PER_METER/m_levelModel->getTileSetTileHeight(); float avatarX = m_avatarModel->getTerrainPosition()[0]*PIXELS_PER_METER/m_levelModel->getTileSetTileWidth(); float avatarY = m_avatarModel->getTerrainPosition()[1]*PIXELS_PER_METER/m_levelModel->getTileSetTileHeight(); //check solidity of tiles going from Player to Enemy/Avatar in a straight line //if the x tiles of player and avatar coincide we simplify the checking and avoid an exception (the slope is inf) int tilePlayerX =playerX; int tileAvatarX = avatarX; int tilePlayerY =playerY; int tileAvatarY = avatarY; if( tilePlayerX != tileAvatarX) { float slope = (float)(playerY - avatarY)/(float)(playerX-avatarX); float y = playerY; if(playerX > avatarX) { //I have to assume only one solidity in the first layer. This is to be corrected in the future TO_DO //Even better would be to have a visibility layer //IMPORTANT: we visit the tiles using small steps in x otherwise we could jump tiles for very steep slopes!!! //We assume a solid tile is a tile the enemies cannot see through. for(float x = playerX; x > avatarX; x-= std::abs(playerX-avatarX)/50.0f) { //ATTENTION: the casts to int are extremely important! y=(slope*x + playerY-playerX*slope); if(m_levelModel->getTileSolidity((int)x,(int)y) == 9) {return false;} } } else { for(float x = playerX; x < avatarX; x+=std::abs(playerX-avatarX)/50.0f) { y=(slope*x + playerY-playerX*slope); //ATTENTION:the cast to int are extremely important! if(m_levelModel->getTileSolidity((int)x,(int)y) == 9) {return false;} } } } else { //move on a straight vertical line from player to avatar checking the tiles if(tilePlayerY> tileAvatarY) { //I have to assume only one solidity in the first layer. This is to be corrected in the future TO_DO //Even better would be to have a visibility layer for(int y = tilePlayerY; y > tileAvatarY; y--) { if(m_levelModel->getTileSolidity((int)avatarX,(int)y) == 9) {return false;} } } else { for(int y = tilePlayerY; y < tileAvatarY; y++) { if(m_levelModel->getTileSolidity((int)avatarX,(int)y) == 9) {return false;} } } } return true; }
#include "Player.h" Player::Player() { } Player::~Player() { } bool Player::initWithNum(int num) { char filename[64] = { 0 }; sprintf(filename, "%d", num); if (!Sprite::initWithFile("playerbg.png")) { return false; } this->setAnchorPoint(Vec2(0.5, 0.5)); this->setOnBall(false); _title = LabelTTF::create(filename, "Arial", TITLE_FONT_SIZE(18)); _title->setAnchorPoint(Vec2(0.5, 0.5)); _title->setPosition(Vec2(this->getBoundingBox().size.width / 2, this->getBoundingBox().size.height / 2)); this->addChild(_title); return true; } Vec2 Player::getStartPosition(void) { return this->_startPosition; } Rect Player::getHomeRegion(void) { return this->_homeRegion; } void Player::changeTagPostion() { if (_onBall) return; float max_width = _homeRegion.getMaxX() - this->getBoundingBox().size.width / 2; float min_width = _homeRegion.getMinX() + this->getBoundingBox().size.width / 2; float max_height = _homeRegion.getMaxY() - this->getBoundingBox().size.height / 2; float min_height = _homeRegion.getMinY() + this->getBoundingBox().size.height / 2; float x = (rand() % (int)(max_width - min_width + 1)) + min_width; float y = (rand() % (int)(max_height - min_height + 1)) + min_height; this->setTagPosition(Vec2(x, y)); } void Player::setColor(const Color3B &color) { _title->setColor(color); } void Player::initAnimate() { Armature *armature = Armature::create("PlayerAnimation"); armature->setAnchorPoint(Vec2(0, 0)); armature->setPosition(Vec2(0, 0)); armature->setScale(FOOTBALLSCALE); _armature = armature; _armature->retain(); }
#include <iostream> #include <boost/log/core.hpp> #include <boost/log/attributes.hpp> #include <boost/log/attributes/scoped_attribute.hpp> #include <boost/log/expressions.hpp> #include <boost/log/expressions/keyword.hpp> #include <boost/log/sources/global_logger_storage.hpp> #include <boost/log/sources/severity_channel_logger.hpp> #include <boost/log/trivial.hpp> #include <boost/log/utility/manipulators/add_value.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/utility/setup/console.hpp> int main() { std::cout << "cout" << std::endl; std::cerr << "cerr" << std::endl; std::clog << "clog" << std::endl; BOOST_LOG_TRIVIAL(trace) << "A trace severity message"; }
#pragma once #include <stdint.h> #define XHCI_PORT_OFFSET 0x400 #define USB_CMD_RS (1 << 0) // Run/Stop #define USB_CMD_HCRST (1 << 1) // Host Controller Reset #define USB_CMD_INTE (1 << 2) // Interrupter enable #define USB_STS_HCH (1 << 0) // HCHalted - 0 if CMD_RS is 1 #define USB_STS_HSE (1 << 2) // Host System Error - set to 1 on error #define USB_STS_EINT (1 << 3) // Event Interrupt #define USB_STS_PCD (1 << 4) // Port change detect #define USB_STS_SSS (1 << 8) // Save State Status - 1 when CMD_CSS is 1 #define USB_STS_RSS (1 << 9) // Restore State Status - 1 when CMD_CRS is 1 #define USB_STS_SRE (1 << 10) // Save/Restore Error - 1 when error during save or restore operation #define USB_STS_CNR (1 << 11) // Controller Not Ready - 0 = Ready, 1 = Not Ready #define USB_STS_HCE (1 << 12) // Host Controller Error #define USB_CFG_MAXSLOTSEN (0xFF) // Max slots enabled #define USB_CFG_U3E (1 << 8) // U3 Entry Enable #define USB_CFG_CIE (1 << 9) // Configuration Information Enable #define USB_CCR_RCS (1 << 0) // Ring Cycle State #define USB_CCR_CS (1 << 1) // Command Stop #define USB_CCR_CA (1 << 2) // Command Abort #define USB_CCR_CRR (1 << 3) // Command Ring Running #define USB_CCR_PTR_LO 0xFFFFFFC0‬ #define USB_CCR_PTR 0xFFFFFFFFFFFFFFC0‬ // Command Ring Pointer namespace USB{ class XHCIController{ protected: typedef struct { uint8_t capLength; // Capability Register Length uint8_t reserved; uint16_t hciVersion; // Interface Version Number uint32_t hcsParams1; uint32_t hcsParams2; uint32_t hcsParams3; uint32_t hccParams1; uint32_t dbOff; // Doorbell offset uint32_t rtsOff; // Runtime registers space offset uint32_t hccParams2; inline uint8_t MaxSlots(){ // Number of Device Slots return hcsParams1 & 0xFF; } inline uint16_t MaxIntrs(){ // Number of Interrupters return (hcsParams1 >> 8) & 0x3FF; } inline uint8_t MaxPorts(){ // Number of Ports return (hcsParams1 >> 24) & 0xFF; } inline uint8_t IST(){ // Isochronous Scheduling Threshold return hcsParams2 & 0xF; } inline uint8_t ERSTMax(){ // Event Ring Segment Table Max return (hcsParams2 >> 4) & 0xF; } inline uint16_t MaxScratchpadBuffers(){ return (((hcsParams2 >> 21) & 0x1F) << 5) | ((hcsParams2 >> 27) & 0x1F); } inline uint8_t U1DeviceExitLatency(){ return hcsParams3 & 0xFF; } inline uint16_t U2DeviceExitLatency(){ return (hcsParams3 >> 16) & 0xFFFF; } } __attribute__ ((packed)) xhci_cap_regs_t; // Capability Registers typedef struct { uint32_t usbCommand; // USB Command uint32_t usbStatus; // USB Status uint32_t pageSize; // Page Size uint8_t rsvd1[8]; uint32_t deviceNotificationControl; // Device Notification Control union{ uint64_t cmdRingCtl; // Command Ring Control struct { uint64_t cmdRingCtlRCS : 1; // Ring cycle state uint64_t cmdRingCtlCS : 1; // Command stop uint64_t cmdRingCtlCA : 1; // Command Abort uint64_t cmdRingCtlCRR : 1; // Command Ring Running uint64_t cmdRingCtlReserved : 2; uint64_t cmdRingCtlPointer : 58; } __attribute__((packed)); } __attribute__((packed)); uint8_t rsvd2[16]; uint64_t devContextBaseAddrArrayPtr; // Device Context Base Address Array Pointer uint32_t configure; // Configure inline void SetMaxSlotsEnabled(uint8_t value){ uint32_t temp = configure; temp &= ~((uint32_t)USB_CFG_MAXSLOTSEN); temp |= temp & USB_CFG_MAXSLOTSEN; configure = temp; } inline uint8_t MaxSlotsEnabled(){ return configure & USB_CFG_MAXSLOTSEN; } } __attribute__((packed)) xhci_op_regs_t; // Operational Registers typedef struct { uint32_t portSC; // Port Status and Control uint32_t portPMSC; // Power Management Status and Control uint32_t portLinkInfo; // Port Link Info uint32_t portHardwareLPMCtl; // Port Hardware LPM Control } __attribute__((packed)) xhci_port_regs_t; // Port Registers enum { SlotStateDisabledEnabled = 0, // Disabled / Enabled SlotStateDefault = 1, SlotStateAddressed = 2, SlotStateConfigured = 3, }; typedef struct { // Offset 00h uint32_t routeString : 20; // Route string uint32_t speed : 4; // Speed (deprecated) uint32_t resvd : 1; uint32_t mtt : 1; // Multi TT uint32_t hub : 1; // Hub (1) or Function (0) uint32_t ctxEntries : 5; // Index of the last valid Endpoint Context // Offset 04h uint32_t maxExitLatency : 16; uint32_t rootHubPortNumber : 8; // Root Hub Port Number uint32_t numberOfPorts : 8; // If Hub then set to number of downstream facing ports // Offset 08h uint32_t parentHubSlotID : 8; uint32_t parentPortNumber : 8; // Parent Port Number uint32_t ttt : 2; // TT Think Time uint32_t resvdZ : 4; uint32_t interrupterTarget : 10; // Offset 0Ch uint32_t usbDeviceAddress : 8; // Address assigned to USB device by the Host Controller uint32_t resvdZ_2 : 19; uint32_t slotState : 5; } __attribute__((packed)) xhci_slot_context_t; uintptr_t xhciBaseAddress; uintptr_t xhciVirtualAddress; xhci_cap_regs_t* capRegs; xhci_op_regs_t* opRegs; xhci_port_regs_t* portRegs; uint64_t devContextBaseAddressArrayPhys; uint64_t* devContextBaseAddressArray; uint64_t cmdRingPointerPhys; uint64_t* cmdRingPointer; public: enum Status{ ControllerNotInitialized, ControllerInitialized, }; private: Status controllerStatus = ControllerNotInitialized; public: XHCIController(uintptr_t baseAddress); inline Status GetControllerStatus() { return controllerStatus; } static int Initialize(); }; }
// $Id$ // // (C) Copyright Mateusz Loskot 2008, mateusz@loskot.net // Distributed under the BSD License // (See accompanying file LICENSE.txt or copy at // http://www.opensource.org/licenses/bsd-license.php) // #include <liblas/header.hpp> #include <tut/tut.hpp> #include "common.hpp" // boost #include <boost/cstdint.hpp> // std #include <string> using namespace boost; namespace tut { void test_default_header(liblas::Header const& h) { using liblas::Header; ensure_equals("wrong default file signature", h.GetFileSignature(), Header::FileSignature); ensure_equals("wrong default file source id", h.GetFileSourceId(), 0); ensure_equals("wrong default reserved value", h.GetReserved(), 0); boost::uuids::uuid g = boost::uuids::nil_uuid(); ensure_equals("wrong default project guid", h.GetProjectId(), g); ensure_equals("wrong default major version", h.GetVersionMajor(), 1); ensure_equals("wrong default minor version", h.GetVersionMinor(), 2); ensure_equals("wrong default system id", h.GetSystemId(), Header::SystemIdentifier); ensure_equals("wrong default software id", h.GetSoftwareId(), Header::SoftwareIdentifier); // TODO: Fix me to use todays day # and year // ensure_equals("wrong default creation day-of-year", // h.GetCreationDOY(), 0); // ensure_equals("wrong default creation year", // h.GetCreationYear(), 0); ensure_equals("wrong default header size", h.GetHeaderSize(), boost::uint16_t(227)); boost::uint32_t offset = 229; if (h.GetVersionMinor() == 1 || h.GetVersionMinor() == 2) { offset = 227; } ensure_equals("wrong default data offset", h.GetDataOffset(), offset); ensure_equals("wrong default records count", h.GetRecordsCount(), boost::uint32_t(0)); ensure_equals("wrong default data format id", h.GetDataFormatId(), liblas::ePointFormat3); ensure_equals("wrong default data record length", h.GetDataRecordLength(), liblas::ePointSize3); ensure_equals("wrong default point records count", h.GetPointRecordsCount(), boost::uint32_t(0)); ensure_equals("wrong default X scale", h.GetScaleX(), double(1.0)); ensure_equals("wrong default Y scale", h.GetScaleY(), double(1.0)); ensure_equals("wrong default Z scale", h.GetScaleZ(), double(1.0)); ensure_equals("wrong default X offset", h.GetOffsetX(), double(0)); ensure_equals("wrong default Y offset", h.GetOffsetY(), double(0)); ensure_equals("wrong default Z offset", h.GetOffsetZ(), double(0)); ensure_equals("wrong default min X", h.GetMinX(), double(0)); ensure_equals("wrong default max X", h.GetMaxX(), double(0)); ensure_equals("wrong default min Y", h.GetMinY(), double(0)); ensure_equals("wrong default max Y", h.GetMaxY(), double(0)); ensure_equals("wrong default min Z", h.GetMinZ(), double(0)); ensure_equals("wrong default max Z", h.GetMaxZ(), double(0)); } void test_default_point(liblas::Point const& p) { ensure_equals("wrong default X coordinate", p.GetX(), double(0)); ensure_equals("wrong default Y coordinate", p.GetY(), double(0)); ensure_equals("wrong default Z coordinate", p.GetZ(), double(0)); ensure_equals("wrong defualt intensity", p.GetIntensity(), 0); ensure_equals("wrong defualt return number", p.GetReturnNumber(), 0); ensure_equals("wrong defualt number of returns", p.GetNumberOfReturns(), 0); ensure_equals("wrong defualt scan direction", p.GetScanDirection(), 0); ensure_equals("wrong defualt edge of flight line", p.GetFlightLineEdge(), 0); ensure_equals("wrong defualt classification", p.GetClassification(), liblas::Classification::bitset_type()); ensure_equals("wrong defualt scan angle rank", p.GetScanAngleRank(), 0); ensure_equals("wrong defualt file marker/user data value", p.GetUserData(), 0); ensure_equals("wrong defualt user bit field/point source id value", p.GetPointSourceID(), 0); ensure_equals("wrong defualt time", p.GetTime(), double(0)); ensure_equals("invalid default red color", p.GetColor().GetRed(), 0); ensure_equals("invalid default green color", p.GetColor().GetGreen(), 0); ensure_equals("invalid default blue color", p.GetColor().GetBlue(), 0); ensure("invalid defualt point record", p.IsValid()); } void test_file10_header(liblas::Header const& h) { ensure_equals(h.GetFileSignature(), liblas::Header::FileSignature); ensure_equals(h.GetFileSourceId(), 0); ensure_equals(h.GetReserved(), 0); boost::uuids::uuid g = boost::uuids::nil_uuid(); ensure_equals(g, boost::uuids::nil_uuid()); ensure_equals("wrong ProjectId", h.GetProjectId(), g); ensure_equals("wrong VersionMajor", h.GetVersionMajor(), 1); ensure_equals("wrong VersionMinor", h.GetVersionMinor(), 0); ensure_equals("wrong GetSystemId", h.GetSystemId(), std::string("")); ensure_equals("wrong GetSoftwareId", h.GetSoftwareId(), std::string("TerraScan")); ensure_equals("Wrong GetCreationDOY", h.GetCreationDOY(), 0); ensure_equals("Wrong GetCreationYear", h.GetCreationYear(), 0); ensure_equals("Wrong GetHeaderSize", h.GetHeaderSize(), boost::uint16_t(227)); ensure_equals("Wrong GetDataOffset", h.GetDataOffset(), boost::uint32_t(229)); ensure_equals("Wrong GetRecordsCount", h.GetRecordsCount(), boost::uint32_t(0)); ensure_equals("Wrong GetDataFormatId", h.GetDataFormatId(), liblas::ePointFormat1); ensure_equals("Wrong GetDataRecordLength", h.GetDataRecordLength(), liblas::ePointSize1); ensure_equals("Wrong GetPointRecordsCount", h.GetPointRecordsCount(), boost::uint32_t(8)); ensure_equals("Wrong GetScaleX", h.GetScaleX(), double(0.01)); ensure_equals("Wrong GetScaleY", h.GetScaleY(), double(0.01)); ensure_equals("Wrong GetScaleZ", h.GetScaleZ(), double(0.01)); ensure_equals("Wrong GetOffsetX", h.GetOffsetX(),double(-0)); ensure_equals("Wrong GetOffsetY", h.GetOffsetY(), double(-0)); ensure_equals("Wrong GetOffsetZ", h.GetOffsetZ(), double(-0)); ensure_equals("Wrong GetMinX", h.GetMinX(), double(630262.3)); ensure_equals("Wrong GetMaxX", h.GetMaxX(), double(630346.83)); ensure_equals("Wrong GetMinY", h.GetMinY(), double(4834500)); ensure_equals("Wrong GetMaxY", h.GetMaxY(), double(4834500)); ensure_equals("Wrong GetMinZ", h.GetMinZ(), double(50.9)); ensure_equals("Wrong GetMaxZ", h.GetMaxZ(), double(55.26)); } void test_file10_point1(liblas::Point const& p) { ensure_distance(p.GetX(), double(630262.30), 0.0001); ensure_distance(p.GetY(), double(4834500), 0.0001); ensure_distance(p.GetZ(), double(51.53), 0.0001); ensure_equals(p.GetIntensity(), 670); ensure_equals(p.GetClassification(), liblas::Classification::bitset_type(1)); ensure_equals(p.GetScanAngleRank(), 0); ensure_equals(p.GetUserData(), 3); ensure_equals(p.GetPointSourceID(), 0); ensure_equals(p.GetScanFlags(), 9); ensure_distance(p.GetTime(), double(413665.23360000004), 0.0001); } void test_file10_point2(liblas::Point const& p) { ensure_distance(p.GetX(), double(630282.45), 0.0001); ensure_distance(p.GetY(), double(4834500), 0.0001); ensure_distance(p.GetZ(), double(51.63), 0.0001); ensure_equals(p.GetIntensity(), 350); ensure_equals(p.GetClassification(), liblas::Classification::bitset_type(1)); ensure_equals(p.GetScanAngleRank(), 0); ensure_equals(p.GetUserData(), 3); ensure_equals(p.GetPointSourceID(), 0); ensure_equals(p.GetScanFlags(), 9); ensure_distance(p.GetTime(), double(413665.52880000003), 0.0001); } void test_file10_point4(liblas::Point const& p) { ensure_distance(p.GetX(), double(630346.83), 0.0001); ensure_distance(p.GetY(), double(4834500), 0.0001); ensure_distance(p.GetZ(), double(50.90), 0.0001); ensure_equals(p.GetIntensity(), 150); ensure_equals(p.GetClassification(), liblas::Classification::bitset_type(1)); ensure_equals(p.GetScanAngleRank(), 0); ensure_equals(p.GetUserData(), 4); ensure_equals(p.GetPointSourceID(), 0); ensure_equals(p.GetScanFlags(), 18); ensure_distance(p.GetTime(), double(414093.84360000002), 0.0001); } void test_file_12Color_point0(liblas::Point const& p) { ensure_distance(p.GetX(), double(637012.240000), 0.0001); ensure_distance(p.GetY(), double(849028.310000), 0.0001); ensure_distance(p.GetZ(), double(431.660000), 0.0001); ensure_distance(p.GetTime(), double(245380.782550), 0.0001); ensure_equals(p.GetReturnNumber(), 1); ensure_equals(p.GetNumberOfReturns(), 1); ensure_equals(p.GetFlightLineEdge(), 0); ensure_equals(p.GetIntensity(), 143); ensure_equals(p.GetScanDirection(), 1); ensure_equals(p.GetScanAngleRank(), -9); ensure_equals(p.GetClassification().GetClass(), 1); ensure_equals(p.GetClassification().IsWithheld(), false); ensure_equals(p.GetClassification().IsKeyPoint(), false); ensure_equals(p.GetClassification().IsSynthetic(), false); ensure_equals(p.GetColor().GetRed(), 68); ensure_equals(p.GetColor().GetGreen(), 77); ensure_equals(p.GetColor().GetBlue(), 88); } void test_file_12Color_point1(liblas::Point const& p) { ensure_distance(p.GetX(), double(636896.330000), 0.0001); ensure_distance(p.GetY(), double(849087.700000), 0.0001); ensure_distance(p.GetZ(), double(446.390000), 0.0001); ensure_distance(p.GetTime(), double(245381.452799), 0.0001); ensure_equals(p.GetReturnNumber(), 1); ensure_equals(p.GetNumberOfReturns(), 2); ensure_equals(p.GetFlightLineEdge(), 0); ensure_equals(p.GetIntensity(), 18); ensure_equals(p.GetScanDirection(), 1); ensure_equals(p.GetScanAngleRank(), -11); ensure_equals(p.GetClassification().GetClass(), 1); ensure_equals(p.GetClassification().IsWithheld(), false); ensure_equals(p.GetClassification().IsKeyPoint(), false); ensure_equals(p.GetClassification().IsSynthetic(), false); ensure_equals(p.GetColor().GetRed(), 54); ensure_equals(p.GetColor().GetGreen(), 66); ensure_equals(p.GetColor().GetBlue(), 68); } void test_file_12Color_point2(liblas::Point const& p) { ensure_distance(p.GetX(), double(636784.740000), 0.0001); ensure_distance(p.GetY(), double(849106.660000), 0.0001); ensure_distance(p.GetZ(), double(426.710000), 0.0001); ensure_distance(p.GetTime(), double(245382.135950), 0.0001); ensure_equals(p.GetReturnNumber(), 1); ensure_equals(p.GetNumberOfReturns(), 1); ensure_equals(p.GetFlightLineEdge(), 0); ensure_equals(p.GetIntensity(), 118); ensure_equals(p.GetScanDirection(), 0); ensure_equals(p.GetScanAngleRank(), -10); ensure_equals(p.GetClassification().GetClass(), 1); ensure_equals(p.GetClassification().IsWithheld(), false); ensure_equals(p.GetClassification().IsKeyPoint(), false); ensure_equals(p.GetClassification().IsSynthetic(), false); ensure_equals(p.GetColor().GetRed(), 112); ensure_equals(p.GetColor().GetGreen(), 97); ensure_equals(p.GetColor().GetBlue(), 114); } void test_laszip_vlr(liblas::Header const& header) { bool found_vlr = false; std::vector<liblas::VariableRecord> const& vlrs = header.GetVLRs(); std::vector<liblas::VariableRecord>::const_iterator it; for (it = vlrs.begin(); it != vlrs.end(); ++it) { liblas::VariableRecord const& vlr = *it; if (vlr.GetUserId(false).compare("laszip encoded") == 0) { ensure_equals(found_vlr, false); // make sure we only find one found_vlr = true; ensure_equals(vlr.GetRecordId(), 22204); ensure_equals(vlr.GetRecordLength(), 52); } } ensure_equals(found_vlr, true); // make sure we found exactly one return; } }
#ifdef _PSP_VER #include "Vector3.h" #include <libvfpu.h> //--------------------Operators-----------------------// Vector3& Vector3::operator =(const Vector3 &rhs) { _vec.x = rhs.X(); _vec.y = rhs.Y(); _vec.z = rhs.Z(); return *this; } bool Vector3::operator ==(const Vector3 &rhs) { return ( _vec.x == rhs.X() && _vec.y == rhs.Y() && _vec.z == rhs.Z() ); } bool Vector3::operator !=(const Vector3 &rhs) { return !( _vec.x == rhs.X() && _vec.y == rhs.Y() && _vec.z == rhs.Z() ); } Vector3 Vector3::operator +(const Vector3 &rhs) const { Vector3 ret; sceVfpuVector3Add( &ret._vec, &_vec, &rhs._vec ); return ret; } Vector3& Vector3::operator +=(const Vector3 &rhs) { sceVfpuVector3Add( &_vec, &_vec, &rhs._vec ); return *this; } Vector3 Vector3::operator -(const Vector3 &rhs) const { Vector3 ret; sceVfpuVector3Sub( &ret._vec, &_vec, &rhs._vec ); return ret; } Vector3& Vector3::operator -=(const Vector3 &rhs) { sceVfpuVector3Sub( &_vec, &_vec, &rhs._vec ); return *this; } Vector3 Vector3::operator *(const float scalar) const { Vector3 ret; sceVfpuVector3Scale( &ret._vec, &_vec, scalar ); return ret; } Vector3& Vector3::operator *=(const float scalar) { sceVfpuVector3Scale( &_vec, &_vec, scalar ); return *this; } //---------------------End of Operators-----------------// //--------------Start of Arthmetric Method--------------// void Vector3::Add(const Vector3 &rhs) { sceVfpuVector3Add( &_vec, &_vec, &rhs._vec ); } void Vector3::Add(const Vector3 &vec1, const Vector3 &vec2, Vector3 &out) { sceVfpuVector3Add( &out._vec, &vec1._vec, &vec2._vec ); } void Vector3::Subtract(const Vector3 &rhs) { sceVfpuVector3Sub( &_vec, &_vec, &rhs._vec ); } void Vector3::Subtract(const Vector3 &vec1, const Vector3 &vec2, Vector3 &out) { sceVfpuVector3Sub( &out._vec, &vec1._vec, &vec2._vec ); } void Vector3::Multiply(const Vector3 &rhs) { sceVfpuVector3Mul( &_vec, &_vec, &rhs._vec ); } void Vector3::Multiply(const Vector3 &vec1, const Vector3 &vec2, Vector3 &out) { sceVfpuVector3Mul( &out._vec, &vec1._vec, &vec2._vec ); } void Vector3::Multiply(float scalar) { sceVfpuVector3Scale( &_vec, &_vec, scalar ); } void Vector3::Multiply(float scalar, Vector3 &in, Vector3 &out) { sceVfpuVector3Scale( &out._vec, &in._vec, scalar ); } void Vector3::Divide(const Vector3 &rhs) { sceVfpuVector3Div( &_vec, &_vec, &rhs._vec ); } void Vector3::Divide(const Vector3 &vec1, const Vector3 &vec2, Vector3 &out) { sceVfpuVector3Div( &out._vec, &vec1._vec, &vec2._vec ); } //----------------End of Arthmetric Method--------------// //----------------Start of Vector Operations--------------// float Vector3::DotProduct(const Vector3 &rhs) { return sceVfpuVector3InnerProduct( &_vec, &rhs._vec ); } float Vector3::DotProduct(const Vector3 &vec1, const Vector3 &vec2) { return sceVfpuVector3InnerProduct( &vec1._vec, &vec2._vec ); } Vector3 Vector3::CrossProduct(const Vector3 &rhs, const Vector3 &rhs2) { Vector3 ret; sceVfpuVector3OuterProduct( &ret._vec, &rhs._vec, &rhs2._vec ); return ret; } void Vector3::CrossProduct(const Vector3 &vec1, const Vector3 &vec2, Vector3 &out) { sceVfpuVector3OuterProduct( &out._vec, &vec1._vec, &vec2._vec ); } Vector3 Vector3::Lerp(Vector3 &start, Vector3 &end, float amount) { Vector3 ret; sceVfpuVector3Lerp( &ret._vec, &start._vec, &end._vec, amount ); return ret; } void Vector3::Lerp(Vector3 &start, Vector3 &end, float amount, Vector3 &out) { sceVfpuVector3Lerp( &out._vec, &start._vec, &end._vec, amount ); } float Vector3::MagnitudeSquare() { return ( _vec.x * _vec.x ) + ( _vec.y * _vec.y ) + ( _vec.z * _vec.z ); } float Vector3::MagnitudeSquare(const Vector3 &rhs) { return ( rhs._vec.x * rhs._vec.x ) + ( rhs._vec.y * rhs._vec.y ) + ( rhs._vec.z * rhs._vec.z ); } void Vector3::Normalize() { sceVfpuVector3Normalize( &_vec, &_vec ); } void Vector3::Normalize(const Vector3 &in, Vector3 &out) { sceVfpuVector3Normalize( &out._vec, &in._vec ); } //----------------end of Vector Operations--------------// #endif
// Created on: 1993-01-09 // Created by: CKY / Contract Toubro-Larsen ( TCD ) // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IGESDraw_DrawingWithRotation_HeaderFile #define _IGESDraw_DrawingWithRotation_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <IGESDraw_HArray1OfViewKindEntity.hxx> #include <TColgp_HArray1OfXY.hxx> #include <TColStd_HArray1OfReal.hxx> #include <IGESData_HArray1OfIGESEntity.hxx> #include <IGESData_IGESEntity.hxx> #include <Standard_Integer.hxx> class IGESData_ViewKindEntity; class gp_Pnt2d; class gp_XY; class gp_XYZ; class IGESDraw_DrawingWithRotation; DEFINE_STANDARD_HANDLE(IGESDraw_DrawingWithRotation, IGESData_IGESEntity) //! defines IGESDrawingWithRotation, Type <404> Form <1> //! in package IGESDraw //! //! Permits rotation, in addition to transformation and //! scaling, between the view and drawing coordinate systems class IGESDraw_DrawingWithRotation : public IGESData_IGESEntity { public: Standard_EXPORT IGESDraw_DrawingWithRotation(); //! This method is used to set the fields of the class //! DrawingWithRotation //! - allViews : Pointers to View entities //! - allViewOrigins : Origin coords of transformed views //! - allOrientationAngles : Orientation angles of transformed views //! - allAnnotations : Pointers to Annotation entities //! raises exception if Lengths of allViews, allViewOrigins and //! allOrientationAngles are not same. Standard_EXPORT void Init (const Handle(IGESDraw_HArray1OfViewKindEntity)& allViews, const Handle(TColgp_HArray1OfXY)& allViewOrigins, const Handle(TColStd_HArray1OfReal)& allOrientationAngles, const Handle(IGESData_HArray1OfIGESEntity)& allAnnotations); //! returns the number of view pointers in <me> Standard_EXPORT Standard_Integer NbViews() const; //! returns the View entity indicated by Index //! raises an exception if Index <= 0 or Index > NbViews(). Standard_EXPORT Handle(IGESData_ViewKindEntity) ViewItem (const Standard_Integer Index) const; //! returns the Drawing space coordinates of the origin of the //! Transformed view indicated by Index //! raises an exception if Index <= 0 or Index > NbViews(). Standard_EXPORT gp_Pnt2d ViewOrigin (const Standard_Integer Index) const; //! returns the Orientation angle for the Transformed view //! indicated by Index //! raises an exception if Index <= 0 or Index > NbViews(). Standard_EXPORT Standard_Real OrientationAngle (const Standard_Integer Index) const; //! returns the number of Annotation entities in <me> Standard_EXPORT Standard_Integer NbAnnotations() const; //! returns the Annotation entity in this Drawing, indicated by Index //! raises an exception if Index <= 0 or Index > NbAnnotations(). Standard_EXPORT Handle(IGESData_IGESEntity) Annotation (const Standard_Integer Index) const; Standard_EXPORT gp_XY ViewToDrawing (const Standard_Integer NumView, const gp_XYZ& ViewCoords) const; //! Returns the Drawing Unit Value if it is specified (by a //! specific property entity) //! If not specified, returns False, and val as zero : //! unit to consider is then the model unit in GlobalSection Standard_EXPORT Standard_Boolean DrawingUnit (Standard_Real& value) const; //! Returns the Drawing Size if it is specified (by a //! specific property entity) //! If not specified, returns False, and X,Y as zero : //! unit to consider is then the model unit in GlobalSection Standard_EXPORT Standard_Boolean DrawingSize (Standard_Real& X, Standard_Real& Y) const; DEFINE_STANDARD_RTTIEXT(IGESDraw_DrawingWithRotation,IGESData_IGESEntity) protected: private: Handle(IGESDraw_HArray1OfViewKindEntity) theViews; Handle(TColgp_HArray1OfXY) theViewOrigins; Handle(TColStd_HArray1OfReal) theOrientationAngles; Handle(IGESData_HArray1OfIGESEntity) theAnnotations; }; #endif // _IGESDraw_DrawingWithRotation_HeaderFile
#pragma once #include <pv/Exception.hh> #include <cstdarg> #include "visibility.h" namespace pv { class DSO_LOCAL Logger; class Logger { public: virtual ~Logger() = default; virtual void error(const Exception&) const noexcept = 0; virtual void error(const char *, int, unsigned int, const char * = "") const noexcept; virtual void debug(const char *, int, const char *, ...) const noexcept __attribute__((format(printf, 4, 5))); virtual void debug(const char *, int, const char *, va_list) const noexcept = 0; }; inline void Logger::error(const char *file, int line, unsigned int code, const char *args) const noexcept { error(Exception(file, line, code, "%s", args)); } inline void Logger::debug(const char *file, int line, const char *format, ...) const noexcept { va_list va; va_start(va, format); debug(file, line, format, va); va_end(va); } }
// // EventReceiver.hpp for event receiver in /home/deneub_s/cpp_indie_studio // // Made by Stanislas Deneubourg // Login <deneub_s@epitech.net> // // Started on Fri May 5 18:11:56 2017 Stanislas Deneubourg // Last update Fri May 5 18:19:34 2017 Stanislas Deneubourg // #ifndef EVENTRECEIVER_HPP #define EVENTRECEIVER_HPP #include "Dependencies/Dependencies.hpp" #include "Events/buttonState.hpp" #include "Events/EventStatus.hpp" #include "Events/MenuButton.hpp" class EventReceiver : public irr::IEventReceiver { public: struct SMouseState { bool LeftButtonDown; SMouseState(); } MouseState; explicit EventReceiver(irr::IrrlichtDevice *device, irrklang::ISoundEngine *soundEngine, irrklang::ISound *mainSound, bool *playMainSound); bool OnEvent(const irr::SEvent& event) override; virtual bool IsKeyDown(irr::EKEY_CODE keyCode) const; virtual bool IsKeyUp(irr::EKEY_CODE keyCode); // custom functions void setMenuInGameButtons(irr::gui::IGUITabControl *tabctrl); void setWeaponsButtons(irr::gui::IGUITabControl *tabctrl); EventStatus const &getEventStatus() const; void setMainButtonsHidden(); void setMainButtonsVisible(); void setWeaponId(size_t *); void setweaponIsSelected(bool *); EventReceiver &operator=(EventReceiver const &eventReceiver); protected: // ESSENTIALS bool KeyIsDown[irr::KEY_KEY_CODES_COUNT]; bool *playMainSound; buttonState KeyIsUp[irr::KEY_KEY_CODES_COUNT]; irr::gui::IGUIEnvironment *guienv; irr::video::IVideoDriver *driver; irr::IrrlichtDevice *device; irrklang::ISoundEngine *soundEngine; // BUTTONS irr::gui::IGUIButton *backToGameButton; irr::gui::IGUIButton *uziButton; irr::gui::IGUIButton *shotgunButton; irr::gui::IGUIButton *surrenderButton; irr::gui::IGUIButton *saintBombButton; irr::gui::IGUIButton *cordeButton; irr::gui::IGUIButton *issouButton; irr::gui::IGUIButton *saveCurrentGameButton; irr::gui::IGUIButton *soundOptionButton; irr::gui::IGUIButton *backToMenuButton; irr::gui::IGUIButton *exitGameButton; irr::gui::IGUIButton *soundCheckboxButton; irr::video::ITexture *soundCheckboxCheckedButton; irr::video::ITexture *soundCheckboxNotCheckedButton; bool isSoundCheckboxChecked; irr::gui::IGUIButton *backButton; irrklang::ISound *mainSound; // OTHER EventStatus eventStatus; size_t *idWeapon; bool *weaponIsSelected; }; #endif //EVENTRECEIVER_HPP
// Created on: 1997-09-22 // Created by: Roman BORISOV // Copyright (c) 1997-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _ProjLib_CompProjectedCurve_HeaderFile #define _ProjLib_CompProjectedCurve_HeaderFile #include <Adaptor2d_Curve2d.hxx> #include <Adaptor3d_Surface.hxx> #include <ProjLib_HSequenceOfHSequenceOfPnt.hxx> #include <ProjLib_Projector.hxx> #include <TColGeom_HArray1OfCurve.hxx> #include <TColGeom2d_HArray1OfCurve.hxx> #include <TColgp_HArray1OfPnt.hxx> #include <TColgp_HArray1OfPnt2d.hxx> #include <TColStd_HArray1OfBoolean.hxx> #include <TColStd_HArray1OfReal.hxx> #include <Geom_Curve.hxx> #include <Geom2d_Curve.hxx> #include <GeomAbs_Shape.hxx> #include <TColStd_Array1OfReal.hxx> #include <GeomAbs_CurveType.hxx> class gp_Pnt2d; class gp_Vec2d; class ProjLib_CompProjectedCurve : public Adaptor2d_Curve2d { DEFINE_STANDARD_RTTIEXT(ProjLib_CompProjectedCurve, Adaptor2d_Curve2d) public: Standard_EXPORT ProjLib_CompProjectedCurve(); //! try to find all solutions Standard_EXPORT ProjLib_CompProjectedCurve(const Handle(Adaptor3d_Surface)& S, const Handle(Adaptor3d_Curve)& C, const Standard_Real TolU, const Standard_Real TolV); //! this constructor tries to optimize the search using the //! assumption that maximum distance between surface and curve less or //! equal then MaxDist. //! if MaxDist < 0 then algorithm works as above. Standard_EXPORT ProjLib_CompProjectedCurve(const Handle(Adaptor3d_Surface)& S, const Handle(Adaptor3d_Curve)& C, const Standard_Real TolU, const Standard_Real TolV, const Standard_Real MaxDist); //! this constructor tries to optimize the search using the //! assumption that maximum distance between surface and curve less or //! equal then MaxDist. //! if MaxDist < 0 then algorithm try to find all solutions //! Tolerances of parameters are calculated automatically. Standard_EXPORT ProjLib_CompProjectedCurve(const Standard_Real Tol3d, const Handle(Adaptor3d_Surface)& S, const Handle(Adaptor3d_Curve)& C, const Standard_Real MaxDist = -1.0); //! Shallow copy of adaptor Standard_EXPORT virtual Handle(Adaptor2d_Curve2d) ShallowCopy() const Standard_OVERRIDE; //! computes a set of projected point and determine the //! continuous parts of the projected curves. The points //! corresponding to a projection on the bounds of the surface are //! included in this set of points. Standard_EXPORT void Init(); //! Performs projecting for given curve. //! If projecting uses approximation, //! approximation parameters can be set before by corresponding methods //! SetTol3d(...), SeContinuity(...), SetMaxDegree(...), SetMaxSeg(...) Standard_EXPORT void Perform(); //! Set the parameter, which defines 3d tolerance of approximation. Standard_EXPORT void SetTol3d(const Standard_Real theTol3d); //! Set the parameter, which defines curve continuity. //! Default value is GeomAbs_C2; Standard_EXPORT void SetContinuity(const GeomAbs_Shape theContinuity); //! Set max possible degree of result BSpline curve2d, which is got by approximation. //! If MaxDegree < 0, algorithm uses values that are chosen depending of types curve 3d //! and surface. Standard_EXPORT void SetMaxDegree(const Standard_Integer theMaxDegree); //! Set the parameter, which defines maximal value of parametric intervals the projected //! curve can be cut for approximation. If MaxSeg < 0, algorithm uses default //! value = 16. Standard_EXPORT void SetMaxSeg(const Standard_Integer theMaxSeg); //! Set the parameter, which defines necessity of 2d results. Standard_EXPORT void SetProj2d(const Standard_Boolean theProj2d); //! Set the parameter, which defines necessity of 3d results. Standard_EXPORT void SetProj3d(const Standard_Boolean theProj3d); //! Changes the surface. Standard_EXPORT void Load (const Handle(Adaptor3d_Surface)& S); //! Changes the curve. Standard_EXPORT void Load (const Handle(Adaptor3d_Curve)& C); Standard_EXPORT const Handle(Adaptor3d_Surface)& GetSurface() const; Standard_EXPORT const Handle(Adaptor3d_Curve)& GetCurve() const; Standard_EXPORT void GetTolerance (Standard_Real& TolU, Standard_Real& TolV) const; //! returns the number of continuous part of the projected curve Standard_EXPORT Standard_Integer NbCurves() const; //! returns the bounds of the continuous part corresponding to Index Standard_EXPORT void Bounds (const Standard_Integer Index, Standard_Real& Udeb, Standard_Real& Ufin) const; //! returns True if part of projection with number Index is a single point and writes its coordinates in P Standard_EXPORT Standard_Boolean IsSinglePnt (const Standard_Integer Index, gp_Pnt2d& P) const; //! returns True if part of projection with number Index is an u-isoparametric curve of input surface Standard_EXPORT Standard_Boolean IsUIso (const Standard_Integer Index, Standard_Real& U) const; //! returns True if part of projection with number Index is an v-isoparametric curve of input surface Standard_EXPORT Standard_Boolean IsVIso (const Standard_Integer Index, Standard_Real& V) const; //! Computes the point of parameter U on the curve. Standard_EXPORT gp_Pnt2d Value (const Standard_Real U) const Standard_OVERRIDE; //! Computes the point of parameter U on the curve. Standard_EXPORT void D0 (const Standard_Real U, gp_Pnt2d& P) const Standard_OVERRIDE; //! Computes the point of parameter U on the curve with its //! first derivative. //! Raised if the continuity of the current interval //! is not C1. Standard_EXPORT void D1 (const Standard_Real U, gp_Pnt2d& P, gp_Vec2d& V) const Standard_OVERRIDE; //! Returns the point P of parameter U, the first and second //! derivatives V1 and V2. //! Raised if the continuity of the current interval //! is not C2. Standard_EXPORT void D2 (const Standard_Real U, gp_Pnt2d& P, gp_Vec2d& V1, gp_Vec2d& V2) const Standard_OVERRIDE; //! The returned vector gives the value of the derivative for the //! order of derivation N. //! Raised if N < 1. //! Raised if N > 2. Standard_EXPORT gp_Vec2d DN (const Standard_Real U, const Standard_Integer N) const Standard_OVERRIDE; //! Returns the first parameter of the curve C //! which has a projection on S. Standard_EXPORT Standard_Real FirstParameter() const Standard_OVERRIDE; //! Returns the last parameter of the curve C //! which has a projection on S. Standard_EXPORT Standard_Real LastParameter() const Standard_OVERRIDE; //! Returns the Continuity used in the approximation. Standard_EXPORT GeomAbs_Shape Continuity() const Standard_OVERRIDE; //! Returns the number of intervals which define //! an S continuous part of the projected curve Standard_EXPORT Standard_Integer NbIntervals (const GeomAbs_Shape S) const Standard_OVERRIDE; //! Returns a curve equivalent of <me> between //! parameters <First> and <Last>. <Tol> is used to //! test for 2d points confusion. //! If <First> >= <Last> Standard_EXPORT Handle(Adaptor2d_Curve2d) Trim (const Standard_Real FirstParam, const Standard_Real LastParam, const Standard_Real Tol) const Standard_OVERRIDE; //! Returns the parameters corresponding to //! S discontinuities. //! //! The array must provide enough room to accommodate //! for the parameters. i.e. T.Length() > NbIntervals() Standard_EXPORT void Intervals (TColStd_Array1OfReal& T, const GeomAbs_Shape S) const Standard_OVERRIDE; //! returns the maximum distance between //! curve to project and surface Standard_EXPORT Standard_Real MaxDistance (const Standard_Integer Index) const; Standard_EXPORT const Handle(ProjLib_HSequenceOfHSequenceOfPnt)& GetSequence() const; //! Returns the type of the curve in the current //! interval : Line, Circle, Ellipse, Hyperbola, //! Parabola, BezierCurve, BSplineCurve, OtherCurve. Standard_EXPORT GeomAbs_CurveType GetType() const Standard_OVERRIDE; //! Returns true if result of projecting of the curve interval //! with number Index is point. Standard_EXPORT Standard_Boolean ResultIsPoint(const Standard_Integer theIndex) const; //! Returns the error of approximation of U parameter 2d-curve as a result //! projecting of the curve interval with number Index. Standard_EXPORT Standard_Real GetResult2dUApproxError(const Standard_Integer theIndex) const; //! Returns the error of approximation of V parameter 2d-curve as a result //! projecting of the curve interval with number Index. Standard_EXPORT Standard_Real GetResult2dVApproxError(const Standard_Integer theIndex) const; //! Returns the error of approximation of 3d-curve as a result //! projecting of the curve interval with number Index. Standard_EXPORT Standard_Real GetResult3dApproxError(const Standard_Integer theIndex) const; //! Returns the resulting 2d-curve of projecting //! of the curve interval with number Index. Standard_EXPORT Handle(Geom2d_Curve) GetResult2dC(const Standard_Integer theIndex) const; //! Returns the resulting 3d-curve of projecting //! of the curve interval with number Index. Standard_EXPORT Handle(Geom_Curve) GetResult3dC(const Standard_Integer theIndex) const; //! Returns the resulting 2d-point of projecting //! of the curve interval with number Index. Standard_EXPORT gp_Pnt2d GetResult2dP(const Standard_Integer theIndex) const; //! Returns the resulting 3d-point of projecting //! of the curve interval with number Index. Standard_EXPORT gp_Pnt GetResult3dP(const Standard_Integer theIndex) const; //! Returns the parameter, which defines necessity of only 2d results. Standard_Boolean GetProj2d() const { return myProj2d; } //! Returns the parameter, which defines necessity of only 3d results. Standard_Boolean GetProj3d() const { return myProj3d; } private: //! This method performs check possibility of optimization traps and tries to go out from them. //@return thePoint - input / corrected point. Standard_EXPORT void UpdateTripleByTrapCriteria(gp_Pnt &thePoint) const; Standard_EXPORT void BuildIntervals (const GeomAbs_Shape S) const; private: Handle(Adaptor3d_Surface) mySurface; Handle(Adaptor3d_Curve) myCurve; Standard_Integer myNbCurves; Handle(ProjLib_HSequenceOfHSequenceOfPnt) mySequence; Handle(TColStd_HArray1OfBoolean) myUIso; Handle(TColStd_HArray1OfBoolean) myVIso; Handle(TColStd_HArray1OfBoolean) mySnglPnts; Handle(TColStd_HArray1OfReal) myMaxDistance; Handle(TColStd_HArray1OfReal) myTabInt; Standard_Real myTol3d; GeomAbs_Shape myContinuity; Standard_Integer myMaxDegree; Standard_Integer myMaxSeg; Standard_Boolean myProj2d; Standard_Boolean myProj3d; Standard_Real myMaxDist; Standard_Real myTolU; Standard_Real myTolV; Handle(TColStd_HArray1OfBoolean) myResultIsPoint; Handle(TColStd_HArray1OfReal) myResult2dUApproxError; Handle(TColStd_HArray1OfReal) myResult2dVApproxError; Handle(TColStd_HArray1OfReal) myResult3dApproxError; Handle(TColgp_HArray1OfPnt) myResult3dPoint; Handle(TColgp_HArray1OfPnt2d) myResult2dPoint; Handle(TColGeom_HArray1OfCurve) myResult3dCurve; Handle(TColGeom2d_HArray1OfCurve) myResult2dCurve; }; DEFINE_STANDARD_HANDLE(ProjLib_CompProjectedCurve, Adaptor2d_Curve2d) #endif // _ProjLib_CompProjectedCurve_HeaderFile
#ifndef _PCSORT_H_ #define _PCSORT_H_ template<class T> inline void swap(T *x,T *y){ T t; t=*x; *x=*y; *y=t; } template<class T> void Bubble(T *data,int n){ int i,j; for(i=0;i<n;i++){ for(j=i+1;j<n;j++){ if(data[j-1]>data[j]) swap(&data[j-1],&data[j]); } } } template<class T> void Selection(T *data,int n){ int i,j; for(i=0;i<n;i++){ for(j=i+1;j<n;j++){ if(data[i]>data[j]) swap(&data[i],&data[j]); } } } #endif //_PCSORT_H_
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<string> binaryTreePaths(TreeNode* root) { if(!root) return{}; vector<string> paths; getPath(root, "", paths); return paths; } void getPath(TreeNode* node, string str, vector<string>& paths){ str += to_string(node->val); if(node->left == NULL && node->right == NULL){ paths.push_back(str); }else{ str += "->"; if(node->left != NULL) getPath(node->left, str, paths); if(node->right != NULL) getPath(node->right, str, paths); } } };
#pragma once #include"Shaders.h" #include"VertexBuffer.h" #include"ConstantBuffer.h" #include"MovementComponent.h" #include"IndexBuffer.h" #include"Material.h" static const char* MODEL_PATH = "Models/"; static const char* ERROR_MODEL = "cube.obj"; class Model { enum class ModelFormat { ModelFormat_obj, ModelFormat_bff, ModelFormat_custom }; private: ID3D11Device* m_devicePtr; ID3D11DeviceContext* m_deviceContextPtr; VertexBuffer<Vertex> m_vertexBuffer; std::vector<Vertex> m_vertices; IndexBuffer m_indexBuffer; ImporterBFF::Manager* m_myManager; ModelFormat m_format; bool m_drawWithIndex; bool m_loaded; void loadOBJModel(bool async = false); void loadBffModel(bool async = false); public: Model(); void initForAsyncLoad(ID3D11Device* device, ID3D11DeviceContext* dContext, const char* modelFilePath, const MaterialData material, const wchar_t* texturePath = L""); void loadModelAsync(); void loadModel(ID3D11Device* device, ID3D11DeviceContext* dContext, const char* modelFilePath, const MaterialData material, const wchar_t* texturePath = L""); void initQuadModel(ID3D11Device* device, ID3D11DeviceContext* dContext, const MaterialData material, const std::wstring texturePath = L"", bool flipped = false); void initModelFromData(ID3D11Device* device, ID3D11DeviceContext* dContext, std::vector<Vertex> vertexVector, const MaterialData material, const std::wstring texturePath = L""); void printBffModel(const ModelBFF model) const; bool is_loaded() const; void draw(); DirectX::BoundingBox m_aabb; Material m_material; std::wstring m_texturePath; std::string m_modelPath; // Makes it easier to debug };
#include "StrLib.h" #include <stdio.h> #include <sstream> #include <string> int S2I(string & s, bool &check){ istringstream buffer(s); int i=0; if(buffer>>i) check = true; else check = false; return i; } string I2S(int i){ ostringstream buffer; buffer<<i; return buffer.str(); } string ReadString(FILE * const f){ strsize strLen = 0; fread(&strLen, sizeof(strsize), 1, f); char * buffer = new char[strLen+1]; if(buffer != NULL && strLen > 0) fread(buffer, sizeof(char), strLen, f); buffer[strLen] = '\0'; return string(buffer); } void WriteString(const string & str, FILE * const f){ strsize strLen = str.size(); fwrite(&strLen, sizeof(strsize), 1, f); if(strLen > 0) fwrite(str.c_str(), sizeof(char), strLen, f); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 2009 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ /** \file * * \brief Declare a memory policy manager class * * The memory policy manager class is used to controll how much memory * is used for what, and whether an allocation can be allowed or not. * The decisions about allocation/no allocation is typically taken * right before a system call would request more memory from the * system (through e.g. the \c OpMemory allocation porting interface). * * \author Morten Rolland, mortenro@opera.com */ #ifndef MEMORY_MANAGER_H #define MEMORY_MANAGER_H /** * \brief All allocation classes of interest * * This enumeration is used to identify allocation types, and tie * allocations into the accounting done in the \c OpMemoryManager class. * * Accounting may be important to certain projects, and for dynamically * keeping track of memory usage. * * The information for the classes MEMCLS_OP_SBRK and MEMCLS_OP_MMAP * will only be valid when the Opera emulation layer is used for * these functions, or the platform takes care to update these * values accordingly to what happens in the platform layer. * * The selftest accounts are only used by the selftests, and should * not be used for anything else. */ enum OpMemoryClass { MEMCLS_UNACCOUNTED = 0, ///< This class is not counted nor policied MEMCLS_DEFAULT, ///< If nothing else is better MEMCLS_OP_SBRK, ///< Allocations by op_sbrk() or by similar platform code MEMCLS_OP_MMAP, ///< Allocations by op_mmap() or by similar platform code MEMCLS_ECMASCRIPT_EXEC, ///< Ecmascript memory for native execution MEMCLS_REGEXP_EXEC, ///< Regexp memory for native execution #ifdef ENABLE_OPERA_MMAP_SEGMENT MEMCLS_MMAP_HEADER, ///< Default memory class for OpMmapSegment headers MEMCLS_MMAP_UNUSED, ///< Memory held by OpMmapSegment for possible reuse #endif #ifdef SELFTEST MEMCLS_SELFTEST1, ///< Used during selftests to verify correct accounting MEMCLS_SELFTEST2, ///< Used during selftests to verify correct accounting MEMCLS_SELFTEST3, ///< Used during selftests to verify correct accounting #endif MEMCLS_LAST ///< End marker to determine number of entries }; #ifdef ENABLE_MEMORY_MANAGER class OpMemoryManager { public: OpMemoryManager(void); BOOL Alloc(enum OpMemoryClass type, size_t size); void ForceAlloc(enum OpMemoryClass type, size_t); BOOL Transfer(enum OpMemoryClass src, enum OpMemoryClass dst, size_t size); void ForceTransfer(enum OpMemoryClass src, enum OpMemoryClass dst, size_t size); void Free(enum OpMemoryClass type, size_t); size_t GetTotal(void) { return total; } size_t GetTotal(enum OpMemoryClass type) { return allocated[type]; } void SetMax(size_t val) { total_max = val; } void SetMax(enum OpMemoryClass type, size_t val) { max[type] = val; } size_t GetMax(enum OpMemoryClass type) { return max[type]; } void Dump(void); private: size_t total; size_t total_max; size_t max[MEMCLS_LAST]; size_t allocated[MEMCLS_LAST]; }; #endif // ENABLE_MEMORY_MANAGER #endif // MEMORY_MANAGER_H
#include "core/pch.h" #ifdef MDEFONT_MODULE #ifdef MDF_FREETYPE_SUPPORT # ifdef MDF_FREETYPE_PCF_FONT_SUPPORT #include "modules/mdefont/mdf_ft_pcf_ext.h" #include "modules/unicode/unicode.h" static inline uint16 get_word(void* buf) { byte* byte_buf = static_cast<byte*>(buf); return static_cast<uint16>( *byte_buf << 8 ) | static_cast<uint16>( *(byte_buf+1) ); } static inline uint32 get_long(void* buf) { byte* byte_buf = static_cast<byte*>(buf); return static_cast<uint32>( *byte_buf << 24 ) | static_cast<uint32>( *(byte_buf+1) << 16 ) | static_cast<uint32>( *(byte_buf+2) << 8 ) | static_cast<uint32>( *(byte_buf+3) ); } static inline uint16 b2lendian(uint16 x) { return ((x & 0xff) << 8) | ((x & 0xff00) >> 8); } static inline uint32 b2lendian32(uint32 x) { return ((x & 0xff) << 24) | ((x & 0xff00) << 8) | ((x & 0xff0000) >> 8) | ((x & 0xff000000) >> 24); } struct toc_entry { void init(byte* buf) { type = b2lendian32(get_long(buf)); buf += 4; format = b2lendian32(get_long(buf)); buf += 4; size = b2lendian32(get_long(buf)); buf += 4; offset = b2lendian32(get_long(buf)); buf += 4; } int32 type; // Indicates which table int32 format; // See below, indicates how the data are formatted in the table int32 size; // In bytes int32 offset; // from start of file }; #define PCF_PROPERTIES (1<<0) #define PCF_ACCELERATORS (1<<1) #define PCF_METRICS (1<<2) #define PCF_BITMAPS (1<<3) #define PCF_INK_METRICS (1<<4) #define PCF_BDF_ENCODINGS (1<<5) #define PCF_SWIDTHS (1<<6) #define PCF_GLYPH_NAMES (1<<7) #define PCF_BDF_ACCELERATORS (1<<8) #define PCF_DEFAULT_FORMAT 0x00000000 #define PCF_INKBOUNDS 0x00000200 #define PCF_ACCEL_W_INKBOUNDS 0x00000100 #define PCF_COMPRESSED_METRICS 0x00000100 //returns false if no blockinfo was found static bool GetUnicodeBlockInfo(UnicodePoint ch, /* int start_block,*/ int &block_no, UnicodePoint &block_lowest, UnicodePoint &block_highest) { const uint32_t unicode_blocks[][2] = { {0x0000, 0x007F}, // Basic Latin {0x0080, 0x00FF}, // Latin-1 Supplement {0x0100, 0x017F}, // Latin Extended-A {0x0180, 0x024F}, // Latin Extended-B {0x0250, 0x02AF}, // IPA Extensions {0x02B0, 0x02FF}, // Spacing Modifier Letters {0x0300, 0x036F}, // Combining Diacritical Marks {0x0370, 0x03FF}, // Greek and Coptic {0x0400, 0x04FF}, // Cyrillic // 8 {0x0500, 0x052F}, // Cyrillic Supplement {0x0530, 0x058F}, // Armenian {0x0590, 0x05FF}, // Hebrew {0x0600, 0x06FF}, // Arabic // 12 {0x0700, 0x074F}, // Syriac {0x0750, 0x077F}, // Arabic Supplement {0x0780, 0x07BF}, // Thaana {0x0900, 0x097F}, // Devanagari {0x0980, 0x09FF}, // Bengali {0x0A00, 0x0A7F}, // Gurmukhi {0x0A80, 0x0AFF}, // Gujarati {0x0B00, 0x0B7F}, // Oriya // 20 {0x0B80, 0x0BFF}, // Tamil {0x0C00, 0x0C7F}, // Telugu {0x0C80, 0x0CFF}, // Kannada {0x0D00, 0x0D7F}, // Malayalam //24 {0x0D80, 0x0DFF}, // Sinhala {0x0E00, 0x0E7F}, // Thai // 26 {0x0E80, 0x0EFF}, // Lao {0x0F00, 0x0FFF}, // Tibetan {0x1000, 0x109F}, // Myanmar {0x10A0, 0x10FF}, // Georgian // 30 {0x1100, 0x11FF}, // Hangul Jamo {0x1200, 0x137F}, // Ethiopic {0x1380, 0x139F}, // Ethiopic Supplement {0x13A0, 0x13FF}, // Cherokee {0x1400, 0x167F}, // Unified Canadian Aboriginal Syllabics {0x1680, 0x169F}, // Ogham {0x16A0, 0x16FF}, // Runic {0x1700, 0x171F}, // Tagalog // 38 {0x1720, 0x173F}, // Hanunoo {0x1740, 0x175F}, // Buhid {0x1760, 0x177F}, // Tagbanwa // 41 {0x1780, 0x17FF}, // Khmer {0x1800, 0x18AF}, // Mongolian {0x1900, 0x194F}, // Limbu {0x1950, 0x197F}, // Tai Le // 45 {0x1980, 0x19DF}, // New Tai Lue {0x19E0, 0x19FF}, // Khmer Symbols {0x1A00, 0x1A1F}, // Buginese {0x1D00, 0x1D7F}, // Phonetic Extensions // 49 {0x1D80, 0x1DBF}, // Phonetic Extensions Supplement {0x1DC0, 0x1DFF}, // Combining Diacritical Marks Supplement {0x1E00, 0x1EFF}, // Latin Extended Additional // 52 {0x1F00, 0x1FFF}, // Greek Extended {0x2000, 0x206F}, // General Punctuation {0x2070, 0x209F}, // Superscripts and Subscripts // 55 {0x20A0, 0x20CF}, // Currency Symbols {0x20D0, 0x20FF}, // Combining Diacritical Marks for Symbols {0x2100, 0x214F}, // Letterlike Symbols {0x2150, 0x218F}, // Number Forms // 59 {0x2190, 0x21FF}, // Arrows {0x2200, 0x22FF}, // Mathematical Operators {0x2300, 0x23FF}, // Miscellaneous Technical {0x2400, 0x243F}, // Control Pictures // 63 {0x2440, 0x245F}, // Optical Character Recognition {0x2460, 0x24FF}, // Enclosed Alphanumerics {0x2500, 0x257F}, // Box Drawing {0x2580, 0x259F}, // Block Elements // 67 {0x25A0, 0x25FF}, // Geometric Shapes {0x2600, 0x26FF}, // Miscellaneous Symbols {0x2700, 0x27BF}, // Dingbats {0x27C0, 0x27EF}, // Miscellaneous Mathematical Symbols-A // 71 {0x27F0, 0x27FF}, // Supplemental Arrows-A {0x2800, 0x28FF}, // Braille Patterns {0x2900, 0x297F}, // Supplemental Arrows-B {0x2980, 0x29FF}, // Miscellaneous Mathematical Symbols-B // 75 {0x2A00, 0x2AFF}, // Supplemental Mathematical Operators {0x2B00, 0x2BFF}, // Miscellaneous Symbols and Arrows {0x2C00, 0x2C5F}, // Glagolitic {0x2C80, 0x2CFF}, // Coptic // 79 {0x2D00, 0x2D2F}, // Georgian Supplement {0x2D30, 0x2D7F}, // Tifinagh {0x2D80, 0x2DDF}, // Ethiopic Extended {0x2E00, 0x2E7F}, // Supplemental Punctuation // 83 {0x2E80, 0x2EFF}, // CJK Radicals Supplement {0x2F00, 0x2FDF}, // Kangxi Radicals {0x2FF0, 0x2FFF}, // Ideographic Description Characters {0x3000, 0x303F}, // CJK Symbols and Punctuation // 87 {0x3040, 0x309F}, // Hiragana {0x30A0, 0x30FF}, // Katakana {0x3100, 0x312F}, // Bopomofo {0x3130, 0x318F}, // Hangul Compatibility Jamo // 91 {0x3190, 0x319F}, // Kanbun {0x31A0, 0x31BF}, // Bopomofo Extended {0x31C0, 0x31EF}, // CJK Strokes {0x31F0, 0x31FF}, // Katakana Phonetic Extensions // 95 {0x3200, 0x32FF}, // Enclosed CJK Letters and Months {0x3300, 0x33FF}, // CJK Compatibility {0x3400, 0x4DBF}, // CJK Unified Ideographs Extension A {0x4DC0, 0x4DFF}, // Yijing Hexagram Symbols // 99 {0x4E00, 0x9FFF}, // CJK Unified Ideographs {0xA000, 0xA48F}, // Yi Syllables {0xA490, 0xA4CF}, // Yi Radicals {0xA700, 0xA71F}, // Modifier Tone Letters // 103 {0xA800, 0xA82F}, // Syloti Nagri {0xAC00, 0xD7AF}, // Hangul Syllables {0xD800, 0xDB7F}, // High Surrogates {0xDB80, 0xDBFF}, // High Private Use Surrogates // 107 {0xDC00, 0xDFFF}, // Low Surrogates {0xE000, 0xF8FF}, // Private Use Area {0xF900, 0xFAFF}, // CJK Compatibility Ideographs {0xFB00, 0xFB4F}, // Alphabetic Presentation Forms // 111 {0xFB50, 0xFDFF}, // Arabic Presentation Forms-A {0xFE00, 0xFE0F}, // Variation Selectors {0xFE10, 0xFE1F}, // Vertical Forms {0xFE20, 0xFE2F}, // Combining Half Marks // 115 {0xFE30, 0xFE4F}, // CJK Compatibility Forms {0xFE50, 0xFE6F}, // Small Form Variants {0xFE70, 0xFEFF}, // Arabic Presentation Forms-B {0xFF00, 0xFFEF}, // Halfwidth and Fullwidth Forms // 119 {0xFFF0, 0xFFFF}, // Specials {0x10000, 0x1007F}, // Linear B Syllabary {0x10080, 0x100FF}, // Linear B Ideograms {0x10100, 0x1013F}, // Aegean Numbers // 123 {0x10140, 0x1018F}, // Ancient Greek Numbers {0x10300, 0x1032F}, // Old Italic {0x10330, 0x1034F}, // Gothic {0x10380, 0x1039F}, // Ugaritic {0x103A0, 0x103DF}, // Old Persian {0x10400, 0x1044F}, // Deseret // 129 {0x10450, 0x1047F}, // Shavian {0x10480, 0x104AF}, // Osmanya {0x10800, 0x1083F}, // Cypriot Syllabary {0x10A00, 0x10A5F}, // Kharoshthi {0x1D000, 0x1D0FF}, // Byzantine Musical Symbols {0x1D100, 0x1D1FF}, // Musical Symbols // 135 {0x1D200, 0x1D24F}, // Ancient Greek Musical Notation {0x1D300, 0x1D35F}, // Tai Xuan Jing Symbols {0x1D400, 0x1D7FF}, // Mathematical Alphanumeric Symbols {0x20000, 0x2A6DF}, // CJK Unified Ideographs Extension B // 139 {0x2F800, 0x2FA1F}, // CJK Compatibility Ideographs Supplement {0xE0000, 0xE007F}, // Tags {0xE0100, 0xE01EF}, // Variation Selectors Supplement {0xF0000, 0xFFFFF}, // Supplementary Private Use Area-A // 143 {0x100000, 0x10FFFF}, // Supplementary Private Use Area-B {0xFFFFFF, 0xFFFFFF} //End }; const int rangemapping[][8] = { {0, -1}, // Basic Latin {1, -1}, // Latin-1 Supplement {2, -1}, // Latin Extended-A {3, -1}, // Latin Extended-B {4, -1}, // IPA Extensions {5, -1}, // Spacing Modifier Letters {6, -1}, // Combining Diacritical Marks {7, -1}, // Greek and Coptic {-1}, // Reserved for Unicode SubRanges {8, // Cyrillic 9, -1}, // Cyrillic Supplementary {10, -1}, // Armenian {11, -1}, // Hebrew {-1}, // Reserved for Unicode SubRanges {12, -1}, // Arabic {-1}, // Reserved for Unicode SubRanges {16, -1}, // Devanagari {17, -1}, // Bengali {18, -1}, // Gurmukhi {19, -1}, // Gujarati {20, -1}, // Oriya {21, -1}, // Tamil {22, -1}, // Telugu {23, -1}, // Kannada {24, -1}, // Malayalam {26, -1}, // Thai {27, -1}, // Lao {30, -1}, // Georgian {-1}, // Reserved for Unicode SubRanges {31, -1}, // Hangul Jamo {52, -1}, // Latin Extended Additional {53, -1}, // Greek Extended {54, -1}, // General Punctuation {55, -1}, // Superscripts And Subscripts {56, -1}, // Currency Symbols {57, -1}, // Combining Diacritical Marks For Symbols {58, -1}, // Letterlike Symbols {59, -1}, // Number Forms {60, // Arrows 72, // Supplemental Arrows-A 74, -1}, // Supplemental Arrows-B {61, // Mathematical Operators 76, // Supplemental Mathematical Operators 71, // Miscellaneous Mathematical Symbols-A 75, -1}, // Miscellaneous Mathematical Symbols-B {62, -1}, // Miscellaneous Technical {63, -1}, // Control Pictures {64, -1}, // Optical Character Recognition {65, -1}, // Enclosed Alphanumerics {66, -1}, // Box Drawing {67, -1}, // Block Elements {68, -1}, // Geometric Shapes {69, -1}, // Miscellaneous Symbols {70, -1}, // Dingbats {87, -1}, // CJK Symbols And Punctuation {88, -1}, // Hiragana {89, // Katakana 95, -1}, // Katakana Phonetic Extensions {90, // Bopomofo 93, -1}, // Bopomofo Extended {91, -1}, // Hangul Compatibility Jamo {-1}, // Reserved for Unicode SubRanges {96, -1}, // Enclosed CJK Letters And Months {97, -1}, // CJK Compatibility {105, -1},// Hangul Syllables {-1}, // Non-Plane 0 * (subrange) {-1}, // Reserved for Unicode SubRanges {100, // CJK Unified Ideographs 84, // CJK Radicals Supplement 85, // Kangxi Radicals 86, // Ideographic Description Characters 98, // CJK Unified Ideograph Extension A 139, // CJK Unified Ideographs Extension B 92, -1}, // Kanbun {109, -1}, // Private Use Area {110, // CJK Compatibility Ideographs 140, -1}, // CJK Compatibility Ideographs Supplement {111, -1}, // Alphabetic Presentation Forms {112, -1}, // Arabic Presentation Forms-A {115, -1}, // Combining Half Marks {116, -1}, // CJK Compatibility Forms {117, -1}, // Small Form Variants {118, -1}, // Arabic Presentation Forms-B {119, -1}, // Halfwidth And Fullwidth Forms {120, -1}, // Specials {28, -1}, // Tibetan {13, -1}, // Syriac {15, -1}, // Thaana {25, -1}, // Sinhala {29, -1}, // Myanmar {32, -1}, // Ethiopic {34, -1}, // Cherokee {35, -1}, // Unified Canadian Aboriginal Syllabics {36, -1}, // Ogham {37, -1}, // Runic {42, -1}, // Khmer {43, -1}, // Mongolian {73, -1}, // Braille Patterns {101, // Yi Syllables 102, -1}, // Yi Radicals {38, -1}, // Tagalog {39, // Hanunoo 40, // Buhid 41, -1}, // Tagbanwa {125, -1}, // Old Italic {126, -1}, // Gothic {129, -1}, // Deseret {134, // Byzantine Musical Symbols 135, -1}, // Musical Symbols {138, -1}, // Mathematical Alphanumeric Symbols {-1, // Private Use (plane 15) -1},// Private Use (plane 16) {113, -1}, // Variation Selectors {141, -1}, // Tags {-1},// 93-127 Reserved for Unicode SubRanges {-1000} // End }; int range_idx = 0; while (true) { for (int sub=0; ;++sub) { int block_idx = rangemapping[range_idx][sub]; if (block_idx == -1) break; if (block_idx == -1000) { return false; } uint32_t block_start = unicode_blocks[ block_idx ][0]; uint32_t block_end = unicode_blocks[ block_idx ][1]; if ( block_start <= ch && ch <= block_end ) { block_no = range_idx; block_lowest = block_start; block_highest = block_end; return true; } } ++range_idx; } } //This class holds an FT_Stream and buffers the data. //Used to be able to read data from gzipped pcf font files. class FontTableStream { public: explicit FontTableStream(FT_Stream stream, int initial_buf_size = 128) : m_stream(stream), m_buf(NULL), m_bytes_read(0), m_buf_start(0), m_font_table_max_size(initial_buf_size) {} ~FontTableStream() { if (m_stream->read) { OP_DELETEA(m_buf); } } //Second phase constructor. Must be used. OP_STATUS Construct() { // If the read function is not NULL we haven to read // and buffer, otherwise the stream is already buffered // in m_stream->base. if (m_stream->read) { m_buf = OP_NEWA(byte, m_font_table_max_size ); } else { m_buf = m_stream->base; } return m_buf ? OpStatus::OK : OpStatus::ERR_NO_MEMORY; } byte* seek_and_buffer(int offset, int nr_of_bytes); private: //Standard procedure FontTableStream(const FontTableStream&); FontTableStream& operator=(const FontTableStream&); FT_Stream m_stream; byte* m_buf; int m_bytes_read; //The actual number off buffered bytes. int m_buf_start; //Offset from start of stream int m_font_table_max_size; //Buffer max size }; //Seek to the offset in stream. nr_of_bytes is the number of bytes the //caller will/can read from the returned pointer. byte* FontTableStream::seek_and_buffer(int offset, int nr_of_bytes) { int requested_end = offset + nr_of_bytes; if (m_stream->read) { if (nr_of_bytes > m_font_table_max_size) { m_font_table_max_size = nr_of_bytes; OP_DELETEA(m_buf); m_buf = OP_NEWA(byte, m_font_table_max_size ); if (!m_buf) { return NULL; } } int available_end = m_buf_start + m_bytes_read; if (nr_of_bytes != 0 && (offset < m_buf_start || available_end < requested_end) ) { m_buf_start = offset; m_bytes_read = m_stream->read(m_stream, m_buf_start, m_buf, m_font_table_max_size ); if (m_bytes_read < nr_of_bytes) { return NULL; } } } else if (m_stream->size < requested_end) { return NULL; } byte* return_ptr = m_buf + offset - m_buf_start; return return_ptr; } //Freetype does not supply unicode ranges for pcf files. bool GetPcfUnicodeRanges(const FT_Face& face, unsigned int ranges[4]) { const int PREL_SIZE_OF_GLYPHIDX_TAB = 128512; FontTableStream table_stream(face->stream, PREL_SIZE_OF_GLYPHIDX_TAB); OP_STATUS status = table_stream.Construct(); if (OpStatus::IsError(status)) { return false; } int buf_pos = 0; byte* buf_ptr = table_stream.seek_and_buffer(buf_pos, 4); if (buf_ptr == NULL) { return false; } uint32 header = get_long(buf_ptr); if ( header != FT_MAKE_TAG('\1', 'f', 'c', 'p') ) { //No PCF bitmap font return false; } buf_pos +=4; buf_ptr = table_stream.seek_and_buffer(buf_pos, 4); if (buf_ptr == NULL) { return false; } int32 table_count = b2lendian32(get_long(buf_ptr)); buf_pos += 4; for ( int i = 0; i < table_count; ++i ) { buf_ptr = table_stream.seek_and_buffer(buf_pos, 16); if (buf_ptr == NULL) { return false; } buf_pos += 16; toc_entry table; table.init(buf_ptr); if ( table.type == PCF_BDF_ENCODINGS ) { int enc_pos = table.offset; byte* enc_tab = table_stream.seek_and_buffer(enc_pos, 14); if (enc_tab == NULL) { return false; } enc_pos += 14; enc_tab +=4; //format int16 min_char_or_byte2 = get_word(enc_tab); enc_tab += 2; int16 max_char_or_byte2 = get_word(enc_tab); enc_tab +=2; int16 min_byte1 = get_word(enc_tab); enc_tab +=2; int16 max_byte1 = get_word(enc_tab); enc_tab +=2; int16 default_char = get_word(enc_tab); enc_tab +=2; //ranges[4] = {0, 0, 0, 0}; int nr_of_indeces = (max_char_or_byte2-min_char_or_byte2+1)*(max_byte1-min_byte1+1); byte* glyph_indeces = table_stream.seek_and_buffer(enc_pos, nr_of_indeces*2); if (glyph_indeces == NULL) { return false; } for ( int16 enc1 = min_byte1; enc1 <= max_byte1; enc1++ ) { for (int16 enc2 = min_char_or_byte2; enc2 <= max_char_or_byte2; enc2++) { int enc_idx = (enc1-min_byte1)*(max_char_or_byte2-min_char_or_byte2+1) + enc2-min_char_or_byte2; uint16 glyph_idx = get_word(glyph_indeces + enc_idx*2); if (glyph_idx != 0xffff && glyph_idx != default_char) { UnicodePoint encoding = (enc1 << 8) | enc2; int block_no = 0; UnicodePoint block_lowest = 0; UnicodePoint block_highest = 0; BOOL block_found = GetUnicodeBlockInfo(encoding, block_no, block_lowest, block_highest); if (block_found) { if (block_no < 32) ranges[0] |= (1 << block_no); else if (32 <= block_no && block_no < 64) ranges[1] |= 1 << (block_no-32); else if (64 <= block_no && block_no < 96) ranges[2] |= 1 << (block_no-64); else if (96 <= block_no && block_no < 128) ranges[3] |= 1 << (block_no-96); } } } } } } return true; } void GetPcfMetrics(FT_Face& face) { FontTableStream table_stream(face->stream, 20); OP_STATUS status = table_stream.Construct(); if (OpStatus::IsError(status)) { return; } int buf_pos = 4; //Skip header byte* buf_ptr = table_stream.seek_and_buffer(buf_pos, 4); if (buf_ptr == NULL) { return; } int32 table_count = b2lendian32(get_long(buf_ptr)); buf_pos += 4; for ( int i = 0; i < table_count; ++i ) { buf_ptr = table_stream.seek_and_buffer(buf_pos, 16); if (buf_ptr == NULL) { return; } buf_pos += 16; toc_entry table; table.init(buf_ptr); if ( table.type == PCF_BDF_ACCELERATORS ) { byte* accel_tab = table_stream.seek_and_buffer(table.offset, 20); if (accel_tab == NULL) { return; } accel_tab += 12; face->size->metrics.ascender = get_long(accel_tab); accel_tab += 4; face->size->metrics.descender = get_long(accel_tab); accel_tab +=4; break; } } } bool IsPcfFont(const FT_Face& face) { FontTableStream table_stream(face->stream, 4); OP_STATUS status = table_stream.Construct(); if (OpStatus::IsError(status)) { return false; } int buf_pos = 0; byte* buf_ptr = table_stream.seek_and_buffer(buf_pos, 4); if (buf_ptr == NULL) { return false; } uint32 header = get_long(buf_ptr); if ( header != FT_MAKE_TAG('\1', 'f', 'c', 'p') ) { //No PCF bitmap font return false; } return true; } # endif // MDF_FREETYPE_PCF_FONT_SUPPORT #endif // MDF_FREETYPE_SUPPORT #endif // MDEFONT_MODULE
#include "Firebase_Client_Version.h" #if !FIREBASE_CLIENT_VERSION_CHECK(40319) #error "Mixed versions compilation." #endif /** * * This library supports Espressif ESP8266, ESP32 and Raspberry Pi Pico (RP2040) * * Created July 20, 2023 * * This work is a part of Firebase ESP Client library * Copyright (c) 2023 K. Suwatchai (Mobizt) * * The MIT License (MIT) * Copyright (c) 2023 K. Suwatchai (Mobizt) * * * Permission is hereby granted, free of charge, to any person returning a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FB_UTILS_H #define FB_UTILS_H #include <Arduino.h> #include "mbfs/MB_MCU.h" #include "FirebaseFS.h" #include <Arduino.h> #include "FB_Const.h" #if defined(ESP8266) #include <Schedule.h> #endif #if defined(ESP8266) #if __has_include(<core_esp8266_version.h>) #include <core_esp8266_version.h> #endif #endif using namespace mb_string; #define stringPtr2Str(p) (MB_String().appendPtr(p).c_str()) namespace Utils { inline void idle() { #if defined(ARDUINO_ESP8266_MAJOR) && defined(ARDUINO_ESP8266_MINOR) && defined(ARDUINO_ESP8266_REVISION) && ((ARDUINO_ESP8266_MAJOR == 3 && ARDUINO_ESP8266_MINOR >= 1) || ARDUINO_ESP8266_MAJOR > 3) esp_yield(); #else delay(0); #endif } }; namespace MemoryHelper { template <typename T> inline T createBuffer(MB_FS *mbfs, size_t size, bool clear = true) { return reinterpret_cast<T>(mbfs->newP(size, clear)); } template <typename T> inline T creatDownloadBuffer(MB_FS *mbfs, int &bufLen, bool clear = false) { if (bufLen < 512) bufLen = 512; if (bufLen > 1024 * 16) bufLen = 1024 * 16; return createBuffer<T>(mbfs, bufLen, clear); } inline void freeBuffer(MB_FS *mbfs, void *ptr) { mbfs->delP(&ptr); } }; namespace StringHelper { inline int strpos(const char *haystack, const char *needle, int offset) { if (!haystack || !needle) return -1; int hlen = strlen(haystack); int nlen = strlen(needle); if (hlen == 0 || nlen == 0) return -1; int hidx = offset, nidx = 0; while ((*(haystack + hidx) != '\0') && (*(needle + nidx) != '\0') && hidx < hlen) { if (*(needle + nidx) != *(haystack + hidx)) { hidx++; nidx = 0; } else { nidx++; hidx++; if (nidx == nlen) return hidx - nidx; } } return -1; } inline size_t getReservedLen(MB_FS *mbfs, size_t len) { return mbfs->getReservedLen(len); } inline void splitString(const MB_String &str, MB_VECTOR<MB_String> out, const char delim) { size_t current = 0, previous = 0; current = str.find(delim, 0); MB_String s; while (current != MB_String::npos) { s.clear(); str.substr(s, previous, current - previous); s.trim(); if (s.length() > 0) out.push_back(s); previous = current + 1; current = str.find(delim, previous); } s.clear(); if (previous > 0 && current == MB_String::npos) str.substr(s, previous, str.length() - previous); else s = str; s.trim(); if (s.length() > 0) out.push_back(s); s.clear(); } inline void pushTk(const MB_String &str, MB_VECTOR<MB_String> &tk) { MB_String s = str; s.trim(); if (s.length() > 0) tk.push_back(s); } inline void splitTk(const MB_String &str, MB_VECTOR<MB_String> &tk, const char *delim) { size_t current, previous = 0; current = str.find(delim, previous); while (current != MB_String::npos) { pushTk(str.substr(previous, current - previous), tk); previous = current + strlen(delim); current = str.find(delim, previous); } pushTk(str.substr(previous, current - previous), tk); } inline bool find(const MB_String &src, PGM_P token, bool last, size_t offset, int &pos) { size_t ret = last ? src.find_last_of(pgm2Str(token), offset) : src.find(pgm2Str(token), offset); if (ret != MB_String::npos) { pos = ret; return true; } pos = -1; return false; } inline bool compare(const MB_String &src, int ofs, PGM_P token, bool caseInSensitive = false) { MB_String copy; src.substr(copy, ofs, strlen_P(token)); return caseInSensitive ? (strcasecmp(pgm2Str(token), copy.c_str()) == 0) : (strcmp(pgm2Str(token), copy.c_str()) == 0); } /* convert string to boolean */ inline bool str2Bool(const MB_String &v) { return v.length() > 0 && strcmp(v.c_str(), pgm2Str(fb_esp_pgm_str_20 /* "true" */)) == 0; } inline MB_String intStr2Str(const MB_String &v) { return MB_String(atoi(v.c_str())); } inline MB_String boolStr2Str(const MB_String &v) { return MB_String(str2Bool(v.c_str())); } inline bool tokenSubString(const MB_String &src, MB_String &out, PGM_P token1, PGM_P token2, int &ofs1, int ofs2, bool advanced) { size_t pos1 = src.find(pgm2Str(token1), ofs1); size_t pos2 = MB_String::npos; int len1 = strlen_P(token1); int len2 = 0; if (pos1 != MB_String::npos) { if (ofs2 > 0) pos2 = ofs2; else if (ofs2 == 0) { len2 = strlen_P(token2); pos2 = src.find(pgm2Str(token2), pos1 + len1 + 1); } else if (ofs2 == -1) ofs1 = pos1 + len1; if (pos2 == MB_String::npos) pos2 = src.length(); if (pos2 != MB_String::npos) { // advanced the begin position before return if (advanced) ofs1 = pos2 + len2; out = src.substr(pos1 + len1, pos2 - pos1 - len1); return true; } } return false; } inline bool tokenSubStringInt(const MB_String &buf, int &out, PGM_P token1, PGM_P token2, int &ofs1, int ofs2, bool advanced) { MB_String s; if (tokenSubString(buf, s, token1, token2, ofs1, ofs2, advanced)) { out = atoi(s.c_str()); return true; } return false; } } namespace URLHelper { /* Append a parameter to URL */ inline bool addParam(MB_String &url, PGM_P key, const MB_String &val, bool &hasParam, bool allowEmptyValue = false) { if (!allowEmptyValue && val.length() == 0) return false; MB_String _key(key); if (!hasParam && _key[0] == '&') _key[0] = '?'; else if (hasParam && _key[0] == '?') _key[0] = '&'; if (_key[0] != '?' && _key[0] != '&') url += !hasParam ? fb_esp_pgm_str_7 /* "?" */ : fb_esp_pgm_str_8 /* "&" */; if (_key[_key.length() - 1] != '=' && _key.find('=') == MB_String::npos) _key += fb_esp_pgm_str_13; // "=" url += _key; url += val; hasParam = true; return true; } /* Append the comma separated tokens as URL parameters */ inline void addParamsTokens(MB_String &url, PGM_P key, MB_String val, bool &hasParam) { if (val.length() == 0) return; MB_VECTOR<MB_String> tk; StringHelper::splitTk(val, tk, ","); for (size_t i = 0; i < tk.size(); i++) addParam(url, key, tk[i], hasParam); } /* Append the path to URL */ inline void addPath(MB_String &url, const MB_String &path) { if (path.length() > 0) { if (path[0] != '/') url += fb_esp_pgm_str_1; // "/" } else url += fb_esp_pgm_str_1; // "/" url += path; } #if defined(FIREBASE_ESP_CLIENT) /* Append the string with google storage URL */ inline void addGStorageURL(MB_String &uri, const MB_String &bucketID, const MB_String &storagePath) { uri += fb_esp_pgm_str_21; // "gs://" uri += bucketID; if (storagePath[0] != '/') uri += fb_esp_pgm_str_1; // "/" uri += storagePath; } /* Append the string with cloudfunctions project host */ inline void addFunctionsHost(MB_String &uri, const MB_String &locationId, const MB_String &projectId, const MB_String &path, bool url) { #if defined(ENABLE_FB_FUNCTIONS) if (url) uri = fb_esp_pgm_str_22; // "https://" uri += locationId; uri += fb_esp_pgm_str_14; // "-" uri += projectId; uri += fb_esp_func_pgm_str_82; // ".cloudfunctions.net" if (path.length() > 0) { uri += fb_esp_pgm_str_1; // "/" uri += path; } #endif } inline void addGAPIv1Path(MB_String &uri) { uri += fb_esp_pgm_str_23; // "/v1/projects/" } inline void addGAPIv1beta1Path(MB_String &uri) { uri += fb_esp_pgm_str_24; // "/v1beta1/projects/" } #endif inline void host2Url(MB_String &url, MB_String &host) { url = fb_esp_pgm_str_22; // "https://" url += host; } inline void parse(MB_FS *mbfs, const MB_String &url, struct fb_esp_url_info_t &info) { char *host = MemoryHelper::createBuffer<char *>(mbfs, url.length()); char *uri = MemoryHelper::createBuffer<char *>(mbfs, url.length()); char *auth = MemoryHelper::createBuffer<char *>(mbfs, url.length()); int p1 = 0; int x = sscanf(url.c_str(), pgm2Str(fb_esp_pgm_str_25 /* "https://%[^/]/%s" */), host, uri); x ? p1 = 8 : x = sscanf(url.c_str(), pgm2Str(fb_esp_pgm_str_26 /* "http://%[^/]/%s" */), host, uri); x ? p1 = 7 : x = sscanf(url.c_str(), pgm2Str(fb_esp_pgm_str_27 /* "%[^/]/%s" */), host, uri); size_t p2 = 0; if (x > 0) { p2 = MB_String(host).find(pgm2Str(fb_esp_pgm_str_7 /* "?" */), 0); if (p2 != MB_String::npos) x = sscanf(url.c_str() + p1, pgm2Str(fb_esp_pgm_str_28 /* "%[^?]?%s" */), host, uri); } if (strlen(uri) > 0) { #if defined(ENABLE_RTDB) p2 = MB_String(uri).find(pgm2Str(fb_esp_rtdb_pgm_str_19 /* "auth=" */), 0); if (p2 != MB_String::npos) x = sscanf(uri + p2 + 5, pgm2Str(fb_esp_pgm_str_29 /* "%[^&]" */), auth); #endif } info.uri = uri; info.host = host; info.auth = auth; MemoryHelper::freeBuffer(mbfs, host); MemoryHelper::freeBuffer(mbfs, uri); MemoryHelper::freeBuffer(mbfs, auth); } inline void hexchar(char c, char &hex1, char &hex2) { hex1 = c / 16; hex2 = c % 16; hex1 += hex1 < 10 ? '0' : 'A' - 10; hex2 += hex2 < 10 ? '0' : 'A' - 10; } inline MB_String encode(const MB_String &s) { MB_String ret; ret.reserve(s.length() * 3 + 1); for (size_t i = 0, l = s.size(); i < l; i++) { char c = s[i]; if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '-' || c == '_' || c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')') { ret += c; } else { ret += '%'; char d1, d2; hexchar(c, d1, d2); ret += d1; ret += d2; } } ret.shrink_to_fit(); return ret; } }; namespace JsonHelper { /* check for the JSON path or key */ inline bool isJsonPath(PGM_P path) { return MB_String(path).find('/') != MB_String::npos; } inline bool parseChunk(MB_String &val, const MB_String &chunk, const MB_String &key, int &pos) { if (key.length() == 0) return false; MB_String token = fb_esp_pgm_str_4; // "\"" MB_String _key; if (key[0] != '"') _key += token; _key += key; if (key[key.length() - 1] != '"') _key += token; size_t p1 = chunk.find(_key, pos); if (p1 != MB_String::npos) { size_t p2 = chunk.find(MB_String(fb_esp_pgm_str_2 /* ":" */).c_str(), p1 + _key.length()); if (p2 != MB_String::npos) p2 = chunk.find(token, p2 + 1); if (p2 != MB_String::npos) { size_t p3 = chunk.find(token, p2 + token.length()); if (p3 != MB_String::npos) { pos = p3; val = chunk.substr(p2 + token.length(), p3 - p2 - token.length()); return true; } } } return false; } /* convert comma separated tokens into JSON Array and set/add to JSON object */ inline void addTokens(FirebaseJson *json, PGM_P key, const MB_String &tokens, const char *pre = "") { if (json && tokens.length() > 0) { FirebaseJsonArray arr; MB_VECTOR<MB_String> ta; StringHelper::splitTk(tokens, ta, ","); for (size_t i = 0; i < ta.size(); i++) { if (strlen(pre)) { MB_String s = pre; s += ta[i]; arr.add(s); } else arr.add(ta[i]); } if (ta.size() > 0) { if (isJsonPath(key)) json->set(pgm2Str(key), arr); else json->add(pgm2Str(key), arr); } } } inline bool addString(FirebaseJson *json, PGM_P key, const MB_String &val) { if (json && val.length() > 0) { if (isJsonPath(key)) json->set(pgm2Str(key), val); else json->add(pgm2Str(key), val); return true; } return false; } inline bool remove(FirebaseJson *json, PGM_P key) { if (json) return json->remove(pgm2Str(key)); return false; } inline void addString(FirebaseJson *json, PGM_P key, const MB_String &val, bool &flag) { if (addString(json, key, val)) flag = true; } inline void addBoolString(FirebaseJson *json, PGM_P key, const MB_String &val, bool &flag) { if (json && val.length() > 0) { if (isJsonPath(key)) json->set(pgm2Str(key), strcmp(val.c_str(), pgm2Str(fb_esp_pgm_str_20 /* "true" */)) == 0 ? true : false); else json->add(pgm2Str(key), strcmp(val.c_str(), pgm2Str(fb_esp_pgm_str_20 /* "true" */)) == 0 ? true : false); flag = true; } } inline void addArrayString(FirebaseJson *json, PGM_P key, const MB_String &val, bool &flag) { if (val.length() > 0) { static FirebaseJsonArray arr; arr.clear(); arr.setJsonArrayData(val); if (isJsonPath(key)) json->set(pgm2Str(key), arr); else json->add(pgm2Str(key), arr); flag = true; } } inline void addObject(FirebaseJson *json, PGM_P key, FirebaseJson *val, bool clearAfterAdded) { if (json) { FirebaseJson js; if (!val) val = &js; if (isJsonPath(key)) json->set(pgm2Str(key), *val); else json->add(pgm2Str(key), *val); if (clearAfterAdded && val) val->clear(); } } inline void addNumberString(FirebaseJson *json, PGM_P key, const MB_String &val) { if (json && val.length() > 0) { if (isJsonPath(key)) json->set(pgm2Str(key), atoi(val.c_str())); else json->add(pgm2Str(key), atoi(val.c_str())); } } inline void arrayAddObjectString(FirebaseJsonArray *arr, MB_String &val, bool clearAfterAdded) { if (arr && val.length() > 0) { FirebaseJson json(val); arr->add(json); if (clearAfterAdded) val.clear(); } } inline void arrayAddObject(FirebaseJsonArray *arr, FirebaseJson *val, bool clearAfterAdded) { if (arr && val) { arr->add(*val); if (clearAfterAdded) val->clear(); } } inline void addArray(FirebaseJson *json, PGM_P key, FirebaseJsonArray *val, bool clearAfterAdded) { if (json && val) { if (isJsonPath(key)) json->set(pgm2Str(key), *val); else json->add(pgm2Str(key), *val); if (clearAfterAdded) val->clear(); } } inline bool parse(FirebaseJson *json, FirebaseJsonData *result, PGM_P key) { bool ret = false; if (json && result) { result->clear(); json->get(*result, pgm2Str(key)); ret = result->success; } return ret; } inline bool setData(FirebaseJson *json, MB_String &val, bool clearAfterAdded) { bool ret = false; if (json && val.length() > 0) ret = json->setJsonData(val); if (clearAfterAdded) val.clear(); return ret; } inline void toString(FirebaseJson *json, MB_String &out, bool clearSource, bool prettify = false) { if (json) { out.clear(); json->toString(out, prettify); if (clearSource) json->clear(); } } inline void clear(FirebaseJson *json) { if (json) json->clear(); } inline void arrayClear(FirebaseJsonArray *arr) { if (arr) arr->clear(); } }; namespace HttpHelper { inline void addNewLine(MB_String &header) { header += fb_esp_pgm_str_30; // "\r\n" } inline void addGAPIsHost(MB_String &str, PGM_P sub) { str += sub; if (str[str.length() - 1] != '.') str += fb_esp_pgm_str_5; // "." str += fb_esp_pgm_str_31; // "googleapis.com" } inline void addGAPIsHostHeader(MB_String &header, PGM_P sub) { header += fb_esp_pgm_str_32; // "Host: " addGAPIsHost(header, sub); addNewLine(header); } inline void addHostHeader(MB_String &header, PGM_P host) { header += fb_esp_pgm_str_32; // "Host: " header += host; addNewLine(header); } inline void addContentTypeHeader(MB_String &header, PGM_P v) { header += fb_esp_pgm_str_33; // "Content-Type: " header += v; header += fb_esp_pgm_str_30; // "\r\n" } inline void addContentLengthHeader(MB_String &header, size_t len) { header += fb_esp_pgm_str_34; // "Content-Length: " header += len; addNewLine(header); } inline void addUAHeader(MB_String &header) { header += fb_esp_pgm_str_35; // "User-Agent: ESP\r\n" } inline void addConnectionHeader(MB_String &header, bool keepAlive) { header += keepAlive ? fb_esp_pgm_str_36 /* "Connection: keep-alive\r\n" */ : fb_esp_pgm_str_37 /* "Connection: close\r\n" */; } /* Append the string with first request line (HTTP method) */ inline bool addRequestHeaderFirst(MB_String &header, fb_esp_request_method method) { bool post = false; switch (method) { case http_get: header += fb_esp_pgm_str_41; // "GET" break; case http_post: header += fb_esp_pgm_str_40; // "POST" post = true; break; case http_patch: header += fb_esp_pgm_str_38; // "PATCH" post = true; break; case http_delete: header += fb_esp_pgm_str_42; // "DELETE" break; case http_put: header += fb_esp_pgm_str_39; // "PUT" break; default: break; } if (method == http_get || method == http_post || method == http_patch || method == http_delete || method == http_put) header += fb_esp_pgm_str_9; // " " return post; } /* Append the string with last request line (HTTP version) */ inline void addRequestHeaderLast(MB_String &header) { header += fb_esp_pgm_str_43; // " HTTP/1.1\r\n" } /* Append the string with first part of Authorization header */ inline void addAuthHeaderFirst(MB_String &header, fb_esp_auth_token_type type) { header += fb_esp_pgm_str_44; // "Authorization: " if (type == token_type_oauth2_access_token) header += fb_esp_pgm_str_45; // "Bearer " else if (type == token_type_id_token || type == token_type_custom_token) header += fb_esp_pgm_str_46; // "Firebase " else header += fb_esp_pgm_str_47; // "key=" } inline void parseRespHeader(const MB_String &src, struct server_response_data_t &response) { int beginPos = 0; MB_String out; if (response.httpCode != -1) { StringHelper::tokenSubString(src, response.connection, fb_esp_pgm_str_48 /* "Connection: " */, fb_esp_pgm_str_30 /* "\r\n" */, beginPos, 0, false); StringHelper::tokenSubString(src, response.contentType, fb_esp_pgm_str_33 /* "Content-Type: " */, fb_esp_pgm_str_30 /* "\r\n" */, beginPos, 0, false); StringHelper::tokenSubStringInt(src, response.contentLen, fb_esp_pgm_str_34 /* "Content-Length: " */, fb_esp_pgm_str_30 /* "\r\n" */, beginPos, 0, false); StringHelper::tokenSubString(src, response.etag, fb_esp_pgm_str_49 /* "ETag: " */, fb_esp_pgm_str_30 /* "\r\n" */, beginPos, 0, false); response.payloadLen = response.contentLen; if (StringHelper::tokenSubString(src, response.transferEnc, fb_esp_pgm_str_50 /* "Transfer-Encoding: " */, fb_esp_pgm_str_30 /* "\r\n" */, beginPos, 0, false) && StringHelper::compare(response.transferEnc, 0, fb_esp_pgm_str_51 /* "chunked" */)) response.isChunkedEnc = true; if (response.httpCode == FIREBASE_ERROR_HTTP_CODE_OK || response.httpCode == FIREBASE_ERROR_HTTP_CODE_TEMPORARY_REDIRECT || response.httpCode == FIREBASE_ERROR_HTTP_CODE_PERMANENT_REDIRECT || response.httpCode == FIREBASE_ERROR_HTTP_CODE_MOVED_PERMANENTLY || response.httpCode == FIREBASE_ERROR_HTTP_CODE_FOUND) StringHelper::tokenSubString(src, response.location, fb_esp_pgm_str_52 /* "Location: " */, fb_esp_pgm_str_30 /* "\r\n" */, beginPos, 0, false); if (response.httpCode == FIREBASE_ERROR_HTTP_CODE_NO_CONTENT) response.noContent = true; } } inline int getStatusCode(const MB_String &header, int &pos) { int code = 0; StringHelper::tokenSubStringInt(header, code, fb_esp_pgm_str_53 /* "HTTP/1.1 " */, fb_esp_pgm_str_9 /* " " */, pos, 0, false); return code; } inline void setNumDataType(const MB_String &buf, int ofs, struct server_response_data_t &response, bool dec) { if (ofs < 0) return; int len = (int)buf.length(); if (ofs >= len) return; if (response.payloadLen > 0 && response.payloadLen <= len && ofs < len && ofs + response.payloadLen <= len) { double d = atof(buf.substr(ofs, response.payloadLen).c_str()); if (dec) { if (response.payloadLen <= 7) { response.floatData = d; response.dataType = fb_esp_data_type::d_float; } else { response.doubleData = d; response.dataType = fb_esp_data_type::d_double; } } else { if (d > 0x7fffffff) { response.doubleData = d; response.dataType = fb_esp_data_type::d_double; } else { response.intData = (int)d; response.dataType = fb_esp_data_type::d_integer; } } } } inline void parseRespPayload(const MB_String &src, struct server_response_data_t &response, bool getOfs) { int payloadPos = 0; int payloadOfs = 0; MB_String out; #if defined(ENABLE_RTDB) if (!response.isEvent && !response.noEvent) { if (StringHelper::tokenSubString(src, response.eventType, fb_esp_rtdb_pgm_str_12 /* "event: " */, fb_esp_pgm_str_12 /* "\n" */, payloadPos, 0, true)) { response.isEvent = true; payloadOfs = payloadPos; if (StringHelper::tokenSubString(src, out, fb_esp_rtdb_pgm_str_13 /* "data: " */, fb_esp_pgm_str_12 /* "\n" */, payloadPos, 0, true)) { payloadOfs += strlen_P(fb_esp_rtdb_pgm_str_13 /* "data: " */); payloadPos = payloadOfs; response.hasEventData = true; if (StringHelper::tokenSubString(src, response.eventPath, fb_esp_pgm_str_54 /* "\"path\":\"" */, fb_esp_pgm_str_4 /* "\"" */, payloadPos, 0, true)) { payloadOfs = payloadPos; if (StringHelper::tokenSubString(src, response.eventData, fb_esp_pgm_str_55 /* "\"data\":" */, fb_esp_pgm_str_12 /* "\n" */, payloadPos, 0, true)) { response.eventData[response.eventData.length() - 1] = 0; response.payloadLen = response.eventData.length(); payloadOfs += strlen_P(fb_esp_pgm_str_55 /* "\"data\":" */) + 1; response.payloadOfs = payloadOfs; } } } } } #endif if (src.length() < (size_t)payloadOfs) return; if (response.dataType == 0) { StringHelper::tokenSubString(src, response.pushName, fb_esp_pgm_str_56 /* "{\"name\":\"" */, fb_esp_pgm_str_4 /* "\"" */, payloadPos, 0, true); if (StringHelper::tokenSubString(src, out, fb_esp_pgm_str_57 /* "\"error\" : " */, fb_esp_pgm_str_4 /* "\"" */, payloadPos, 0, true)) { FirebaseJson js; FirebaseJsonData d; js.setJsonData(src); js.get(d, pgm2Str(fb_esp_pgm_str_58 /* "error" */)); if (d.success) response.fbError = d.stringValue.c_str(); } #if defined(ENABLE_RTDB) if (StringHelper::compare(src, payloadOfs, fb_esp_rtdb_pgm_str_7 /* "\"blob,base64," */, true)) { response.dataType = fb_esp_data_type::d_blob; if ((response.isEvent && response.hasEventData) || getOfs) { if (response.eventData.length() > 0) { int dlen = response.eventData.length() - strlen_P(fb_esp_rtdb_pgm_str_7) - 1; response.payloadLen = dlen; } response.payloadOfs += strlen_P(fb_esp_rtdb_pgm_str_7); response.eventData.clear(); } } else if (StringHelper::compare(src, payloadOfs, fb_esp_rtdb_pgm_str_8 /* "\"file,base64," */, true)) { response.dataType = fb_esp_data_type::d_file; if ((response.isEvent && response.hasEventData) || getOfs) { if (response.eventData.length() > 0) { int dlen = response.eventData.length() - strlen_P(fb_esp_rtdb_pgm_str_8) - 1; response.payloadLen = dlen; } response.payloadOfs += strlen_P(fb_esp_rtdb_pgm_str_8); response.eventData.clear(); } } else if (StringHelper::compare(src, payloadOfs, fb_esp_pgm_str_4 /* "\"" */)) response.dataType = fb_esp_data_type::d_string; else if (StringHelper::compare(src, payloadOfs, fb_esp_pgm_str_10 /* "{" */)) response.dataType = fb_esp_data_type::d_json; else if (StringHelper::compare(src, payloadOfs, fb_esp_pgm_str_6 /* "[" */)) response.dataType = fb_esp_data_type::d_array; else if (StringHelper::compare(src, payloadOfs, fb_esp_pgm_str_19 /* "false" */) || StringHelper::compare(src, payloadOfs, fb_esp_pgm_str_20 /* "true" */)) { response.dataType = fb_esp_data_type::d_boolean; response.boolData = StringHelper::compare(src, payloadOfs, fb_esp_pgm_str_20 /* "true" */); } else if (StringHelper::compare(src, payloadOfs, fb_esp_pgm_str_59 /* "null" */)) response.dataType = fb_esp_data_type::d_null; else setNumDataType(src, payloadOfs, response, src.find(pgm2Str(fb_esp_pgm_str_5 /* "." */), payloadOfs) != MB_String::npos); #endif } } inline void getCustomHeaders(MB_String &header, const MB_String &tokens) { if (tokens.length() > 0) { MB_VECTOR<MB_String> headers; StringHelper::splitTk(tokens, headers, ","); for (size_t i = 0; i < headers.size(); i++) { size_t p1 = headers[i].find(F("X-Firebase-")); size_t p2 = headers[i].find(':'); size_t p3 = headers[i].find(F("-ETag")); if (p1 != MB_String::npos && p2 != MB_String::npos && p2 > p1 && p3 == MB_String::npos) { header += headers[i]; addNewLine(header); } headers[i].clear(); } headers.clear(); } } inline void initTCPSession(struct fb_esp_session_info_t &session) { #ifdef ENABLE_RTDB if (session.con_mode == fb_esp_con_mode_rtdb) session.rtdb.raw.clear(); #endif #ifdef ENABLE_FIRESTORE if (session.con_mode == fb_esp_con_mode_firestore) session.cfs.payload.clear(); #endif #ifdef ENABLE_FB_FUNCTIONS if (session.con_mode == fb_esp_con_mode_functions) session.cfn.payload.clear(); #endif #if defined(ENABLE_FCM) && defined(FIREBASE_ESP_CLIENT) if (session.con_mode == fb_esp_con_mode_fcm) session.fcm.payload.clear(); #endif #ifdef ENABLE_GC_STORAGE if (session.con_mode == fb_esp_con_mode_gc_storage) session.gcs.payload.clear(); #endif #ifdef ENABLE_FB_STORAGE if (session.con_mode == fb_esp_con_mode_storage) session.fcs.files.items.clear(); #endif session.response.code = FIREBASE_ERROR_HTTP_CODE_UNDEFINED; session.content_length = -1; session.payload_length = 0; session.chunked_encoding = false; session.buffer_ovf = false; } inline void intTCPHandler(Client *client, struct fb_esp_tcp_response_handler_t &tcpHandler, size_t defaultChunkSize, size_t respSize, MB_String *payload, bool isOTA) { // set the client before calling available tcpHandler.client = client; tcpHandler.payloadLen = 0; tcpHandler.payloadRead = 0; tcpHandler.chunkBufSize = tcpHandler.available(); // client must be set before calling tcpHandler.defaultChunkSize = respSize; tcpHandler.error.code = -1; tcpHandler.defaultChunkSize = defaultChunkSize; tcpHandler.bufferAvailable = 0; tcpHandler.header.clear(); tcpHandler.dataTime = millis(); tcpHandler.downloadOTA = isOTA; tcpHandler.payload = payload; } inline int readLine(Client *client, char *buf, int bufLen) { if (!client) return 0; int res = -1; char c = 0; int idx = 0; if (!client) return idx; while (client->available() && idx < bufLen) { if (!client) break; Utils::idle(); res = client->read(); if (res > -1) { c = (char)res; buf[idx++] = c; if (c == '\n') return idx; } } return idx; } inline int readLine(Client *client, MB_String &buf) { if (!client) return 0; int res = -1; char c = 0; int idx = 0; if (!client) return idx; while (client->available()) { if (!client) break; Utils::idle(); res = client->read(); if (res > -1) { c = (char)res; buf += c; idx++; if (c == '\n') return idx; } } return idx; } inline uint32_t hex2int(const char *hex) { uint32_t val = 0; while (*hex) { // get current character then increment uint8_t byte = *hex++; // transform hex character to the 4bit equivalent number, using the ascii table indexes if (byte >= '0' && byte <= '9') byte = byte - '0'; else if (byte >= 'a' && byte <= 'f') byte = byte - 'a' + 10; else if (byte >= 'A' && byte <= 'F') byte = byte - 'A' + 10; // shift 4 to make space for new digit, and add the 4 bits of the new digit val = (val << 4) | (byte & 0xF); } return val; } // Returns -1 when complete inline int readChunkedData(MB_FS *mbfs, Client *client, char *out1, MB_String *out2, struct fb_esp_tcp_response_handler_t &tcpHandler) { if (!client) return 0; int bufLen = tcpHandler.chunkBufSize; char *buf = nullptr; int p1 = 0; int olen = 0; if (tcpHandler.chunkState.state == 0) { tcpHandler.chunkState.state = 1; tcpHandler.chunkState.chunkedSize = -1; tcpHandler.chunkState.dataLen = 0; MB_String s; int readLen = 0; if (out2) readLen = readLine(client, s); else if (out1) { buf = MemoryHelper::createBuffer<char *>(mbfs, bufLen); readLen = readLine(client, buf, bufLen); } if (readLen) { if (out1) s = buf; p1 = StringHelper::strpos(s.c_str(), (const char *)MBSTRING_FLASH_MCR(";"), 0); if (p1 == -1) p1 = StringHelper::strpos(s.c_str(), (const char *)MBSTRING_FLASH_MCR("\r\n"), 0); if (p1 != -1) { if (out2) tcpHandler.chunkState.chunkedSize = hex2int(s.substr(0, p1).c_str()); else if (out1) { char *temp = MemoryHelper::createBuffer<char *>(mbfs, p1 + 1); memcpy(temp, buf, p1); tcpHandler.chunkState.chunkedSize = hex2int(temp); MemoryHelper::freeBuffer(mbfs, temp); } } // last chunk if (tcpHandler.chunkState.chunkedSize < 1) olen = -1; } else tcpHandler.chunkState.state = 0; if (out1) MemoryHelper::freeBuffer(mbfs, buf); } else { if (tcpHandler.chunkState.chunkedSize > -1) { MB_String s; int readLen = 0; if (out2) readLen = readLine(client, s); else if (out1) { buf = MemoryHelper::createBuffer<char *>(mbfs, bufLen); readLen = readLine(client, buf, bufLen); } if (readLen > 0) { // chunk may contain trailing if (tcpHandler.chunkState.dataLen + readLen - 2 < tcpHandler.chunkState.chunkedSize) { tcpHandler.chunkState.dataLen += readLen; if (out2) *out2 += s; else if (out1) memcpy(out1, buf, readLen); olen = readLen; } else { if (tcpHandler.chunkState.chunkedSize - tcpHandler.chunkState.dataLen > 0) { if (out2) *out2 += s; else if (out1) memcpy(out1, buf, tcpHandler.chunkState.chunkedSize - tcpHandler.chunkState.dataLen); } tcpHandler.chunkState.dataLen = tcpHandler.chunkState.chunkedSize; tcpHandler.chunkState.state = 0; olen = readLen; } } // if all chunks read, returns -1 else if (tcpHandler.chunkState.dataLen == tcpHandler.chunkState.chunkedSize) olen = -1; if (out1) MemoryHelper::freeBuffer(mbfs, buf); } } return olen; } inline bool readStatusLine(MB_FS *mbfs, Client *client, struct fb_esp_tcp_response_handler_t &tcpHandler, struct server_response_data_t &response) { tcpHandler.chunkIdx++; if (!tcpHandler.isHeader && tcpHandler.chunkIdx > 1) tcpHandler.pChunkIdx++; if (tcpHandler.chunkIdx > 1) return false; // the first chunk (line) can be http response status or already connected stream payload char *hChunk = MemoryHelper::createBuffer<char *>(mbfs, tcpHandler.chunkBufSize); int readLen = readLine(client, hChunk, tcpHandler.chunkBufSize); if (readLen > 0) tcpHandler.header += hChunk; int pos = 0; int status = HttpHelper::getStatusCode(hChunk, pos); if (status > 0) { // http response status tcpHandler.isHeader = true; response.httpCode = status; } MemoryHelper::freeBuffer(mbfs, hChunk); return true; } inline bool readHeader(MB_FS *mbfs, Client *client, struct fb_esp_tcp_response_handler_t &tcpHandler, struct server_response_data_t &response) { // do not check of the config here to allow legacy fcm to work char *hChunk = MemoryHelper::createBuffer<char *>(mbfs, tcpHandler.chunkBufSize); int readLen = readLine(client, hChunk, tcpHandler.chunkBufSize); // check is it the end of http header (\n or \r\n)? if ((readLen == 1 && hChunk[0] == '\r') || (readLen == 2 && hChunk[0] == '\r' && hChunk[1] == '\n')) tcpHandler.headerEnded = true; if (tcpHandler.headerEnded) { // parse header string to get the header field tcpHandler.isHeader = false; HttpHelper::parseRespHeader(tcpHandler.header, response); } // accumulate the remaining header field else if (readLen > 0) tcpHandler.header += hChunk; MemoryHelper::freeBuffer(mbfs, hChunk); return tcpHandler.headerEnded; } }; namespace Base64Helper { inline int getBase64Len(int n) { int len = (4 * ceil(n / 3.0)); return len; } inline int getBase64Padding(int n) { int pLen = getBase64Len(n); int uLen = ceil(4.0 * n / 3.0); return pLen - uLen; } inline size_t encodedLength(size_t len) { return ((len + 2) / 3 * 4) + 1; } inline int decodedLen(const char *src) { int len = strlen(src), i = len - 1, pad = 0; if (len < 4) return 0; while (i > 0 && src[i--] == '=') { pad++; } return (3 * (len / 4)) - pad; } inline unsigned char *creatBase64EncBuffer(MB_FS *mbfs, bool isURL) { unsigned char *base64EncBuf = MemoryHelper::createBuffer<unsigned char *>(mbfs, 65); strcpy_P((char *)base64EncBuf, (char *)fb_esp_base64_table); if (isURL) { base64EncBuf[62] = '-'; base64EncBuf[63] = '_'; } return base64EncBuf; } inline bool updateWrite(uint8_t *data, size_t len) { #if defined(ENABLE_OTA_FIRMWARE_UPDATE) && (defined(ENABLE_RTDB) || defined(ENABLE_FB_STORAGE) || defined(ENABLE_GC_STORAGE)) #if defined(ESP32) || defined(ESP8266) || defined(MB_ARDUINO_PICO) return Update.write(data, len) == len; #endif #endif return false; } inline unsigned char *creatBase64DecBuffer(MB_FS *mbfs) { unsigned char *base64DecBuf = MemoryHelper::createBuffer<unsigned char *>(mbfs, 256, false); memset(base64DecBuf, 0x80, 256); for (size_t i = 0; i < sizeof(fb_esp_base64_table) - 1; i++) base64DecBuf[fb_esp_base64_table[i]] = (unsigned char)i; base64DecBuf['='] = 0; return base64DecBuf; } template <typename T = uint8_t> inline bool writeOutput(MB_FS *mbfs, fb_esp_base64_io_t<T> &out) { size_t write = out.bufWrite; out.bufWrite = 0; if (write == 0) return true; if (out.outC && out.outC->write((uint8_t *)out.outT, write) == write) return true; else if (out.filetype != mb_fs_mem_storage_type_undefined && mbfs->write(mbfs_type out.filetype, (uint8_t *)out.outT, write) == (int)write) return true; #if defined(OTA_UPDATE_ENABLED) else if (out.ota && updateWrite((uint8_t *)out.outT, write)) return true; #endif return false; } template <typename T = uint8_t> inline bool setOutput(MB_FS *mbfs, uint8_t val, fb_esp_base64_io_t<T> &out, T **pos) { if (out.outT) { if (out.ota || out.outC || out.filetype != mb_fs_mem_storage_type_undefined) { out.outT[out.bufWrite++] = val; if (out.bufWrite == (int)out.bufLen && !writeOutput(mbfs, out)) return false; } else *(*pos)++ = (T)(val); } else if (out.outL) out.outL->push_back(val); return true; } template <typename T> inline bool decode(MB_FS *mbfs, unsigned char *base64DecBuf, const char *src, size_t len, fb_esp_base64_io_t<T> &out) { // the maximum chunk size that writes to output is limited by out.bufLen, the minimum is depending on the source length bool ret = false; unsigned char *block = MemoryHelper::createBuffer<unsigned char *>(mbfs, 4, false); unsigned char temp; size_t i, count; int pad = 0; size_t extra_pad; T *pos = out.outT ? (T *)&out.outT[0] : nullptr; if (len == 0) len = strlen(src); count = 0; for (i = 0; i < len; i++) { if ((uint8_t)base64DecBuf[(uint8_t)src[i]] != 0x80) count++; } if (count == 0) goto skip; extra_pad = (4 - count % 4) % 4; count = 0; for (i = 0; i < len + extra_pad; i++) { unsigned char val; if (i >= len) val = '='; else val = src[i]; temp = base64DecBuf[val]; if (temp == 0x80) continue; if (val == '=') pad++; block[count] = temp; count++; if (count == 4) { setOutput(mbfs, (block[0] << 2) | (block[1] >> 4), out, &pos); count = 0; if (pad) { if (pad == 1) setOutput(mbfs, (block[1] << 4) | (block[2] >> 2), out, &pos); else if (pad > 2) goto skip; break; } else { setOutput(mbfs, (block[1] << 4) | (block[2] >> 2), out, &pos); setOutput(mbfs, (block[2] << 6) | block[3], out, &pos); } } } // write remaining if (out.bufWrite > 0 && !writeOutput(mbfs, out)) goto skip; ret = true; skip: MemoryHelper::freeBuffer(mbfs, block); return ret; } template <typename T> inline bool encodeLast(MB_FS *mbfs, unsigned char *base64EncBuf, const unsigned char *in, size_t len, fb_esp_base64_io_t<T> &out, T **pos) { if (len > 2) return false; if (!setOutput(mbfs, base64EncBuf[in[0] >> 2], out, pos)) return false; if (len == 1) { if (!setOutput(mbfs, base64EncBuf[(in[0] & 0x03) << 4], out, pos)) return false; if (!setOutput(mbfs, '=', out, pos)) return false; } else { if (!setOutput(mbfs, base64EncBuf[((in[0] & 0x03) << 4) | (in[1] >> 4)], out, pos)) return false; if (!setOutput(mbfs, base64EncBuf[(in[1] & 0x0f) << 2], out, pos)) return false; } if (!setOutput(mbfs, '=', out, pos)) return false; return true; } template <typename T> inline bool encode(MB_FS *mbfs, unsigned char *base64EncBuf, uint8_t *src, size_t len, fb_esp_base64_io_t<T> &out, bool writeAllRemaining = true) { const unsigned char *end, *in; T *pos = out.outT ? (T *)&out.outT[0] : nullptr; in = src; end = src + len; while (end - in >= 3) { if (!setOutput(mbfs, base64EncBuf[in[0] >> 2], out, &pos)) return false; if (!setOutput(mbfs, base64EncBuf[((in[0] & 0x03) << 4) | (in[1] >> 4)], out, &pos)) return false; if (!setOutput(mbfs, base64EncBuf[((in[1] & 0x0f) << 2) | (in[2] >> 6)], out, &pos)) return false; if (!setOutput(mbfs, base64EncBuf[in[2] & 0x3f], out, &pos)) return false; in += 3; } if (end - in && !encodeLast(mbfs, base64EncBuf, in, end - in, out, &pos)) return false; if (writeAllRemaining && out.bufWrite > 0 && !writeOutput(mbfs, out)) return false; return true; } template <typename T> inline bool decodeToArray(MB_FS *mbfs, const MB_String &src, MB_VECTOR<T> &val) { fb_esp_base64_io_t<T> out; out.outL = &val; unsigned char *base64DecBuf = creatBase64DecBuffer(mbfs); bool ret = decode<T>(mbfs, base64DecBuf, src.c_str(), src.length(), out); MemoryHelper::freeBuffer(mbfs, base64DecBuf); return ret; } inline bool decodeToFile(MB_FS *mbfs, const char *src, size_t len, mbfs_file_type type) { fb_esp_base64_io_t<uint8_t> out; out.filetype = type; uint8_t *buf = MemoryHelper::createBuffer<uint8_t *>(mbfs, out.bufLen); out.outT = buf; unsigned char *base64DecBuf = creatBase64DecBuffer(mbfs); bool ret = decode<uint8_t>(mbfs, base64DecBuf, src, strlen(src), out); MemoryHelper::freeBuffer(mbfs, buf); MemoryHelper::freeBuffer(mbfs, base64DecBuf); return ret; } inline void encodeUrl(MB_FS *mbfs, char *encoded, unsigned char *string, size_t len) { size_t i; char *p = encoded; unsigned char *base64EncBuf = creatBase64EncBuffer(mbfs, true); for (i = 0; i < len - 2; i += 3) { *p++ = base64EncBuf[(string[i] >> 2) & 0x3F]; *p++ = base64EncBuf[((string[i] & 0x3) << 4) | ((int)(string[i + 1] & 0xF0) >> 4)]; *p++ = base64EncBuf[((string[i + 1] & 0xF) << 2) | ((int)(string[i + 2] & 0xC0) >> 6)]; *p++ = base64EncBuf[string[i + 2] & 0x3F]; } if (i < len) { *p++ = base64EncBuf[(string[i] >> 2) & 0x3F]; if (i == (len - 1)) *p++ = base64EncBuf[((string[i] & 0x3) << 4)]; else { *p++ = base64EncBuf[((string[i] & 0x3) << 4) | ((int)(string[i + 1] & 0xF0) >> 4)]; *p++ = base64EncBuf[((string[i + 1] & 0xF) << 2)]; } } *p++ = '\0'; MemoryHelper::freeBuffer(mbfs, base64EncBuf); } inline MB_String encodeToString(MB_FS *mbfs, uint8_t *src, size_t len) { MB_String str; char *encoded = MemoryHelper::createBuffer<char *>(mbfs, encodedLength(len) + 1); fb_esp_base64_io_t<char> out; out.outT = encoded; unsigned char *base64EncBuf = creatBase64EncBuffer(mbfs, false); if (encode<char>(mbfs, base64EncBuf, (uint8_t *)src, len, out)) str = encoded; MemoryHelper::freeBuffer(mbfs, encoded); MemoryHelper::freeBuffer(mbfs, base64EncBuf); return str; } inline bool encodeToClient(Client *client, MB_FS *mbfs, size_t bufSize, uint8_t *data, size_t len) { fb_esp_base64_io_t<uint8_t> out; out.outC = client; uint8_t *buf = MemoryHelper::createBuffer<uint8_t *>(mbfs, out.bufLen); out.outT = buf; unsigned char *base64EncBuf = creatBase64EncBuffer(mbfs, false); bool ret = encode<uint8_t>(mbfs, base64EncBuf, (uint8_t *)data, len, out); MemoryHelper::freeBuffer(mbfs, buf); MemoryHelper::freeBuffer(mbfs, base64EncBuf); return ret; } }; namespace OtaHelper { // trim double quotes and return pad length inline int trimLastChunkBase64(MB_String &s, int len) { int padLen = -1; if (len > 1) { if (s[len - 1] == '"') { padLen = 0; if (len > 2) { if (s[len - 2] == '=') padLen++; } if (len > 3) { if (s[len - 3] == '=') padLen++; } s[len - 1] = 0; } } return padLen; } inline bool decodeBase64OTA(MB_FS *mbfs, const char *src, size_t len, int &code) { bool ret = true; fb_esp_base64_io_t<uint8_t> out; uint8_t *buf = MemoryHelper::createBuffer<uint8_t *>(mbfs, out.bufLen); out.ota = true; out.outT = buf; unsigned char *base64DecBuf = Base64Helper::creatBase64DecBuffer(mbfs); if (!Base64Helper::decode<uint8_t>(mbfs, base64DecBuf, src, strlen(src), out)) { code = FIREBASE_ERROR_FW_UPDATE_WRITE_FAILED; ret = false; } MemoryHelper::freeBuffer(mbfs, buf); MemoryHelper::freeBuffer(mbfs, base64DecBuf); return ret; } }; namespace TimeHelper { inline time_t getTime(uint32_t *mb_ts, uint32_t *mb_ts_offset) { uint32_t &tm = *mb_ts; #if defined(FB_ENABLE_EXTERNAL_CLIENT) || defined(MB_ARDUINO_PICO) tm = *mb_ts_offset + millis() / 1000; #if defined(MB_ARDUINO_PICO) || defined(ESP32) || defined(ESP8266) if (tm < time(nullptr)) tm = time(nullptr); #endif #elif defined(ESP32) || defined(ESP8266) tm = time(nullptr); #endif return tm; } inline int setTimestamp(time_t ts) { #if defined(ESP32) || defined(ESP8266) struct timeval tm = {ts, 0}; // sec, us return settimeofday((const timeval *)&tm, 0); #endif return -1; } inline bool setTime(time_t ts, uint32_t *mb_ts, uint32_t *mb_ts_offset) { bool ret = false; #if defined(ESP32) || defined(ESP8266) ret = TimeHelper::setTimestamp(ts) == 0; *mb_ts = time(nullptr); #else if (ts > ESP_DEFAULT_TS) { *mb_ts_offset = ts - millis() / 1000; *mb_ts = ts; ret = true; } #endif return ret; } inline bool updateClock(MB_NTP *ntp, uint32_t *mb_ts, uint32_t *mb_ts_offset) { uint32_t ts = ntp->getTime(2000 /* wait 10000 ms */); if (ts > 0) *mb_ts_offset = ts - millis() / 1000; time_t now = getTime(mb_ts, mb_ts_offset); bool rdy = now > ESP_DEFAULT_TS; #if defined(ESP32) || defined(ESP8266) if (rdy && time(nullptr) < now) setTime(now, mb_ts, mb_ts_offset); #endif return rdy; } inline bool syncClock(MB_NTP *ntp, uint32_t *mb_ts, uint32_t *mb_ts_offset, float gmtOffset, FirebaseConfig *config) { if (!config) return false; time_t now = getTime(mb_ts, mb_ts_offset); config->internal.fb_clock_rdy = (unsigned long)now > ESP_DEFAULT_TS; if (config->internal.fb_clock_rdy && gmtOffset == config->internal.fb_gmt_offset) return true; if (!config->internal.fb_clock_rdy || gmtOffset != config->internal.fb_gmt_offset) { if (config->internal.fb_clock_rdy && gmtOffset != config->internal.fb_gmt_offset) config->internal.fb_clock_synched = false; if (!config->internal.fb_clock_synched) { config->internal.fb_clock_synched = true; #if defined(FB_ENABLE_EXTERNAL_CLIENT) updateClock(ntp, mb_ts, mb_ts_offset); #else #if defined(ESP32) || defined(ESP8266) || defined(MB_ARDUINO_PICO) #if defined(MB_ARDUINO_PICO) NTP.begin("pool.ntp.org", "time.nist.gov"); NTP.waitSet(); now = time(nullptr); if (now > ESP_DEFAULT_TS) *mb_ts_offset = now - millis() / 1000; #else configTime(gmtOffset * 3600, 0, "pool.ntp.org", "time.nist.gov"); #endif #endif #endif } } now = getTime(mb_ts, mb_ts_offset); config->internal.fb_clock_rdy = (unsigned long)now > ESP_DEFAULT_TS; if (config->internal.fb_clock_rdy) config->internal.fb_gmt_offset = gmtOffset; return config->internal.fb_clock_rdy; } }; namespace Utils { inline int ishex(int x) { return (x >= '0' && x <= '9') || (x >= 'a' && x <= 'f') || (x >= 'A' && x <= 'F'); } inline char from_hex(char ch) { return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10; } inline void createDirs(MB_String dirs, fb_esp_mem_storage_type storageType) { #if defined(SD_FS) MB_String dir; size_t count = 0; for (size_t i = 0; i < dirs.length(); i++) { dir.append(1, dirs[i]); count++; if (dirs[i] == '/') { if (dir.length() > 0) { if (storageType == mem_storage_type_sd) SD_FS.mkdir(dir.substr(0, dir.length() - 1).c_str()); } count = 0; } } if (count > 0) { if (storageType == mem_storage_type_sd) SD_FS.mkdir(dir.c_str()); } dir.clear(); #endif } #if defined(__AVR__) inline unsigned long long strtoull_alt(const char *s) { unsigned long long sum = 0; while (*s) { sum = sum * 10 + (*s++ - '0'); } return sum; } #endif inline void setFloatDigit(uint8_t digit, FirebaseConfig *config) { if (!config) return; config->internal.fb_float_digits = digit; } inline void setDoubleDigit(uint8_t digit, FirebaseConfig *config) { if (!config) return; config->internal.fb_double_digits = digit; } inline MB_String getBoundary(MB_FS *mbfs, size_t len) { MB_String temp = fb_esp_boundary_table; char *buf = MemoryHelper::createBuffer<char *>(mbfs, len); if (len) { --len; buf[0] = temp[0]; buf[1] = temp[1]; for (size_t n = 2; n < len; n++) { int key = rand() % (int)(temp.length() - 1); buf[n] = temp[key]; } buf[len] = '\0'; } MB_String out = buf; MemoryHelper::freeBuffer(mbfs, buf); return out; } inline bool boolVal(const MB_String &v) { return v.find(pgm2Str(fb_esp_pgm_str_20 /* "true" */)) != MB_String::npos; } inline bool waitIdle(int &httpCode, FirebaseConfig *config) { if (!config) return true; #if defined(ESP32) || defined(MB_ARDUINO_PICO) if (config->internal.fb_multiple_requests) return true; unsigned long wTime = millis(); while (config->internal.fb_processing) { if (millis() - wTime > 3000) { httpCode = FIREBASE_ERROR_TCP_ERROR_CONNECTION_INUSED; return false; } Utils::idle(); } #endif return true; } inline bool validJS(const char *c) { size_t ob = 0, cb = 0, os = 0, cs = 0; for (size_t i = 0; i < strlen(c); i++) { if (c[i] == '{') ob++; else if (c[i] == '}') cb++; else if (c[i] == '[') os++; else if (c[i] == ']') cs++; } return (ob == cb && os == cs); } inline uint16_t calCRC(MB_FS *mbfs, const char *buf) { return mbfs->calCRC(buf); } inline void makePath(MB_String &path) { if (path.length() > 0) { if (path[0] != '/') path.prepend('/'); } } inline MB_String makeFCMMsgPath(PGM_P sub = NULL) { MB_String path = fb_esp_pgm_str_60; // "msg" path += fb_esp_pgm_str_1; // "/" if (sub) path += sub; return path; } #if defined(ENABLE_FCM) inline MB_String makeFCMMessagePath(PGM_P sub = NULL) { MB_String path = fb_esp_fcm_pgm_str_68; // "message" path += fb_esp_pgm_str_1; // "/" if (sub) path += sub; return path; } inline void addFCMNotificationPath(MB_String &path, PGM_P sub = NULL) { path += fb_esp_fcm_pgm_str_67; // "notification" path += fb_esp_pgm_str_1; // "/" if (sub) path += sub; } inline void addFCMAndroidPath(MB_String &path, PGM_P sub = NULL) { path += fb_esp_fcm_pgm_str_69; // "android" path += fb_esp_pgm_str_1; // "/" if (sub) path += sub; } inline void addFCMWebpushPath(MB_String &path, PGM_P sub = NULL) { path += fb_esp_fcm_pgm_str_70; // "webpush"; path += fb_esp_pgm_str_1; // "/" if (sub) path += sub; } inline void addFCMApnsPath(MB_String &path, PGM_P sub = NULL) { path += fb_esp_fcm_pgm_str_71; // "apns"; path += fb_esp_pgm_str_1; // "/" if (sub) path += sub; } inline MB_String makeFCMNotificationPath(PGM_P sub = NULL) { MB_String path = fb_esp_fcm_pgm_str_67; // "notification" path += fb_esp_pgm_str_1; // "/" if (sub) path += sub; return path; } #endif #if defined(FIREBASE_ESP_CLIENT) && defined(ENABLE_FIRESTORE) inline MB_String makeDocPath(struct fb_esp_firestore_req_t &req, const MB_String &projectId) { MB_String str = fb_esp_func_pgm_str_47; // "projects/" str += req.projectId.length() == 0 ? projectId : req.projectId; str += fb_esp_cfs_pgm_str_32; // "/databases/" str += req.databaseId.length() > 0 ? req.databaseId : fb_esp_cfs_pgm_str_33 /* "(default)" */; str += fb_esp_cfs_pgm_str_21; // "/documents" return str; } #endif inline size_t getUploadBufSize(FirebaseConfig *config, fb_esp_con_mode mode) { int bufLen = 0; #if defined(ENABLE_RTDB) if (mode == fb_esp_con_mode_rtdb) bufLen = config->rtdb.upload_buffer_size; #endif #if defined(ENABLE_FB_FUNCTIONS) if (mode == fb_esp_con_mode_functions) bufLen = config->functions.upload_buffer_size; #endif #if defined(ENABLE_GC_STORAGE) if (mode == fb_esp_con_mode_gc_storage) bufLen = config->gcs.upload_buffer_size; #endif #if defined(ENABLE_FB_STORAGE) if (mode == fb_esp_con_mode_storage) bufLen = config->fcs.upload_buffer_size; #endif if (bufLen < 512) bufLen = 512; if (bufLen > 1024 * 16) bufLen = 1024 * 16; return bufLen; } inline bool isNoContent(server_response_data_t *response) { return !response->isChunkedEnc && response->contentLen == 0; } inline bool isResponseTimeout(fb_esp_tcp_response_handler_t *tcpHandler, bool &complete) { if (millis() - tcpHandler->dataTime > 5000) { // Read all remaining data tcpHandler->client->flush(); complete = true; } return complete; } inline bool isResponseComplete(fb_esp_tcp_response_handler_t *tcpHandler, server_response_data_t *response, bool &complete, bool check = true) { if (check && !response->isChunkedEnc && (tcpHandler->bufferAvailable < 0 || tcpHandler->payloadRead >= response->contentLen)) { complete = true; return true; } return false; } inline bool isChunkComplete(fb_esp_tcp_response_handler_t *tcpHandler, server_response_data_t *response, bool &complete) { if (response->isChunkedEnc && tcpHandler->bufferAvailable < 0) { // Read all remaining data tcpHandler->client->flush(); complete = true; return true; } return false; } }; #endif
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; // Author: Tatparya Shankar // Implementation : Integer Partitioning void printArray( int * array, int length ) { cout << "Array :"; for( int i = 0; i < length; i++ ) { cout << " " << array[i]; } cout << endl; } void partitionAll_fn( int * array, int index, int value ) { cout << "Partitioning : " << value << endl; cout << "Index : " << index << endl; // Check for base case if( value > 0 ) { // Recursive case for( int val = 1; val <= value; val++ ) { array[index] = val; partitionAll_fn( array, index + 1, value - val ); } } else if( value == 0 ) { // Base case cout << "Partioned array : " << endl; printArray( array, index ); cout << endl; } } void partitionAll( int value ) { int * array; int index = 0; // Allocate array to value, since biggest partiton is all ones array = (int *) malloc( sizeof( int ) * value ); // Partition funciton call partitionAll_fn( array, index, value ); // Free memory allocated free( array ); } int main() { int n; cout << "Enter partition value : "; cin >> n; partitionAll( n ); return 0; }
#include<iostream> using namespace std; int main() { int n,k,i,j; cin >> n; for(i = n; i >= 1; i--) { for(k=i;k<n;k++) cout << " "; for(j=1;j<=i;j++) cout << j; cout << "\n"; } return 0; }
// // NBody_gendata.cpp // generate test data // // #include<stdio.h> #include<stdlib.h> #include<fstream> #include<string> #include<iostream> #include<sstream> #include<math.h> #include<vector> using namespace std; void createTestCase(int x, int maxLevel, string file) { ofstream out; double fx = (double)x; out.open(file.c_str()); out<< x*x <<" "<<maxLevel<<endl; for(int i = 0; i < x; i++) for(int j = 0; j < x; j++) { out <<(i+1)/(fx+1)<<" "<<(j+1)/(fx+1)<<" "<<1<<endl; } out.close(); } void createHelper(ofstream &out, double corX, double corY, int level, int n, vector<double> &r){ double loc = (double)rand()/ RAND_MAX; double scale = pow(2,level+1); double gap = 1.0/scale; double x = (double)rand()/RAND_MAX /scale; double y = (double)rand()/RAND_MAX /scale; if (loc <= 0.4){ r.push_back(corX + x); r.push_back(corY + y); }else if(loc <= 0.7){ r.push_back(corX + x); r.push_back(corY + y + gap); }else if(loc <= 0.9){ r.push_back(corX + x + gap); r.push_back(corY + y); }else{ r.push_back(corX + x + gap); r.push_back(corY + y + gap); } // if you want 2**(2n+2) points if (level >= n){ return; } createHelper(out, corX, corY, level+1, n,r); createHelper(out, corX+gap, corY, level+1, n,r); createHelper(out, corX, corY+gap, level+1, n,r); createHelper(out, corX+gap, corY+gap, level+1, n,r); } void createTestCaseNU(int x, int maxLevel, string file) { ofstream out; // total number of Points int totalPoints = x*x; int n = (int)log2(totalPoints); vector<double> r; double corX = 0; double corY = 0; int level = 0; for (int i=0; i<3; i++){ createHelper(out, corX, corY, level, (n-2)/2, r); } r.push_back(0.45); r.push_back(0.55); cout << "rsize = 2**" << log2(r.size()/2) << endl; out.open(file.c_str()); out<< x*x <<" "<<maxLevel<<endl; for (int i=0; i< r.size()/2; i++){ out << r[2*i] << " " << r[2*i+1] << " " << 1 << endl; } out.close(); } int main(int argc, char* argv[]) { //string file = "/Users/xinyangyi/test.txt"; // create 512*512, 1024*1024, 2048*2048 points createTestCase(512, 20, "NodeTest18"); createTestCase(1024, 20, "NodeTest20"); createTestCase(2048, 20, "NodeTest22"); createTestCaseNU(512, 20, "NodeTest18nu"); createTestCaseNU(1024, 20, "NodeTest20nu"); createTestCaseNU(2048, 20, "NodeTest22nu"); }
// BEGIN CUT HERE // PROBLEM STATEMENT // Consider a hexagonal grid with 6 sides, with the side // lengths given by the int[] s (in the clockwise order), as // shown in the following picture: // // Count the number of ways to color each cell with one of // two colors, black or white, such that every non-border // black cell has exactly a black neighbors, and every non- // border white cell has exactly b white neighbors (a cell is // called non-border if and only if it has exactly 6 // neighbors in the grid). // // DEFINITION // Class:BeautifulHexagonalTilings // Method:howMany // Parameters:vector <int>, int, int // Returns:int // Method signature:int howMany(vector <int> s, int a, int b) // // // CONSTRAINTS // -s will contain exactly 6 elements. // -Each element of s will be between 2 and 6, inclusive. // -a and b will each be between 0 and 6, inclusive. // -s will define a valid hexagonal grid. // -The answer will always fit into an int. // // // EXAMPLES // // 0) // {2,2,2,2,2,2} // 6 // 6 // // Returns: 2 // // Either all white or all black. // // 1) // {6,6,6,6,6,6} // 6 // 6 // // Returns: 2 // // The field is bigger, but still all white or all black. // // 2) // {2,2,2,2,2,2} // 2 // 2 // // Returns: 30 // // // // 3) // {4,4,3,5,3,4} // 4 // 1 // // Returns: 213 // // The grid from the picture. // // END CUT HERE #line 70 "BeautifulHexagonalTilings.cpp" #include <string> #include <vector> #include <iostream> #include <sstream> #include <algorithm> #include <numeric> #include <functional> #include <map> #include <set> #include <cassert> #include <list> #include <deque> #include <iomanip> #include <cstring> #include <cmath> #include <cstdio> #include <cctype> using namespace std; #define fi(n) for(int i=0;i<(n);i++) #define fj(n) for(int j=0;j<(n);j++) #define f(i,a,b) for(int (i)=(a);(i)<(b);(i)++) typedef vector <int> VI; typedef vector <string> VS; typedef vector <VI> VVI; class BeautifulHexagonalTilings { public: int howMany(vector <int> s, int a, int b) { } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arr0[] = {2,2,2,2,2,2}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 6; int Arg2 = 6; int Arg3 = 2; verify_case(0, Arg3, howMany(Arg0, Arg1, Arg2)); } void test_case_1() { int Arr0[] = {6,6,6,6,6,6}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 6; int Arg2 = 6; int Arg3 = 2; verify_case(1, Arg3, howMany(Arg0, Arg1, Arg2)); } void test_case_2() { int Arr0[] = {2,2,2,2,2,2}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; int Arg2 = 2; int Arg3 = 30; verify_case(2, Arg3, howMany(Arg0, Arg1, Arg2)); } void test_case_3() { int Arr0[] = {4,4,3,5,3,4}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 4; int Arg2 = 1; int Arg3 = 213; verify_case(3, Arg3, howMany(Arg0, Arg1, Arg2)); } // END CUT HERE }; // BEGIN CUT HERE int main() { BeautifulHexagonalTilings ___test; ___test.run_test(-1); } // END CUT HERE
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 2004-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #ifdef WIDGET_RUNTIME_SUPPORT #include <unistd.h> #include "desktop_entry.h" #include "unix_gadgetuninstaller.h" #include "adjunct/desktop_util/shortcuts/DesktopShortcutInfo.h" #include "adjunct/widgetruntime/GadgetInstallerContext.h" #include "adjunct/widgetruntime/pi/PlatformGadgetUtils.h" #include "modules/util/opfile/opfile.h" #include "platforms/posix/posix_native_util.h" UnixGadgetUninstaller::UnixGadgetUninstaller() : m_context(NULL) { } OP_STATUS UnixGadgetUninstaller::Init(const GadgetInstallerContext& context) { m_context = &context; return OpStatus::OK; } const OpStringC& UnixGadgetUninstaller::GetGadgetDir() const { OP_ASSERT(NULL != m_context); return m_context->m_dest_dir_path; } const OpStringC& UnixGadgetUninstaller::GetInstallationName() const { OP_ASSERT(NULL != m_context); return m_context->m_profile_name; } OP_STATUS UnixGadgetUninstaller::Uninstall() { RETURN_IF_ERROR(RemoveShareDir()); // if removing share dir suceeded, then we should return status OK, no matter if // removing wrapper script and desktop entry also succeeded OpStatus::Ignore(UnlinkWrapperScript()); OpStatus::Ignore(RemoveWrapperScript()); OpStatus::Ignore(RemoveDesktopEntries()); return OpStatus::OK; } OP_STATUS UnixGadgetUninstaller::RemoveShareDir() { OpFile share; share.Construct(GetGadgetDir().CStr()); RETURN_IF_ERROR(share.Delete(TRUE)); return OpStatus::OK; } OP_STATUS UnixGadgetUninstaller::RemoveWrapperScript() { OpString wrapper_path; OpString tmp_storage; g_folder_manager->GetFolderPathIgnoreErrors(OPFILE_DEFAULT_GADGET_FOLDER, tmp_storage); RETURN_IF_ERROR(wrapper_path.Set(tmp_storage)); RETURN_IF_ERROR(wrapper_path.Append("bin/")); RETURN_IF_ERROR(wrapper_path.Append(GetInstallationName().CStr())); #ifdef _DEBUG OpString8 wrapper_path8; RETURN_IF_ERROR(wrapper_path8.Set(wrapper_path)); printf("wrapper location: %s\n", wrapper_path8.CStr()); #endif OpFile wrapper; RETURN_IF_ERROR(wrapper.Construct(wrapper_path.CStr())); RETURN_IF_ERROR(wrapper.Delete()); return OpStatus::OK; } OP_STATUS UnixGadgetUninstaller::RemoveDesktopEntries() { OP_ASSERT(NULL != m_context); DesktopShortcutInfo shortcut_info; shortcut_info.m_destination = DesktopShortcutInfo::SC_DEST_MENU; RETURN_IF_ERROR(shortcut_info.m_file_name.Set(GetInstallationName())); DesktopEntry desktop_entry; RETURN_IF_ERROR(desktop_entry.Init(shortcut_info)); RETURN_IF_ERROR(desktop_entry.Remove()); return OpStatus::OK; } OP_STATUS UnixGadgetUninstaller::UnlinkWrapperScript() { OpString link_path; RETURN_IF_ERROR(link_path.Set(op_getenv("HOME"))); RETURN_IF_ERROR(link_path.Append("/bin/" )); RETURN_IF_ERROR(link_path.Append(GetInstallationName().CStr())); OpFile link; RETURN_IF_ERROR(link.Construct(link_path.CStr())); RETURN_IF_ERROR(link.Delete(FALSE)); return OpStatus::OK; } #endif // WIDGET_RUNTIME_SUPPORT
#include <cctype> #include <chrono> #include <gsl/gsl> #include <iostream> #include <benchmark/benchmark.h> #include <HistoryItem.h> #include <HistoryItemModel.h> #include <QStandardItemModel> #include <FuzzySearch.h> static size_t GetTimestamp() { auto duration = std::chrono::system_clock::now().time_since_epoch(); return std::chrono::duration_cast<std::chrono::milliseconds>(duration).count(); } struct StringWithScore { std::string m_String; int m_MatchScore; }; static std::string_view GetStringFunc(const StringWithScore& obj) { return obj.m_String; } #define HISTORY_MODEL_BENCHMARK(BENCHMARK_NAME) BENCHMARK(BENCHMARK_NAME)->Range(8, 8 << 10)->Unit(benchmark::kMicrosecond); void BM_ModelInsert(benchmark::State& state) { std::vector<std::string> strings = { "git init", "git status", "git add my_new_file.txt", "git commit -m \"Add three files\"", "git reset --soft HEAD^", "git remote add origin https://github.com/heftyy/fuzzy-search.git", }; HistoryItemModel history_model(nullptr); for (const auto _ : state) { for (auto i = 0; i < state.range(0); ++i) { for (std::string text : strings) { text += std::to_string(i); std::hash<std::string> hasher; const size_t text_hash = hasher(text); history_model.AddToHistory({text, text_hash, GetTimestamp()}); } } history_model.Clear(); } } HISTORY_MODEL_BENCHMARK(BM_ModelInsert); void BM_BasicInsert(benchmark::State& state) { std::vector<std::string> strings = { "git init", "git status", "git add my_new_file.txt", "git commit -m \"Add three files\"", "git reset --soft HEAD^", "git remote add origin https://github.com/heftyy/fuzzy-search.git", }; std::vector<HistoryItem> history_items; for (const auto _ : state) { for (auto i = 0; i < state.range(0); ++i) { for (std::string text : strings) { text += std::to_string(i); std::hash<std::string> hasher; const size_t text_hash = hasher(text); history_items.emplace_back(HistoryItemData{text, text_hash, GetTimestamp()}); } } history_items.clear(); } } HISTORY_MODEL_BENCHMARK(BM_BasicInsert); #include <thread> void BM_ModelFilterAndSort(benchmark::State& state) { std::vector<std::string> strings = { "git init", "git status", "git add my_new_file.txt", "git commit -m \"Add three files\"", "git reset --soft HEAD^", "git remote add origin https://github.com/heftyy/fuzzy-search.git", }; HistoryItemModel history_model(nullptr); std::vector<HistoryItemData> history_items_data; for (auto i = 0; i < state.range(0); ++i) { for (std::string text : strings) { text += std::to_string(i); std::hash<std::string> hasher; const size_t text_hash = hasher(text); history_model.AddToHistory({text, text_hash, GetTimestamp()}); } } bool pattern_switch = false; for (const auto _ : state) { //! Need to switch the pattern for every other search because UpdateFilterPattern won't search and resort //! for the same pattern twice in a row bool result = history_model.UpdateFilterPattern(pattern_switch ? "add1" : "add2"); pattern_switch = !pattern_switch; benchmark::DoNotOptimize(result); } } HISTORY_MODEL_BENCHMARK(BM_ModelFilterAndSort); void BM_BasicFilterAndSort(benchmark::State& state) { std::vector<std::string> strings = { "git init", "git status", "git add my_new_file.txt", "git commit -m \"Add three files\"", "git reset --soft HEAD^", "git remote add origin https://github.com/heftyy/fuzzy-search.git", }; std::vector<StringWithScore> benchmark_strings; for (auto i = 0; i < state.range(0); ++i) { for (std::string text : strings) { text += std::to_string(i); benchmark_strings.push_back({text, 0}); } } for (const auto _ : state) { auto result = FuzzySearch::Search("add", benchmark_strings.begin(), benchmark_strings.end(), &GetStringFunc, FuzzySearch::MatchMode::E_STRINGS); benchmark::DoNotOptimize(result); } } HISTORY_MODEL_BENCHMARK(BM_BasicFilterAndSort); BENCHMARK_MAIN();
#ifndef _JYC_COMMON_H_ #define _JYC_COMMON_H_ #include <stdio.h> #include <string.h> #include <string> #include <iostream> #include <stdlib.h> #include <time.h> #include <ctype.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <vector> #include <map> #endif
#include <iostream> using namespace std; using ll = long long; const int INF = 1 << 25; int main() { int N, M; cin >> N >> M; int a[M][N + 1], rev[M][N]; for (int i = 0; i < M; ++i) { for (int j = 0; j < N; ++j) { cin >> a[i][j]; --a[i][j]; rev[i][a[i][j]] = j; } a[i][N] = INF + i; } ll ans = 0; int b; for (b = 0; b < N;) { int itr[M]; for (int i = 0; i < M; ++i) { itr[i] = rev[i][a[0][b]]; } bool judge = true; while (judge) { for (int i = 0; i < M; ++i) { ++itr[i]; if (itr[i] >= N) judge = false; } if (!judge) break; for (int i = 0; i < M - 1; ++i) { if (a[i][itr[i]] != a[i + 1][itr[i + 1]]) judge = false; } } ll len = itr[0] - b; ans += len * (len + 1) / 2; b = itr[0]; } cout << ans << endl; return 0; }
vector<int> Solution::solve(vector<int> &A) { int n = A.size(); vector<int> suffix(n, 0); int maxx = INT_MIN; for (int i = n - 1; i >= 0; i--) { maxx = max(A[i], maxx); suffix[i] = maxx; } vector<int> ans; for (int i = 0; i < n - 1; i++) { if (A[i] > suffix[i + 1]) ans.push_back(A[i]); } ans.push_back(A[n - 1]); return ans; }
#ifndef DEDVS_TYPES_H #define DEDVS_TYPES_H #include <cstdint> #include <vector> #include <chrono> //EDVSTOOLS #include "Edvs/Event.hpp" namespace dedvs { typedef std::chrono::high_resolution_clock::time_point ctp; struct StreamInfo { int x_resolution; int y_resolution; int fps; bool mirroring_enabled; }; struct DEvent { uint16_t u, v; uint16_t x, y; uint16_t depth; uint64_t time; uint8_t parity; ctp ct; void operator= (const DEvent &b) { u = b.u; v = b.v; x = b.x; y = b.y; depth = b.depth; time = b.time; parity = b.parity; ct = b.ct; } DEvent() {}; DEvent(const Edvs::Event &b, const ctp &ct_in) { u = b.x; v = b.y; time = b.t; parity = b.parity; ct = ct_in; } }; struct DEventExt { uint16_t u; // X-coordinate of the event uint16_t v; // Y-coordinate of the event float x; // X-coordinate of the led float y; // Y-coordinate of the led uint16_t depth; // depth of the led uint64_t time; // timestamp of the event uint8_t parity; // 0->1 1->0 ctp ct; void operator= (const DEventExt &b) { u = b.u; v = b.v; x = b.x; y = b.y; depth = b.depth; time = b.time; parity = b.parity; ct = b.ct; } }; /* Used to create the normalized FANN calibration material */ struct DEventExtF { float u; // X-coordinate of the event float v; // Y-coordinate of the event float x; // X-coordinate of the led float y; // Y-coordinate of the led float depth; // depth of the led uint64_t time; // timestamp of the event uint8_t parity; // 0->1 1->0 ctp ct; void operator= (const DEventExtF &b) { u = b.u; v = b.v; x = b.x; y = b.y; depth = b.depth; time = b.time; parity = b.parity; ct = b.ct; } }; struct Point3D { uint16_t x; uint16_t y; uint16_t depth; void operator= (const Point3D &b) { x = b.x; y = b.y; depth = b.depth; } bool operator== (const Point3D &b) const { return(x == b.x && y == b.y && depth == b.depth ); } Point3D() : x(0), y(0), depth(0) {} Point3D(uint16_t in_x, uint16_t in_y, uint16_t in_depth) : x(in_x), y(in_y), depth(in_depth) {} }; struct Point3DF { float x; float y; float depth; void operator= (const Point3DF &b) { x = b.x; y = b.y; depth = b.depth; } Point3DF() : x(0.0), y(0.0), depth(0.0) {} Point3DF(float in_x, float in_y, float in_depth) : x(in_x), y(in_y), depth(in_depth) {} }; } #endif
#ifndef Second_HPP #define Second_HPP #include <QObject> class Second : public QObject { Q_OBJECT public: Second(); ~Second(); }; #endif
#pragma once #include <string> #include <AL/al.h> enum EAudioSourceState { STATE_EMPTY, STATE_STOP, STATE_PLAY, STATE_PAUSE, STATE_REWIND }; class AudioSource { public: AudioSource(unsigned int& buffer); void play(bool loop=false); void pause(); void stop(); void rewind(); void free(); void setPosition(float x, float y, float z); void setDirection(float x, float y, float z); void setVelocity(float x, float y, float z); void setPitch(float pitch); void setGain(float gain); void setRollOffFactor(float x); void setReferenceDistance(float x); int getState(); private: unsigned int buffer; unsigned int source; EAudioSourceState state; };
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #ifndef BAJKA_LAYOUT_ALIGN_H_ #define BAJKA_LAYOUT_ALIGN_H_ #include <core/variant/Variant.h> namespace Model { /** * HAlign */ enum HAlign { HA_LEFT, HA_RIGHT, HA_CENTER }; /** * Do konwersji na wariant, użyteczne dla kontenera. */ extern Core::Variant stringToHAlign (std::string const &p); /** * VAlign */ enum VAlign { VA_TOP, VA_BOTTOM, VA_CENTER, }; /** * Do konwersji na wariant, użyteczne dla kontenera. */ extern Core::Variant stringToVAlign (std::string const &p); /** * HGravity */ enum HGravity { HG_LEFT, HG_RIGHT, HG_CENTER }; /** * Do konwersji na wariant, użyteczne dla kontenera. */ extern Core::Variant stringToHGravity (std::string const &p); /** * VGravity */ enum VGravity { VG_TOP, VG_BOTTOM, VG_CENTER }; /** * Do konwersji na wariant, użyteczne dla kontenera. */ extern Core::Variant stringToVGravity (std::string const &p); } //namespace #endif /* ALIGN_H_ */
// // 1012.cpp // baekjoon // // Created by 최희연 on 2021/06/29. // #include <iostream> using namespace std; int dx[4] = {0, 0, 1, -1}; int dy[4] = {1, -1, 0, 0}; int arr[51][51]; int visited[51][51]; void dfs(int M, int N, int x, int y){ if(visited[x][y] == 1) return; visited[x][y] = 1; for(int i=0;i<4;i++){ int nextX = x+dx[i]; int nextY = y+dy[i]; if(arr[nextX][nextY] == 1 && visited[nextX][nextY] == 0) dfs(M, N, nextX, nextY); } } int main(){ int T; scanf("%d", &T); while(T--){ for(int i=0;i<51;i++){ for(int j=0;j<51;j++){ arr[i][j]=0; } } for(int i=0;i<51;i++){ for(int j=0;j<51;j++){ visited[i][j]=0; } } int M, N, K; scanf("%d", &M); scanf("%d", &N); scanf("%d", &K); while(K--){ int X, Y; scanf("%d", &X); scanf("%d", &Y); arr[X][Y] = 1; } int cnt = 0; for(int i =0;i<M;i++){ for(int j = 0 ;j<N;j++){ if(arr[i][j] == 1 && visited[i][j] == 0){ cnt++; dfs(M, N, i, j); } } } cout<<cnt<<endl; } }
#include "chunkblock.h" #include "blockmanager.h" ChunkBlock::ChunkBlock(Block_t id) : id(id) { } ChunkBlock::ChunkBlock(BlockId id) : id(static_cast<Block_t>(id)) { } const Block &ChunkBlock::getBlock() const { return BlockManager::instance().getBlock(static_cast<BlockId>(id)); } const BlockData &ChunkBlock::getData() const { return getBlock().data(); }
// // Created by Brady Bodily on 2/27/17. // #ifndef BINGO_CARD_HPP #define BINGO_CARD_HPP #include <iostream> #include <vector> class Card { public: friend class CardTester; friend class DeckTester; Card(int cardSize, int numberMax, int cardIndex); void print(std::ostream& out) const; private: int m_cardSize; int m_numberMax; int m_cardIndex; std::vector<int> numbers; std::vector<std::vector<int>> vCard; }; #endif //BINGO_CARD_HPP
#ifndef PHYSICSLIST_HH #define PHYSICSLIST_HH #include "G4VModularPhysicsList.hh" class PhysicsList : public G4VModularPhysicsList { public: PhysicsList(); ~PhysicsList(); protected: void SetCuts(); }; #endif //PHYSICSLIST_HH
//---------------------------------------------------------------- // IconManager.cpp // // Copyright 2002-2004 Raven Software //---------------------------------------------------------------- #include "../idlib/precompiled.h" #pragma hdrstop #include "Game_local.h" #include "IconManager.h" rvIconManager iconManagerLocal; rvIconManager* iconManager = &iconManagerLocal; /* =============================================================================== rvIconManager =============================================================================== */ void rvIconManager::AddIcon( int clientNum, const char* iconName ) { assert( gameLocal.GetLocalPlayer() ); idPlayer* player = gameLocal.GetLocalPlayer(); icons[ clientNum ].Append( rvPair<rvIcon*, int>(new rvIcon(), gameLocal.time + ICON_STAY_TIME) ); icons[ clientNum ][ icons[ clientNum ].Num() - 1 ].First()->CreateIcon( player->spawnArgs.GetString( iconName ), (clientNum == gameLocal.localClientNum ? gameLocal.localClientNum + 1 : 0) ); } void rvIconManager::UpdateIcons( void ) { if( gameLocal.GetLocalPlayer() == NULL || !gameLocal.GetLocalPlayer()->GetRenderView() ) { return; } // draw team icons if( gameLocal.IsTeamGame() ) { UpdateTeamIcons(); } // draw chat icons UpdateChatIcons(); // remove old icons and icons not in our snapshot // ** if you want to have permanent icons, you'll have to add support // ** for the icons to re-appear when the player comes back in your snapshot (like team icons and chat icons) for ( int i = 0; i < MAX_CLIENTS; i++ ) { for( int j = 0; j < icons[ i ].Num(); j++ ) { if( gameLocal.time > icons[ i ][ j ].Second() || (gameLocal.entities[ i ] && gameLocal.entities[ i ]->fl.networkStale) ) { rvIcon* oldIcon = icons[ i ][ j ].First(); oldIcon->FreeIcon(); icons[ i ].RemoveIndex( j-- ); delete oldIcon; } } } idPlayer* localPlayer = gameLocal.GetLocalPlayer(); // draw extra icons for ( int i = 0; i < MAX_CLIENTS; i++ ) { if( gameLocal.localClientNum == i ) { continue; } if( gameLocal.entities[ i ] && gameLocal.entities[ i ]->IsType( idPlayer::GetClassType() ) ) { idPlayer* player = static_cast<idPlayer*>(gameLocal.entities[ i ]); if( player->IsHidden() || !icons[ i ].Num() ) { continue; } // distribute the icons appropriately int maxHeight = 0; int totalWidth = 0; for( int j = 0; j < icons[ i ].Num(); j++ ) { if( icons[ i ][ j ].First()->GetHeight() > maxHeight ) { maxHeight = icons[ i ][ j ].First()->GetHeight(); } totalWidth += icons[ i ][ j ].First()->GetWidth(); } idVec3 centerIconPosition = player->spawnArgs.GetVector( (player->team ? "team_icon_height_strogg" : "team_icon_height_marine") ); if( teamIcons[ player->entityNumber ].GetHandle() >= 0 ) { centerIconPosition[ 2 ] += teamIcons[ player->entityNumber ].GetHeight(); } int incrementalWidth = 0; for( int j = 0; j < icons[ i ].Num(); j++ ) { idVec3 iconPosition = centerIconPosition; iconPosition += ( (-totalWidth / 2) + incrementalWidth + (icons[ i ][ j ].First()->GetWidth() / 2) ) * localPlayer->GetRenderView()->viewaxis[ 1 ]; incrementalWidth += icons[ i ][ j ].First()->GetWidth(); icons[ i ][ j ].First()->UpdateIcon( player->GetPhysics()->GetOrigin() + iconPosition, localPlayer->GetRenderView()->viewaxis ); } } } } void rvIconManager::UpdateTeamIcons( void ) { idPlayer* localPlayer = gameLocal.GetLocalPlayer(); if ( !localPlayer ) { return; } int localTeam = localPlayer->team; bool spectating = localPlayer->spectating; if( localPlayer->spectating ) { idPlayer* spec = (idPlayer*)gameLocal.entities[ localPlayer->spectator ]; if( spec ) { localTeam = spec->team; localPlayer = spec; } else { localTeam = -1; } } for ( int i = 0; i < MAX_CLIENTS; i++ ) { if( gameLocal.localClientNum == i ) { continue; } //if entity i is a player, manage his icon. if( gameLocal.entities[ i ] && gameLocal.entities[ i ]->IsType( idPlayer::GetClassType() ) && !gameLocal.entities[ i ]->fl.networkStale && !spectating ) { idPlayer* player = static_cast<idPlayer*>(gameLocal.entities[ i ]); //if the player is alive and not hidden, show his icon. if( player->team == localTeam && !player->IsHidden() && !player->pfl.dead && gameLocal.mpGame.IsInGame( i ) ) { if( teamIcons[ i ].GetHandle() < 0 ) { teamIcons[ i ].CreateIcon( player->spawnArgs.GetString( player->team ? "mtr_team_icon_strogg" : "mtr_team_icon_marine" ), (player == localPlayer ? localPlayer->entityNumber + 1 : 0) ); } teamIcons[ i ].UpdateIcon( player->GetPhysics()->GetOrigin() + player->spawnArgs.GetVector( (player->team ? "team_icon_height_strogg" : "team_icon_height_marine") ), localPlayer->GetRenderView()->viewaxis ); //else, the player is hidden, dead, or otherwise not needing an icon-- free it. } else { if( teamIcons[ i ].GetHandle() >= 0 ) { teamIcons[ i ].FreeIcon(); } } //if entity i is not a player, free icon i from the map. } else if( teamIcons[ i ].GetHandle() >= 0 ) { teamIcons[ i ].FreeIcon(); } } } void rvIconManager::UpdateChatIcons( void ) { int localInst = gameLocal.GetLocalPlayer()->GetInstance(); for ( int i = 0; i < MAX_CLIENTS; i++ ) { if ( gameLocal.localClientNum == i ) { continue; } if ( gameLocal.entities[ i ] && gameLocal.entities[ i ]->IsType( idPlayer::GetClassType() ) && !gameLocal.entities[ i ]->fl.networkStale ) { idPlayer *player = static_cast< idPlayer* >( gameLocal.entities[ i ] ); if ( player->isChatting && !player->IsHidden() && !( ( idPhysics_Player* )player->GetPhysics() )->IsDead() && gameLocal.mpGame.IsInGame( i ) && (localInst == player->GetInstance())) { if ( chatIcons[ i ].GetHandle() < 0 ) { chatIcons[ i ].CreateIcon( player->spawnArgs.GetString( "mtr_icon_chatting" ), ( player == gameLocal.GetLocalPlayer() ? player->entityNumber + 1 : 0) ); } int maxHeight = 0; for ( int j = 0; j < icons[ i ].Num(); j++ ) { if ( icons[ i ][ j ].First()->GetHeight() > maxHeight ) { maxHeight = icons[ i ][ j ].First()->GetHeight(); } } if ( teamIcons[ i ].GetHandle() >= 0 && teamIcons[ i ].GetHeight() > maxHeight ) { maxHeight = teamIcons[ i ].GetHeight(); } idVec3 centerIconPosition = player->spawnArgs.GetVector( ( player->team ? "team_icon_height_strogg" : "team_icon_height_marine") ); centerIconPosition[ 2 ] += maxHeight; chatIcons[ i ].UpdateIcon( player->GetPhysics()->GetOrigin() + centerIconPosition, gameLocal.GetLocalPlayer()->GetRenderView()->viewaxis ); } else if ( chatIcons[ i ].GetHandle() >= 0 ) { chatIcons[ i ].FreeIcon(); } } else if ( chatIcons[ i ].GetHandle() >= 0 ) { chatIcons[ i ].FreeIcon(); } } } /* =============== rvIconManager::Shutdown =============== */ void rvIconManager::Shutdown( void ) { int i, j; for ( i = 0; i < MAX_CLIENTS; i++ ) { for ( j = 0; j < icons[ i ].Num(); j++ ) { icons[ i ][ j ].First()->FreeIcon(); } icons[ i ].Clear(); teamIcons[ i ].FreeIcon(); chatIcons[ i ].FreeIcon(); } }
#ifdef USES_P064 //####################################################################################################### //#################################### Plugin 064: APDS9960 Gesture ############################## //####################################################################################################### // ESPEasy Plugin to scan a gesture, proximity and light chip APDS9960 // written by Jochen Krapf (jk@nerd2nerd.org) // A new gesture is send immediately to controllers. // Proximity and Light are scanned frequently by given 'Delay' setting. // RGB is not scanned because there are only 4 vars per task. // Known BUG: While performing a gesture the reader function blocks rest of ESPEasy processing!!! (Feel free to fix...) // Note: The chip has a wide view-of-angle. If housing is in this angle the chip blocks! #define PLUGIN_064 #define PLUGIN_ID_064 64 #define PLUGIN_NAME_064 "Gesture - APDS9960 [DEVELOPMENT]" #define PLUGIN_VALUENAME1_064 "Gesture" #define PLUGIN_VALUENAME2_064 "Proximity" #define PLUGIN_VALUENAME3_064 "Light" /* #define PLUGIN_VALUENAME4_064 "R" #define PLUGIN_VALUENAME5_064 "G" #define PLUGIN_VALUENAME6_064 "B" */ #include <SparkFun_APDS9960.h> //Lib is modified to work with ESP SparkFun_APDS9960* PLUGIN_064_pds = NULL; boolean Plugin_064(byte function, struct EventStruct *event, String& string) { boolean success = false; switch (function) { case PLUGIN_DEVICE_ADD: { Device[++deviceCount].Number = PLUGIN_ID_064; Device[deviceCount].Type = DEVICE_TYPE_I2C; Device[deviceCount].Ports = 0; Device[deviceCount].VType = SENSOR_TYPE_SWITCH; Device[deviceCount].PullUpOption = false; Device[deviceCount].InverseLogicOption = false; Device[deviceCount].FormulaOption = false; Device[deviceCount].ValueCount = 3; Device[deviceCount].SendDataOption = true; Device[deviceCount].TimerOption = true; Device[deviceCount].TimerOptional = true; Device[deviceCount].GlobalSyncOption = true; break; } case PLUGIN_GET_DEVICENAME: { string = F(PLUGIN_NAME_064); break; } case PLUGIN_GET_DEVICEVALUENAMES: { strcpy_P(ExtraTaskSettings.TaskDeviceValueNames[0], PSTR(PLUGIN_VALUENAME1_064)); strcpy_P(ExtraTaskSettings.TaskDeviceValueNames[1], PSTR(PLUGIN_VALUENAME2_064)); strcpy_P(ExtraTaskSettings.TaskDeviceValueNames[2], PSTR(PLUGIN_VALUENAME3_064)); /* strcpy_P(ExtraTaskSettings.TaskDeviceValueNames[3], PSTR(PLUGIN_VALUENAME4_064)); strcpy_P(ExtraTaskSettings.TaskDeviceValueNames[4], PSTR(PLUGIN_VALUENAME5_064)); strcpy_P(ExtraTaskSettings.TaskDeviceValueNames[5], PSTR(PLUGIN_VALUENAME6_064)); */ break; } case PLUGIN_WEBFORM_LOAD: { byte addr = 0x39; // PCONFIG(0); chip has only 1 address int optionValues[1] = { 0x39 }; addFormSelectorI2C(F("i2c_addr"), 1, optionValues, addr); //Only for display I2C address success = true; break; } case PLUGIN_WEBFORM_SAVE: { //PCONFIG(0) = getFormItemInt(F("i2c_addr")); success = true; break; } case PLUGIN_INIT: { if (PLUGIN_064_pds) delete PLUGIN_064_pds; PLUGIN_064_pds = new SparkFun_APDS9960(); String log = F("APDS : "); if ( PLUGIN_064_pds->init() ) { log += F("Init"); PLUGIN_064_pds->enablePower(); if (! PLUGIN_064_pds->enableLightSensor(false)) log += F(" - Error during light sensor init!"); if (! PLUGIN_064_pds->enableProximitySensor(false)) log += F(" - Error during proximity sensor init!"); if (! PLUGIN_064_pds->enableGestureSensor(false)) log += F(" - Error during gesture sensor init!"); } else { log += F("Error during APDS-9960 init!"); } addLog(LOG_LEVEL_INFO, log); success = true; break; } case PLUGIN_FIFTY_PER_SECOND: { if (!PLUGIN_064_pds) break; if ( !PLUGIN_064_pds->isGestureAvailable() ) break; int gesture = PLUGIN_064_pds->readGesture(); //int gesture = PLUGIN_064_pds->readGestureNonBlocking(); //if (gesture == -1) serialPrint("."); //if (gesture == -2) serialPrint(":"); //if (gesture == -3) serialPrint("|"); //if ( 0 && PLUGIN_064_pds->isGestureAvailable() ) if (gesture >= 0) { String log = F("APDS : Gesture="); switch ( gesture ) { case DIR_UP: log += F("UP"); break; case DIR_DOWN: log += F("DOWN"); break; case DIR_LEFT: log += F("LEFT"); break; case DIR_RIGHT: log += F("RIGHT"); break; case DIR_NEAR: log += F("NEAR"); break; case DIR_FAR: log += F("FAR"); break; default: log += F("NONE"); break; } log += " ("; log += gesture; log += ')'; UserVar[event->BaseVarIndex] = (float)gesture; event->sensorType = SENSOR_TYPE_SWITCH; sendData(event); addLog(LOG_LEVEL_INFO, log); } success = true; break; } case PLUGIN_READ: { if (!PLUGIN_064_pds) break; // Gesture - work is done in PLUGIN_FIFTY_PER_SECOND if (1) { uint8_t proximity_data = 0; PLUGIN_064_pds->readProximity(proximity_data); UserVar[event->BaseVarIndex + 1] = (float)proximity_data; uint16_t ambient_light = 0; PLUGIN_064_pds->readAmbientLight(ambient_light); UserVar[event->BaseVarIndex + 2] = (float)ambient_light; /* uint16_t red_light = 0; uint16_t green_light = 0; uint16_t blue_light = 0; PLUGIN_064_pds->readRedLight(red_light); PLUGIN_064_pds->readGreenLight(green_light); PLUGIN_064_pds->readBlueLight(blue_light); UserVar[event->BaseVarIndex + 3] = (float)red_light; UserVar[event->BaseVarIndex + 4] = (float)green_light; UserVar[event->BaseVarIndex + 5] = (float)blue_light; */ } success = true; break; } } return success; } #endif // USES_P064
#ifndef G_XMATH_H #define G_XMATH_H #include <stdlib.h> #include <math.h> namespace XMath { // double version of rand() (in stdlib.h) double dRand() { return double(rand()) / RAND_MAX; } // norm of a vector (sqrt(x1*x1 + ... + xn*xn)) double dNorm(double* vec, int dim) { double elem; double sum = 0; for (int i = 0; i < dim; i++) { elem = vec[i]; sum += elem * elem; } return sqrt(sum); } // normalize x to [-1, 1] double dNormalize(double x, double width) { return x * 2.0 / width - 1; } // normalize a vector void vNormalize(double* v) { double d = sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); if (d == 0) { return; } else { v[0] /= d; v[1] /= d; v[2] /= d; } } // cross product of two vectors void vCross(double* v, double* u1, double* u2) { v[0] = u1[1] * u2[2] - u1[2] * u2[1]; v[1] = u1[2] * u2[0] - u1[0] * u2[2]; v[2] = u1[0] * u2[1] - u1[1] * u2[0]; } // inner product of two vectors double vInner(double* u1, double* u2) { return u1[0] * u2[0] + u1[1] * u2[1] + u1[2] * u2[2]; } }; #endif // G_XMATH_H
<<<<<<< HEAD /* ============================================================================== This file is part of the juce_core module of the JUCE library. Copyright (c) 2016 - ROLI Ltd. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ------------------------------------------------------------------------------ NOTE! This permissive ISC license applies ONLY to files within the juce_core module! All other JUCE modules are covered by a dual GPL/commercial license, so if you are using any other modules, be sure to check that you also comply with their license. For more details, visit www.juce.com ============================================================================== */ #if ! JUCE_ANDROID // We currently don't request runtime permissions on any other platform // than Android, so this file contains a dummy implementation for those. // This may change in the future. void RuntimePermissions::request (PermissionID /*permission*/, Callback callback) { callback (true); } bool RuntimePermissions::isRequired (PermissionID /*permission*/) { return false; } bool RuntimePermissions::isGranted (PermissionID /*permission*/) { return true; } #endif ======= /* ============================================================================== This file is part of the juce_core module of the JUCE library. Copyright (c) 2016 - ROLI Ltd. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ------------------------------------------------------------------------------ NOTE! This permissive ISC license applies ONLY to files within the juce_core module! All other JUCE modules are covered by a dual GPL/commercial license, so if you are using any other modules, be sure to check that you also comply with their license. For more details, visit www.juce.com ============================================================================== */ #if ! JUCE_ANDROID // We currently don't request runtime permissions on any other platform // than Android, so this file contains a dummy implementation for those. // This may change in the future. void RuntimePermissions::request (PermissionID /*permission*/, Callback callback) { callback (true); } bool RuntimePermissions::isRequired (PermissionID /*permission*/) { return false; } bool RuntimePermissions::isGranted (PermissionID /*permission*/) { return true; } #endif >>>>>>> Penhorse/master
/* * Copyright (c) 2021 Morwenn * SPDX-License-Identifier: MIT */ #ifndef CPPSORT_DETAIL_IMMOVABLE_VECTOR_H_ #define CPPSORT_DETAIL_IMMOVABLE_VECTOR_H_ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <cstddef> #include <new> #include <utility> #include <cpp-sort/utility/iter_move.h> #include "config.h" #include "memory.h" namespace cppsort { namespace detail { //////////////////////////////////////////////////////////// // Immovable vector // // Lightweight class similar to std::vector, but with a few // key differences: it allocates a buffer sufficient to store // a given number of elements during construction, and it can // not be moved. While its original goal was to provide an // std::vector-like class for immovable types, it is also // through the library as a light contiguous collection when // the number of elements to allocate is already known at // construction time. template<typename T> class immovable_vector { public: // Make the collection immovable immovable_vector(const immovable_vector&) = delete; immovable_vector(immovable_vector&&) = delete; immovable_vector& operator=(const immovable_vector&) = delete; immovable_vector& operator=(immovable_vector&&) = delete; //////////////////////////////////////////////////////////// // Construction immovable_vector(std::ptrdiff_t n): capacity_(n), memory_( static_cast<T*>(::operator new(n * sizeof(T))) ), end_(memory_) {} //////////////////////////////////////////////////////////// // Destruction ~immovable_vector() { // Destroy the constructed elements detail::destroy(memory_, end_); // Free the allocated memory #ifdef __cpp_sized_deallocation ::operator delete(memory_, capacity_ * sizeof(T)); #else ::operator delete(memory_); #endif } //////////////////////////////////////////////////////////// // Element access auto operator[](std::ptrdiff_t pos) -> T& { CPPSORT_ASSERT(pos <= end_ - memory_); return memory_[pos]; } auto front() -> T& { CPPSORT_ASSERT(memory_ != end_); return *memory_; } auto back() -> T& { CPPSORT_ASSERT(end_ - memory_ > 0); return *(end_ - 1); } //////////////////////////////////////////////////////////// // Iterators auto begin() -> T* { return memory_; } auto end() -> T* { return end_; } //////////////////////////////////////////////////////////// // Modifiers auto clear() noexcept -> void { // Destroy the constructed elements detail::destroy(memory_, end_); // Ensure the new size is zero end_ = memory_; } template<typename... Args> auto emplace_back(Args&&... args) -> void { CPPSORT_ASSERT(end_ - memory_ < capacity_); ::new(end_) T(std::forward<Args>(args)...); ++end_; } template<typename Iterator> auto insert_back(Iterator first, Iterator last) -> void { auto writer = end_; try { for (; first != last; ++first) { using utility::iter_move; ::new(writer) T(iter_move(first)); ++writer; } } catch (...) { // Cleanup detail::destroy(end_, writer); throw; } end_ = writer; } private: std::ptrdiff_t capacity_; T* memory_; T* end_; }; }} #endif // CPPSORT_DETAIL_IMMOVABLE_VECTOR_H_
// // Created by roy on 12/21/18. // #ifndef PROJECTPART1_SYMBOLTABLE_H #define PROJECTPART1_SYMBOLTABLE_H #include <unordered_map> #include <string> #include <mutex> #include <iostream> using namespace std; /** * This class is responsible for the storage of the variables which have * assigned (double) values, both binded variables and local variables. */ class SymbolTable { unordered_map<string, double> symbols; mutex m; public: /** * This method checks if a given symbol string is valid in * symbol map, and returns the fitting double value. * @param symbolString given string to search in map. * @return double value of the given string. */ double get(string symbolString) { lock_guard<mutex> guard(this->m); return symbols.at(symbolString); } /** * This method checks if a variable is in the map and returns the answer. * @param varName variable name for the check. * @return true if in map, else false. */ bool isInMap(string varName) { lock_guard<mutex> guard(this->m); for (unordered_map<string, double>::iterator it = symbols.begin(); it != symbols.end(); ++it) { if (it->first == varName) { return true; } } return false; } /** * This method sets given symbol and value to the symbol map. * @param symbolString string of the given symbol. * @param symbolValue value of the symbol. */ void set(string symbolString, double symbolValue) { lock_guard<mutex> guard(this->m); this->symbols[symbolString] = symbolValue; } }; #endif //PROJECTPART1_SYMBOLTABLE_H
#ifndef CYCLISTDETECTOR_HPP #define CYCLISTDETECTOR_HPP #include "Detector.hpp" #include "PointTracker.hpp" #include "ObjectLocator.hpp" class CyclistDetector: public Detector { private: RectangleTracker *old_tracker = nullptr; RectangleTracker *new_tracker = nullptr; ObjectLocator *object_locator = nullptr; unsigned int distance_threshold; unsigned int image_counter = 0; public: CyclistDetector(int, Conf &); ~CyclistDetector(); DetectionResult *Detect(cv::Mat &); private: void CreateNewTracker(); void AddRectanglesToTracker(cv::Mat &fore); void AccountNewObjects(DetectionResult *dr); void RenewTrackers(); }; #endif
#include "Arduino.h" #include <RZV_Blinking.h> void setup_RZV_Blink(){ pinMode(LED_BUILTIN,OUTPUT); } void RZV_Blink(int durata){ digitalWrite(LED_BUILTIN,HIGH); delay(durata); digitalWrite(LED_BUILTIN,LOW); delay(durata); }