hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
7945a84d9a2c62378e2471d1edfb16dfbf3fdc95
819
cpp
C++
cpp1st/week07/byongmin/01.constexpr.cpp
th4inquiry/PentaDevs
aa379d24494a485ad5e7fdcc385c6ccfb02cf307
[ "Apache-2.0" ]
2
2022-03-10T10:18:23.000Z
2022-03-16T15:37:22.000Z
cpp1st/week07/byongmin/01.constexpr.cpp
th4inquiry/PentaDevs
aa379d24494a485ad5e7fdcc385c6ccfb02cf307
[ "Apache-2.0" ]
8
2022-03-09T16:14:47.000Z
2022-03-28T15:35:17.000Z
cpp1st/week07/byongmin/01.constexpr.cpp
th4inquiry/PentaDevs
aa379d24494a485ad5e7fdcc385c6ccfb02cf307
[ "Apache-2.0" ]
4
2022-03-08T00:22:29.000Z
2022-03-12T13:22:43.000Z
#include <iostream> using namespace std; class RectConst { public: constexpr RectConst(size_t width, size_t height) : myWidth(width), myHeight(height) { } constexpr size_t getArea() const { return myWidth * myHeight; } private: int myWidth; int myHeight; }; class Rect { public: Rect(size_t width, size_t height) : myWidth(width), myHeight(height) { } size_t getArea() const { return myWidth * myHeight; } private: int myWidth; int myHeight; }; int main() { RectConst rectConst{8, 2}; int array[rectConst.getArea()]; cout << "getArea = " << rectConst.getArea() << endl; Rect rect{8, 2}; //int array[rect.getArea()]; // Error. conflicting declaration 'int array [<anonymous>]' return 0; }
15.75
93
0.600733
th4inquiry
794a1568ac8c9fa554b21ebbbf04ecf8e77adaec
25,708
cpp
C++
fhq-jury-ad/src/core/light_http_server.cpp
SibirCTF/2019-jury-system
bbd09c36b325ba1b616abfeca147ca1d113a2e97
[ "MIT" ]
null
null
null
fhq-jury-ad/src/core/light_http_server.cpp
SibirCTF/2019-jury-system
bbd09c36b325ba1b616abfeca147ca1d113a2e97
[ "MIT" ]
null
null
null
fhq-jury-ad/src/core/light_http_server.cpp
SibirCTF/2019-jury-system
bbd09c36b325ba1b616abfeca147ca1d113a2e97
[ "MIT" ]
null
null
null
#include "light_http_server.h" #include <utils_logger.h> #include <sstream> #include <iostream> #include <vector> #include <sys/stat.h> #include <sys/time.h> #include <fstream> #include <regex> // regex, sregex_token_iterator #include <stdio.h> #include <math.h> #include <thread> #include <algorithm> #include <fs.h> #include <ts.h> #include <fallen.h> // ---------------------------------------------------------------------- // LightHttpResponse // enum for http responses std::map<int, std::string> *LightHttpResponse::g_mapReponseDescription = nullptr; // deprecated std::string LightHttpResponse::RESP_OK = "HTTP/1.1 200 OK"; std::string LightHttpResponse::RESP_BAD_REQUEST = "HTTP/1.1 400 Bad Request"; std::string LightHttpResponse::RESP_FORBIDDEN = "HTTP/1.1 403 Forbidden"; std::string LightHttpResponse::RESP_NOT_FOUND = "HTTP/1.1 404 Not Found"; std::string LightHttpResponse::RESP_PAYLOAD_TOO_LARGE = "HTTP/1.1 413 Payload Too Large"; std::string LightHttpResponse::RESP_INTERNAL_SERVER_ERROR = "HTTP/1.1 500 Internal Server Error"; std::string LightHttpResponse::RESP_NOT_IMPLEMENTED = "HTTP/1.1 501 Not Implemented"; // ---------------------------------------------------------------------- LightHttpResponse::LightHttpResponse(int nSockFd) { TAG = "LightHttpResponse"; if (LightHttpResponse::g_mapReponseDescription == nullptr) { LightHttpResponse::g_mapReponseDescription = new std::map<int, std::string>(); LightHttpResponse::g_mapReponseDescription->insert(std::pair<int, std::string>(200,"HTTP/1.1 200 OK")); LightHttpResponse::g_mapReponseDescription->insert(std::pair<int, std::string>(400, "HTTP/1.1 400 Bad Request")); LightHttpResponse::g_mapReponseDescription->insert(std::pair<int, std::string>(403, "HTTP/1.1 403 Forbidden")); LightHttpResponse::g_mapReponseDescription->insert(std::pair<int, std::string>(404, "HTTP/1.1 404 Not Found")); LightHttpResponse::g_mapReponseDescription->insert(std::pair<int, std::string>(413, "HTTP/1.1 413 Payload Too Large")); LightHttpResponse::g_mapReponseDescription->insert(std::pair<int, std::string>(500, "HTTP/1.1 500 Internal Server Error")); LightHttpResponse::g_mapReponseDescription->insert(std::pair<int, std::string>(501, "HTTP/1.1 501 Not Implemented")); } m_nSockFd = nSockFd; m_bClosed = false; noCache(); long nSec = Fallen::currentTime_seconds(); m_sLastModified = Fallen::formatTimeForWeb(nSec); m_nResponseCode = 500; m_sDataType = "text/html"; } // ---------------------------------------------------------------------- LightHttpResponse &LightHttpResponse::ok() { m_nResponseCode = 200; return *this; } // ---------------------------------------------------------------------- LightHttpResponse &LightHttpResponse::badRequest() { m_nResponseCode = 400; return *this; } // ---------------------------------------------------------------------- LightHttpResponse &LightHttpResponse::forbidden() { m_nResponseCode = 403; return *this; } // ---------------------------------------------------------------------- LightHttpResponse &LightHttpResponse::notFound() { m_nResponseCode = 404; return *this; } // ---------------------------------------------------------------------- LightHttpResponse &LightHttpResponse::payloadTooLarge() { m_nResponseCode = 413; return *this; } // ---------------------------------------------------------------------- LightHttpResponse &LightHttpResponse::internalServerError() { m_nResponseCode = 500; return *this; } // ---------------------------------------------------------------------- LightHttpResponse &LightHttpResponse::notImplemented() { m_nResponseCode = 501; return *this; } // ---------------------------------------------------------------------- LightHttpResponse &LightHttpResponse::noCache() { m_sCacheControl = "no-cache, no-store, must-revalidate"; return *this; } // ---------------------------------------------------------------------- LightHttpResponse &LightHttpResponse::cacheSec(int nCacheSec) { m_sCacheControl = "max-age=" + std::to_string(nCacheSec); return *this; } // ---------------------------------------------------------------------- std::string LightHttpResponse::prepareHeaders(int nLength) { std::string sResponseCode = LightHttpResponse::g_mapReponseDescription->at(m_nResponseCode); return sResponseCode + "\r\n" "Date: " + m_sLastModified + "\r\n" "Server: wsjcpp\r\n" "Access-Control-Allow-Origin: *\r\n" "Cache-Control: " + m_sCacheControl + "\r\n" "Last-Modified: " + m_sLastModified + "\r\n" // TODO generate data "Content-Length: " + std::to_string(nLength) + "\r\n" "Content-Type: " + m_sDataType + "\r\n" "Connection: Closed\r\n"; } // ---------------------------------------------------------------------- std::string LightHttpResponse::detectTypeOfFile(const std::string &sFilePath) { // TODO cache: check file in cache std::string sFileExt = sFilePath.substr(sFilePath.find_last_of(".") + 1); std::string sType = "application/octet-stream"; if (sFileExt == "json") { sType = "application/json"; } else if (sFileExt == "css") { sType = "text/css"; } else if (sFileExt == "js") { sType = "text/javascript"; } else if (sFileExt == "html") { sType = "text/html"; } else if (sFileExt == "gif") { sType = "image/gif"; } else if (sFileExt == "ico") { sType = "image/x-icon"; } else if (sFileExt == "xml") { sType = "application/xml"; } else if (sFileExt == "png") { sType = "application/xml"; } else if (sFileExt == "jpg" || sFileExt == "jpeg") { sType = "image/jpeg"; } else if (sFileExt == "svg") { sType = "image/svg+xml"; } return sType; } // ---------------------------------------------------------------------- void LightHttpResponse::sendText(const std::string &sBody) { m_sDataType = "text/html"; std::string sResponse = prepareHeaders(sBody.length()) + "\r\n" + sBody; if (m_bClosed) { Log::warn(TAG, "Already sended response"); return; } m_bClosed = true; // Log::info(TAG, "\nResponse: \n>>>\n" + sResponse + "\n<<<"); send(m_nSockFd, sResponse.c_str(), sResponse.length(),0); close(m_nSockFd); } // ---------------------------------------------------------------------- void LightHttpResponse::sendEmpty() { this->sendText(""); } // ---------------------------------------------------------------------- void LightHttpResponse::sendOptions(const std::string &sOptions) { m_sDataType = "text/html"; std::string sResponse = prepareHeaders(0) + "Access-Control-Allow-Methods: " + sOptions + "\r\n\r\n"; if (m_bClosed) { Log::warn(TAG, "Already sended response"); return; } m_bClosed = true; // Log::info(TAG, "\nResponse: \n>>>\n" + sResponse + "\n<<<"); send(m_nSockFd, sResponse.c_str(), sResponse.length(),0); close(m_nSockFd); } // ---------------------------------------------------------------------- void LightHttpResponse::sendDontUnderstand() { std::string sResponse = "I don't understand you! Are you just a machine? Or maybe hacker?"; if (m_bClosed) { Log::warn(TAG, "Already sended response"); return; } m_bClosed = true; // Log::info(TAG, "\nResponse: \n>>>\n" + sResponse + "\n<<<"); send(m_nSockFd, sResponse.c_str(), sResponse.length(),0); close(m_nSockFd); } // ---------------------------------------------------------------------- void LightHttpResponse::sendFile(const std::string &sFilePath) { // read data from file std::ifstream f(sFilePath, std::ios::binary | std::ios::ate); std::streamsize nSize = f.tellg(); f.seekg(0, std::ios::beg); char *pData = new char[nSize]; // std::vector<char> buffer(size); if (nSize > 10*1024*1024) { this->payloadTooLarge(); this->sendEmpty(); delete[] pData; return; } if (!f.read(pData, nSize)) { this->forbidden(); this->sendEmpty(); delete[] pData; return; // std::cout << sFilePath << "\n filesize: " << nSize << " bytes\n"; } this->sendBuffer(sFilePath, pData, nSize); delete[] pData; } // ---------------------------------------------------------------------- void LightHttpResponse::sendBuffer(const std::string &sFilePath, const char *pBuffer, const int nBufferSize) { // TODO cache: check file in cache m_sDataType = detectTypeOfFile(sFilePath); std::string sResponse = prepareHeaders(nBufferSize) + "\r\n"; if (m_bClosed) { Log::warn(TAG, "Already sended response"); // delete[] pData; return; } m_bClosed = true; #if __APPLE__ send(m_nSockFd, sResponse.c_str(), sResponse.length(),SO_NOSIGPIPE); send(m_nSockFd, pData, nSize, SO_NOSIGPIPE); // #if // TARGET_OS_MAC #else send(m_nSockFd, sResponse.c_str(), sResponse.length(), MSG_CONFIRM); send(m_nSockFd, pBuffer, nBufferSize, MSG_CONFIRM); #endif close(m_nSockFd); } // ---------------------------------------------------------------------- // LightHttpRequest LightHttpRequest::LightHttpRequest(int nSockFd, const std::string &sAddress) { m_nSockFd = nSockFd; m_sAddress = sAddress; m_bClosed = false; m_sRequest = ""; m_nParserState = EnumParserState::START; TAG = "LightHttpRequest"; long nSec = Fallen::currentTime_seconds(); m_sLastModified = Fallen::formatTimeForWeb(nSec); m_nContentLength = 0; } // ---------------------------------------------------------------------- int LightHttpRequest::sockFd() { return m_nSockFd; } // ---------------------------------------------------------------------- std::string LightHttpRequest::requestType() { return m_sRequestType; } // ---------------------------------------------------------------------- std::string LightHttpRequest::requestPath() { return m_sRequestPath; } // ---------------------------------------------------------------------- std::string LightHttpRequest::requestHttpVersion() { return m_sRequestHttpVersion; } // ---------------------------------------------------------------------- std::map<std::string,std::string> &LightHttpRequest::requestQueryParams() { return m_sRequestQueryParams; } // ---------------------------------------------------------------------- std::string LightHttpRequest::address() { return m_sAddress; } // ---------------------------------------------------------------------- void LightHttpRequest::appendRecieveRequest(const std::string &sRequestPart) { m_sRequest += sRequestPart; const std::string sContentLengthPrefix = "content-length:"; if (m_nParserState == EnumParserState::START) { m_vHeaders.clear(); // Log::info(TAG, "START \n>>>\n" + m_sRequest + "\n<<<\n"); std::istringstream f(m_sRequest); std::string sLine = ""; int nSize = 0; bool bHeadersEnded = false; while (getline(f, sLine, '\n')) { nSize += sLine.length() + 1; Fallen::trim(sLine); // Log::info(TAG, "Line: {" + sLine + "}, size=" + std::to_string(sLine.length())); if (sLine.length() == 0) { bHeadersEnded = true; break; } m_vHeaders.push_back(sLine); Fallen::to_lower(sLine); if (!sLine.compare(0, sContentLengthPrefix.size(), sContentLengthPrefix)) { m_nContentLength = atoi(sLine.substr(sContentLengthPrefix.size()).c_str()); // Log::warn(TAG, "Content-Length: " + std::to_string(m_nContentLength)); } } if (bHeadersEnded) { if (m_vHeaders.size() > 0) { this->parseFirstLine(m_vHeaders[0]); } m_sRequest.erase(0, nSize); // Log::info(TAG, "AFTER ERASE \n>>>\n" + m_sRequest + "\n<<<\n"); m_nParserState = EnumParserState::BODY; } else { // Log::info(TAG, "Not ended"); } } if (m_nParserState == EnumParserState::BODY && m_sRequest.length() == m_nContentLength) { m_nParserState = EnumParserState::ENDED; m_sRequestBody = m_sRequest; } } // ---------------------------------------------------------------------- bool LightHttpRequest::isEnoughAppendReceived() { return m_nParserState == EnumParserState::ENDED; } // ---------------------------------------------------------------------- void LightHttpRequest::parseFirstLine(const std::string &sHeader) { if (sHeader.size() > 0) { std::istringstream f(sHeader); std::vector<std::string> params; std::string s; while (getline(f, s, ' ')) { params.push_back(s); } if (params.size() > 0) { m_sRequestType = params[0]; } if (params.size() > 1) { m_sRequestPath = params[1]; } // TODO m_sRequestPath - need split by ? if exists if (params.size() > 2) { m_sRequestHttpVersion = params[2]; } } // parse query std::size_t nFound = m_sRequestPath.find("?"); if (nFound != std::string::npos) { std::string sQuery = m_sRequestPath.substr(nFound+1); m_sRequestPath = m_sRequestPath.substr(0, nFound); std::istringstream f(sQuery); std::string sParam; while (getline(f, sParam, '&')) { std::size_t nFound2 = sParam.find("="); std::string sValue = sParam.substr(nFound2+1); std::string sName = sParam.substr(0, nFound2); m_sRequestQueryParams[sName] = sValue; // wrong use map for params } } } // ---------------------------------------------------------------------- // LightHttpDequeRequests LightHttpRequest *LightHttpDequeRequests::popRequest() { if (m_dequeRequests.size() == 0) { m_mtxWaiterRequests.lock(); } std::lock_guard<std::mutex> guard(this->m_mtxDequeRequests); LightHttpRequest *pRequest = nullptr; int nSize = m_dequeRequests.size(); if (nSize > 0) { pRequest = m_dequeRequests.back(); m_dequeRequests.pop_back(); } return pRequest; } // ---------------------------------------------------------------------- void LightHttpDequeRequests::pushRequest(LightHttpRequest *pRequest) { { std::lock_guard<std::mutex> guard(this->m_mtxDequeRequests); if (m_dequeRequests.size() > 20) { Log::warn(TAG, " deque more than " + std::to_string(m_dequeRequests.size())); } m_dequeRequests.push_front(pRequest); } if (m_dequeRequests.size() == 1) { m_mtxWaiterRequests.unlock(); } } // ---------------------------------------------------------------------- void LightHttpDequeRequests::cleanup() { std::lock_guard<std::mutex> guard(this->m_mtxDequeRequests); while (m_dequeRequests.size() > 0) { delete m_dequeRequests.back(); m_dequeRequests.pop_back(); } } // --------------------------------------------------------------------- // LightHttpHandlerBase LightHttpHandlerBase::LightHttpHandlerBase(const std::string &sName) { m_sName = sName; } // --------------------------------------------------------------------- const std::string &LightHttpHandlerBase::name() { return m_sName; } // --------------------------------------------------------------------- // LightHttpHandlers LightHttpHandlers::LightHttpHandlers() { TAG = "LightHttpHandlers"; } // --------------------------------------------------------------------- void LightHttpHandlers::add(LightHttpHandlerBase *pHandler) { m_pHandlers.push_back(pHandler); } // --------------------------------------------------------------------- void LightHttpHandlers::remove(const std::string &sName) { std::vector<LightHttpHandlerBase *>::iterator it = m_pHandlers.begin(); for (it = m_pHandlers.end(); it != m_pHandlers.begin(); it--) { LightHttpHandlerBase *pHandler = *it; if (pHandler->name() == sName) { m_pHandlers.erase(it); } } } // --------------------------------------------------------------------- bool LightHttpHandlers::find(const std::string &sName, LightHttpHandlerBase *pHandler) { std::vector<LightHttpHandlerBase *>::iterator it = m_pHandlers.begin(); for (it = m_pHandlers.begin(); it != m_pHandlers.end(); ++it) { LightHttpHandlerBase *p = *it; if (p->name() == sName) { pHandler = p; return true; } } return false; } // --------------------------------------------------------------------- bool LightHttpHandlers::handle(const std::string &sWorkerId, LightHttpRequest *pRequest) { std::string _tag = TAG + "-" + sWorkerId; for (int i = 0; i < m_pHandlers.size(); i++) { if (m_pHandlers[i]->canHandle(sWorkerId, pRequest)) { if (m_pHandlers[i]->handle(sWorkerId, pRequest)) { return true; } else { Log::warn("LightHttpHandlers", m_pHandlers[i]->name() + " - could not handle request '" + pRequest->requestPath() + "'"); } } } return false; } // ---------------------------------------------------------------------- // LightHttpThreadWorker void* processRequest(void *arg) { LightHttpThreadWorker *pWorker = (LightHttpThreadWorker *)arg; pthread_detach(pthread_self()); pWorker->run(); return 0; } // ---------------------------------------------------------------------- LightHttpThreadWorker::LightHttpThreadWorker(const std::string &sName, LightHttpDequeRequests *pDeque, LightHttpHandlers *pHandlers) { TAG = "LightHttpThreadWorker-" + sName; m_pDeque = pDeque; m_bStop = false; m_sName = sName; m_pHandlers = pHandlers; } // ---------------------------------------------------------------------- void LightHttpThreadWorker::start() { m_bStop = false; pthread_create(&m_serverThread, NULL, &processRequest, (void *)this); } // ---------------------------------------------------------------------- void LightHttpThreadWorker::stop() { m_bStop = true; } // ---------------------------------------------------------------------- void LightHttpThreadWorker::run() { const int nMaxPackageSize = 4096; while (1) { if (m_bStop) return; LightHttpRequest *pInfo = m_pDeque->popRequest(); bool bExists = pInfo != nullptr; // TODO refactor if (bExists) { int nSockFd = pInfo->sockFd(); // set timeout options struct timeval timeout; timeout.tv_sec = 1; // 1 seconds timeout timeout.tv_usec = 0; setsockopt(nSockFd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); struct sockaddr_in addr; socklen_t addr_size = sizeof(struct sockaddr_in); int res = getpeername(nSockFd, (struct sockaddr *)&addr, &addr_size); char *clientip = new char[20]; memset(clientip, 0, 20); strcpy(clientip, inet_ntoa(addr.sin_addr)); // Log::info(TAG, "IP-address: " + std::string(clientip)); LightHttpResponse *pResponse = new LightHttpResponse(nSockFd); int n; // int newsockfd = (long)arg; char msg[nMaxPackageSize]; std::string sRequest; // std::cout << nSockFd << ": address = " << info->address() << "\n"; // read data from socket bool bErrorRead = false; while (1) { // problem can be here // std::cout << nSockFd << ": wait recv...\n"; memset(msg, 0, nMaxPackageSize); n = recv(nSockFd, msg, nMaxPackageSize, 0); // std::cout << "N: " << n << std::endl; if (n == -1) { bErrorRead = true; std::cout << nSockFd << ": error read... \n"; break; } if (n == 0) { //close(nSockFd); break; } // Log::info(TAG, "Readed " + std::to_string(n) + " bytes..."); msg[n] = 0; //send(newsockfd,msg,n,0); sRequest = std::string(msg); std::string sRecv(msg); pInfo->appendRecieveRequest(sRecv); if (pInfo->isEnoughAppendReceived()) { break; } std::this_thread::sleep_for(std::chrono::milliseconds(10)); } // Log::info(TAG, "\nRequest: \n>>>\n" + sRequest + "\n<<<"); if (bErrorRead) { pResponse->sendDontUnderstand(); } else if (pInfo->requestType() == "OPTIONS") { pResponse->ok().sendOptions("OPTIONS, GET, POST"); } else if (pInfo->requestType() != "GET" && pInfo->requestType() != "POST") { pResponse->notImplemented().sendEmpty(); } else { if (!m_pHandlers->handle(m_sName, pInfo)) { pResponse->notFound().sendEmpty(); } else { // TODO resp internal error // this->response(LightHttpResponse::RESP_INTERNAL_SERVER_ERROR); } } delete pInfo; delete pResponse; } /*if (!bExists) { if (m_bStop) return; std::this_thread::sleep_for(std::chrono::milliseconds(100)); if (m_bStop) return; }*/ } } // ---------------------------------------------------------------------- // LightHttpServer LightHttpServer::LightHttpServer() { TAG = "LightHttpServer"; m_nMaxWorkers = 4; m_pDeque = new LightHttpDequeRequests(); m_pHandlers = new LightHttpHandlers(); m_bStop = false; m_nPort = 8080; } // ---------------------------------------------------------------------- void LightHttpServer::setPort(int nPort) { if (nPort > 10 && nPort < 65536) { m_nPort = nPort; } else { Log::warn(TAG, "Port must be 10...65535"); } m_nPort = nPort; } // ---------------------------------------------------------------------- void LightHttpServer::setMaxWorkers(int nMaxWorkers) { if (nMaxWorkers > 0 && nMaxWorkers <= 100) { m_nMaxWorkers = nMaxWorkers; } else { Log::warn(TAG, "Max workers must be 1...100"); } } // ---------------------------------------------------------------------- void LightHttpServer::startSync() { m_nSockFd = socket(AF_INET, SOCK_STREAM, 0); if (m_nSockFd <= 0) { Log::err(TAG, "Failed to establish socket connection"); return; } int enable = 1; if (setsockopt(m_nSockFd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) { Log::err(TAG, "setsockopt(SO_REUSEADDR) failed"); return; } memset(&m_serverAddress, 0, sizeof(m_serverAddress)); m_serverAddress.sin_family = AF_INET; m_serverAddress.sin_addr.s_addr = htonl(INADDR_ANY); m_serverAddress.sin_port = htons(m_nPort); if (bind(m_nSockFd, (struct sockaddr *)&m_serverAddress, sizeof(m_serverAddress)) == -1) { Log::err(TAG, "Error binding to port " + std::to_string(m_nPort)); return; } listen(m_nSockFd, 5); Log::info("LightHttpServer", "Light Http Server started on " + std::to_string(m_nPort) + " port."); for (int i = 0; i < m_nMaxWorkers; i++) { m_vWorkers.push_back(new LightHttpThreadWorker("worker" + std::to_string(i), m_pDeque, m_pHandlers)); } for (int i = 0; i < m_vWorkers.size(); i++) { m_vWorkers[i]->start(); } std::string str; m_bStop = false; while (!m_bStop) { // or problem can be here struct sockaddr_in clientAddress; socklen_t sosize = sizeof(clientAddress); int nSockFd = accept(m_nSockFd,(struct sockaddr*)&clientAddress,&sosize); std::string sAddress = inet_ntoa(clientAddress.sin_addr); LightHttpRequest *pInfo = new LightHttpRequest(nSockFd, sAddress); // info will be removed inside a thread m_pDeque->pushRequest(pInfo); // pthread_create(&m_serverThread, NULL, &newRequest, (void *)pInfo); // std::cout << "wait \n"; // std::this_thread::sleep_for(std::chrono::milliseconds(100)); } m_pDeque->cleanup(); for (int i = 0; i < m_vWorkers.size(); i++) { m_vWorkers[i]->stop(); } close(m_nSockFd); } // ---------------------------------------------------------------------- void* processWebServerStart(void *arg) { LightHttpServer *pWebServer = (LightHttpServer *)arg; pthread_detach(pthread_self()); pWebServer->startSync(); return 0; } // ---------------------------------------------------------------------- void LightHttpServer::start() { m_bStop = false; pthread_create(&m_serverThread, NULL, &processWebServerStart, (void *)this); } // ---------------------------------------------------------------------- LightHttpHandlers *LightHttpServer::handlers() { return m_pHandlers; } // ---------------------------------------------------------------------- void LightHttpServer::stop() { m_bStop = true; }
32.707379
137
0.512603
SibirCTF
794eabe2a177cfb60461b8cfdd4cc07673433e37
3,416
cpp
C++
c++/serial2com/v0.2/serial_write.cpp
BoKoIsMe/J1900_FreeBSD
19c4f7f01a37f4eda11a64040dad307a06563fb9
[ "BSD-2-Clause" ]
null
null
null
c++/serial2com/v0.2/serial_write.cpp
BoKoIsMe/J1900_FreeBSD
19c4f7f01a37f4eda11a64040dad307a06563fb9
[ "BSD-2-Clause" ]
null
null
null
c++/serial2com/v0.2/serial_write.cpp
BoKoIsMe/J1900_FreeBSD
19c4f7f01a37f4eda11a64040dad307a06563fb9
[ "BSD-2-Clause" ]
null
null
null
#include <iostream> #include <string> #include <sys/types.h> #include <errno.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <termios.h> //#include <stdlib.h> int open_port(int fd,int comport); int set_opt(int fd,int nSpeed,int nBits,char nEvent,int nStop); int main(int argc,char * argv[]) { using namespace std; int fd; int nwrite,arg_return; char buff[255] = "hello\n"; if((fd = open_port(fd,1))<0) { perror("open_port error"); return 0; } if((arg_return = set_opt(fd,115200,8,'N',1))<0) { perror("set_opt error"); return 0; } cout << "opened serial fd = " << fd << endl; for(int index = 65535;index != 0;index--) { nwrite = write(fd,buff,8); cout <<"nwrite = " << nwrite << ',' << buff << "at " << index << " time" << endl; } close(fd); return 0; } int set_opt(int fd,int nSpeed,int nBits,char nEvent,int nStop) { struct termios newtio,oldtio; //保存测试现有串口参数设置,在这里如果串口号等出错,会有相关出错信息 if (tcgetattr(fd,&oldtio) != 0) { perror("SetupSerial 1"); return -1; } bzero(&newtio,sizeof(newtio)); //设置字符大小 newtio.c_cflag |= CLOCAL | CREAD; newtio.c_cflag &= ~CSIZE; //设置停止位 switch(nBits) { case 7: newtio.c_cflag |= CS7; break; case 8: newtio.c_cflag |= CS8; break; } //设置奇偶校验位 switch(nEvent) { case 'O'://奇数 newtio.c_cflag |= PARENB; newtio.c_cflag |= PARODD; newtio.c_iflag |= (INPCK | ISTRIP); break; case 'E'://偶数 newtio.c_iflag |= (INPCK | ISTRIP); newtio.c_cflag |= PARENB; newtio.c_cflag &= ~PARODD; break; case 'N': newtio.c_cflag &= PARENB; break; } //设置数据传输率 switch(nSpeed) { case 2400: cfsetispeed(&newtio,B2400); cfsetospeed(&newtio,B2400); break; case 4800: cfsetispeed(&newtio,B4800); cfsetospeed(&newtio,B4800); break; case 9600: cfsetispeed(&newtio,B9600); cfsetospeed(&newtio,B9600); break; case 115200: cfsetispeed(&newtio,B115200); cfsetospeed(&newtio,B115200); break; case 460800: cfsetispeed(&newtio,B460800); cfsetospeed(&newtio,B460800); break; default: cfsetispeed(&newtio,B2400); cfsetospeed(&newtio,B2400); break; } //设置停止位 if (nStop == 1) newtio.c_cflag &= ~CSTOPB; else if (nStop == 2) newtio.c_cflag |= CSTOPB; //设置等待时间和最小接收字符 newtio.c_cc[VTIME] = 0; newtio.c_cc[VMIN] = 0; //处理未接收字符 tcflush(fd,TCIFLUSH); //激活新配置 if((tcsetattr(fd,TCSANOW,&newtio)) != 0) { perror("com set error"); return -1; } std::cout << "set done!" << std::endl; return 0; } int open_port(int fd,int comport) { //char *dev[] {"/dev/cuau1","/dev/cuau2","/dev/cuau3"}; //long vdisable; if (comport == 1)//串口1 { fd = open("/dev/ttyu1",O_RDWR|O_NOCTTY|O_NDELAY); if (-1 == fd) { perror("Can't Open Serial Port"); return -1; } } else if(comport == 2)//串口2 { fd = open("/dev/ttyu2",O_RDWR|O_NOCTTY|O_NDELAY); if (-1 == fd) { perror("Can't Open Serial Port"); return -1; } } else if (comport == 3)//串口3 { fd = open("/dev/ttyu3",O_RDWR|O_NOCTTY|O_NDELAY); if (-1 == fd) { perror("Can't Open Serial Port"); return -1; } } //恢复串口为阻塞状态 if(fcntl(fd,F_SETFL,0)<0) std::cout << "fcntl failed!" << std::endl; else std::cout << "fcntl = " << fcntl(fd,F_SETFL,0) << std::endl; //测试是否为终端设备 if (isatty(STDIN_FILENO) == 0) std::cout << "standard input is not a terminal device" << std::endl; else std::cout << "isatty success!" << std::endl; return fd; }
19.745665
82
0.619145
BoKoIsMe
7951c2099d2a2305c69ec684eb3cd8f04736fdcd
3,107
cpp
C++
Legacy/PrintBotDevelopmentEnvironment/Dialog.cpp
reghrafa/PrintBot
fb6b8e5dcb5cbf2c1b80ae89635e09081fff1617
[ "MIT" ]
null
null
null
Legacy/PrintBotDevelopmentEnvironment/Dialog.cpp
reghrafa/PrintBot
fb6b8e5dcb5cbf2c1b80ae89635e09081fff1617
[ "MIT" ]
null
null
null
Legacy/PrintBotDevelopmentEnvironment/Dialog.cpp
reghrafa/PrintBot
fb6b8e5dcb5cbf2c1b80ae89635e09081fff1617
[ "MIT" ]
null
null
null
#include "Dialog.h" #include "ProgramBlock.h" Dialog::Dialog(ProgramBlock *newProgramBlock, QWidget *parent) : programBlock(newProgramBlock), QWidget(parent) { // qDebug() << "neuer Dialog, this: " << this; qGridGroupBox.setFixedSize(DIALOG_WIDTH,DIALOG_HEIGHT); if (programBlock) { // qDebug() << "neuer Dialog mit newProgramBlock: " << programBlock; this->programBlock->createDialog(this); this->programBlock->updateSourcecodeWidget(); this->programBlock->generateGraphics(); // this->setupWidgets(); } else ///Leerer Dialog { // qDebug() << "neuer Dialog ohne newProgramBlock"; } this->qGridLayout.setColumnStretch(3,1); this->qGridLayout.setRowStretch(0,100); this->qGridLayout.setRowStretch(1,50); this->qGridGroupBox.setLayout(&qGridLayout); this->qGridGroupBox.setParent(this); } Dialog::~Dialog() { // qDebug() << "~Dialog"; // qDebug() << "~Dialog, this: " << this; // qDebug() << "~Dialog, programBlock: " << programBlock; // qDebug() << "~Dialog Mitte"; if (this->programBlock) { if (this->programBlock->getDialog() == this) { this->programBlock->deleteDialog(); } else { qDebug() << "ERROR?, ~Dialog: es existiert noch ein anderer Dialog: " << this->programBlock->getDialog(); } ///TODO: Evtl. Problem, dass Destruktor von programBlock gerade beim Durchlaufen ist!? programBlock->generateGraphics(); //deselectBlock programBlock->updateSourcecodeWidget(); } } ///entfernt den Rahmen des Blocks, der zu diesem Dialog gehört void Dialog::deselectBlock() { qDebug() << "Dialog::deselectBlock()"; if (programBlock) { programBlock->deleteDialog(); // qDebug() << "Dialog::deselectBlock(), Mitte"; programBlock->generateGraphics(); } // qDebug() << "Dialog::deselectBlock(), Ende"; } ProgramBlock *Dialog::getProgramBlock() { // qDebug() << "Dialog::getProgramBlock()"; return this->programBlock; } void Dialog::setProgramBlock(ProgramBlock *newProgramBlock) { this->programBlock = newProgramBlock; } QGridLayout &Dialog::getQGridLayout() { return this->qGridLayout; } QLabel &Dialog::getQLabel(int labelNumber) { if (labelNumber == 0) return this->qLabel0; else if (labelNumber == 1) return this->qLabel1; else qDebug() << "ERROR: Dialog::getLabel, undefined labelNumber"; } QSpinBox &Dialog::getQSpinBox() { return this->qSpinBox0; } QComboBox &Dialog::getQComboBox(int comboBoxNumber) { if (comboBoxNumber == 0) return this->qComboBox0; else if (comboBoxNumber == 1) return this->qComboBox1; else if (comboBoxNumber == 2) return this->qComboBox2; else qDebug() << "ERROR: Dialog::getQComboBox, undefined comboBoxNumber"; } QSlider &Dialog::getQSlider() { return qSlider0; } QLineEdit &Dialog::getQLineEdit() { return qLineEdit0; } QDoubleSpinBox &Dialog::getQDoubleSpinBox() { return qDoubleSpinBox; } QDial &Dialog::getQDial() { return qDial; }
25.260163
117
0.646283
reghrafa
7959fe8af057f9068966bdfb0e40465848e2d815
1,249
cpp
C++
src/common/ServiceThread.cpp
kangliqiang/rocketmq-client4cpp
ebea2464f769f24f60206e998411f65c53f87b01
[ "Apache-2.0" ]
12
2016-01-07T07:24:05.000Z
2021-02-03T08:03:20.000Z
src/common/ServiceThread.cpp
yaosiming/vesselmq-client4c
a7af22d83c2e8cd27346940cd7215c7fe2918961
[ "Apache-2.0" ]
1
2016-12-27T07:45:14.000Z
2018-03-21T05:09:51.000Z
src/common/ServiceThread.cpp
yaosiming/vesselmq-client4c
a7af22d83c2e8cd27346940cd7215c7fe2918961
[ "Apache-2.0" ]
4
2016-01-14T11:10:22.000Z
2018-01-16T02:16:59.000Z
/** * Copyright (C) 2013 kangliqiang ,[email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ServiceThread.h" #include "Monitor.h" #include "ScopedLock.h" ServiceThread::ServiceThread(const char* name) :kpr::Thread(name), m_notified(false), m_stoped(false) { } ServiceThread::~ServiceThread() { } void ServiceThread::stop() { m_stoped = true; wakeup(); } void ServiceThread::wakeup() { kpr::ScopedLock<kpr::Monitor> lock(*this); if (!m_notified) { m_notified = true; Notify(); } } void ServiceThread::waitForRunning(long interval) { kpr::ScopedLock<kpr::Monitor> lock(*this); if (m_notified) { m_notified = false; return; } try { Wait(interval); } catch (...) { m_notified = false; } }
18.101449
74
0.705364
kangliqiang
79627c204104b1e470dac018c9aa33a0dc3dc6d0
11,414
hpp
C++
qmath/include/qmath/mat3.hpp
jeanleflambeur/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
36
2015-03-09T16:47:14.000Z
2021-02-04T08:32:04.000Z
qmath/include/qmath/mat3.hpp
jeanlemotan/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
42
2017-02-11T11:15:51.000Z
2019-12-28T16:00:44.000Z
qmath/include/qmath/mat3.hpp
jeanleflambeur/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
5
2015-10-15T05:46:48.000Z
2020-05-11T17:40:36.000Z
namespace math { template<typename T> mat3<T> const mat3<T>::zero(0); \ template<typename T> mat3<T> const mat3<T>::one(1); \ template<typename T> mat3<T> const mat3<T>::identity; \ /////////////////////////////////////////////////////////////////////////////// //constructors /////////////////////////////////////////////////////////////////////////////// template <typename T> inline mat3<T>::mat3() : column0(math::uninitialized) , column1(math::uninitialized) , column2(math::uninitialized) { set_identity(); } template <typename T> inline mat3<T>::mat3(ZUninitialized) : column0(math::uninitialized) , column1(math::uninitialized) , column2(math::uninitialized) { } template <typename T> inline mat3<T>::mat3(T value) : column0(math::uninitialized) , column1(math::uninitialized) , column2(math::uninitialized) { MATH_ASSERT(is_finite(value)); m[0] = m[1] = m[2] = value; m[3] = m[4] = m[5] = value; m[6] = m[7] = m[8] = value; } template<typename T> template<typename U> inline mat3<T>::mat3(mat3<U> const& other) : column0(math::uninitialized) , column1(math::uninitialized) , column2(math::uninitialized) { m[0] = (T)other.m[0]; m[1] = (T)other.m[1]; m[2] = (T)other.m[2]; m[3] = (T)other.m[3]; m[4] = (T)other.m[4]; m[5] = (T)other.m[5]; m[6] = (T)other.m[6]; m[7] = (T)other.m[7]; m[8] = (T)other.m[8]; } template<typename T> inline mat3<T>::mat3(T const v0, T const v1, T const v2, T const v3, T const v4, T const v5, T const v6, T const v7, T const v8) : column0(math::uninitialized) , column1(math::uninitialized) , column2(math::uninitialized) { m[0] = v0; m[1] = v1; m[2] = v2; m[3] = v3; m[4] = v4; m[5] = v5; m[6] = v6; m[7] = v7; m[8] = v8; MATH_ASSERT(is_finite(m[0]) && is_finite(m[1]) && is_finite(m[2]) && is_finite(m[3]) && is_finite(m[4]) && is_finite(m[5]) && is_finite(m[6]) && is_finite(m[7]) && is_finite(m[8])); } template<typename T> inline mat3<T>::mat3(vec3<T> const& column0, vec3<T> const& column1, vec3<T> const& column2) : column0(column0) , column1(column1) , column2(column2) { m[0] = column0.x; m[1] = column0.y; m[2] = column0.z; m[3] = column1.x; m[4] = column1.y; m[5] = column1.z; m[6] = column2.x; m[7] = column2.y; m[8] = column2.z; } ///! Creates a world space lookat matrix (front axis is -yaxis, up axis is zaxis) /// This lookAt method computes a look at matrix in jet coordinate system (3dmax biped). /// This means that when you send a front of (0,1,0) and an up of (0,0,1) the resulting matrix is identity. template<class T> template<class Policy> inline mat3<T> mat3<T>::look_at(vec3<T> const& front, vec3<T> const& up) { vec3<T> axisY = normalized<T, Policy>(front); vec3<T> axisX = cross(axisY, normalized<T, Policy>(up)); axisX.template normalize<Policy>(); //this normalize is mandatory because axisY and up may be unitary but they hardly are orthogonal vec3<T> axisZ = cross(axisX, axisY); mat3<T> mat; T* m = mat.m; m[0] = axisX.x; m[1] = axisX.y; m[2] = axisX.z; m[3] = axisY.x; m[4] = axisY.y; m[5] = axisY.z; m[6] = axisZ.x; m[7] = axisZ.y; m[8] = axisZ.z; MATH_ASSERT(is_finite(m[0]) && is_finite(m[1]) && is_finite(m[2]) && is_finite(m[3]) && is_finite(m[4]) && is_finite(m[5]) && is_finite(m[6]) && is_finite(m[7]) && is_finite(m[8])); return mat; } /////////////////////////////////////////////////////////////////////////////// //methods /////////////////////////////////////////////////////////////////////////////// template<typename T> inline void mat3<T>::set(T const values[9]) { MATH_ASSERT(values); memcpy(m, values, sizeof(T)*element_count); MATH_ASSERT(is_finite(m[0]) && is_finite(m[1]) && is_finite(m[2]) && is_finite(m[3]) && is_finite(m[4]) && is_finite(m[5]) && is_finite(m[6]) && is_finite(m[7]) && is_finite(m[8])); } template <typename T> inline void mat3<T>::set_identity() { m[0] = m[4] = (T)1; m[1] = m[2] = m[3] = m[5] = (T)0; m[8] = (T)1; m[6] = m[7] = (T)0; } template <typename T> template <class Policy> inline bool mat3<T>::invert() { // http://www.geometrictools.com/LibFoundation/Mathematics/Wm4Matrix3.inl // Invert a 3x3 using cofactors. This is faster than using a generic // Gaussian elimination because of the loop overhead of such a method. mat3<T> inv; inv.m[0] = m[4]*m[8] - m[5]*m[7]; inv.m[1] = m[2]*m[7] - m[1]*m[8]; inv.m[2] = m[1]*m[5] - m[2]*m[4]; inv.m[3] = m[5]*m[6] - m[3]*m[8]; inv.m[4] = m[0]*m[8] - m[2]*m[6]; inv.m[5] = m[2]*m[3] - m[0]*m[5]; inv.m[6] = m[3]*m[7] - m[4]*m[6]; inv.m[7] = m[1]*m[6] - m[0]*m[7]; inv.m[8] = m[0]*m[4] - m[1]*m[3]; T fDet = m[0]*inv.m[0] + m[1]*inv.m[3] + m[2]*inv.m[6]; if (is_zero(fDet)) { return false; } T fInvDet = inverse<T, Policy>(fDet); inv.m[0] *= fInvDet; inv.m[1] *= fInvDet; inv.m[2] *= fInvDet; inv.m[3] *= fInvDet; inv.m[4] *= fInvDet; inv.m[5] *= fInvDet; inv.m[6] *= fInvDet; inv.m[7] *= fInvDet; inv.m[8] *= fInvDet; *this = inv; MATH_ASSERT(is_finite(m[0]) && is_finite(m[1]) && is_finite(m[2]) && is_finite(m[3]) && is_finite(m[4]) && is_finite(m[5]) && is_finite(m[6]) && is_finite(m[7]) && is_finite(m[8])); return true; } template <typename T> inline void mat3<T>::transpose() { std::swap(m[1], m[3]); std::swap(m[2], m[6]); std::swap(m[5], m[7]); } template <typename T> inline vec3<T> mat3<T>::get_row(uint8_t row) const { MATH_ASSERT(row < row_count); return vec3<T>(m[row + 0], m[row + 3], m[row + 6]); } template <typename T> inline void mat3<T>::set_row(uint8_t row, vec3<T> const& v) { MATH_ASSERT(is_finite(v)); MATH_ASSERT(row < row_count); m[row + 0] = v.x; m[row + 3] = v.y; m[row + 6] = v.z; } template <typename T> inline vec3<T> const& mat3<T>::get_column(uint8_t column) const { MATH_ASSERT(column < column_count); uint8_t idx = column * row_count; return reinterpret_cast<vec3<T> const&>(m[idx + 0]); } template <typename T> inline void mat3<T>::set_column(uint8_t column, vec3<T> const& v) { MATH_ASSERT(is_finite(v)); MATH_ASSERT(column < column_count); uint8_t idx = column * row_count; m[idx + 0] = v.x; m[idx + 1] = v.y; m[idx + 2] = v.z; } template <typename T> inline vec3<T> const& mat3<T>::get_axis_x() const { return get_column(0); } template <typename T> inline vec3<T> const& mat3<T>::get_axis_y() const { return get_column(1); } template <typename T> inline vec3<T> const& mat3<T>::get_axis_z() const { return get_column(2); } template <typename T> inline vec3<T> mat3<T>::get_scale() const { return vec3<T>(math::length(get_axis_x()), math::length(get_axis_y()), math::length(get_axis_z())); } template <typename T> inline void mat3<T>::set_axis_x(vec3<T> const& axis) { MATH_ASSERT(is_finite(axis)); m[0] = axis.x; m[1] = axis.y; m[2] = axis.z; } template <typename T> inline void mat3<T>::set_axis_y(vec3<T> const& axis) { MATH_ASSERT(is_finite(axis)); m[3] = axis.x; m[4] = axis.y; m[5] = axis.z; } template <typename T> inline void mat3<T>::set_axis_z(vec3<T> const& axis) { MATH_ASSERT(is_finite(axis)); m[6] = axis.x; m[7] = axis.y; m[8] = axis.z; } template <typename T> inline void mat3<T>::set_scale(vec3<T> const& s) { MATH_ASSERT(is_finite(s)); m[0] = s.x; m[4] = s.y; m[8] = s.z; } template <typename T> inline void mat3<T>::post_scale(vec3<T> const& s) { MATH_ASSERT(is_finite(s)); m[0] *= s.x; m[4] *= s.y; m[8] *= s.z; } ////////////////////////////////////////////////////////////////////////// template <typename T> inline bool mat3<T>::operator==(mat3<T> const& m) const { return memcmp(this->m, m.m, sizeof(T) * element_count) == 0; } template <typename T> inline bool mat3<T>::operator!=(mat3<T> const& m) const { return !operator==(m); } /////////////////////////////////////////////////////////////////////////////// // indexing operators /////////////////////////////////////////////////////////////////////////////// template <typename T> inline T* mat3<T>::data() { return m; } template <typename T> inline T const* mat3<T>::data() const { return m; } template <typename T> inline T& mat3<T>::operator()(uint8_t column, uint8_t row) { MATH_ASSERT(column < column_count && row < row_count); return m[column*row_count + row]; } template <typename T> inline T const& mat3<T>::operator()(uint8_t column, uint8_t row) const { MATH_ASSERT(column < column_count && row < row_count); return m[column*row_count + row]; } template <typename T> inline mat3<T> mat3<T>::operator*(mat3<T> const& other) const { mat3<T> ret(math::uninitialized); return multiply(ret, *this, other); } template <typename T> inline mat3<T> mat3<T>::operator+(mat3<T> const& other) const { mat3<T> ret(math::uninitialized); return cwise::add(ret, *this, other); } template <typename T> inline mat3<T> mat3<T>::operator-(mat3<T> const& other) const { mat3<T> ret(math::uninitialized); return cwise::substract(ret, *this, other); } template <typename T> inline mat3<T>& mat3<T>::operator*=(mat3<T> const& other) { mat3<T> a(*this); return multiply(*this, a, other); } template <typename T> inline mat3<T>& mat3<T>::operator+=(mat3<T> const& other) { return cwise::add(*this, *this, other); } template <typename T> inline mat3<T>& mat3<T>::operator-=(mat3<T> const& other) { return cwise::substract(*this, *this, other); } template <typename T> inline mat3<T> mat3<T>::operator*(T scalar) const { MATH_ASSERT(is_finite(scalar)); mat3<T> ret(math::uninitialized); return cwise::multiply(ret, *this, scalar); } template <typename T> inline mat3<T> mat3<T>::operator+(T scalar) const { MATH_ASSERT(is_finite(scalar)); mat3<T> ret(math::uninitialized); return cwise::add(ret, *this, scalar); } template <typename T> inline mat3<T> mat3<T>::operator-(T scalar) const { MATH_ASSERT(is_finite(scalar)); mat3<T> ret(math::uninitialized); return cwise::substract(ret, *this, scalar); } template <typename T> inline mat3<T>& mat3<T>::operator*=(T scalar) { MATH_ASSERT(is_finite(scalar)); return cwise::multiply(*this, *this, scalar); } template <typename T> inline mat3<T>& mat3<T>::operator+=(T scalar) { MATH_ASSERT(is_finite(scalar)); return cwise::add(*this, *this, scalar); } template <typename T> inline mat3<T>& mat3<T>::operator-=(T scalar) { MATH_ASSERT(is_finite(scalar)); return cwise::substract(*this, *this, scalar); } }
26.482599
137
0.545733
jeanleflambeur
7966b213fa4cf117f76763778ebf11d519786445
11,667
hpp
C++
falcon/algorithm/recursive_for_each.hpp
jonathanpoelen/falcon
5b60a39787eedf15b801d83384193a05efd41a89
[ "MIT" ]
2
2018-02-02T14:19:59.000Z
2018-05-13T02:48:24.000Z
falcon/algorithm/recursive_for_each.hpp
jonathanpoelen/falcon
5b60a39787eedf15b801d83384193a05efd41a89
[ "MIT" ]
null
null
null
falcon/algorithm/recursive_for_each.hpp
jonathanpoelen/falcon
5b60a39787eedf15b801d83384193a05efd41a89
[ "MIT" ]
null
null
null
#ifndef FALCON_ALGORITHM_RECURSIVE_FOR_EACH_HPP #define FALCON_ALGORITHM_RECURSIVE_FOR_EACH_HPP #include <falcon/c++/reference.hpp> #include <falcon/c++/conditional_cpp.hpp> #include <falcon/iterator/subrange_access_iterator.hpp> #include <falcon/type_traits/dimension.hpp> #include <falcon/type_traits/ignore.hpp> #include <falcon/utility/move.hpp> namespace falcon { namespace _aux { template <class Function, class T, bool Break = true> struct break_off { Function function; T value; #if __cplusplus < 201103L break_off(const Function& function, const T& value) : function(function) , value(value) {} #endif }; template <class Function, class Functor, bool Break = true> struct break_if { Function function; Functor functor; #if __cplusplus < 201103L break_if(const Function& function, const T& functor) : function(function) , functor(functor) {} #endif }; template <class Function, class T, bool Break = true> struct return_off { Function function; T value; #if __cplusplus < 201103L return_off(const Function& function, const T& value) : function(function) , value(value) {} #endif }; template <class Function, class Functor, bool Break = true> struct return_if { Function function; Functor functor; #if __cplusplus < 201103L return_if(const Function& function, const T& functor) : function(function) , functor(functor) {} #endif }; template <std::size_t Dimension> struct recursive_for_each { template<class Iterator, class Function> static void for_each(Iterator first, Iterator last, Function& f) { for (; first != last; ++first) { recursive_for_each<Dimension-1>::for_each(begin(*first), end(*first), f); } } template<class Iterator, class Function, class T, bool Break> static bool for_each(Iterator first, Iterator last, return_off<Function, T, Break>& w) { for (; first != last; ++first) { if (!recursive_for_each<Dimension-1>::for_each(begin(*first), end(*first), w)) { return false; } } return true; } template<class Iterator, class Function, class Functor, bool Break> static bool for_each(Iterator first, Iterator last, return_if<Function, Functor, Break>& w) { for (; first != last; ++first) { if (!recursive_for_each<Dimension-1>::for_each(begin(*first), end(*first), w)) { return false; } } return true; } }; template <> struct recursive_for_each<0> { template<class Iterator, class Function> static void for_each(Iterator first, Iterator last, Function& f) { for (; first != last; ++first) { f(*first); } } template<class Iterator, class Function, class T, bool B> static void for_each(Iterator first, Iterator last, break_off<Function, T, B>& w) { for (; first != last && (B ? *first != w.value : *first != w.value); ++first) { w.function(*first); } } template<class Iterator, class Function, class Functor, bool B> static void for_each(Iterator first, Iterator last, break_if<Function, Functor, B>& w) { for (; first != last && B == w.functor(*first); ++first) { w.function(*first); } } template<class Iterator, class Function, class T, bool B> static bool for_each(Iterator first, Iterator last, return_off<Function, T, B>& w) { for (; first != last; ++first) { if (B ? *first == w.value : *first != w.value) { return false; } w.function(*first); } return true; } template<class Iterator, class Function, class Functor, bool B> static bool for_each(Iterator first, Iterator last, return_if<Function, Functor, B>& w) { for (; first != last; ++first) { if (B != w.functor(*first)) { return false; } w.function(*first); } return true; } }; template<class Preface, class Function, class Postface, std::size_t Dimension> class recursive_intermediate; } #if __cplusplus >= 201103L template <class Function, class T> inline _aux::break_off<Function, T> break_off(Function&& function, T&& value) { return {std::forward<Function>(function), std::forward<T>(value)}; } template <class Function, class T> inline _aux::break_off<Function, T, false> break_off_not(Function&& function, T&& value) { return {std::forward<Function>(function), std::forward<T>(value)}; } template <class Function, class Functor> inline _aux::break_if<Function, Functor> break_if(Function&& function, Functor&& functor) { return {std::forward<Function>(function), std::forward<Functor>(functor)}; } template <class Function, class Functor> inline _aux::break_if<Function, Functor, false> break_if_not(Function&& function, Functor&& functor) { return {std::forward<Function>(function), std::forward<Functor>(functor)}; } #else template <class Function, class T> inline _aux::break_off<Function, T> break_off(Function function, const T& value) { return _aux::break_off<Function, T>(function, value); } template <class Function, class T> inline _aux::break_off<Function, T, false> break_off_not(Function function, const T& value) { return _aux::break_off<Function, T, false>(function, value); } template <class Function, class Functor> inline _aux::break_if<Function, Functor> break_if(Function function, Functor functor) { return _aux::break_if<Function, Functor>(function, functor); } template <class Function, class Functor> inline _aux::break_if<Function, Functor, false> break_if_not(Function function, Functor functor) { return _aux::break_if<Function, Functor, false>(function, functor); } #endif #if __cplusplus >= 201103L template <class Function, class T> inline _aux::return_off<Function, T> return_off(Function&& function, T&& value) { return {std::forward<Function>(function), std::forward<T>(value)}; } template <class Function, class T> inline _aux::return_off<Function, T, false> return_off_not(Function&& function, T&& value) { return {std::forward<Function>(function), std::forward<T>(value)}; } template <class Function, class Functor> inline _aux::return_if<Function, Functor> return_if(Function&& function, Functor&& functor) { return {std::forward<Function>(function), std::forward<Functor>(functor)}; } template <class Function, class Functor> inline _aux::return_if<Function, Functor, false> return_if_not(Function&& function, Functor&& functor) { return {std::forward<Function>(function), std::forward<Functor>(functor)}; } #else template <class Function, class T> inline _aux::return_off<Function, T> return_off(Function function, const T& value) { return _aux::return_off<Function, T>(function, value); } template <class Function, class T> inline _aux::return_off<Function, T, false> return_off_not(Function function, const T& value) { return _aux::return_off<Function, T, false>(function, value); } template <class Function, class Functor> inline _aux::return_if<Function, Functor> return_if(Function function, Functor functor) { return _aux::return_if<Function, Functor>(function, functor); } template <class Function, class Functor> inline _aux::return_if<Function, Functor, false> return_if_not(Function function, Functor functor) { return _aux::return_if<Function, Functor, false>(function, functor); } #endif template <class Iterator, class Function> Function recursive_for_each(Iterator first, Iterator last, Function f) { _aux::recursive_for_each<dimension< #if __cplusplus >= 201103L decltype(*std::declval<Iterator>()) #else std::iterator_traits<Iterator>::type #endif >::value - 1>::for_each(first, last, f); return FALCON_FORWARD(Function, f); } template <std::size_t Dimension, class Iterator, class Function> Function recursive_for_each(Iterator first, Iterator last, Function f) { _aux::recursive_for_each< (Dimension == -1u ? dimension< #if __cplusplus >= 201103L decltype(*std::declval<Iterator>()) #else std::iterator_traits<Iterator>::type #endif >::value : Dimension) - 1 >::for_each(first, last, f); return FALCON_FORWARD(Function, f); } template <class Container, class Function> Function recursive_for_each(Container CPP_RVALUE_OR_REFERENCE container, Function f) { _aux::recursive_for_each<dimension<Container>::value - 1> ::for_each(begin(container), end(container), f); return FALCON_FORWARD(Function, f); } template <std::size_t Dimension, class Container, class Function> Function recursive_for_each(Container CPP_RVALUE_OR_REFERENCE container, Function f) { _aux::recursive_for_each< (Dimension == -1u ? dimension<Container>::value : Dimension) - 1 >::for_each(begin(container), end(container), f); return FALCON_FORWARD(Function, f); } template<class Preface, class Function, class Postface CPP_IF_CPP11(= ignore_t)> _aux::recursive_intermediate<Preface, Function, Postface, -1u> recursive_intermediate(Preface CPP_RVALUE preface, Function CPP_RVALUE functor, Postface CPP_RVALUE postface = Postface()) { #if __cplusplus >= 201103L return { std::forward<Preface>(preface) , std::forward<Function>(functor) , std::forward<Postface>(postface) }; #else return _aux::recursive_intermediate<Preface, Function, Postface, -1u>( preface, functor, postface); #endif } template<std::size_t Dimension, class Preface, class Function, class Postface CPP_IF_CPP11(= ignore_t)> _aux::recursive_intermediate<Preface, Function, Postface, Dimension> recursive_intermediate(Preface CPP_RVALUE preface, Function CPP_RVALUE functor, Postface CPP_RVALUE postface = Postface()) { #if __cplusplus >= 201103L return { std::forward<Preface>(preface) , std::forward<Function>(functor) , std::forward<Postface>(postface) }; #else return _aux::recursive_intermediate<Preface, Function, Postface, Dimension>( preface, functor, postface); #endif } namespace _aux { template<class Preface, class Function, class Postface, std::size_t Dimension> struct recursive_intermediate { Preface preface; Function functor; Postface postface; #if __cplusplus < 201103L recursive_intermediate(Preface preface, Function functor, Postface postface) : preface(preface) , functor(functor) , postface(postface) {} #endif template<class Container> void operator()(Container& v) { preface(); ::falcon::recursive_for_each<Dimension>(v, functor); postface(); } }; template<class Function, class Postface, std::size_t Dimension> struct recursive_intermediate<ignore_t, Function, Postface, Dimension> { Function functor; Postface postface; #if __cplusplus < 201103L recursive_intermediate(const ignore_t&, Function functor, Postface postface) : functor(functor) , postface(postface) {} #endif template<class Container> void operator()(Container& v) { ::falcon::recursive_for_each<Dimension>(v, functor); postface(); } }; template<class Preface, class Function, std::size_t Dimension> struct recursive_intermediate<Preface, Function, ignore_t, Dimension> { Preface preface; Function functor; #if __cplusplus < 201103L recursive_intermediate(Preface preface, Function functor, const ignore_t&) : preface(preface) , functor(functor) {} #endif template<class Container> void operator()(Container& v) { preface(); ::falcon::recursive_for_each<Dimension>(v, functor); } }; template<class Function, std::size_t Dimension> struct recursive_intermediate<ignore_t, Function, ignore_t, Dimension> { Function functor; #if __cplusplus < 201103L recursive_intermediate(const ignore_t&, Function functor, const ignore_t&) : functor(functor) {} #endif template<class Container> void operator()(Container& v) { ::falcon::recursive_for_each<Dimension>(v, functor); } }; } } #endif
29.240602
103
0.719294
jonathanpoelen
7967f4030b153b6da525d91f34be03b3ee49bf48
12,242
cpp
C++
platform/windows/Corona.Simulator/Rtt/Rtt_WinPlatformServices.cpp
sekodev/corona
b9a559d0cc68f5d9048444d710161fc5b778d981
[ "MIT" ]
null
null
null
platform/windows/Corona.Simulator/Rtt/Rtt_WinPlatformServices.cpp
sekodev/corona
b9a559d0cc68f5d9048444d710161fc5b778d981
[ "MIT" ]
null
null
null
platform/windows/Corona.Simulator/Rtt/Rtt_WinPlatformServices.cpp
sekodev/corona
b9a559d0cc68f5d9048444d710161fc5b778d981
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////////////// // // This file is part of the Corona game engine. // For overview and more information on licensing please refer to README.md // Home page: https://github.com/coronalabs/corona // Contact: [email protected] // ////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Core\Rtt_Build.h" #include "Rtt_WinConnection.h" #include "Rtt_WinPlatform.h" #include "Rtt_WinPlatformServices.h" #include "WinGlobalProperties.h" #include "WinString.h" namespace Rtt { #define Rtt_REGISTRY_SECTION _T("Preferences") // These functions are used for WinPlatformServices::GetPreference() and SetPreference() // Registry code copied from MFC Source appui3.cpp (CWinApp) // returns key for HKEY_CURRENT_USER\"Software"\RegistryKey\ProfileName // (or other top level key) creating it if it doesn't exist // responsibility of the caller to call RegCloseKey() on the returned HKEY // Modified to get registry key and profile name from WinGlobalProperties, // initialized in CSimulatorApp::InitInstance() static HKEY GetAppRegistryKey( HKEY hkeyTopLevel ) { WinString strRegKey, strRegProfile; #ifdef Rtt_NO_GUI strRegKey.SetUTF8("Ansca Corona"); strRegProfile.SetUTF8("Corona Simulator"); #else Rtt_ASSERT( GetWinProperties()->GetRegistryKey() != NULL); Rtt_ASSERT( GetWinProperties()->GetRegistryProfile() != NULL); strRegKey.SetUTF8( GetWinProperties()->GetRegistryKey() ); strRegProfile.SetUTF8( GetWinProperties()->GetRegistryProfile() ); #endif // Rtt_NO_GUI HKEY hAppKey = NULL; HKEY hSoftKey = NULL; HKEY hCompanyKey = NULL; if (RegOpenKeyEx(HKEY_CURRENT_USER, _T("software"), 0, KEY_WRITE|KEY_READ, &hSoftKey) == ERROR_SUCCESS) { DWORD dw; if (RegCreateKeyEx(hSoftKey, strRegKey.GetTCHAR(), 0, REG_NONE, REG_OPTION_NON_VOLATILE, KEY_WRITE|KEY_READ, NULL, &hCompanyKey, &dw) == ERROR_SUCCESS) { RegCreateKeyEx(hCompanyKey, strRegProfile.GetTCHAR(), 0, REG_NONE, REG_OPTION_NON_VOLATILE, KEY_WRITE|KEY_READ, NULL, &hAppKey, &dw); } } if (hSoftKey != NULL) RegCloseKey(hSoftKey); if (hCompanyKey != NULL) RegCloseKey(hCompanyKey); return hAppKey; } // returns key for: // HKEY_CURRENT_USER\"Software"\RegistryKey\AppName\lpszSection // creating it if it doesn't exist. // responsibility of the caller to call RegCloseKey() on the returned HKEY // Returns void * to avoid including windows.h before header file static HKEY GetSectionKey(LPCTSTR lpszSection, HKEY hkeyTopLevel ) { Rtt_ASSERT(lpszSection != NULL); HKEY hSectionKey = NULL; HKEY hAppKey = GetAppRegistryKey( hkeyTopLevel ); if (hAppKey == NULL) return NULL; DWORD dw; RegCreateKeyEx(hAppKey, lpszSection, 0, REG_NONE, REG_OPTION_NON_VOLATILE, KEY_WRITE|KEY_READ, NULL, &hSectionKey, &dw); RegCloseKey(hAppKey); return hSectionKey; } static bool GetProfileString( WinString *pstrValue, LPCTSTR lpszSection, LPCTSTR lpszEntry, HKEY hkeyTopLevel = HKEY_CURRENT_USER) { Rtt_ASSERT(lpszSection != NULL); Rtt_ASSERT(lpszEntry != NULL); HKEY hSecKey = GetSectionKey(lpszSection, hkeyTopLevel); if (hSecKey == NULL) { return false; } DWORD dwType=REG_NONE; DWORD dwCount=0; LONG lResult = RegQueryValueEx(hSecKey, (LPTSTR)lpszEntry, NULL, &dwType, NULL, &dwCount); if (lResult == ERROR_SUCCESS) { if( dwType == REG_SZ) // if type is string { // dwCount is in bytes, Expand takes # of characters and adds 1 (*pstrValue).Expand( dwCount/sizeof(TCHAR) ); lResult = RegQueryValueEx(hSecKey, (LPTSTR)lpszEntry, NULL, &dwType, (LPBYTE)(*pstrValue).GetBuffer(), &dwCount); } } RegCloseKey(hSecKey); if (lResult == ERROR_SUCCESS) { // If we found the key, but type was not string (REG_SZ), return false return (dwType == REG_SZ); } return false; } static BOOL WriteProfileString( LPCTSTR lpszSection, LPCTSTR lpszEntry, LPCTSTR lpszValue, HKEY hkeyTopLevel = HKEY_CURRENT_USER) { Rtt_ASSERT(lpszSection != NULL); Rtt_ASSERT(lpszEntry != NULL); LONG lResult; #if 0 // I don't think we want the whole section deleted by accident... if (lpszEntry == NULL) //delete whole section { HKEY hAppKey = GetAppRegistryKey(); if (hAppKey == NULL) return FALSE; lResult = ::RegDeleteKey(hAppKey, lpszSection); RegCloseKey(hAppKey); } else #endif if (lpszValue == NULL) { HKEY hSecKey = GetSectionKey(lpszSection, hkeyTopLevel); if (hSecKey == NULL) return FALSE; // necessary to cast away const below lResult = ::RegDeleteValue(hSecKey, (LPTSTR)lpszEntry); RegCloseKey(hSecKey); } else { HKEY hSecKey = GetSectionKey(lpszSection, hkeyTopLevel); if (hSecKey == NULL) return FALSE; lResult = RegSetValueEx(hSecKey, lpszEntry, NULL, REG_SZ, (LPBYTE)lpszValue, (lstrlen(lpszValue)+1)*sizeof(TCHAR)); RegCloseKey(hSecKey); } return lResult == ERROR_SUCCESS; } static bool GetProfileBinary(LPCTSTR lpszSection, LPCTSTR lpszEntry, BYTE** ppData, UINT* pBytes) { Rtt_ASSERT(lpszSection != NULL); Rtt_ASSERT(lpszEntry != NULL); Rtt_ASSERT(ppData != NULL); Rtt_ASSERT(pBytes != NULL); *ppData = NULL; *pBytes = 0; HKEY hSecKey = GetSectionKey(lpszSection, HKEY_CURRENT_USER ); if (hSecKey == NULL) { return false; } DWORD dwType=0; DWORD dwCount=0; LONG lResult = RegQueryValueEx(hSecKey, (LPTSTR)lpszEntry, NULL, &dwType, NULL, &dwCount); *pBytes = dwCount; if (lResult == ERROR_SUCCESS) { if( dwType == REG_BINARY ) // if type is binary { *ppData = new BYTE[*pBytes]; lResult = RegQueryValueEx(hSecKey, (LPTSTR)lpszEntry, NULL, &dwType, *ppData, &dwCount); } } RegCloseKey(hSecKey); // If we found the key, but type was not binary, delete data and return false if (lResult == ERROR_SUCCESS && (dwType == REG_BINARY)) { return true; } else { delete [] *ppData; *ppData = NULL; } return false; } static bool WriteProfileBinary(LPCTSTR lpszSection, LPCTSTR lpszEntry, LPBYTE pData, UINT nBytes) { Rtt_ASSERT(lpszSection != NULL); LONG lResult; HKEY hSecKey = GetSectionKey(lpszSection, HKEY_CURRENT_USER ); if (hSecKey == NULL) return false; if( NULL == pData ) // delete key if pData is null lResult = ::RegDeleteValue(hSecKey, (LPTSTR)lpszEntry); else lResult = RegSetValueEx(hSecKey, lpszEntry, NULL, REG_BINARY, pData, nBytes); RegCloseKey(hSecKey); return lResult == ERROR_SUCCESS; } static void EncryptString( const char *sSecret, BYTE **paBytes, UINT *pnBytes ) { *paBytes = NULL; *pnBytes = 0; if( NULL == sSecret ) return; DATA_BLOB unencryptedData, encryptedData; unencryptedData.pbData = (BYTE *)sSecret; // Save the NULL character in the data // We need to multiply the length of the string by the // size of the data contained therein to support multi- // byte character sets. unencryptedData.cbData = (strlen( sSecret ) + 1) * sizeof( sSecret[0] ); if (!CryptProtectData( &unencryptedData, _T("Marker"), NULL, NULL, NULL, 0, &encryptedData)) { return; } // Save the encrypted data buffer in heap-allocated memory *paBytes = new BYTE [encryptedData.cbData]; memcpy( *paBytes, encryptedData.pbData, encryptedData.cbData ); *pnBytes = encryptedData.cbData; // clean up LocalFree( encryptedData.pbData ); } static bool DecryptString( WinString *pStr, BYTE *aBytes, UINT nBytes ) { DATA_BLOB encryptedData, unencryptedData; encryptedData.pbData = aBytes; encryptedData.cbData = nBytes; LPWSTR dataDescription; // Receives the description saved with data if (!CryptUnprotectData( &encryptedData, &dataDescription, NULL, NULL, NULL, 0, &unencryptedData)) { return false; } // And the data description string as well. LocalFree(dataDescription); // NOTE: Contains NULL terminator pStr->SetUTF8( (char *)unencryptedData.pbData ); // Cleanup LocalFree(unencryptedData.pbData); return true; } WinPlatformServices::WinPlatformServices( const MPlatform& platform ) : fPlatform( platform ) { } const MPlatform& WinPlatformServices::Platform() const { return fPlatform; } PlatformConnection* WinPlatformServices::CreateConnection( const char* url ) const { return Rtt_NEW( & fPlatform.GetAllocator(), WinConnection( * this, url ) ); } void WinPlatformServices::GetPreference( const char *key, String * value ) const { WinString strResult, strKey; strKey.SetUTF8( key ); bool bFound = GetProfileString( &strResult, Rtt_REGISTRY_SECTION, strKey.GetTCHAR()); if( bFound ) { value->Set( strResult.GetUTF8() ); } } void WinPlatformServices::SetPreference( const char *key, const char *value ) const { if ( Rtt_VERIFY( key ) ) { WinString strKey, strValue; strKey.SetUTF8( key ); strValue.SetUTF8( value ); WriteProfileString( Rtt_REGISTRY_SECTION, strKey.GetTCHAR(), strValue.GetTCHAR() ); } } void WinPlatformServices::GetSecurePreference( const char *key, String * value ) const { const char *sResult = NULL; BYTE *aBytes; UINT nBytes; WinString strKey; strKey.SetUTF8( key ); bool bFound = GetProfileBinary(Rtt_REGISTRY_SECTION, strKey.GetTCHAR(), &aBytes, &nBytes); if( bFound ) { WinString strResult; if( DecryptString( &strResult, aBytes, nBytes ) ) { value->Set( strResult.GetUTF8() ); } } } bool WinPlatformServices::SetSecurePreference( const char *key, const char *value ) const { bool result = false; if ( Rtt_VERIFY( key ) ) { BYTE *aBytes; UINT nBytes; EncryptString( value, &aBytes, &nBytes ); WinString strKey; strKey.SetUTF8( key ); result = WriteProfileBinary( Rtt_REGISTRY_SECTION, strKey.GetTCHAR(), aBytes, nBytes ); if( aBytes ) delete aBytes; } return result; } void WinPlatformServices::GetLibraryPreference( const char *key, String * value ) const { // Get the value from HKLM WinString strResult, strKey; strKey.SetUTF8( key ); bool bFound = GetProfileString( &strResult, Rtt_REGISTRY_SECTION, strKey.GetTCHAR(), HKEY_LOCAL_MACHINE ); if( bFound ) { value->Set( strResult.GetUTF8() ); } } void WinPlatformServices::SetLibraryPreference( const char *key, const char *value ) const { // Set the value in HKLM if ( Rtt_VERIFY( key ) ) { WinString strKey, strValue; strKey.SetUTF8( key ); strValue.SetUTF8( value ); WriteProfileString( Rtt_REGISTRY_SECTION, strKey.GetTCHAR(), strValue.GetTCHAR(), HKEY_LOCAL_MACHINE ); } } // Checks for Internet connectivity. // Returns true if the Internet is assumed available. Returns false if not. bool WinPlatformServices::IsInternetAvailable() const { MIB_IPFORWARDTABLE *pRoutingTable; DWORD dwBufferSize = 0; DWORD dwRowCount; DWORD dwIndex; DWORD dwResult; bool bIsInternetAvailable = false; // Fetch routing table information. // We'll assume that the Internet is available if we can find a default route to a gateway. GetIpForwardTable(NULL, &dwBufferSize, FALSE); pRoutingTable = (MIB_IPFORWARDTABLE*)new BYTE[dwBufferSize]; dwResult = GetIpForwardTable(pRoutingTable, &dwBufferSize, FALSE); if (NO_ERROR == dwResult) { dwRowCount = pRoutingTable->dwNumEntries; for (dwIndex = 0; dwIndex < dwRowCount; dwIndex++) { // Default route designated by 0.0.0.0 in table. if (0 == pRoutingTable->table[dwIndex].dwForwardDest) { bIsInternetAvailable = true; break; } } } delete pRoutingTable; // Return the result. return bIsInternetAvailable; } bool WinPlatformServices::IsLocalWifiAvailable() const { Rtt_ASSERT_NOT_IMPLEMENTED(); return false; } void WinPlatformServices::Terminate() const { // Exit the application. CWnd* windowPointer = ::AfxGetMainWnd(); if (windowPointer) { SendMessage(windowPointer->GetSafeHwnd(), WM_CLOSE, 0, 0); } } void WinPlatformServices::Sleep( int milliseconds ) const { if (milliseconds >= 0) { ::Sleep( (DWORD)milliseconds ); } } } // namespace Rtt
25.772632
101
0.689103
sekodev
7969faa8338352043414df4fa2fec8467422614b
20,523
cc
C++
src/asn1/oidc.cc
1computerguy/mercury
193bf6432e4f53f1253965f5ca8634bd6ca69136
[ "BSD-2-Clause" ]
null
null
null
src/asn1/oidc.cc
1computerguy/mercury
193bf6432e4f53f1253965f5ca8634bd6ca69136
[ "BSD-2-Clause" ]
null
null
null
src/asn1/oidc.cc
1computerguy/mercury
193bf6432e4f53f1253965f5ca8634bd6ca69136
[ "BSD-2-Clause" ]
null
null
null
// // oidc.cc - ASN.1 Object IDentifier Compiler // #include <string> #include <vector> #include <list> #include <iostream> #include <sstream> #include <iterator> #include <regex> #include <unordered_map> #include <map> #include <set> #include <algorithm> void oid_print(std::vector<uint32_t> oid, const char *label) { if (label) { printf("%s: ", label); } bool first = true; printf("{"); for (const uint32_t &i : oid) { if (!first) { printf(","); } else { first = false; } printf(" %d", i); } printf(" }\n"); } struct char_pair { char first; char second; }; inline struct char_pair raw_to_hex(unsigned char x) { char hex[]= "0123456789abcdef"; struct char_pair result = { hex[x >> 4], hex[x & 0x0f] }; return result; } inline uint8_t hex_to_raw(const char *hex) { int value = 0; if(*hex >= '0' && *hex <= '9') { value = (*hex - '0'); } else if (*hex >= 'A' && *hex <= 'F') { value = (10 + (*hex - 'A')); } else if (*hex >= 'a' && *hex <= 'f') { value = (10 + (*hex - 'a')); } value = value << 4; hex++; if(*hex >= '0' && *hex <= '9') { value |= (*hex - '0'); } else if (*hex >= 'A' && *hex <= 'F') { value |= (10 + (*hex - 'A')); } else if (*hex >= 'a' && *hex <= 'f') { value |= (10 + (*hex - 'a')); } return value; } std::string raw_to_hex_string(std::vector<uint8_t> v) { std::string s; for (const auto &x: v) { char_pair p = raw_to_hex(x); s.push_back(p.first); s.push_back(p.second); } return s; } std::string raw_to_hex_array(std::vector<uint8_t> v) { std::string s; s.push_back('{'); bool comma = false; for (const auto &x: v) { if (comma) { s.push_back(','); } else { comma = true; } s.push_back('0'); s.push_back('x'); char_pair p = raw_to_hex(x); s.push_back(p.first); s.push_back(p.second); } s.push_back('}'); return s; } std::vector<uint8_t> oid_to_raw_string(std::vector<uint32_t> oid) { std::vector<uint8_t> raw; raw.push_back(40 * oid[0] + oid[1]); for (size_t i = 2; i < oid.size(); i++) { uint32_t tmp = oid[i]; std::vector<uint8_t> v; if (tmp == 0) { v.push_back(0); } else { while (tmp > 0) { uint32_t div = tmp/128; uint32_t rem = tmp - div * 128; v.push_back(rem); tmp = div; } } if (v.size() > 1) { for (size_t j=v.size()-1; j>0; j--) { raw.push_back(0x80 | v[j]); } } raw.push_back(v[0]); } // printf("raw: "); // for (const auto &x: raw) { // printf("%02x", x); // } return raw; } std::string oid_to_hex_string(const std::vector<uint32_t> &oid) { return raw_to_hex_string(oid_to_raw_string(oid)); } std::string oid_to_hex_array(const std::vector<uint32_t> &oid) { return raw_to_hex_array(oid_to_raw_string(oid)); } std::vector<uint32_t> hex_string_to_oid(std::string s) { std::vector<uint32_t> v; if (s.size() & 1) { return v; } const char *c = s.c_str(); uint32_t component = hex_to_raw(c); uint32_t div = component / 40; uint32_t rem = component - (div * 40); if (div > 2 || rem > 39) { return v; // error: invalid input } v.push_back(div); v.push_back(rem); c += 2; component = 0; for (unsigned int i=2; i<s.size(); i += 2) { uint8_t tmp = hex_to_raw(c); if (tmp & 0x80) { component = component * 128 + (tmp & 0x7f); } else { component = component * 128 + tmp; v.push_back(component); component = 0; } c += 2; } return v; } void output_oid(std::vector<uint32_t> oid, const char *delimiter) { if (oid.size() < 1) { return; // nothing to output } unsigned int i = 0; for ( ; i < oid.size() - 1; i++) { std::cout << oid[i] << delimiter; } std::cout << oid[i] << '\n'; } enum token_type { token_unknown, token_str, token_num, token_lbrace, token_rbrace, token_assignment, token_comment }; enum token_type type(const std::string &t) { using namespace std; regex str("[a-zA-Z_][a-zA-Z_\\-\\(\\)0-9]*"); regex num("[0-9]+"); if (t == "{") { return token_lbrace; } else if (t == "}") { return token_rbrace; } else if (t == "::=") { return token_assignment; } else if (t == "--") { return token_comment; } else if (regex_match(t, str)) { return token_str; } else if (regex_match(t, num)) { return token_num; } return token_unknown; } enum assignment_type { type_oid = 0, type_other = 1 }; struct oid_assignment { std::string name; enum assignment_type type; std::vector<uint32_t> asn_notation; }; struct oid_set { std::unordered_map<std::string, std::vector<uint32_t>> oid_dict; std::unordered_map<std::string, std::vector<uint32_t>> nonterminal_oid_dict; std::unordered_map<std::string, std::string> keyword_dict; std::unordered_map<std::string, std::string> synonym; std::multiset<std::string> keywords; void dump_oid_dict_sorted(); void dump_oid_enum_dict_sorted(); void verify_oid_dict(); std::vector<uint32_t> get_vector_from_keyword(const std::string &keyword) { auto x = oid_dict.find(keyword); if (x != oid_dict.end()) { return x->second; } auto syn = synonym.find(keyword); if (syn != synonym.end()) { return oid_dict[syn->second]; } std::cerr << "error: unknown OID keyword '" << keyword << "'\n"; throw "parse error"; } void add_oid(const std::string &name, const std::vector<uint32_t> &v, enum assignment_type type) { // if 'v' is already in use as an OID, don't add anything to // the OID set, but instead create a synonym // std::string oid_hex_string = oid_to_hex_string(v); if (keyword_dict.find(oid_hex_string) != keyword_dict.end()) { std::cerr << "note: OID "; bool not_first = 0; for (auto &c : v) { if (not_first) { std::cerr << '.'; } else { not_first = 1; } std::cerr << c; } std::cerr << " is already in the OID set with keyword " << name; if (keyword_dict[oid_hex_string] != name) { std::cerr << " creating synonym for " << keyword_dict[oid_hex_string]; synonym[name] = keyword_dict[oid_hex_string]; } std::cerr << std::endl; return; } // if 'name' is already in use as a keyword, then append a // distinct number // auto count = keywords.count(name); std::string k(name); keywords.insert(name); if (count != 0) { std::cerr << "note: keyword " << name << " is already in use, appending [" << count << "]" << std::endl; k.append("[").append(std::to_string(count)).append("]"); } // cout << "assignment: " << name << "\t" << type << endl; oid_dict[k] = v; if (type == type_other) { std::cerr << "assigning synonym " << name << "\n"; } keyword_dict[oid_to_hex_string(v)] = k; } void remove_nonterminals() { for (std::pair <std::string, std::vector<uint32_t>> x : oid_dict) { std::vector<uint32_t> v = x.second; //std::cout << s << std::endl; while (1) { v.erase(v.end() - 1); if (v.empty()) { break; } std::string oid_hex_string = oid_to_hex_string(v); const auto &o = keyword_dict.find(oid_hex_string); if (o != keyword_dict.end()) { //std::cout << "found in dict" << std::endl; //nonterminal_oid_dict.insert(o); keyword_dict.erase(o); } // for (auto &c : v) { // std::cout << c << ' '; //} //std::cout << '\n'; } } } }; struct oid_set oid_set; void parse_asn1_line(std::list<std::string> &tokens) { using namespace std; regex str("[a-zA-Z][a-zA-Z\\-\\(\\)0-9]*"); regex num("[0-9]+"); regex str_with_num("(\\([0-9]*\\))"); /* * examples of lines: * * id-at OBJECT IDENTIFIER ::= { joint-iso-ccitt(2) ds(5) 4 } * id-at-name AttributeType ::= { id-at 41 } * * string OBJECT IDENTIFIER ::= { string+ number+ } * string string ::= { string+ number+ } */ #if 0 for (auto t: tokens) { cout << "token\t" << t << "\t"; if (regex_match(t, str)) { cout << "is a string"; } if (regex_match(t, num)) { cout << "is a number"; } if (t == "{") { cout << "is a left brace"; } else if (t == "}") { cout << "is a right brace"; } else if (t == "::=") { cout << "is an assignment operator"; } else if (t == "--") { cout << "is a comment"; } if (type(t) == token_unknown) { cout << "UNKNOWN TOKEN"; } cout << "\n"; } #endif struct oid_assignment assignment; std::list<std::string>::const_iterator t = tokens.begin(); if (type(*t) == token_comment) { return; } if (type(*t) == token_str) { assignment.name = *t; } else { cout << "error: expected string, got '" << *t << "'\n"; throw "parse error"; } ++t; string category_name; if (type(*t) == token_str) { if (*t == "OBJECT") { ++t; if (type(*t) == token_str && *t == "IDENTIFIER") { assignment.type = type_oid; } } else { assignment.type = type_other; category_name = *t; } } else if (type(*t) == token_assignment) { ++t; if (type(*t) == token_str && *t == "OBJECT") { ++t; if (type(*t) == token_str && *t == "IDENTIFIER") { assignment.type = type_oid; } else { throw "parse error"; } } else { return; } cout << assignment.name << " is a synonym for OBJECT IDENTIFIER\n"; return; } else { cout << "error: expected OBJECT IDENTIFIER or ::=, got '" << *t << "'\n"; throw "parse error"; } ++t; if (type(*t) != token_assignment) { cout << "error: expected '::=', got '" << *t << "'\n"; throw "parse error"; } ++t; if (type(*t) != token_lbrace) { cout << "error: expected '{', got '" << *t << "'\n"; throw "parse error"; } ++t; while (type(*t) != token_rbrace) { // cout << "got token " << *t << endl; if (type(*t) == token_str) { smatch string_match; if (regex_search(*t, string_match, str_with_num)) { string s = string_match.str(1); // cout << "got str_with_num " << s << endl; uint32_t component = stoi(s.substr(1, s.size() - 2)); // cout << "component " << component << endl; assignment.asn_notation.push_back(component); } else { std::vector<uint32_t> x = oid_set.get_vector_from_keyword(*t); for (uint32_t &component: x) { assignment.asn_notation.push_back(component); } } } else if (type(*t) == token_num) { assignment.asn_notation.push_back(stoi(*t)); } ++t; } oid_set.add_oid(assignment.name, assignment.asn_notation, assignment.type); } int paren_balance(const char *s) { int balance = 0; while (*s != 0 && *s != '\n') { // std::cout << *s; switch(*s) { case '{': balance++; break; case '}': balance--; break; default: break; } s++; } // std::cout << "balance: " << balance << "\n"; return balance; } void parse_asn1_file(const char *filename) { using namespace std; FILE *stream; char *line = NULL; size_t len = 0; ssize_t nread; stream = fopen(filename, "r"); if (stream == NULL) { perror("fopen"); exit(EXIT_FAILURE); } size_t balance = 0; list<string> statement; while ((nread = getline(&line, &len, stream)) != -1) { // printf("got line of length %zu:\n", nread); // fwrite(line, nread, 1, stdout); string word; istringstream iss(line, istringstream::in); //while( iss >> word ) { // cout << word << endl; //} list<string> tokens{istream_iterator<string>{iss}, istream_iterator<string>{}}; balance += paren_balance(line); statement.splice(statement.end(), tokens); if (balance == 0 && statement.size() > 0) { // cout << "parsing balanced line\n"; // for (auto x: statement) { // cout << x << endl; // } parse_asn1_line(statement); statement.clear(); } else { // cout << "line is unbalanced (" << balance << ")\n"; } } fclose(stream); } void oid_set::dump_oid_dict_sorted() { using namespace std; struct pair_cmp { inline bool operator() (const pair<string, vector<uint32_t>> &s1, const pair<string, vector<uint32_t>> &s2) { return (s1.second < s2.second); } }; vector<pair<string, vector<uint32_t>>> ordered_dict(oid_dict.begin(), oid_dict.end()); sort(ordered_dict.begin(), ordered_dict.end(), pair_cmp()); cout << "std::unordered_map<std::basic_string<uint8_t>, std::string> oid_dict = {\n"; for (pair <string, vector<uint32_t>> x : ordered_dict) { cout << "\t{ " << oid_to_hex_array(x.second) << ", \"" << x.first << "\" },\n"; } cout << "};\n"; } void oid_set::dump_oid_enum_dict_sorted() { using namespace std; struct pair_cmp { inline bool operator() (const pair<string, vector<uint32_t>> &s1, const pair<string, vector<uint32_t>> &s2) { return (s1.second < s2.second); } }; vector<pair<string, vector<uint32_t>>> ordered_dict(oid_dict.begin(), oid_dict.end()); sort(ordered_dict.begin(), ordered_dict.end(), pair_cmp()); cout << "std::unordered_map<std::basic_string<uint8_t>, std::string> oid_dict = {\n"; for (pair <string, vector<uint32_t>> x : ordered_dict) { cout << "\t{ " << oid_to_hex_array(x.second) << ", \"" << x.first << "\" },\n"; } cout << "};\n"; cout << "enum oid {\n"; unsigned int oid_num = 0; cout << "\t" << "unknown" << " = " << oid_num++ << ",\n"; for (pair <string, vector<uint32_t>> x : ordered_dict) { std::string tmp_string(x.first); std::replace(tmp_string.begin(), tmp_string.end(), '-', '_'); std::replace(tmp_string.begin(), tmp_string.end(), '[', '_'); std::replace(tmp_string.begin(), tmp_string.end(), ']', '_'); cout << "\t" << tmp_string << " = " << oid_num << ",\n"; //const auto &syn = synonym.find(x.first); //if (syn != synonym.end()) { // std::cerr << syn->second << " is a synonym for " << x.first << std::endl; // std::string tmp_string2(syn->second); // std::replace(tmp_string2.begin(), tmp_string2.end(), '-', '_'); // std::replace(tmp_string2.begin(), tmp_string2.end(), '[', '_'); // std::replace(tmp_string2.begin(), tmp_string2.end(), ']', '_'); // cout << "\t" << tmp_string2 << " = " << oid_num << ",\n"; //} oid_num++; } cout << "};\n"; cout << "std::unordered_map<std::basic_string<uint8_t>, enum oid> oid_to_enum = {\n"; for (pair <string, vector<uint32_t>> x : ordered_dict) { std::string tmp_string(x.first); std::replace(tmp_string.begin(), tmp_string.end(), '-', '_'); std::replace(tmp_string.begin(), tmp_string.end(), '[', '_'); std::replace(tmp_string.begin(), tmp_string.end(), ']', '_'); cout << "\t{ " << oid_to_hex_array(x.second) << ", " << tmp_string << " },\n"; } cout << "};\n"; } void oid_set::verify_oid_dict() { using namespace std; struct pair_cmp { inline bool operator() (const pair<string, vector<uint32_t>> &s1, const pair<string, vector<uint32_t>> &s2) { return (s1.second < s2.second); } }; vector<pair<string, vector<uint32_t>>> ordered_dict(oid_dict.begin(), oid_dict.end()); sort(ordered_dict.begin(), ordered_dict.end(), pair_cmp()); for (pair <string, vector<uint32_t>> x : ordered_dict) { string s = oid_to_hex_string(x.second); vector<uint32_t> v = hex_string_to_oid(s); if (v != x.second) { cout << "error with oid " << oid_to_hex_string(x.second) << "\n"; auto iv = v.begin(); auto ix = x.second.begin(); while (iv != v.end() || ix != x.second.end()) { if (iv != v.end()) { cout << "v: " << *iv; if (*iv != *ix) { cout << "\t***"; } cout << endl; iv++; } if (ix != x.second.end()) { cout << "x: " << *ix << endl; ix++; } } } } } int main(int argc, char *argv[]) { using namespace std; #if 0 auto unknown_oids = { "2a8648ce3d030107", "2b81040022", "2b0e03021d", "2a864886f70d01010b", "2a864886f70d01090f", "2a864886f70d010914", "2b0601040182371402", "2b0601040182371501", "2b0601040182371502", "2b0601040182371507", "2b060104018237150a", "2b0601040182373c020101", "2b0601040182373c020102", "2b0601040182373c020103", "2b060104018237540101", "2b06010401d04701028245", "2b06010401d679020402", "2b06010505070101", "2b06010505070103", "550409", "55040c", "55040f", "550411", "55042a", "550461", "551d01", "551d07", "551d0a", "551d10", "551d11", "551d12", "551d13", "551d1e", "551d1f", "551d20", "551d23", "6086480186f8420101", "6086480186f8420103", "6086480186f8420104", "6086480186f842010c", "6086480186f842010d" }; for (auto &hexstring : unknown_oids) { cout << hexstring << '\t'; auto v = hex_string_to_oid(hexstring); const char *delimeter = "."; output_oid(v, delimeter); } #endif /* 0 */ if (argc < 2) { fprintf(stderr, "Usage: %s <file> [<file2> ... ]\n", argv[0]); exit(EXIT_FAILURE); } for (int i=1; i<argc; i++) { // cerr << "reading file " << argv[i] << endl; parse_asn1_file(argv[i]); } #if 0 cout << "dictionary dump:" << endl; for (pair <string, vector<uint32_t>> x : oid_dict) { cout << x.first << " = { "; for (auto c: x.second) { cout << c << " "; } cout << "}\t"; cout << oid_to_hex_string(x.second) << endl; } cout << endl; for (pair <string, vector<uint32_t>> x : oid_dict) { cout << oid_to_hex_string(x.second) << "\t\t" << x.first << endl; } #endif oid_set.remove_nonterminals(); oid_set.dump_oid_enum_dict_sorted(); // oid_set.verify_oid_dict(); // for (auto &x : oid_set.keyword_dict) { // cout << x.first << "\t" << x.second << endl; // } return 0; }
28.036885
117
0.489694
1computerguy
796c39e81409a53f2ec85d3123a382684bb29c4b
907
cpp
C++
src/medTest/medTestApplication.cpp
papadop/medInria-public
fd8bec14c97bb95bf4d58a60741ef3b7c159f757
[ "BSD-4-Clause" ]
null
null
null
src/medTest/medTestApplication.cpp
papadop/medInria-public
fd8bec14c97bb95bf4d58a60741ef3b7c159f757
[ "BSD-4-Clause" ]
null
null
null
src/medTest/medTestApplication.cpp
papadop/medInria-public
fd8bec14c97bb95bf4d58a60741ef3b7c159f757
[ "BSD-4-Clause" ]
null
null
null
/*========================================================================= medInria Copyright (c) INRIA 2013. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. =========================================================================*/ #include <medTestApplication.h> #include <stdexcept> medTestApplication::medTestApplication ( int & argc, char ** argv ) : QCoreApplication(argc, argv) { } medTestApplication::~medTestApplication() { } //static void medTestApplication::CheckTestResult( bool condition, const char *cond, const char *file, const int line /*= 0*/ ) { if (!condition) { QString msg = QString("%1(%2): Test failed (%3)").arg(file).arg(line).arg(cond); throw std::runtime_error(msg.toStdString()); } }
23.868421
118
0.585447
papadop
79711981a6ebb023671dcaad360a7ecd25dc4056
3,995
cpp
C++
speedcc/stage/SCBehaviorCocos.cpp
kevinwu1024/SpeedCC
7b32e3444236d8aebf8198ebc3fede8faf201dee
[ "MIT" ]
7
2018-03-10T02:01:49.000Z
2021-09-14T15:42:10.000Z
speedcc/stage/SCBehaviorCocos.cpp
kevinwu1024/SpeedCC
7b32e3444236d8aebf8198ebc3fede8faf201dee
[ "MIT" ]
null
null
null
speedcc/stage/SCBehaviorCocos.cpp
kevinwu1024/SpeedCC
7b32e3444236d8aebf8198ebc3fede8faf201dee
[ "MIT" ]
1
2018-03-10T02:01:58.000Z
2018-03-10T02:01:58.000Z
/**************************************************************************** Copyright (c) 2017-2020 Kevin Wu (Wu Feng) github: http://github.com/kevinwu1024 Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://opensource.org/licenses/MIT 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 NON INFRINGEMENT. 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. ****************************************************************************/ #include "SCBehaviorCocos.h" #include "../cocos/SCViewController.h" #include "../cocos/SCViewControllerLog.h" #include "../system/SCSystem.h" NAMESPACE_SPEEDCC_BEGIN ///--------------- SCBehaviorViewGoto SCBehaviorViewGoto::~SCBehaviorViewGoto() { } SCBehaviorViewGoto::SCBehaviorViewGoto(const SCViewNavigator::SSceneSwitchInfo& swi,const SCDictionary& dic) :_switch(swi) ,_parameterDic(dic) ,_bDirect(false) { } void SCBehaviorViewGoto::execute(const SCDictionary& par) { SC_RETURN_V_IF(!this->getActive()); if(_bDirect) { this->onBvrFunc(); } else if(_ptrDelayBvr==nullptr) { auto ptr = SCBehaviorCallFunc::create(SC_MAKE_FUNC(onBvrFunc, this)); _ptrDelayBvr = SCBehaviorDelayExecute::create(0, ptr); _ptrDelayBvr->addObject(this->makeObjPtr(this)); // keep this instance alive _ptrDelayBvr->execute(par); } } void SCBehaviorViewGoto::setSceneParameter(const SCDictionary& dic) { _parameterDic = dic; } void SCBehaviorViewGoto::onBvrFunc() { SCViewNav()->setSceneParameter(_parameterDic); SCViewNav()->gotoView(_switch); _ptrDelayBvr->frameRetain(); // instance keep alive in current frame _ptrDelayBvr = nullptr; } ///--------------- SCBehaviorViewBack void SCBehaviorViewBack::execute(const SCDictionary& par) { SC_RETURN_V_IF(!this->getActive()); if(_bDirect) { this->onBvrFunc(); } else if(_ptrDelayBvr==nullptr) { auto ptr = SCBehaviorCallFunc::create(SC_MAKE_FUNC(onBvrFunc, this)); _ptrDelayBvr = SCBehaviorDelayExecute::create(0, ptr); _ptrDelayBvr->addObject(this->makeObjPtr(this)); _ptrDelayBvr->execute(par); } } void SCBehaviorViewBack::onBvrFunc() { SCViewNavigator::getInstance()->back(_nSceneNum); _ptrDelayBvr->frameRetain(); // instance keep alive in current frame _ptrDelayBvr = nullptr; } ///--------------- SCBehaviorAlertBoxSelected SCBehaviorAlertBoxSelected::SCBehaviorAlertBoxSelected() :_pController(nullptr) ,_nSelected(0) { } SCBehaviorAlertBoxSelected::SCBehaviorAlertBoxSelected(SCViewController* pController,const int nSelected) :_pController(pController) ,_nSelected(nSelected) { } void SCBehaviorAlertBoxSelected::setController(SCViewController* pController) { _pController = pController; } void SCBehaviorAlertBoxSelected::setSelectedIndex(const int nSelectedIndex) { _nSelected = nSelectedIndex; } void SCBehaviorAlertBoxSelected::execute(const SCDictionary& par) { SC_RETURN_V_IF(!this->getActive()); if(_pController!=nullptr) { SCBehaviorViewBack::create()->execute(); _pController->finish(SC_NUM_2_PVOID(_nSelected)); } } ///----------- SCBehaviorShowLog SCBehaviorShowLog::SCBehaviorShowLog() { } SCBehaviorShowLog::~SCBehaviorShowLog() { } void SCBehaviorShowLog::execute(const SCDictionary& par) { SC_RETURN_V_IF(!this->getActive()); SCBehaviorViewGoto::create<SCViewControllerLog>(SCViewNavigator::kLayerModal)->execute(); } NAMESPACE_SPEEDCC_END
27.176871
108
0.690363
kevinwu1024
7971b7f0d66aee308f86c5e4f098c13ae18881ff
2,189
cpp
C++
examples/pangomm/measure-text-pixel-size-simple-example.cpp
zhanglin-wu/cairomm-pangomm-on-linux-docker
aaec738fdd35c4540173e40d8203c022d36155d2
[ "BSD-3-Clause" ]
null
null
null
examples/pangomm/measure-text-pixel-size-simple-example.cpp
zhanglin-wu/cairomm-pangomm-on-linux-docker
aaec738fdd35c4540173e40d8203c022d36155d2
[ "BSD-3-Clause" ]
null
null
null
examples/pangomm/measure-text-pixel-size-simple-example.cpp
zhanglin-wu/cairomm-pangomm-on-linux-docker
aaec738fdd35c4540173e40d8203c022d36155d2
[ "BSD-3-Clause" ]
null
null
null
// apt-get install libpangomm-1.4-dev -y // mkdir -p build && cd build // g++ -g -Wall -o measure-text-pixel-size-simple-example `pkg-config --cflags cairomm-1.0 pangomm-1.4` ../measure-text-pixel-size-simple-example.cpp `pkg-config --libs cairomm-1.0 pangomm-1.4` #include <sstream> #include <iostream> #include <glibmm.h> #include <string> #include <pangomm.h> #include <pangomm/fontdescription.h> #include <pangomm/item.h> #include <pangomm/glyphstring.h> #include <cairomm/cairomm.h> #include <pangomm.h> #include <pangomm/init.h> int main() { Pango::init(); auto surf = Cairo::ImageSurface::create(Cairo::Format::FORMAT_ARGB32, 600, 800); auto cr = Cairo::Context::create(surf); cr->set_source_rgb(0.5, 0.7, 0.5); cr->paint(); cr->move_to(0.0, 0.0); cr->set_source_rgb(1.0, 1.0, 1.0); auto layout = Pango::Layout::create(cr); // auto font = Glib::ustring("OpenSansEmoji"); // Pango::FontDescription desc(font); // std::cout << std::endl << desc.get_family() << std::endl; // layout->set_font_description(desc); // Glib::ustring text = Glib::locale_to_utf8("好人"); // auto text = Glib::ustring("Hello World!\n\xE4\xB8\xAD\xE5\x9B\xBD\xE2\x9A\xA1\xF0\x9F\x99\x82"); // auto text = Glib::ustring("Hello World!"); auto text = Glib::ustring("\xE4\xB8\xAD\xE5\x9B\xBD\xE2\x9A\xA1\xF0\x9F\x99\x82"); // auto text = Glib::ustring("\xE4\xB8\xAD\xE5\x9B\xBD\xE2\x9A\xA1\xF0\x9F\x99\x82\n\n\xE2\x9A\xA1\xF0\x9F\x99\x82\xE2\x9A\xA1\xF0\x9F\x99\x82"); // auto text = Glib::ustring("\xE4\xB8\xAD"); // text = Glib::ustring("\xE5\x9B\xBD"); // text = Glib::ustring("\xE2\x9A\xA1"); // text = Glib::ustring("\xF0\x9F\x99\x82"); layout->set_text(text); layout->update_from_cairo_context(cr); layout->show_in_cairo_context(cr); // Measure the text int text_width; int text_height; layout->get_pixel_size(text_width, text_height); std::stringstream ss; ss << "\n(" << text_width << ", " << text_height << ")\n"; cr->move_to(10, 50); layout->set_text(ss.str()); layout->update_from_cairo_context(cr); layout->show_in_cairo_context(cr); surf->write_to_png("measure-text-pixel-size-simple-example.png"); return 0; }
32.671642
193
0.669255
zhanglin-wu
7974ef528620669111c7a8fd717287e38ccbdd65
51,002
hpp
C++
dsp/L1/include/aie/fir_interpolate_asym.hpp
dycz0fx/Vitis_Libraries
d3fc414b552493657101ddb5245f24528720823d
[ "Apache-2.0" ]
1
2021-09-11T01:05:01.000Z
2021-09-11T01:05:01.000Z
dsp/L1/include/aie/fir_interpolate_asym.hpp
maxpark/Vitis_Libraries
4bd100518d93a8842d1678046ad7457f94eb355c
[ "Apache-2.0" ]
null
null
null
dsp/L1/include/aie/fir_interpolate_asym.hpp
maxpark/Vitis_Libraries
4bd100518d93a8842d1678046ad7457f94eb355c
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2021 Xilinx, Inc. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef FIR_INTERPOLATE_ASYM_HPP #define FIR_INTERPOLATE_ASYM_HPP /* Interpolating FIR class definition The file holds the definition of the Asymmetric Interpolation FIR kernel class. Note on Coefficient reversal. The AIE processor intrinsics naturally sum data and coefficients in the same order, but the conventional definition of a FIR has data and coefficient indices in opposite order. The order of coefficients is therefore reversed during construction to yield conventional FIR behaviour. */ /* Coding conventions TT_ template type suffix TP_ template parameter suffix */ #include <adf.h> #include <assert.h> #include <array> #include <cstdint> #include "fir_utils.hpp" #include "fir_interpolate_asym_traits.hpp" // CEIL rounds x up to the next multiple of y, which may be x itself. #define CEIL(x, y) (((x + y - 1) / y) * y) namespace xf { namespace dsp { namespace aie { namespace fir { namespace interpolate_asym { //#define _DSPLIB_FIR_INTERPOLATE_ASYM_HPP_DEBUG_ //----------------------------------------------------------------------------------------------------- template <typename TT_DATA, typename TT_COEFF, unsigned int TP_FIR_LEN, unsigned int TP_INTERPOLATE_FACTOR, unsigned int TP_SHIFT, unsigned int TP_RND, unsigned int TP_INPUT_WINDOW_VSIZE, bool TP_CASC_IN = CASC_IN_FALSE, bool TP_CASC_OUT = CASC_OUT_FALSE, unsigned int TP_FIR_RANGE_LEN = TP_FIR_LEN, unsigned int TP_KERNEL_POSITION = 0, unsigned int TP_CASC_LEN = 1, unsigned int TP_USE_COEFF_RELOAD = 0, unsigned int TP_NUM_OUTPUTS = 1> class kernelFilterClass { private: // Two implementations have been written for this filter. They have identical behaviour, but one is optimised for an // Interpolation factor // greater than the number of accumulator registers available. static constexpr unsigned int kArchIncr = 1; static constexpr unsigned int kArchPhaseSeries = 2; static constexpr unsigned int kArchPhaseParallel = 3; // Parameter value defensive and legality checks static_assert(TP_FIR_LEN <= FIR_LEN_MAX, "ERROR: Max supported FIR length exceeded. "); static_assert(TP_FIR_RANGE_LEN >= FIR_LEN_MIN, "ERROR: Illegal combination of design FIR length and cascade length, resulting in kernel FIR length " "below minimum required value. "); static_assert(TP_SHIFT >= SHIFT_MIN && TP_SHIFT <= SHIFT_MAX, "ERROR: SHIFT is out of the supported range."); static_assert(TP_RND >= ROUND_MIN && TP_RND <= ROUND_MAX, "ERROR: RND is out of the supported range."); static_assert((TP_FIR_LEN % TP_INTERPOLATE_FACTOR) == 0, "ERROR: TP_FIR_LEN must be an integer multiple of INTERPOLATE_FACTOR."); static_assert(fnEnumType<TT_DATA>() != enumUnknownType, "ERROR: TT_DATA is not a supported type."); static_assert(fnEnumType<TT_COEFF>() != enumUnknownType, "ERROR: TT_COEFF is not a supported type."); static_assert(fnTypeCheckDataCoeffSize<TT_DATA, TT_COEFF>() != 0, "ERROR: TT_DATA type less precise than TT_COEFF is not supported."); static_assert(fnTypeCheckDataCoeffCmplx<TT_DATA, TT_COEFF>() != 0, "ERROR: real TT_DATA with complex TT_COEFF is not supported."); static_assert(fnTypeCheckDataCoeffFltInt<TT_DATA, TT_COEFF>() != 0, "ERROR: a mix of float and integer types of TT_DATA and TT_COEFF is not supported."); // static_assert(TP_INTERPOLATE_FACTOR >= INTERPOLATE_FACTOR_MIN && TP_INTERPOLATE_FACTOR <= INTERPOLATE_FACTOR_MAX, "ERROR: TP_INTERPOLATE_FACTOR is out of the supported range"); static_assert(fnUnsupportedTypeCombo<TT_DATA, TT_COEFF>() != 0, "ERROR: The combination of TT_DATA and TT_COEFF is not supported for this class."); static_assert(TP_NUM_OUTPUTS > 0 && TP_NUM_OUTPUTS <= 2, "ERROR: only single or dual outputs are supported."); // There are additional defensive checks after architectural constants have been calculated. // The interpolation FIR calculates over multiple phases where such that the total number of lanes is an integer // multiple of the // interpolation factor. Hence an array of accumulators is needed for this set of lanes. static constexpr unsigned int m_kNumAccRegs = fnAccRegsIntAsym<TT_DATA, TT_COEFF>(); static constexpr unsigned int m_kWinAccessByteSize = 16; // 16 Bytes. The memory data path is min 128-bits wide for vector operations static constexpr unsigned int m_kColumns = sizeof(TT_COEFF) == 2 ? 2 : 1; // number of mult-adds per lane for main intrinsic static constexpr unsigned int m_kLanes = fnNumLanesIntAsym<TT_DATA, TT_COEFF>(); // number of operations in parallel // of this type combinations that // the vector processor can do. static constexpr unsigned int m_kVOutSize = fnVOutSizeIntAsym<TT_DATA, TT_COEFF>(); // This differs from kLanes for cint32/cint32 static constexpr unsigned int m_kDataLoadsInReg = 4; // ratio of 1024-bit data buffer to 256-bit load size. static constexpr unsigned int m_kDataLoadVsize = (32 / sizeof(TT_DATA)); // number of samples in a single 256-bit load static constexpr unsigned int m_kSamplesInBuff = m_kDataLoadsInReg * m_kDataLoadVsize; // static constexpr unsigned int m_kSamplesInBuff = 0; static constexpr unsigned int m_kFirRangeOffset = fnFirRangeOffset<TP_FIR_LEN, TP_CASC_LEN, TP_KERNEL_POSITION, TP_INTERPOLATE_FACTOR>() / TP_INTERPOLATE_FACTOR; // FIR Cascade Offset for this kernel position static constexpr unsigned int m_kFirMarginLen = TP_FIR_LEN / TP_INTERPOLATE_FACTOR; static constexpr unsigned int m_kFirMarginOffset = fnFirMargin<m_kFirMarginLen, TT_DATA>() - m_kFirMarginLen + 1; // FIR Margin Offset. static constexpr unsigned int m_kFirInitOffset = m_kFirRangeOffset + m_kFirMarginOffset; static constexpr unsigned int m_kDataWindowOffset = TRUNC((m_kFirInitOffset), (m_kWinAccessByteSize / sizeof(TT_DATA))); // Window offset - increments by 128bit static constexpr unsigned int m_kDataBuffXOffset = m_kFirInitOffset % (m_kWinAccessByteSize / sizeof(TT_DATA)); // Remainder of m_kFirInitOffset divided by 128bit // In some cases, the number of accumulators needed exceeds the number available in the processor leading to // inefficency as the // accumulators are loaded and stored on the stack. An alternative implementation is used to avoid this. static constexpr unsigned int m_kArch = (((m_kDataBuffXOffset + TP_FIR_RANGE_LEN + m_kLanes * m_kDataLoadVsize / m_kVOutSize) <= m_kSamplesInBuff) && (TP_INPUT_WINDOW_VSIZE % (m_kLanes * m_kDataLoadsInReg) == 0)) ? kArchIncr : // execute incremental load architecture kArchPhaseSeries; // execute each phase in series (reloads data) static constexpr unsigned int m_kZbuffSize = 32; static constexpr unsigned int m_kCoeffRegVsize = m_kZbuffSize / sizeof(TT_COEFF); static constexpr unsigned int m_kTotalLanes = fnLCMIntAsym<TT_DATA, TT_COEFF, TP_INTERPOLATE_FACTOR>(); // Lowest common multiple of Lanes and // Interpolatefactor static constexpr unsigned int m_kLCMPhases = m_kTotalLanes / m_kLanes; static constexpr unsigned int m_kPhases = TP_INTERPOLATE_FACTOR; static constexpr unsigned int m_kNumOps = CEIL(TP_FIR_RANGE_LEN / TP_INTERPOLATE_FACTOR, m_kColumns) / m_kColumns; static constexpr unsigned int m_kXbuffSize = 128; // data buffer size in Bytes static constexpr unsigned int m_kDataRegVsize = m_kXbuffSize / sizeof(TT_DATA); // samples in data buffer static constexpr unsigned int m_kLsize = TP_INPUT_WINDOW_VSIZE / m_kLanes; // loops required to consume input static constexpr unsigned int m_kInitialLoads = (m_kDataBuffXOffset + (m_kPhases * m_kLanes + m_kVOutSize) / TP_INTERPOLATE_FACTOR + m_kColumns - 1 + (m_kLanes - 1)) / m_kLanes; // effectively ceil[(kVOutsize+m_kColumns-1)/kLanes] static constexpr unsigned int m_kInitialLoadsIncr = CEIL(m_kDataBuffXOffset + TP_FIR_RANGE_LEN + m_kLanes * m_kDataLoadVsize / m_kVOutSize - 1, m_kDataLoadVsize) / m_kDataLoadVsize; static constexpr unsigned int m_kRepeatFactor = m_kDataLoadsInReg * m_kDataLoadVsize / m_kVOutSize; // Additional defensive checks static_assert(TP_INPUT_WINDOW_VSIZE % m_kLanes == 0, "ERROR: TP_INPUT_WINDOW_VSIZE must be an integer multiple of the number of lanes for this data type"); // The m_internalTaps is defined in terms of samples, but loaded into a vector, so has to be memory-aligned to the // vector size. TT_COEFF chess_storage(% chess_alignof(v16int16)) m_internalTaps[m_kLCMPhases][m_kNumOps][m_kColumns][m_kLanes]; // Two implementations have been written for this filter. They have identical behaviour, but one is optimised for an // Interpolation factor // greater than the number of accumulator registers available. void filter_impl1(T_inputIF<TP_CASC_IN, TT_DATA> inInterface, T_outputIF<TP_CASC_OUT, TT_DATA> outInterface); // Each phase is calculated in turn which avoids // need for multiple accumulators, but requires // data reloading. void filter_impl2( T_inputIF<TP_CASC_IN, TT_DATA> inInterface, T_outputIF<TP_CASC_OUT, TT_DATA> outInterface); // Parallel phase execution, requires multiple accumulators void filterIncr( T_inputIF<TP_CASC_IN, TT_DATA> inInterface, T_outputIF<TP_CASC_OUT, TT_DATA> outInterface); // Incremental load architecture which applies for short FIR_LEN void filterSelectArch(T_inputIF<TP_CASC_IN, TT_DATA> inInterface, T_outputIF<TP_CASC_OUT, TT_DATA> outInterface); // Constants for coeff reload static constexpr unsigned int m_kCoeffLoadSize = 256 / 8 / sizeof(TT_COEFF); TT_COEFF chess_storage(% chess_alignof(v8cint16)) m_oldInTaps[CEIL(TP_FIR_LEN, m_kCoeffLoadSize)]; // Previous user input coefficients with zero padding bool m_coeffnEq; // Are coefficients sets equal? public: // Access function for AIE Synthesizer static unsigned int get_m_kArch() { return m_kArch; }; // Constructors kernelFilterClass() : m_oldInTaps{} {} kernelFilterClass(const TT_COEFF (&taps)[TP_FIR_LEN]) { // Loads taps/coefficients firReload(taps); }; void firReload(const TT_COEFF* taps) { TT_COEFF* tapsPtr = (TT_COEFF*)taps; firReload(tapsPtr); } void firReload(TT_COEFF* taps) { const unsigned int bitsInNibble = 4; // Since the intrinsics can have columns, any values in memory beyond the end of the taps array could // contaminate the calculation. // To avoid this hazard, the class has its own taps array which is zero-padded to the column width for the type // of coefficient. int tapIndex; // Coefficients are pre-arranged such that during filter execution they may simply be read from a lookup table. for (int phase = 0; phase < m_kLCMPhases; ++phase) { for (int op = 0; op < m_kNumOps; ++op) { for (int column = 0; column < m_kColumns; ++column) { for (int lane = 0; lane < m_kLanes; ++lane) { tapIndex = TP_INTERPOLATE_FACTOR - 1 - ((lane + phase * m_kLanes) % TP_INTERPOLATE_FACTOR) + // datum index of lane (column * TP_INTERPOLATE_FACTOR) + // column offset is additive ((op * m_kColumns * TP_INTERPOLATE_FACTOR)); if (tapIndex < TP_FIR_RANGE_LEN && tapIndex >= 0) { tapIndex = TP_FIR_LEN - 1 - tapIndex - fnFirRangeOffset<TP_FIR_LEN, TP_CASC_LEN, TP_KERNEL_POSITION, TP_INTERPOLATE_FACTOR>(); // Reverse coefficients and apply // cascade range offset. See note at // head of file. m_internalTaps[phase][op][column][lane] = taps[tapIndex]; } else { m_internalTaps[phase][op][column][lane] = nullElem<TT_COEFF>(); // 0 for the type. } } } } } }; // Filter kernel for static coefficient designs void filterKernel(T_inputIF<TP_CASC_IN, TT_DATA> inInterface, T_outputIF<TP_CASC_OUT, TT_DATA> outInterface); // Filter kernel for reloadable coefficient designs void filterKernel(T_inputIF<TP_CASC_IN, TT_DATA> inInterface, T_outputIF<TP_CASC_OUT, TT_DATA> outInterface, const TT_COEFF (&inTaps)[TP_FIR_LEN]); void filterKernelRtp(T_inputIF<TP_CASC_IN, TT_DATA> inInterface, T_outputIF<TP_CASC_OUT, TT_DATA> outInterface); }; //----------------------------------------------------------------------------------------------------- // Cascade layer class and specializations //----------------------------------------------------------------------------------------------------- // This is the main declaration of the fir_interpolate_asym class, and is also used for the Standalone kernel // specialization with no cascade ports, no reload, single output template <typename TT_DATA, typename TT_COEFF, unsigned int TP_FIR_LEN, unsigned int TP_INTERPOLATE_FACTOR, unsigned int TP_SHIFT, unsigned int TP_RND, unsigned int TP_INPUT_WINDOW_VSIZE, bool TP_CASC_IN = CASC_IN_FALSE, bool TP_CASC_OUT = CASC_OUT_FALSE, unsigned int TP_FIR_RANGE_LEN = TP_FIR_LEN, unsigned int TP_KERNEL_POSITION = 0, unsigned int TP_CASC_LEN = 1, unsigned int TP_USE_COEFF_RELOAD = 0, // 1 = use coeff reload, 0 = don't use coeff reload unsigned int TP_NUM_OUTPUTS = 1> class fir_interpolate_asym : public kernelFilterClass<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_FALSE, CASC_OUT_FALSE, TP_FIR_LEN, 0, 1, USE_COEFF_RELOAD_FALSE, TP_NUM_OUTPUTS> { private: public: // Constructor fir_interpolate_asym(const TT_COEFF (&taps)[TP_FIR_LEN]) : kernelFilterClass<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_FALSE, CASC_OUT_FALSE, TP_FIR_LEN, 0, 1, USE_COEFF_RELOAD_FALSE>(taps) {} // Register Kernel Class static void registerKernelClass() { REGISTER_FUNCTION(fir_interpolate_asym::filter); } // FIR void filter(input_window<TT_DATA>* inWindow, output_window<TT_DATA>* restrict outWindow); }; // Single kernel specialization. No cascade ports, with reload coefficients. template <typename TT_DATA, typename TT_COEFF, unsigned int TP_FIR_LEN, unsigned int TP_INTERPOLATE_FACTOR, unsigned int TP_SHIFT, unsigned int TP_RND, unsigned int TP_INPUT_WINDOW_VSIZE, unsigned int TP_FIR_RANGE_LEN, unsigned int TP_KERNEL_POSITION, unsigned int TP_CASC_LEN> class fir_interpolate_asym<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_FALSE, CASC_OUT_FALSE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_FALSE, 2> : public kernelFilterClass<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_FALSE, CASC_OUT_FALSE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_FALSE, 2> { private: public: // Constructor fir_interpolate_asym(const TT_COEFF (&taps)[TP_FIR_LEN]) : kernelFilterClass<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_FALSE, CASC_OUT_FALSE, TP_FIR_LEN, 0, 1, USE_COEFF_RELOAD_FALSE, 2>(taps) {} // Register Kernel Class static void registerKernelClass() { REGISTER_FUNCTION(fir_interpolate_asym::filter); } // FIR void filter(input_window<TT_DATA>* inWindow, output_window<TT_DATA>* restrict outWindow, output_window<TT_DATA>* restrict outWindow2); }; //----------------------------------------------------------------------------------------------------- // Single kernel specialization. No cascade ports, with reload coefficients, single output template <typename TT_DATA, typename TT_COEFF, unsigned int TP_FIR_LEN, unsigned int TP_INTERPOLATE_FACTOR, unsigned int TP_SHIFT, unsigned int TP_RND, unsigned int TP_INPUT_WINDOW_VSIZE, unsigned int TP_FIR_RANGE_LEN, unsigned int TP_KERNEL_POSITION, unsigned int TP_CASC_LEN> class fir_interpolate_asym<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_FALSE, CASC_OUT_FALSE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_TRUE, 1> : public kernelFilterClass<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_FALSE, CASC_OUT_FALSE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_TRUE, 1> { private: public: // Constructor fir_interpolate_asym() : kernelFilterClass<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_FALSE, CASC_OUT_FALSE, TP_FIR_LEN, 0, 1, USE_COEFF_RELOAD_TRUE, 1>() {} // Register Kernel Class static void registerKernelClass() { REGISTER_FUNCTION(fir_interpolate_asym::filter); } // FIR void filter(input_window<TT_DATA>* inWindow, output_window<TT_DATA>* outWindow, const TT_COEFF (&inTaps)[TP_FIR_LEN]); }; // Single kernel specialization. No cascade ports, with reload coefficients, dual output template <typename TT_DATA, typename TT_COEFF, unsigned int TP_FIR_LEN, unsigned int TP_INTERPOLATE_FACTOR, unsigned int TP_SHIFT, unsigned int TP_RND, unsigned int TP_INPUT_WINDOW_VSIZE, unsigned int TP_FIR_RANGE_LEN, unsigned int TP_KERNEL_POSITION, unsigned int TP_CASC_LEN> class fir_interpolate_asym<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_FALSE, CASC_OUT_FALSE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_TRUE, 2> : public kernelFilterClass<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_FALSE, CASC_OUT_FALSE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_TRUE, 2> { private: public: // Constructor fir_interpolate_asym() : kernelFilterClass<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_FALSE, CASC_OUT_FALSE, TP_FIR_LEN, 0, 1, USE_COEFF_RELOAD_TRUE, 2>() {} // Register Kernel Class static void registerKernelClass() { REGISTER_FUNCTION(fir_interpolate_asym::filter); } // FIR void filter(input_window<TT_DATA>* inWindow, output_window<TT_DATA>* outWindow, output_window<TT_DATA>* outWindow2, const TT_COEFF (&inTaps)[TP_FIR_LEN]); }; //----------------------------------------------------------------------------------------------------- // Partially specialized classes for cascaded interface (final kernel in cascade), no reload, single output template <typename TT_DATA, typename TT_COEFF, unsigned int TP_FIR_LEN, unsigned int TP_INTERPOLATE_FACTOR, unsigned int TP_SHIFT, unsigned int TP_RND, unsigned int TP_INPUT_WINDOW_VSIZE, unsigned int TP_FIR_RANGE_LEN, unsigned int TP_KERNEL_POSITION, unsigned int TP_CASC_LEN> class fir_interpolate_asym<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_TRUE, CASC_OUT_FALSE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_FALSE, 1> : public kernelFilterClass<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_TRUE, CASC_OUT_FALSE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_FALSE, 1> { private: public: // Constructor fir_interpolate_asym(const TT_COEFF (&taps)[TP_FIR_LEN]) : kernelFilterClass<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_TRUE, CASC_OUT_FALSE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_FALSE, 1>(taps) {} // Register Kernel Class static void registerKernelClass() { REGISTER_FUNCTION(fir_interpolate_asym::filter); } // FIR void filter(input_window<TT_DATA>* inWindow, input_stream_cacc48* inCascade, output_window<TT_DATA>* restrict outWindow); }; // Partially specialized classes for cascaded interface (final kernel in cascade), no reload, dual output template <typename TT_DATA, typename TT_COEFF, unsigned int TP_FIR_LEN, unsigned int TP_INTERPOLATE_FACTOR, unsigned int TP_SHIFT, unsigned int TP_RND, unsigned int TP_INPUT_WINDOW_VSIZE, unsigned int TP_FIR_RANGE_LEN, unsigned int TP_KERNEL_POSITION, unsigned int TP_CASC_LEN> class fir_interpolate_asym<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_TRUE, CASC_OUT_FALSE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_FALSE, 2> : public kernelFilterClass<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_TRUE, CASC_OUT_FALSE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_FALSE, 2> { private: public: // Constructor fir_interpolate_asym(const TT_COEFF (&taps)[TP_FIR_LEN]) : kernelFilterClass<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_TRUE, CASC_OUT_FALSE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_FALSE, 2>(taps) {} // Register Kernel Class static void registerKernelClass() { REGISTER_FUNCTION(fir_interpolate_asym::filter); } // FIR void filter(input_window<TT_DATA>* inWindow, input_stream_cacc48* inCascade, output_window<TT_DATA>* restrict outWindow, output_window<TT_DATA>* restrict outWindow2); }; // Partially specialized classes for cascaded interface (final kernel in cascade), with reload, single output template <typename TT_DATA, typename TT_COEFF, unsigned int TP_FIR_LEN, unsigned int TP_INTERPOLATE_FACTOR, unsigned int TP_SHIFT, unsigned int TP_RND, unsigned int TP_INPUT_WINDOW_VSIZE, unsigned int TP_FIR_RANGE_LEN, unsigned int TP_KERNEL_POSITION, unsigned int TP_CASC_LEN> class fir_interpolate_asym<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_TRUE, CASC_OUT_FALSE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_TRUE, 1> : public kernelFilterClass<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_TRUE, CASC_OUT_FALSE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_TRUE, 1> { private: public: // Constructor fir_interpolate_asym() : kernelFilterClass<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_TRUE, CASC_OUT_FALSE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_TRUE, 1>() {} // Register Kernel Class static void registerKernelClass() { REGISTER_FUNCTION(fir_interpolate_asym::filter); } // FIR void filter(input_window<TT_DATA>* inWindow, input_stream_cacc48* inCascade, output_window<TT_DATA>* outWindow); // output_window<TT_DATA>* restrict outWindow, // const TT_COEFF (&inTaps)[TP_FIR_LEN]); }; // Partially specialized classes for cascaded interface (final kernel in cascade), with reload, dual output template <typename TT_DATA, typename TT_COEFF, unsigned int TP_FIR_LEN, unsigned int TP_INTERPOLATE_FACTOR, unsigned int TP_SHIFT, unsigned int TP_RND, unsigned int TP_INPUT_WINDOW_VSIZE, unsigned int TP_FIR_RANGE_LEN, unsigned int TP_KERNEL_POSITION, unsigned int TP_CASC_LEN> class fir_interpolate_asym<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_TRUE, CASC_OUT_FALSE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_TRUE, 2> : public kernelFilterClass<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_TRUE, CASC_OUT_FALSE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_TRUE, 2> { private: public: // Constructor fir_interpolate_asym() : kernelFilterClass<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_TRUE, CASC_OUT_FALSE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_TRUE, 2>() {} // Register Kernel Class static void registerKernelClass() { REGISTER_FUNCTION(fir_interpolate_asym::filter); } // FIR void filter(input_window<TT_DATA>* inWindow, input_stream_cacc48* inCascade, output_window<TT_DATA>* outWindow, output_window<TT_DATA>* outWindow2); // output_window<TT_DATA>* restrict outWindow, // const TT_COEFF (&inTaps)[TP_FIR_LEN]); }; //----------------------------------------------------------------------------------------------------- // Partially specialized classes for cascaded interface (First kernel in cascade), no reload template <typename TT_DATA, typename TT_COEFF, unsigned int TP_FIR_LEN, unsigned int TP_INTERPOLATE_FACTOR, unsigned int TP_SHIFT, unsigned int TP_RND, unsigned int TP_INPUT_WINDOW_VSIZE, unsigned int TP_FIR_RANGE_LEN, unsigned int TP_KERNEL_POSITION, unsigned int TP_CASC_LEN> class fir_interpolate_asym<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_FALSE, CASC_OUT_TRUE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_FALSE, 1> : public kernelFilterClass<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_FALSE, CASC_OUT_TRUE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_FALSE, 1> { private: public: // Constructor fir_interpolate_asym(const TT_COEFF (&taps)[TP_FIR_LEN]) : kernelFilterClass<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_FALSE, CASC_OUT_TRUE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_FALSE, 1>(taps) {} // Register Kernel Class static void registerKernelClass() { REGISTER_FUNCTION(fir_interpolate_asym::filter); } // FIR void filter(input_window<TT_DATA>* inWindow, output_stream_cacc48* outCascade, output_window<TT_DATA>* broadcastWindow); }; // Partially specialized classes for cascaded interface (First kernel in cascade), with reload template <typename TT_DATA, typename TT_COEFF, unsigned int TP_FIR_LEN, unsigned int TP_INTERPOLATE_FACTOR, unsigned int TP_SHIFT, unsigned int TP_RND, unsigned int TP_INPUT_WINDOW_VSIZE, unsigned int TP_FIR_RANGE_LEN, unsigned int TP_KERNEL_POSITION, unsigned int TP_CASC_LEN> class fir_interpolate_asym<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_FALSE, CASC_OUT_TRUE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_TRUE, 1> : public kernelFilterClass<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_FALSE, CASC_OUT_TRUE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_TRUE, 1> { private: public: // Constructor fir_interpolate_asym() : kernelFilterClass<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_FALSE, CASC_OUT_TRUE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_TRUE, 1>() {} // Register Kernel Class static void registerKernelClass() { REGISTER_FUNCTION(fir_interpolate_asym::filter); } // FIR void filter(input_window<TT_DATA>* inWindow, output_stream_cacc48* outCascade, output_window<TT_DATA>* broadcastWindow, const TT_COEFF (&inTaps)[TP_FIR_LEN]); }; //----------------------------------------------------------------------------------------------------- // Partially specialized classes for cascaded interface (middle kernels in cascade), no reload template <typename TT_DATA, typename TT_COEFF, unsigned int TP_FIR_LEN, unsigned int TP_INTERPOLATE_FACTOR, unsigned int TP_SHIFT, unsigned int TP_RND, unsigned int TP_INPUT_WINDOW_VSIZE, unsigned int TP_FIR_RANGE_LEN, unsigned int TP_KERNEL_POSITION, unsigned int TP_CASC_LEN> class fir_interpolate_asym<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_TRUE, CASC_OUT_TRUE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_FALSE, 1> : public kernelFilterClass<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_TRUE, CASC_OUT_TRUE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_FALSE, 1> { private: public: // Constructor fir_interpolate_asym(const TT_COEFF (&taps)[TP_FIR_LEN]) : kernelFilterClass<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_TRUE, CASC_OUT_TRUE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_FALSE, 1>(taps) {} // Register Kernel Class static void registerKernelClass() { REGISTER_FUNCTION(fir_interpolate_asym::filter); } // FIR void filter(input_window<TT_DATA>* inWindow, input_stream_cacc48* inCascade, output_stream_cacc48* outCascade, output_window<TT_DATA>* broadcastWindow); }; // Partially specialized classes for cascaded interface (middle kernels in cascade), with reload template <typename TT_DATA, typename TT_COEFF, unsigned int TP_FIR_LEN, unsigned int TP_INTERPOLATE_FACTOR, unsigned int TP_SHIFT, unsigned int TP_RND, unsigned int TP_INPUT_WINDOW_VSIZE, unsigned int TP_FIR_RANGE_LEN, unsigned int TP_KERNEL_POSITION, unsigned int TP_CASC_LEN> class fir_interpolate_asym<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_TRUE, CASC_OUT_TRUE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_TRUE, 1> : public kernelFilterClass<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_TRUE, CASC_OUT_TRUE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_TRUE, 1> { private: public: // Constructor fir_interpolate_asym() : kernelFilterClass<TT_DATA, TT_COEFF, TP_FIR_LEN, TP_INTERPOLATE_FACTOR, TP_SHIFT, TP_RND, TP_INPUT_WINDOW_VSIZE, CASC_IN_TRUE, CASC_OUT_TRUE, TP_FIR_RANGE_LEN, TP_KERNEL_POSITION, TP_CASC_LEN, USE_COEFF_RELOAD_TRUE, 1>() {} // Register Kernel Class static void registerKernelClass() { REGISTER_FUNCTION(fir_interpolate_asym::filter); } // FIR void filter(input_window<TT_DATA>* inWindow, input_stream_cacc48* inCascade, output_stream_cacc48* outCascade, output_window<TT_DATA>* broadcastWindow); }; } } } } } // namespaces #endif // fir_interpolate_asym_HPP
48.619638
120
0.463707
dycz0fx
7976518cf1e1d347ad3a55b752376b017a912b9f
234
cpp
C++
RandomQuestions/001.cpp
harveyc95/ProgrammingProblems
d81dc58de0347fa155f5e25f27d3d426ce13cdc6
[ "MIT" ]
null
null
null
RandomQuestions/001.cpp
harveyc95/ProgrammingProblems
d81dc58de0347fa155f5e25f27d3d426ce13cdc6
[ "MIT" ]
null
null
null
RandomQuestions/001.cpp
harveyc95/ProgrammingProblems
d81dc58de0347fa155f5e25f27d3d426ce13cdc6
[ "MIT" ]
null
null
null
// 1. Round a number to the next largest multiple of 16 #include <iostream> int round_to_largest_16(int x) { return (x & 0xF) ? ((x >> 4 << 4) + 16) : x; } int main () { std::cout<<round_to_largest_16(30)<<std::endl; return 0; }
19.5
55
0.628205
harveyc95
797c72447f93a0bbddb17cc3907cd1059127dff0
2,420
cpp
C++
m07/Pr16-1a_catch_types.cpp
dvcchern/CS200
333df210e70757da7cec481314b1a1e734fd03ed
[ "MIT" ]
4
2020-02-14T23:54:05.000Z
2022-01-30T18:29:06.000Z
m07/Pr16-1a_catch_types.cpp
dvcchern/CS200
333df210e70757da7cec481314b1a1e734fd03ed
[ "MIT" ]
null
null
null
m07/Pr16-1a_catch_types.cpp
dvcchern/CS200
333df210e70757da7cec481314b1a1e734fd03ed
[ "MIT" ]
6
2020-02-24T07:06:47.000Z
2022-02-03T02:46:46.000Z
//__________________________________________ // throw primitive types ... #include <iostream> #include <stdexcept> // for runtime_error #include <string> using namespace std; int main() { string choice, word, text; // User input for choices and input auto menu = [] ( ) { cout << "_______ Throw Primitive Types __________\n" << " m - menu\n" << " c - c_str\n" << " i - integer\n" << " f - float\n" << " s - string\n" << " u - undefined (double)\n" << " q - Quit\n"; }; menu(); string s("Worse"); int i=123; float f=1.23; double d=4.56; const char *c = "foo bar"; bool stay = true; while(stay) { // Main menu while starts cout << " Enter your choice: "; cin >> choice; // Take in user choice from menu cin.ignore(); char ch = choice[0]; try { switch(ch) { // menu switch start case 'b': case 'B': // break out of loop stay = false; break; case 'c': case 'C': // c_str throw("Bad"); break; case 'i': case 'I': // integer throw(123); break; case 'f': case 'F': // float; throw(f); break; case 's': case 'S': // string throw(s); break; case 'm': case 'M': menu(); break; case 'r': case 'R': throw runtime_error("Catastrophe"); break; case 'u': case 'U': // undefined (double) throw(d); break; case 'q': case 'Q': // quit stay = false; break; default: // Invalid! Tells user to try again cout << "\nInvalid command!\nTry again!\n\n"; } } // end of try block catch ( runtime_error &e ) { cout << e.what () << '\n'; } catch (int i) { cout << i << '\n'; } catch (float f) { cout << f << '\n'; } catch (const char *e) { cout << e << '\n'; } catch (string e) { cout << e << '\n'; } catch (...) { cout << "some unknown exception.\n"; } } // end of while cout << "\nProgram exit!"; }
31.025641
67
0.416116
dvcchern
797d6cc72e76b9b5dfdfa7de28f480987c8a673d
206
cpp
C++
CppStrangeIoC/framework/context/icontext.cpp
AndreySkyFoxSidorov/CppStrangeIoC
cae0953ec4a1fce838d7c138153d4279d3fb2c4b
[ "Apache-2.0" ]
2
2018-06-06T11:26:48.000Z
2019-04-11T14:05:42.000Z
CppStrangeIoC/framework/context/icontext.cpp
AndreySkyFoxSidorov/CppStrangeIoC
cae0953ec4a1fce838d7c138153d4279d3fb2c4b
[ "Apache-2.0" ]
null
null
null
CppStrangeIoC/framework/context/icontext.cpp
AndreySkyFoxSidorov/CppStrangeIoC
cae0953ec4a1fce838d7c138153d4279d3fb2c4b
[ "Apache-2.0" ]
2
2018-06-06T11:26:49.000Z
2021-07-26T03:43:16.000Z
#include "IContext.h" using namespace strange::framework::api; using namespace strange::extensions::dispatcher::api; namespace strange { namespace extensions { namespace context { namespace api { } } } }
12.117647
53
0.757282
AndreySkyFoxSidorov
797f505532498773f395f24d9b664e3b2fd4cfbd
1,016
hpp
C++
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/gui/include/gui/common/Defines.hpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/gui/include/gui/common/Defines.hpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F769I_EVAL/Demonstrations/TouchGFX/Gui/gui/include/gui/common/Defines.hpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
/** ****************************************************************************** * This file is part of the TouchGFX 4.10.0 distribution. * * @attention * * Copyright (c) 2018 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file * in the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ #ifndef GUI_DEFINES_HPP #define GUI_DEFINES_HPP #include <touchgfx/hal/HAL.hpp> class Defines { public: enum MainMenuType { ANIMATING_BUTTONS_MENU = 0, CAROUSEL_MENU, NO_MENU }; enum DemoID { GAME2048 = 0, GAME2D, CONTROLS, AUDIO_PLAYER, HOME_AUTOMATION, SETTINGS, VIDEO_PLAYER, NUMBER_OF_DEMO_SCREENS, NO_DEMO_SCREEN }; }; #endif /* GUI_DEFINES_HPP */
20.734694
80
0.526575
ramkumarkoppu
7982bc247455564c345cae3863b9ae57b12b7957
9,354
cpp
C++
OverlordEngine/DebugRenderer.cpp
Ruvah/Overlord-Editor
3193b4986b10edb0fa8fdbc493ee3b05fdea217d
[ "Apache-2.0" ]
1
2018-11-28T12:30:13.000Z
2018-11-28T12:30:13.000Z
OverlordEngine/DebugRenderer.cpp
Ruvah/Overlord-Editor
3193b4986b10edb0fa8fdbc493ee3b05fdea217d
[ "Apache-2.0" ]
null
null
null
OverlordEngine/DebugRenderer.cpp
Ruvah/Overlord-Editor
3193b4986b10edb0fa8fdbc493ee3b05fdea217d
[ "Apache-2.0" ]
2
2019-12-28T12:34:51.000Z
2021-03-08T08:37:33.000Z
#include "stdafx.h" #include "DebugRenderer.h" #include "Logger.h" #include "ContentManager.h" ID3DX11Effect* DebugRenderer::m_pEffect = nullptr; ID3DX11EffectTechnique* DebugRenderer::m_pTechnique = nullptr; unsigned int DebugRenderer::m_BufferSize = 100; ID3D11Buffer* DebugRenderer::m_pVertexBuffer = nullptr; physx::PxScene* DebugRenderer::m_pPhysxDebugScene = nullptr; ID3D11InputLayout* DebugRenderer::m_pInputLayout = nullptr; ID3DX11EffectMatrixVariable* DebugRenderer::m_pWvpVariable = nullptr; std::vector<VertexPosCol> DebugRenderer::m_LineList = std::vector<VertexPosCol>(); std::vector<VertexPosCol> DebugRenderer::m_FixedLineList = std::vector<VertexPosCol>(); unsigned int DebugRenderer::m_FixedBufferSize = 0; bool DebugRenderer::m_RendererEnabled = true; void DebugRenderer::Release() { SafeRelease(m_pInputLayout); SafeRelease(m_pVertexBuffer); } void DebugRenderer::InitRenderer(ID3D11Device *pDevice, unsigned int bufferSize) { m_BufferSize = bufferSize; // TODO: paths shouldn't be hard coded. m_pEffect = ContentManager::Load<ID3DX11Effect>(L"./Resources/Effects/DebugRenderer.fx"); m_pTechnique = m_pEffect->GetTechniqueByIndex(0); m_pWvpVariable = m_pEffect->GetVariableBySemantic("WORLDVIEWPROJECTION")->AsMatrix(); if(!m_pWvpVariable->IsValid()) Logger::LogWarning(L"Debug Renderer: Invalid Shader Variable! (WVP)"); //Input Layout D3D11_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0} }; D3DX11_PASS_DESC passDesc; m_pTechnique->GetPassByIndex(0)->GetDesc(&passDesc); pDevice->CreateInputLayout(layout, 2, passDesc.pIAInputSignature, passDesc.IAInputSignatureSize, &m_pInputLayout); CreateFixedLineList(); CreateVertexBuffer(pDevice); } void DebugRenderer::CreateVertexBuffer(ID3D11Device *pDevice) { SafeRelease(m_pVertexBuffer); //Vertexbuffer D3D11_BUFFER_DESC buffDesc; buffDesc.Usage = D3D11_USAGE_DYNAMIC; buffDesc.ByteWidth = sizeof(VertexPosCol) * (m_BufferSize + m_FixedBufferSize); buffDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; buffDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; buffDesc.MiscFlags = 0; pDevice->CreateBuffer(&buffDesc,nullptr,&m_pVertexBuffer); if(m_FixedBufferSize > 0) { //Map Fixed data manually ID3D11DeviceContext* pDeviceContext; pDevice->GetImmediateContext(&pDeviceContext); D3D11_MAPPED_SUBRESOURCE mappedResource; pDeviceContext->Map(m_pVertexBuffer, 0, D3D11_MAP_WRITE_NO_OVERWRITE, 0, &mappedResource); memcpy(mappedResource.pData, &m_FixedLineList[0], sizeof(VertexPosCol) * m_FixedBufferSize); pDeviceContext->Unmap(m_pVertexBuffer, 0); pDeviceContext->Release(); } } void DebugRenderer::CreateFixedLineList() { //*GRID* const unsigned int numGridLines = 20; const float gridSpacing = 1.0f; const float startOffset = -(static_cast<int>(numGridLines)/2)*gridSpacing; const float size = (numGridLines - 1) * gridSpacing; const auto gridColor = static_cast<DirectX::XMFLOAT4>(DirectX::Colors::LightGray); for(unsigned int i = 0; i < numGridLines; ++i) { //VERTICAL const float lineOffset = startOffset + gridSpacing * i; auto vertStart = DirectX::XMFLOAT3(startOffset, 0, lineOffset); m_FixedLineList.emplace_back(VertexPosCol(vertStart, gridColor)); vertStart.x += size; m_FixedLineList.emplace_back(VertexPosCol(vertStart, gridColor)); //HORIZONTAL vertStart = DirectX::XMFLOAT3(lineOffset, 0, startOffset); m_FixedLineList.emplace_back(VertexPosCol(vertStart, gridColor)); vertStart.z += size; m_FixedLineList.emplace_back(VertexPosCol(vertStart, gridColor)); } //*AXIS m_FixedLineList.emplace_back(VertexPosCol(DirectX::XMFLOAT3(0,0,0), static_cast<DirectX::XMFLOAT4>(DirectX::Colors::DarkRed))); m_FixedLineList.emplace_back(VertexPosCol(DirectX::XMFLOAT3(30,0,0), static_cast<DirectX::XMFLOAT4>(DirectX::Colors::DarkRed))); m_FixedLineList.emplace_back(VertexPosCol(DirectX::XMFLOAT3(0,0,0), static_cast<DirectX::XMFLOAT4>(DirectX::Colors::DarkGreen))); m_FixedLineList.emplace_back(VertexPosCol(DirectX::XMFLOAT3(0,30,0), static_cast<DirectX::XMFLOAT4>(DirectX::Colors::DarkGreen))); m_FixedLineList.emplace_back(VertexPosCol(DirectX::XMFLOAT3(0,0,0), static_cast<DirectX::XMFLOAT4>(DirectX::Colors::DarkBlue))); m_FixedLineList.emplace_back(VertexPosCol(DirectX::XMFLOAT3(0,0,30), static_cast<DirectX::XMFLOAT4>(DirectX::Colors::DarkBlue))); //@END! m_FixedBufferSize = m_FixedLineList.size(); } void DebugRenderer::ToggleDebugRenderer() { m_RendererEnabled = !m_RendererEnabled; } void DebugRenderer::DrawLine(DirectX::XMFLOAT3 start, DirectX::XMFLOAT3 end, DirectX::XMFLOAT4 color) { if(!m_RendererEnabled) return; m_LineList.emplace_back(VertexPosCol(start, color)); m_LineList.emplace_back(VertexPosCol(end, color)); } void DebugRenderer::DrawLine(DirectX::XMFLOAT3 start, DirectX::XMFLOAT4 colorStart, DirectX::XMFLOAT3 end, DirectX::XMFLOAT4 colorEnd) { if(!m_RendererEnabled) return; m_LineList.emplace_back(VertexPosCol(start, colorStart)); m_LineList.emplace_back(VertexPosCol(end, colorEnd)); } void DebugRenderer::DrawPhysX(physx::PxScene* pScene) { if(!m_RendererEnabled) return; //m_pPhysxDebugScene = pScene; const auto pxDebugRenderer = &pScene->getRenderBuffer(); const auto debugLines = pxDebugRenderer->getLines(); for(unsigned int i = 0; i < pxDebugRenderer->getNbLines(); ++i) { const auto line = debugLines[i]; DrawLine(DirectX::XMFLOAT3(line.pos0.x, line.pos0.y, line.pos0.z),ConvertPxColor(line.color0), DirectX::XMFLOAT3(line.pos1.x, line.pos1.y, line.pos1.z),ConvertPxColor(line.color1)); } } DirectX::XMFLOAT4 DebugRenderer::ConvertPxColor(physx::PxU32 color) { //TODO: Check performance, Bitshift+divide vs switch // Alex: maybe check implementation design too. switch(color) { case 0xFF000000: return static_cast<DirectX::XMFLOAT4>(DirectX::Colors::Black); case 0xFFFF0000: return static_cast<DirectX::XMFLOAT4>(DirectX::Colors::Red); case 0xFF00FF00: return static_cast<DirectX::XMFLOAT4>(DirectX::Colors::Green); case 0xFF0000FF: return static_cast<DirectX::XMFLOAT4>(DirectX::Colors::Blue); case 0xFFFFFF00: return static_cast<DirectX::XMFLOAT4>(DirectX::Colors::Yellow); case 0xFFFF00FF: return static_cast<DirectX::XMFLOAT4>(DirectX::Colors::Magenta); case 0xFF00FFFF: return static_cast<DirectX::XMFLOAT4>(DirectX::Colors::Cyan); case 0xFFFFFFFF: return static_cast<DirectX::XMFLOAT4>(DirectX::Colors::White); case 0xFF808080: return static_cast<DirectX::XMFLOAT4>(DirectX::Colors::Gray); case 0x88880000: return static_cast<DirectX::XMFLOAT4>(DirectX::Colors::DarkRed); case 0x88008800: return static_cast<DirectX::XMFLOAT4>(DirectX::Colors::DarkGreen); case 0x88000088: return static_cast<DirectX::XMFLOAT4>(DirectX::Colors::DarkBlue); default: return static_cast<DirectX::XMFLOAT4>(DirectX::Colors::Black); } } void DebugRenderer::Draw(const GameContext& gameContext) { if(!m_RendererEnabled) return; //PhysX RenderBuffer unsigned int pxBuffSize = 0; const physx::PxRenderBuffer* pPxRenderBuffer = nullptr; if (m_pPhysxDebugScene) { pPxRenderBuffer = &m_pPhysxDebugScene->getRenderBuffer(); pxBuffSize = pPxRenderBuffer->getNbLines(); //PxDebugLine == 2* VertexPosCol m_pPhysxDebugScene = nullptr; } //Current Size (DebugDraw + PhysXDraw) const unsigned int regularSize = m_LineList.size(); const unsigned int dynamicSize = regularSize + pxBuffSize; //Total size const unsigned int totalSize = dynamicSize + m_FixedBufferSize; if(totalSize <= 0) return; if(dynamicSize > m_BufferSize) { Logger::LogInfo(L"DebugRenderer::Draw() > Increasing Vertexbuffer Size!"); m_BufferSize = dynamicSize; CreateVertexBuffer(gameContext.pDevice); } auto pDevContext = gameContext.pDeviceContext; if(dynamicSize>0) { D3D11_MAPPED_SUBRESOURCE mappedResource; pDevContext->Map(m_pVertexBuffer, 0, D3D11_MAP_WRITE_NO_OVERWRITE, 0, &mappedResource); if (regularSize > 0) { memcpy(&(static_cast<VertexPosCol*>(mappedResource.pData)[m_FixedBufferSize]), &m_LineList[0], sizeof(VertexPosCol) * regularSize); //Engine Lines } if (pxBuffSize > 0) { auto lineBuffer = pPxRenderBuffer->getLines(); memcpy(&(static_cast<VertexPosCol*>(mappedResource.pData)[m_FixedBufferSize + regularSize]), &lineBuffer, sizeof(VertexPosCol) * pxBuffSize); //PhysX Lines } pDevContext->Unmap(m_pVertexBuffer, 0); } //Set Render Pipeline pDevContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINELIST); unsigned int stride = sizeof(VertexPosCol); unsigned int offset = 0; pDevContext->IASetVertexBuffers(0, 1, &m_pVertexBuffer, &stride, &offset); pDevContext->IASetInputLayout(m_pInputLayout); auto viewProj = gameContext.pCamera->GetViewProjection(); const DirectX::XMMATRIX wvp = DirectX::XMMatrixIdentity() * XMLoadFloat4x4(&viewProj); DirectX::XMFLOAT4X4 wvpConverted; XMStoreFloat4x4( &wvpConverted, wvp); m_pWvpVariable->SetMatrix(reinterpret_cast<float*>(&wvpConverted)); D3DX11_TECHNIQUE_DESC techDesc; m_pTechnique->GetDesc(&techDesc); for(unsigned int i = 0; i < techDesc.Passes; ++i) { m_pTechnique->GetPassByIndex(i)->Apply(0, pDevContext); pDevContext->Draw(totalSize, 0); } m_LineList.clear(); }
34.773234
183
0.770579
Ruvah
798316b442b839d46205c4851fa721d580d0d971
4,737
cpp
C++
cpdp/src/v20190820/model/QueryOpenBankDailyReceiptDownloadUrlResult.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
cpdp/src/v20190820/model/QueryOpenBankDailyReceiptDownloadUrlResult.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
cpdp/src/v20190820/model/QueryOpenBankDailyReceiptDownloadUrlResult.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/cpdp/v20190820/model/QueryOpenBankDailyReceiptDownloadUrlResult.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Cpdp::V20190820::Model; using namespace std; QueryOpenBankDailyReceiptDownloadUrlResult::QueryOpenBankDailyReceiptDownloadUrlResult() : m_downloadUrlHasBeenSet(false), m_expireTimeHasBeenSet(false), m_receiptStatusHasBeenSet(false) { } CoreInternalOutcome QueryOpenBankDailyReceiptDownloadUrlResult::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("DownloadUrl") && !value["DownloadUrl"].IsNull()) { if (!value["DownloadUrl"].IsString()) { return CoreInternalOutcome(Core::Error("response `QueryOpenBankDailyReceiptDownloadUrlResult.DownloadUrl` IsString=false incorrectly").SetRequestId(requestId)); } m_downloadUrl = string(value["DownloadUrl"].GetString()); m_downloadUrlHasBeenSet = true; } if (value.HasMember("ExpireTime") && !value["ExpireTime"].IsNull()) { if (!value["ExpireTime"].IsString()) { return CoreInternalOutcome(Core::Error("response `QueryOpenBankDailyReceiptDownloadUrlResult.ExpireTime` IsString=false incorrectly").SetRequestId(requestId)); } m_expireTime = string(value["ExpireTime"].GetString()); m_expireTimeHasBeenSet = true; } if (value.HasMember("ReceiptStatus") && !value["ReceiptStatus"].IsNull()) { if (!value["ReceiptStatus"].IsString()) { return CoreInternalOutcome(Core::Error("response `QueryOpenBankDailyReceiptDownloadUrlResult.ReceiptStatus` IsString=false incorrectly").SetRequestId(requestId)); } m_receiptStatus = string(value["ReceiptStatus"].GetString()); m_receiptStatusHasBeenSet = true; } return CoreInternalOutcome(true); } void QueryOpenBankDailyReceiptDownloadUrlResult::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_downloadUrlHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DownloadUrl"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_downloadUrl.c_str(), allocator).Move(), allocator); } if (m_expireTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ExpireTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_expireTime.c_str(), allocator).Move(), allocator); } if (m_receiptStatusHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ReceiptStatus"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_receiptStatus.c_str(), allocator).Move(), allocator); } } string QueryOpenBankDailyReceiptDownloadUrlResult::GetDownloadUrl() const { return m_downloadUrl; } void QueryOpenBankDailyReceiptDownloadUrlResult::SetDownloadUrl(const string& _downloadUrl) { m_downloadUrl = _downloadUrl; m_downloadUrlHasBeenSet = true; } bool QueryOpenBankDailyReceiptDownloadUrlResult::DownloadUrlHasBeenSet() const { return m_downloadUrlHasBeenSet; } string QueryOpenBankDailyReceiptDownloadUrlResult::GetExpireTime() const { return m_expireTime; } void QueryOpenBankDailyReceiptDownloadUrlResult::SetExpireTime(const string& _expireTime) { m_expireTime = _expireTime; m_expireTimeHasBeenSet = true; } bool QueryOpenBankDailyReceiptDownloadUrlResult::ExpireTimeHasBeenSet() const { return m_expireTimeHasBeenSet; } string QueryOpenBankDailyReceiptDownloadUrlResult::GetReceiptStatus() const { return m_receiptStatus; } void QueryOpenBankDailyReceiptDownloadUrlResult::SetReceiptStatus(const string& _receiptStatus) { m_receiptStatus = _receiptStatus; m_receiptStatusHasBeenSet = true; } bool QueryOpenBankDailyReceiptDownloadUrlResult::ReceiptStatusHasBeenSet() const { return m_receiptStatusHasBeenSet; }
32.22449
174
0.735487
suluner
798556c70d2ecd19f9baafd5d61c3e305160d27f
2,469
cpp
C++
Compra-venda-produtos/Projeto Integrador/pessoafisica.cpp
CaioMS2000/Meus-projetos
190c987514503125a36d688302eaa738b5f346e4
[ "MIT" ]
null
null
null
Compra-venda-produtos/Projeto Integrador/pessoafisica.cpp
CaioMS2000/Meus-projetos
190c987514503125a36d688302eaa738b5f346e4
[ "MIT" ]
null
null
null
Compra-venda-produtos/Projeto Integrador/pessoafisica.cpp
CaioMS2000/Meus-projetos
190c987514503125a36d688302eaa738b5f346e4
[ "MIT" ]
null
null
null
#include "pessoafisica.h" namespace Caio{ PessoaFisica::PessoaFisica(): Cliente(), cpf(""), nome(""), celular("") { } PessoaFisica::PessoaFisica(QString &log, QString &s, QString &c, QString &e, QString &t, QString &em, QString &cpf, QString &nome, QString &celular): Cliente(log, s, c, e, t, em, "PF"), cpf(cpf), nome(nome), celular(celular) { } bool PessoaFisica::validarCPF(QString &ref) { string s(ref.toStdString()); int digitos[11]; if(s.size() != 11){ return false; } else if(s == "00000000000" || s == "99999999999"){ return false; } else{ for(unsigned long long x=0; x<11; x++) if(isdigit(s[x]) == false){ return false;} for(unsigned long long x=0; x<11; x++) digitos[x]=(int)s[x]-48; int pd=0; bool validarpd=false; for(int x=0, m=10; x<9; x++, m--) pd+=digitos[x]*m; pd=pd%11; if(pd<2) pd=0; else pd=11-pd; int sd=0; bool validarsd=false; int x=0, m=11; for(; x<9; x++, m--){ sd+=digitos[x]*m; } sd+=pd*m; sd=sd%11; if(sd<2) sd=0; else sd=11-sd; if(digitos[9]==pd) validarpd=true; if(digitos[10]==sd) validarsd=true; if(validarpd==true && validarsd==true){ return true; } else return false; } } QString PessoaFisica::toString() const { QString str("Nome: "+nome+"\nCodigo: "+codigo+"\nCPF: "+cpf+"\nLogradouro: "+logradouro+"\nSetor: "+setor+"\nCidade: "+cidade+"\nEstado: "+estado+"\nTelefone: "+telefone+"\nCelular: "+celular+"\nEmail: "+email); return str; //falta adicionar coisa } string PessoaFisica::registro() const { string s("pf;"+logradouro.toStdString()+';'+setor.toStdString()+';'+cidade.toStdString()+';'+estado.toStdString()+';'+telefone.toStdString()+';'+email.toStdString()+';'+cpf.toStdString()+';'+nome.toStdString()+';'+celular.toStdString()); return s; } }//namespace
28.709302
242
0.45565
CaioMS2000
798b9477c4b0b8495021039105638641728d73fa
18,531
hpp
C++
include/pfs/io/unix_socket.hpp
semenovf/io-lib
6e008d0eac584194333f055c90d4810f0bbb74f6
[ "MIT" ]
null
null
null
include/pfs/io/unix_socket.hpp
semenovf/io-lib
6e008d0eac584194333f055c90d4810f0bbb74f6
[ "MIT" ]
null
null
null
include/pfs/io/unix_socket.hpp
semenovf/io-lib
6e008d0eac584194333f055c90d4810f0bbb74f6
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2019 Vladislav Trifochkin // // This file is part of [pfs-io](https://github.com/semenovf/pfs-io) library. // // Changelog: // 2019.10.16 Initial version //////////////////////////////////////////////////////////////////////////////// #pragma once #include "unix_file.hpp" #include <vector> #include <cassert> #include <cstring> #include <arpa/inet.h> #include <netdb.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/un.h> namespace pfs { namespace io { namespace unix_ns { struct host_address { union { sockaddr_in addr4; sockaddr_in6 addr6; } addr; host_address () { std::memset(& addr, 0, sizeof(addr)); } }; inline void swap (host_address & a, host_address & b) { host_address tmp; auto addlen = sizeof(tmp.addr); std::memcpy(& tmp.addr, & a.addr, addlen); std::memcpy(& a.addr, & b.addr, addlen); std::memcpy(& b.addr, & tmp.addr, addlen); } namespace socket { inline bool has_pending_data (device_handle * h) { char buf[1]; ssize_t n = recvfrom(h->fd, buf, 1, MSG_PEEK, nullptr, nullptr); return n > 0; } //////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////// inline ssize_t read (device_handle * h , char * bytes , size_t n , error_code & ec) noexcept { ssize_t rc = recv(h->fd, bytes, n, 0); if (rc < 0 && errno == EAGAIN || (EAGAIN != EWOULDBLOCK && errno == EWOULDBLOCK)) rc = 0; if (rc < 0) ec = get_last_system_error(); return rc; } //////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////// inline ssize_t write (device_handle * h , char const * bytes , size_t n , error_code & ec) noexcept { int total_written = 0; // total sent while (n) { // MSG_NOSIGNAL flag means: // requests not to send SIGPIPE on errors on stream oriented sockets // when the other end breaks the connection. // The EPIPE error is still returned. ssize_t written = send(h->fd, bytes + total_written, n, MSG_NOSIGNAL); if (written < 0) { if (errno == EAGAIN || (EAGAIN != EWOULDBLOCK && errno == EWOULDBLOCK)) continue; total_written = -1; break; } total_written += written; n -= written; } if (total_written < 0) ec = get_last_system_error(); return total_written; } //////////////////////////////////////////////////////////////////////////////// // Close socket //////////////////////////////////////////////////////////////////////////////// inline error_code close (device_handle * h, bool force_shutdown) { error_code ec; if (h->fd > 0) { if (force_shutdown) shutdown(h->fd, SHUT_RDWR); if (::close(h->fd) < 0) ec = get_last_system_error(); } h->fd = -1; return ec; } } // socket namespace local { using file::open_mode; using file::opened; using socket::close; using socket::read; using socket::write; using socket::has_pending_data; //////////////////////////////////////////////////////////////////////////////// // Open local socket //////////////////////////////////////////////////////////////////////////////// inline device_handle open (std::string const & name , bool nonblocking , error_code & ec) { sockaddr_un saddr; device_handle result; do { if (sizeof(saddr.sun_path) < name.size() + 1) { ec = make_error_code(errc::invalid_argument); break; } int socktype = SOCK_STREAM; if (nonblocking) socktype |= SOCK_NONBLOCK; int fd = ::socket(AF_LOCAL, socktype, 0); if (fd < 0) { ec = get_last_system_error(); break; } memset(& saddr, 0, sizeof(saddr)); saddr.sun_family = AF_LOCAL; memcpy(saddr.sun_path, name.c_str(), name.size()); saddr.sun_path[name.size()] = '\0'; int rc = ::connect(fd , reinterpret_cast<sockaddr *>(& saddr) , sizeof(saddr)); if (rc < 0) { ec = get_last_system_error(); break; } result.fd = fd; } while (false); if (ec && result.fd > 0) { ::close(result.fd); return device_handle{}; } return result; } //////////////////////////////////////////////////////////////////////////////// // Open local server //////////////////////////////////////////////////////////////////////////////// inline device_handle open_server (std::string const & name , bool nonblocking , int max_pending_connections , error_code & ec) { sockaddr_un saddr; int fd = -1; do { if (sizeof(saddr.sun_path) < name.size() + 1) { ec = make_error_code(errc::invalid_argument); break; } int socktype = SOCK_STREAM; if (nonblocking) socktype |= SOCK_NONBLOCK; fd = ::socket(AF_LOCAL, socktype, 0); if (fd < 0) { ec = get_last_system_error(); break; } memset(& saddr, 0, sizeof(saddr)); saddr.sun_family = AF_LOCAL; memcpy(saddr.sun_path, name.c_str(), name.size()); saddr.sun_path[name.size()] = '\0'; // TODO File deletion must be more reasonable int rc = unlink(saddr.sun_path); rc = ::bind(fd , reinterpret_cast<sockaddr *>(& saddr) , sizeof(saddr)); if (rc < 0) { ec = get_last_system_error(); break; } rc = listen(fd, max_pending_connections); if (rc < 0) { ec = get_last_system_error(); break; } } while (false); if (ec && fd > 0) { ::close(fd); fd = -1; } return fd < 0 ? device_handle{} : device_handle{fd}; } //////////////////////////////////////////////////////////////////////////////// // Accept local socket //////////////////////////////////////////////////////////////////////////////// inline device_handle accept (device_handle * h, error_code & ec) { sockaddr_un peer_addr; socklen_t peer_addr_len = sizeof(peer_addr); int peer_fd = ::accept(h->fd , reinterpret_cast<sockaddr *> (& peer_addr) , & peer_addr_len); if (peer_fd < 0) ec = get_last_system_error(); return peer_fd < 0 ? device_handle{} : device_handle{peer_fd}; } } // local //////////////////////////////////////////////////////////////////////////////// // Open inet socket //////////////////////////////////////////////////////////////////////////////// inline std::pair<native_handle,std::vector<uint8_t>> open_inet_socket ( std::string const & servername , uint16_t port , int base_socktype , bool nonblocking , error_code & ec) { native_handle fd = -1; std::vector<uint8_t> serveraddr; sockaddr_in serveraddr4; sockaddr_in6 serveraddr6; int socktype = base_socktype; if (nonblocking) socktype |= SOCK_NONBLOCK; addrinfo host_addrinfo; host_addrinfo.ai_family = AF_INET; host_addrinfo.ai_socktype = socktype; host_addrinfo.ai_protocol = 0; host_addrinfo.ai_addrlen = 0; host_addrinfo.ai_addr = nullptr; host_addrinfo.ai_canonname = nullptr; host_addrinfo.ai_next = nullptr; addrinfo * result_addr = nullptr; do { int rc = 0; memset(& serveraddr4, 0, sizeof(serveraddr4)); serveraddr4.sin_family = AF_INET; serveraddr4.sin_port = htons(port); rc = inet_pton(AF_INET, servername.c_str(), & serveraddr4.sin_addr.s_addr); // Success if (rc > 0) { host_addrinfo.ai_family = AF_INET; host_addrinfo.ai_addrlen = sizeof(serveraddr4); host_addrinfo.ai_addr = reinterpret_cast<sockaddr *>(& serveraddr4); result_addr = & host_addrinfo; } else { memset(& serveraddr6, 0, sizeof(serveraddr6)); serveraddr6.sin6_family = AF_INET6; serveraddr6.sin6_port = htons(port); rc = inet_pton(AF_INET6, servername.c_str(), & serveraddr6.sin6_addr.s6_addr); // Success if (rc > 0) { host_addrinfo.ai_family = AF_INET6; host_addrinfo.ai_addrlen = sizeof(serveraddr6); host_addrinfo.ai_addr = reinterpret_cast<sockaddr *>(& serveraddr6); result_addr = & host_addrinfo; } } // servername does not contain a character string representing a // valid network address in the specified address family. if (!result_addr) { addrinfo hints; memset(& hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_flags = AI_V4MAPPED; hints.ai_socktype = socktype; rc = getaddrinfo(servername.c_str(), nullptr, & hints, & result_addr); if (rc != 0) { ec = make_error_code(errc::host_not_found); break; } } if (result_addr) { for (addrinfo * p = result_addr; p != nullptr; p = result_addr->ai_next) { reinterpret_cast<sockaddr_in*>(p->ai_addr)->sin_port = htons(port); fd = ::socket(p->ai_family, p->ai_socktype, p->ai_protocol); if (fd < 0) { ec = get_last_system_error(); continue; } serveraddr = decltype(serveraddr)(reinterpret_cast<uint8_t *>(p->ai_addr) , reinterpret_cast<uint8_t *>(p->ai_addr) + p->ai_addrlen); break; } } if (fd < 0) break; if (ec) { ::close(fd); break; } } while (false); if (result_addr && result_addr != & host_addrinfo) { freeaddrinfo(result_addr); } return std::make_pair(fd, serveraddr); } namespace tcp { using file::open_mode; using file::opened; using socket::close; using socket::read; using socket::write; using socket::has_pending_data; //////////////////////////////////////////////////////////////////////////////// // Open TCP socket //////////////////////////////////////////////////////////////////////////////// inline device_handle open (std::string const & servername , uint16_t port , bool nonblocking , error_code & ec) { auto credentials = open_inet_socket(servername , port , SOCK_STREAM , nonblocking , ec); native_handle & fd = credentials.first; auto addr = reinterpret_cast<sockaddr const *>(credentials.second.data()); auto addrlen = static_cast<socklen_t>(credentials.second.size()); if (fd >= 0) { int rc = ::connect(fd, addr, addrlen); if (rc < 0) { ec = get_last_system_error(); ::close(fd); fd = -1; } } return fd < 0 ? device_handle{} : device_handle{fd}; } //////////////////////////////////////////////////////////////////////////////// // Open TCP server //////////////////////////////////////////////////////////////////////////////// inline device_handle open_server (std::string const & servername , uint16_t port , bool nonblocking , int max_pending_connections , error_code & ec) { auto credentials = open_inet_socket(servername , port , SOCK_STREAM , nonblocking , ec); native_handle & fd = credentials.first; auto addr = reinterpret_cast<sockaddr const *>(credentials.second.data()); auto addrlen = static_cast<socklen_t>(credentials.second.size()); if (fd >= 0) { // The setsockopt() function is used to allow the local // address to be reused when the server is restarted // before the required wait time expires. int on = 1; int rc = setsockopt(fd , SOL_SOCKET , SO_REUSEADDR , reinterpret_cast<char *>(& on) , sizeof(on)); if (rc == 0) { rc = ::bind(fd, addr, addrlen); if (rc == 0) { rc = ::listen(fd, max_pending_connections); } if (rc < 0) { ec = get_last_system_error(); ::close(fd); fd = -1; } } } return fd < 0 ? device_handle{} : device_handle{fd}; } //////////////////////////////////////////////////////////////////////////////// // Accept TCP socket //////////////////////////////////////////////////////////////////////////////// inline device_handle accept (device_handle * h, error_code & ec) { sockaddr_in peer_addr4; sockaddr_in6 peer_addr6; socklen_t peer_addr_len = std::max(sizeof(peer_addr4), sizeof(peer_addr6)); sockaddr * peer_addr = sizeof(peer_addr4) > sizeof(peer_addr6) ? reinterpret_cast<sockaddr *> (& peer_addr4) : reinterpret_cast<sockaddr *> (& peer_addr6); auto peer_fd = ::accept(h->fd, peer_addr, & peer_addr_len); if (peer_fd < 0) ec = get_last_system_error(); return peer_fd < 0 ? device_handle{} : device_handle{peer_fd}; } //////////////////////////////////////////////////////////////////////////////// // Enable keep alive //////////////////////////////////////////////////////////////////////////////// inline error_code enable_keep_alive (device_handle * h, bool enable) { int optval = enable ? 1 : 0; int rc = setsockopt(h->fd, SOL_SOCKET, SO_KEEPALIVE, & optval, sizeof(optval)); return rc < 0 ? get_last_system_error() : error_code{}; } } // tcp namespace udp { using file::open_mode; using file::opened; using socket::close; using socket::has_pending_data; //////////////////////////////////////////////////////////////////////////////// // Open UDP socket //////////////////////////////////////////////////////////////////////////////// inline device_handle open (std::string const & servername , uint16_t port , bool nonblocking , host_address * paddr , error_code & ec) { auto credentials = open_inet_socket(servername , port , SOCK_DGRAM , nonblocking , ec); native_handle & fd = credentials.first; auto addr = reinterpret_cast<sockaddr const *>(credentials.second.data()); socklen_t addrlen = static_cast<socklen_t>(credentials.second.size()); if (paddr) std::memcpy(& paddr->addr, addr , std::min(addrlen, static_cast<socklen_t>(sizeof(paddr->addr)))); return fd < 0 ? device_handle{} : device_handle{fd}; } //////////////////////////////////////////////////////////////////////////////// // Open UDP server //////////////////////////////////////////////////////////////////////////////// inline device_handle open_server (std::string const & servername , uint16_t port , bool nonblocking , error_code & ec) { auto credentials = open_inet_socket(servername , port , SOCK_DGRAM , nonblocking , ec); native_handle & fd = credentials.first; auto addr = reinterpret_cast<sockaddr const *>(credentials.second.data()); auto addrlen = static_cast<socklen_t>(credentials.second.size()); if (fd >= 0) { // The setsockopt() function is used to allow the local // address to be reused when the server is restarted // before the required wait time expires. int on = 1; int rc = setsockopt(fd , SOL_SOCKET , SO_REUSEADDR , reinterpret_cast<char *>(& on) , sizeof(on)); if (rc == 0) { rc = ::bind(fd, addr, addrlen); if (rc < 0) { ec = get_last_system_error(); ::close(fd); fd = -1; } } } return fd < 0 ? device_handle{} : device_handle{fd}; } //////////////////////////////////////////////////////////////////////////////// // Read from UDP socket //////////////////////////////////////////////////////////////////////////////// inline ssize_t read (device_handle * h , host_address * paddr , char * bytes , size_t n , error_code & ec) noexcept { socklen_t addrlen = 0; ssize_t rc = recvfrom(h->fd, bytes, n, 0 , reinterpret_cast<sockaddr *>(& paddr->addr), & addrlen); if (rc < 0 && errno == EAGAIN || (EAGAIN != EWOULDBLOCK && errno == EWOULDBLOCK)) rc = 0; if (rc < 0) ec = get_last_system_error(); return rc; } //////////////////////////////////////////////////////////////////////////////// // Write to UDP socket //////////////////////////////////////////////////////////////////////////////// inline ssize_t write (device_handle * h , host_address const * paddr , char const * bytes , size_t n , error_code & ec) noexcept { int total_written = 0; // total sent while (n) { // MSG_NOSIGNAL flag means: // requests not to send SIGPIPE on errors on stream oriented sockets // when the other end breaks the connection. // The EPIPE error is still returned. ssize_t written = sendto(h->fd , bytes + total_written , n , MSG_NOSIGNAL , reinterpret_cast<sockaddr const *>(& paddr->addr) , sizeof(paddr->addr)); if (written < 0) { if (errno == EAGAIN || (EAGAIN != EWOULDBLOCK && errno == EWOULDBLOCK)) continue; total_written = -1; break; } total_written += written; n -= written; } if (total_written < 0) ec = get_last_system_error(); return total_written; } } // udp }}} // pfs::io::unix_ns
28.034796
90
0.480114
semenovf
7998f624a2a44372107a1e2f6da492cdcc072ca5
29,661
cpp
C++
TestMac/cpp/network_service.cpp
tinyvpn/tvpn_mac
5bb67c8874a05561a05f87e5a9c3470471e5301b
[ "MIT" ]
null
null
null
TestMac/cpp/network_service.cpp
tinyvpn/tvpn_mac
5bb67c8874a05561a05f87e5a9c3470471e5301b
[ "MIT" ]
null
null
null
TestMac/cpp/network_service.cpp
tinyvpn/tvpn_mac
5bb67c8874a05561a05f87e5a9c3470471e5301b
[ "MIT" ]
null
null
null
#include "network_service.h" #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/ioctl.h> #include <arpa/inet.h> #include <memory.h> #include <time.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <fcntl.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/udp.h> #include <netinet/tcp.h> #include <netinet/ip_icmp.h> #include <arpa/inet.h> #include <netdb.h> #include <sys/kern_control.h> #include <sys/uio.h> #include <sys/sys_domain.h> #include <netinet/ip.h> #include <net/if_utun.h> //here defined _NET_IF_UTUN_H_ #include "log.h" #include "fileutl.h" #include "sockutl.h" #include "ssl_client2.h" #include "stringutl.h" #include "http_client.h" #include "sockhttp.h" #include "sysutl.h" #include "timeutl.h" #include "obfuscation_utl.h" const int BUF_SIZE = 4096*4; int g_protocol = kSslType; uint32_t g_private_ip; std::string global_private_ip; std::string global_default_gateway_ip; int g_fd_tun_dev; std::string target_test_ip; //="159.65.226.184"; uint16_t target_test_port; std::string web_server_ip = "www.tinyvpn.xyz"; static uint32_t in_traffic, out_traffic; static int g_isRun; static int client_sock; static int g_in_recv_tun; static int g_in_recv_socket; int premium = 2; std::string g_user_name;// = "[email protected]"; std::string g_password;// = "123456"; std::string g_device_id; static int firstOpen=0; //int current_traffic = 0 ; //bytes uint32_t g_day_traffic; uint32_t g_month_traffic; int popen_fill( char* data, int len, const char* cmd, ... ) { FILE* output; va_list vlist; char line[2048]; int line_len, line_count, total_len, id; if (!data || len <= 0 || !cmd) return -1; va_start(vlist, cmd); line_len = vsnprintf(line, 2048, cmd, vlist); if (line_len < 0) line_len = 0; va_end(vlist); line[line_len] = 0; line_count = id = total_len = 0; if ((output = popen(line, "r"))) { while (!feof(output) && fgets(line, sizeof(line)-1, output)){ line_len = (int)strlen(line); if (len - total_len - 1 < line_len){ break; } memcpy(data + total_len, line, line_len); total_len += line_len; line_count++; id++; } pclose(output); } data[total_len] = 0; return total_len; } int set_dns() { char ret_data[256]; INFO("networksetup -listnetworkserviceorder | grep '(1)' | awk '{print $2}'"); if (popen_fill(ret_data, sizeof(ret_data), "networksetup -listnetworkserviceorder | grep '(1)' | awk '{print $2}'") <= 0) { ERROR("networksetup cmd listnetworkserviceorder fail."); return 1; } for (int i=0;i<strlen(ret_data);i++) if (ret_data[i] == 0x0A) ret_data[i] = ' '; std::string str_cmd; str_cmd = std::string("networksetup -getdnsservers ") + ret_data; std::string str_network_card = ret_data; INFO("cmd: %s", str_cmd.c_str()); if (popen_fill(ret_data, sizeof(ret_data), str_cmd.c_str()) > 0) { for (int i=0;i<strlen(ret_data);i++) if (ret_data[i] == 0x0A) ret_data[i] = ' '; str_cmd = ret_data; //INFO("networksetup getdnsservers ok: %s", string_utl::HexEncode(std::string(ret_data, strlen(ret_data))).c_str()); INFO("networksetup getdnsservers ok: %s", ret_data); if (str_cmd.find("8.8.8.8") != std::string::npos) return 0; if (str_cmd.find("any") != std::string::npos) { str_cmd = std::string("networksetup -setdnsservers ") + str_network_card + " 8.8.8.8"; INFO("cmd: %s", str_cmd.c_str()); system(str_cmd.c_str()); return 0; } str_cmd = std::string("networksetup -setdnsservers ") + str_network_card + std::string("8.8.8.8 ") + str_cmd; INFO("cmd: %s", str_cmd.c_str()); system(str_cmd.c_str()); return 0; } str_cmd = std::string("networksetup -setdnsservers ") + str_network_card + " 8.8.8.8"; INFO("cmd: %s", str_cmd.c_str()); system(str_cmd.c_str()); return 0; } bool ifconfig(const char * ifname, const char * va, const char *pa) { char cmd[2048] = {0}; snprintf(cmd, sizeof(cmd), "ifconfig %s %s %s netmask 255.255.0.0 up",ifname, va, pa); INFO("ifconfig:%s\n", cmd); if (system(cmd) < 0) { ERROR("sys_utl::ifconfig,interface(%s) with param(%s) and params(%s) fail at error:%d\n",ifname,va,pa,errno); return false; } return true; } void exception_signal_handler(int nSignal) { INFO("capture exception signal: %d",nSignal); if(global_default_gateway_ip.size() > 0) { system("sudo route delete default"); std::string add_org_gateway_cmd("sudo route add default "); add_org_gateway_cmd += global_default_gateway_ip; system(add_org_gateway_cmd.c_str()); } } void quit_signal_handler(int nSignal) { INFO("capture quit signal: %d",nSignal); if(global_default_gateway_ip.size() > 0) { system("sudo route delete default"); std::string add_org_gateway_cmd("sudo route add default "); add_org_gateway_cmd += global_default_gateway_ip; system(add_org_gateway_cmd.c_str()); } exit(0); } void add_host_to_route(const std::string ip, const std::string device) { std::string routing_cmd("route add -host "); routing_cmd += ip.c_str(); routing_cmd += (" -interface "); routing_cmd += device; system(routing_cmd.c_str()); INFO("routing_cmd:%s", routing_cmd.c_str()); } void add_host_to_gateway(const std::string ip, const std::string gateway) { std::string routing_cmd("route add -host "); routing_cmd += ip.c_str(); routing_cmd += (" -gateway "); routing_cmd += gateway; system(routing_cmd.c_str()); INFO("routing_cmd:%s", routing_cmd.c_str()); } void delete_host_to_gateway(const std::string ip, const std::string gateway) { std::string routing_cmd("route delete -host "); routing_cmd += ip.c_str(); routing_cmd += (" -gateway "); routing_cmd += gateway; system(routing_cmd.c_str()); INFO("routing_cmd:%s", routing_cmd.c_str()); } void add_network_to_route(const std::string network, const std::string device) { std::string routing_cmd("route add -net "); routing_cmd += network.c_str(); routing_cmd += (" -interface "); routing_cmd += device; system(routing_cmd.c_str()); } void add_network_to_gateway(const std::string network,std::string net_mask,const std::string gateway) { std::string routing_cmd("route add -net "); routing_cmd += network.c_str(); routing_cmd += " netmask "; routing_cmd += net_mask.c_str(); routing_cmd += (" -gateway "); routing_cmd += gateway; system(routing_cmd.c_str()); } static char g_tcp_buf[BUF_SIZE*2]; static int g_tcp_len; int write_tun(char* ip_packet_data, int ip_packet_len){ int len; if (g_tcp_len != 0) { if (ip_packet_len + g_tcp_len > sizeof(g_tcp_buf)) { ERROR("relay size over %lu", sizeof(g_tcp_buf)); g_tcp_len = 0; return 1; } memcpy(g_tcp_buf + g_tcp_len, ip_packet_data, ip_packet_len); ip_packet_data = g_tcp_buf; ip_packet_len += g_tcp_len; g_tcp_len = 0; DEBUG2("relayed packet:%d", ip_packet_len); } while(1) { if (ip_packet_len == 0) break; // todo: recv from socket, send to utun1 if (ip_packet_len < sizeof(struct ip) ) { ERROR("less than ip header:%d.", ip_packet_len); memcpy(g_tcp_buf, ip_packet_data, ip_packet_len); g_tcp_len = ip_packet_len; break; } struct ip *iph = (struct ip *)ip_packet_data; len = ntohs(iph->ip_len); if (ip_packet_len < len) { if (len > BUF_SIZE) { ERROR("something error1.%x,%x,data:%s",len, ip_packet_len, string_utl::HexEncode(std::string(ip_packet_data,ip_packet_len)).c_str()); g_tcp_len = 0; } else { DEBUG2("relay to next packet:%d,current buff len:%d", ip_packet_len, g_tcp_len); if (g_tcp_len == 0) { memcpy(g_tcp_buf +g_tcp_len, ip_packet_data, ip_packet_len); g_tcp_len += ip_packet_len; } } break; } if (len > BUF_SIZE) { ERROR("something error.%x,%x",len, ip_packet_len); g_tcp_len = 0; break; } else if (len == 0) { ERROR("len is zero.%x,%x",len, ip_packet_len); //string_utl::HexEncode(std::string(ip_packet_data,ip_packet_len)).c_str()); g_tcp_len = 0; break; } char ip_src[INET_ADDRSTRLEN + 1]; char ip_dst[INET_ADDRSTRLEN + 1]; inet_ntop(AF_INET,&iph->ip_src.s_addr,ip_src, INET_ADDRSTRLEN); inet_ntop(AF_INET,&iph->ip_dst.s_addr,ip_dst, INET_ADDRSTRLEN); DEBUG2("send to utun, from(%s) to (%s) with size:%d",ip_src,ip_dst,len); if (sys_utl::tun_dev_write(g_fd_tun_dev, (void*)ip_packet_data, len) <= 0) { //if (::write(g_fd_tun_dev, (void*)ip_packet_data, len) <= 0) { ERROR("write tun error:%d", g_fd_tun_dev); return 1; } ip_packet_len -= len; ip_packet_data += len; } return 0; } int write_tun_http(char* ip_packet_data, int ip_packet_len) { static uint32_t g_iv = 0x87654321; int len; if (g_tcp_len != 0) { if (ip_packet_len + g_tcp_len > sizeof(g_tcp_buf)) { INFO("relay size over %d", sizeof(g_tcp_buf)); g_tcp_len = 0; return 1; } memcpy(g_tcp_buf + g_tcp_len, ip_packet_data, ip_packet_len); ip_packet_data = g_tcp_buf; ip_packet_len += g_tcp_len; g_tcp_len = 0; INFO("relayed packet:%d", ip_packet_len); } std::string http_packet; int http_head_length, http_body_length; while (1) { if (ip_packet_len == 0) break; http_packet.assign(ip_packet_data, ip_packet_len); if (sock_http::pop_front_xdpi_head(http_packet, http_head_length, http_body_length) != 0) { // decode http header fail DEBUG2("relay to next packet:%d,current buff len:%d", ip_packet_len, g_tcp_len); if (g_tcp_len == 0) { memcpy(g_tcp_buf + g_tcp_len, ip_packet_data, ip_packet_len); g_tcp_len += ip_packet_len; } break; } ip_packet_len -= http_head_length; ip_packet_data += http_head_length; obfuscation_utl::decode((unsigned char *) ip_packet_data, 4, g_iv); obfuscation_utl::decode((unsigned char *) ip_packet_data + 4, http_body_length - 4, g_iv); struct ip *iph = (struct ip *) ip_packet_data; len = ntohs(iph->ip_len); char ip_src[INET_ADDRSTRLEN + 1]; char ip_dst[INET_ADDRSTRLEN + 1]; inet_ntop(AF_INET, &iph->ip_src.s_addr, ip_src, INET_ADDRSTRLEN); inet_ntop(AF_INET, &iph->ip_dst.s_addr, ip_dst, INET_ADDRSTRLEN); DEBUG2("send to tun,http, from(%s) to (%s) with size:%d, header:%d,body:%d", ip_src, ip_dst, len, http_head_length, http_body_length); sys_utl::tun_dev_write(g_fd_tun_dev, (void *) ip_packet_data, len); ip_packet_len -= http_body_length; ip_packet_data += http_body_length; } return 0; } int network_service::tun_and_socket(void(*trafficCallback)(long, long,long,long,void*), void* target) { INFO("start ssl thread,g_fd_tun_dev:%d,client_sock:%d", g_fd_tun_dev, client_sock); g_isRun= 1; g_in_recv_tun = 1; g_tcp_len = 0; in_traffic = 0; out_traffic = 0; //std::thread tun_thread(client_recv_tun, client_sock); g_in_recv_socket = 1; int ip_packet_len; char ip_packet_data[BUF_SIZE]; int ret; time_t lastTime = time_utl::localtime(); time_t currentTime; time_t recvTime = time_utl::localtime(); time_t sendTime = time_utl::localtime(); fd_set fdsr; int maxfd; while(g_isRun == 1){ FD_ZERO(&fdsr); FD_SET(client_sock, &fdsr); FD_SET(g_fd_tun_dev, &fdsr); maxfd = std::max(client_sock, g_fd_tun_dev); struct timeval tv_select; tv_select.tv_sec = 2; tv_select.tv_usec = 0; int nReady = select(maxfd + 1, &fdsr, NULL, NULL, &tv_select); if (nReady < 0) { ERROR("select error:%d", nReady); break; } else if (nReady == 0) { INFO("select timeout"); continue; } if (FD_ISSET(g_fd_tun_dev, &fdsr)) { // recv from tun static VpnPacket vpn_packet(4096); int readed_from_tun; vpn_packet.reset(); readed_from_tun = sys_utl::tun_dev_read(g_fd_tun_dev, vpn_packet.data(), vpn_packet.remain_size()); vpn_packet.set_back_offset(vpn_packet.front_offset()+readed_from_tun); if(readed_from_tun < sizeof(struct ip)) { ERROR("tun_dev_read error, size:%d", readed_from_tun); break; } if(readed_from_tun > 0) { struct ip *iph = (struct ip *)vpn_packet.data(); char ip_src[INET_ADDRSTRLEN + 1]; char ip_dst[INET_ADDRSTRLEN + 1]; inet_ntop(AF_INET,&iph->ip_src.s_addr,ip_src, INET_ADDRSTRLEN); inet_ntop(AF_INET,&iph->ip_dst.s_addr,ip_dst, INET_ADDRSTRLEN); if(g_private_ip != iph->ip_src.s_addr) { ERROR("src_ip mismatch:%x,%x",g_private_ip, iph->ip_src.s_addr); continue; } DEBUG2("recv from tun, from(%s) to (%s) with size:%d",ip_src,ip_dst,readed_from_tun); //file_utl::write(sockid, vpn_packet.data(), readed_from_tun); out_traffic += readed_from_tun; if (g_protocol == kSslType) { if (ssl_write(vpn_packet.data(), readed_from_tun) != 0) { ERROR("ssl_write error"); break; } } else if (g_protocol == kHttpType){ http_write(vpn_packet); } sendTime = time_utl::localtime(); } // if (--nReady == 0) // read over // continue; } if (FD_ISSET(client_sock, &fdsr)) { // recv from socket ip_packet_len = 0; if (g_protocol == kSslType) { ret = ssl_read(ip_packet_data, ip_packet_len); if (ret != 0) { ERROR("ssl_read error"); break; } } else if (g_protocol == kHttpType) { ip_packet_len = file_utl::read(client_sock, ip_packet_data, BUF_SIZE); } else { ERROR("protocol error."); break; } if (ip_packet_len == 0) continue; in_traffic += ip_packet_len; DEBUG2("recv from socket, size:%d", ip_packet_len); if (g_protocol == kSslType) { if (write_tun((char *) ip_packet_data, ip_packet_len) != 0) { ERROR("write_tun error"); break; } } else if (g_protocol == kHttpType){ if (write_tun_http((char *) ip_packet_data, ip_packet_len) != 0) { ERROR("write_tun error"); break; } } recvTime = time_utl::localtime(); } currentTime = time_utl::localtime(); if (currentTime - recvTime > 60 || currentTime - sendTime > 60) { ERROR("send or recv timeout"); break; } if (currentTime - lastTime >= 1) { /*jclass thisClass = (env)->GetObjectClass(thisObj); jfieldID fidNumber = (env)->GetFieldID(thisClass, "current_traffic", "I"); if (NULL == fidNumber) { ERROR("current_traffic error"); return 1; } // Change the variable (env)->SetIntField(thisObj, fidNumber, in_traffic + out_traffic); INFO("current traffic:%d", in_traffic+out_traffic); jmethodID mtdCallBack = (env)->GetMethodID(thisClass, "trafficCallback", "()I"); if (NULL == mtdCallBack) { ERROR("trafficCallback error"); return 1; } ret = (env)->CallIntMethod(thisObj, mtdCallBack); */ trafficCallback(g_day_traffic + (in_traffic + out_traffic)/1024, g_month_traffic+ (in_traffic + out_traffic)/1024, 0,0, target); lastTime = time_utl::localtime(); } } INFO("main thread stop"); if(g_protocol == kSslType) ssl_close(); else if (g_protocol == kHttpType) close(client_sock); close(g_fd_tun_dev); g_isRun = 0; // callback to app /* jclass thisClass = (env)->GetObjectClass( thisObj); jmethodID midCallBackAverage = (env)->GetMethodID(thisClass, "stopCallback", "()I"); if (NULL == midCallBackAverage) return 1; ret = (env)->CallIntMethod(thisObj, midCallBackAverage); __android_log_print(ANDROID_LOG_DEBUG, "JNI", "stop callback:%d", ret);*/ return 0; } int network_service::init() { signal(SIGKILL, quit_signal_handler); signal(SIGINT, quit_signal_handler); OpenFile("/tmp/tvpn.log"); SetLogLevel(0); firstOpen = 1; system("route -n get default | grep 'gateway' | awk '{print $2}' > /tmp/default_gateway.txt"); file_utl::read_file("/tmp/default_gateway.txt", global_default_gateway_ip); if(global_default_gateway_ip.size() > 0) { //remove \n \r const int last_char = *global_default_gateway_ip.rbegin(); if( (last_char == '\n') || (last_char == '\r') ) global_default_gateway_ip.resize(global_default_gateway_ip.size()-1); } string_utl::set_random_http_domains(); sock_http::init_http_head(); return 0; } int network_service::get_vpnserver_ip(std::string user_name, std::string password, std::string device_id, long premium, std::string country_code, void(*trafficCallback)(long, long,long,long,void*), void* target){ struct hostent *h; if((h=gethostbyname(web_server_ip.c_str()))==NULL) { return 1; } std::string web_ip = inet_ntoa(*((struct in_addr *)h->h_addr)); INFO("web ip:%s", web_ip.c_str()); struct sockaddr_in serv_addr; int sock =socket(PF_INET, SOCK_STREAM, 0); if(sock == -1) { INFO("socket() error"); return 1; } memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family=AF_INET; serv_addr.sin_addr.s_addr=inet_addr(web_ip.c_str()); serv_addr.sin_port=htons(60315); if(connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr))==-1) { INFO("connect() error!"); return 1; } INFO("connect web server ok."); /* std::string::size_type found = country_code.find("\""); if (found == std::string::npos) return 1; std::string strCountry = country_code.substr(found+1); found = country_code.find("\""); if (found == std::string::npos) return 1; strCountry = strCountry.substr(0,found - 1); INFO("country code:%s",strCountry.c_str());*/ std::string strtemp; strtemp += (char)0; strtemp += (char)premium; strtemp += country_code; if (premium <= 1) strtemp += device_id; else strtemp += user_name; INFO("send:%s", string_utl::HexEncode(strtemp).c_str()); int ret=file_utl::write(sock, (char*)strtemp.c_str(), (int)strtemp.size()); char ip_packet_data[BUF_SIZE]; ret=file_utl::read(sock, ip_packet_data, BUF_SIZE); ip_packet_data[ret] = 0; INFO("recv from web_server:%s", string_utl::HexEncode(std::string(ip_packet_data,ret)).c_str()); //current_traffic = 0; int pos = 0; uint32_t day_traffic = ntohl(*(uint32_t*)(ip_packet_data + pos)); pos += sizeof(uint32_t); uint32_t month_traffic = ntohl(*(uint32_t*)(ip_packet_data + pos)); pos += sizeof(uint32_t); uint32_t day_limit = ntohl(*(uint32_t*)(ip_packet_data + pos)); pos += sizeof(uint32_t); uint32_t month_limit = ntohl(*(uint32_t*)(ip_packet_data + pos)); pos += sizeof(uint32_t); g_day_traffic = day_traffic; g_month_traffic = month_traffic; if (premium<=1){ if (day_traffic > day_limit) { trafficCallback(day_traffic,month_traffic,day_limit, month_limit, target); return 2; } } else{ if (month_traffic > month_limit) { trafficCallback(day_traffic,month_traffic,day_limit, month_limit, target); return 2; } } trafficCallback(day_traffic,month_traffic,day_limit, month_limit, target); std::string recv_ip(ip_packet_data + 16, ret-16); std::vector<std::string> recv_data; string_utl::split_string(recv_ip,',', recv_data); if(recv_data.size() < 1) { ERROR("recv server ip data error."); //tunnel.close(); return 1; } INFO("recv:%s", recv_data[0].c_str()); std::vector<std::string> server_data; string_utl::split_string(recv_data[0],':', server_data); if(server_data.size() < 3) { ERROR("parse server ip data error."); //tunnel.close(); return 1; } //Log.i(TAG, "data:" + server_data[0]+","+server_data[1]+","+server_data[2]); g_protocol = std::stoi(server_data[0]); target_test_ip = server_data[1]; //g_ip = "192.168.50.218"; target_test_port = std::stoi(server_data[2]); INFO("protocol:%d,%s,%d",g_protocol, target_test_ip.c_str(),target_test_port); return 0; } int network_service::start_vpn(std::string user_name, std::string password, std::string device_id, long premium, std::string country_code, void(*stopCallback)(long, void*), void(*trafficCallback)(long, long,long,long,void*), void* target) { if(firstOpen==0) { init(); } g_user_name = user_name; g_password = password; g_device_id = device_id; // get vpnserver ip int ret = get_vpnserver_ip(user_name, password, device_id, premium, country_code, trafficCallback, target); if ( ret == 1) { stopCallback(1, target); return 1; } else if (ret == 2) { stopCallback(1, target); return 2; } if (connect_server()!=0){ stopCallback(1, target); return 1; } std::string dev_name; g_fd_tun_dev = sys_utl::open_tun_device(dev_name, false); if (g_fd_tun_dev <= 0) { INFO("open_tun_device error"); stopCallback(1, target); return 1; } socket_utl::set_nonblock(g_fd_tun_dev,false); ifconfig(dev_name.c_str(),global_private_ip.c_str(),global_private_ip.c_str()); if(global_default_gateway_ip.size() <= 0){ stopCallback(1, target); INFO("global_default_gateway_ip empty."); return 1; } add_host_to_gateway(target_test_ip,global_default_gateway_ip); std::string add_default_gateway_cmd("sudo route add default "); add_default_gateway_cmd += global_private_ip; system(add_default_gateway_cmd.c_str()); INFO("add_default_gateway_cmd:%s", add_default_gateway_cmd.c_str()); std::string change_default_gateway_cmd("sudo route change default -interface "); change_default_gateway_cmd += dev_name; system(change_default_gateway_cmd.c_str()); INFO("change_default_gateway_cmd:%s", change_default_gateway_cmd.c_str()); std::string add_org_gateway_cmd("sudo route add default "); add_org_gateway_cmd += global_default_gateway_ip; system(add_org_gateway_cmd.c_str()); INFO("add_org_gateway_cmd:%s", add_org_gateway_cmd.c_str()); add_host_to_route(global_private_ip, dev_name); set_dns(); stopCallback(0, target); ret = tun_and_socket(trafficCallback, target); if (ret != 0) { stopCallback(1, target); return ret; } delete_host_to_gateway(target_test_ip,global_default_gateway_ip); system("sudo route delete default"); INFO("cmd: sudo route delete default"); add_org_gateway_cmd = "sudo route add default "; add_org_gateway_cmd += global_default_gateway_ip; system(add_org_gateway_cmd.c_str()); INFO("add_org_gateway_cmd:%s", add_org_gateway_cmd.c_str()); stopCallback(1, target); return 0; } int network_service::connect_server() { int sock =socket(PF_INET, SOCK_STREAM, 0); if(sock == -1) { INFO("socket() error"); return 1; } //std::string strIp = "159.65.226.184"; //uint16_t port = 14455; if (g_protocol == kSslType) { if (init_ssl_client() != 0) { ERROR( "init ssl fail."); return 1; } INFO("connect ssl"); connect_ssl(target_test_ip, target_test_port, sock); if (sock == 0) { ERROR("sock is zero."); return 1; } } else if (g_protocol == kHttpType) { if (connect_tcp(target_test_ip, target_test_port, sock) != 0) return 1; } else { ERROR( "protocol errror."); return 1; } client_sock = sock; INFO("connect ok."); std::string strPrivateIp; //INFO("get private_ip"); if (g_protocol == kSslType){ //std::string strId = "IOS.00000001"; //std::string strPassword = "123456"; get_private_ip(premium,g_device_id, g_user_name, g_password, strPrivateIp); } g_private_ip = *(uint32_t*)strPrivateIp.c_str(); global_private_ip = socket_utl::socketaddr_to_string(g_private_ip); printf("private_ip:%s", global_private_ip.c_str()); //g_private_ip = ntohl(g_private_ip); return 0; } int network_service::stop_vpn(long value) { g_isRun = 0; return 0; } int network_service::connect_web_server(std::string user_name, long premium, uint32_t* private_ip ) { return 0; } int network_service::login(std::string user_name, std::string password, std::string device_id, void(*trafficCallback)(long, long,long,long,long,long, void*), void* target) { if(firstOpen==0) { init(); } struct hostent *h; if((h=gethostbyname(web_server_ip.c_str()))==NULL) { return 1; } std::string web_ip = inet_ntoa(*((struct in_addr *)h->h_addr)); INFO("web ip:%s", web_ip.c_str()); struct sockaddr_in serv_addr; int sock =socket(PF_INET, SOCK_STREAM, 0); if(sock == -1) { INFO("socket() error"); return 1; } memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family=AF_INET; serv_addr.sin_addr.s_addr=inet_addr(web_ip.c_str()); serv_addr.sin_port=htons(60315); if(connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr))==-1) { INFO("connect() error!"); return 1; } INFO("connect web server ok."); /* std::string::size_type found = country_code.find("\""); if (found == std::string::npos) return 1; std::string strtemp = country_code.substr(found+1); found = country_code.find("\""); if (found == std::string::npos) return 1; strtemp = strtemp.substr(0,found - 1); INFO("country code:%s",strtemp.c_str());*/ std::string strtemp; strtemp += (char)1; strtemp += device_id; strtemp += (char)'\n'; strtemp += user_name; strtemp += (char)'\n'; strtemp += password; int ret=file_utl::write(sock, (char*)strtemp.c_str(), (int)strtemp.size()); char ip_packet_data[BUF_SIZE]; ret=file_utl::read(sock, ip_packet_data, BUF_SIZE); if (ret < 2 + 4*sizeof(uint32_t)) return 1; ip_packet_data[ret] = 0; INFO("recv from web_server:%s", string_utl::HexEncode(std::string(ip_packet_data,ret)).c_str()); int pos=0; int ret1 = ip_packet_data[pos++]; int ret2 = ip_packet_data[pos++]; uint32_t day_traffic = ntohl(*(uint32_t*)(ip_packet_data + pos)); pos += sizeof(uint32_t); uint32_t month_traffic = ntohl(*(uint32_t*)(ip_packet_data + pos)); pos += sizeof(uint32_t); uint32_t day_limit = ntohl(*(uint32_t*)(ip_packet_data + pos)); pos += sizeof(uint32_t); uint32_t month_limit = ntohl(*(uint32_t*)(ip_packet_data + pos)); close(sock); INFO("recv login:%d,%d,%x,%x,%x,%x" , ret1 , ret2, day_traffic , month_traffic, day_limit,month_limit); /* std::string ip_list; ip_list.assign(ip_packet_data, ret); std :: vector < std :: string > values; values.clear(); string_utl::split_string(ip_list, ',', values); if (values.empty()) { printf("get ip fail.\n"); return 1; } std::string one_ip = values[0]; values.clear(); string_utl::split_string(ip_list, ':', values); if (values.size() < 3) { printf("parse ip addr fail.\n"); return 1; } g_protocol = std::stoi(values[0]); target_test_ip = values[1]; // need to fix. target_test_port = std::stoi(values[2]); INFO("protocol:%d, server_ip:%s,port:%d", g_protocol, target_test_ip.c_str(), target_test_port); */ g_user_name = user_name; g_password = password; trafficCallback(day_traffic,month_traffic,day_limit,month_limit,ret1,ret2,target); return 0; }
34.73185
238
0.605677
tinyvpn
799affc25619cf70aca038f6e678b55d4664b2e7
1,194
cpp
C++
king/src/king/Utils/FileUtils.cpp
tobiasbu/king
7a6892a93d5d4c5f14e2618104f2955281f0bada
[ "MIT" ]
3
2017-03-10T13:57:25.000Z
2017-05-31T19:05:35.000Z
king/src/king/Utils/FileUtils.cpp
tobiasbu/king
7a6892a93d5d4c5f14e2618104f2955281f0bada
[ "MIT" ]
null
null
null
king/src/king/Utils/FileUtils.cpp
tobiasbu/king
7a6892a93d5d4c5f14e2618104f2955281f0bada
[ "MIT" ]
null
null
null
#include <king\Utils\FileUtils.hpp> namespace king { std::string FileUtils::getFileName(std::string path) { int i = path.find_last_of('\\'); if (i != std::string::npos) return path.substr(i + 1); // f contains the result :) else { i = path.find_last_of('/'); return path.substr(i + 1); } return path; }; std::string FileUtils::getFileNameWithoutExtension(std::string fname) { fname = getFileName(fname); size_t pos = fname.rfind((".")); if (pos == std::string::npos) //No extension. return fname; if (pos == 0) //. is at the front. Not an extension. return fname; return fname.substr(0, pos); } std::string FileUtils::getFileExtension(std::string fname) { size_t pos = fname.find_last_of("."); if (pos != std::string::npos) return fname.substr(pos + 1); return ""; } std::string FileUtils::getFileDirectory(std::string path) { std::string dir = path; bool found = false; for (int i = path.length() - 1; i >= 0; i--) { if (i == 0) { dir = ""; break; } else { if (path[i] == '\\' || path[i] == '/') { dir = path.substr(0, i + 1); break; } } } return dir; } }
16.135135
72
0.571189
tobiasbu
799b1829f213293f3f5ef9a602f1c5f05003bf8e
239
cpp
C++
model/variable.cpp
kalanzun/fire
5a7f6ca413efa2c64109d36be9db0ca050a076cd
[ "MIT" ]
null
null
null
model/variable.cpp
kalanzun/fire
5a7f6ca413efa2c64109d36be9db0ca050a076cd
[ "MIT" ]
null
null
null
model/variable.cpp
kalanzun/fire
5a7f6ca413efa2c64109d36be9db0ca050a076cd
[ "MIT" ]
null
null
null
#include "variable.h" Variable::Variable(QString label, int index, QObject *parent) : QObject(parent) , label(label) , index(index) { } QString Variable::getLabel() { return QString("<big><b>%1</b></big>").arg(label); }
15.933333
61
0.631799
kalanzun
799fae5dabdccb69e094ad56a358f312baf8dfe2
3,636
cpp
C++
active_3d_planning_core/src/module/trajectory_evaluator/next_selector/subsequent_best_complete.cpp
danielduberg/mav_active_3d_planning
0790e7d26175bf7d315975a4d91548b56f9ee877
[ "BSD-3-Clause" ]
1
2021-01-05T10:17:04.000Z
2021-01-05T10:17:04.000Z
active_3d_planning_core/src/module/trajectory_evaluator/next_selector/subsequent_best_complete.cpp
danielduberg/mav_active_3d_planning
0790e7d26175bf7d315975a4d91548b56f9ee877
[ "BSD-3-Clause" ]
null
null
null
active_3d_planning_core/src/module/trajectory_evaluator/next_selector/subsequent_best_complete.cpp
danielduberg/mav_active_3d_planning
0790e7d26175bf7d315975a4d91548b56f9ee877
[ "BSD-3-Clause" ]
null
null
null
#include "active_3d_planning_core/module/trajectory_evaluator/next_selector/subsequent_best_complete.h" #include <algorithm> #include <vector> namespace active_3d_planning { namespace next_selector { // SubsequentBestComplete ModuleFactoryRegistry::Registration<SubsequentBestComplete> SubsequentBestComplete::registration("SubsequentBestComplete"); SubsequentBestComplete::SubsequentBestComplete(PlannerI &planner) : NextSelector(planner) {} void SubsequentBestComplete::setupFromParamMap(Module::ParamMap *param_map) {} // This is super hacky because for some reason it returns an int and not a // trajsegment* (which would allow us to select w/e a lot easier) int SubsequentBestComplete::selectNextBest(TrajectorySegment *traj_in) { std::vector<int> candidates = {0}; std::vector<TrajectorySegment *> bestSegment = {traj_in->children[0].get()}; double current_max = evaluateSingle(traj_in->children[0].get()).value; for (int i = 1; i < traj_in->children.size(); ++i) { auto current_value = evaluateSingle(traj_in->children[i].get()); if (current_value.value > current_max) { current_max = current_value.value; candidates.clear(); candidates.push_back(i); bestSegment.clear(); bestSegment.push_back(current_value.traj); } else if (current_value.value == current_max) { candidates.push_back(i); bestSegment.push_back(current_value.traj); } } // randomize if multiple maxima (note this is not perfectly uniform, but shoud // do for now) int selected = rand() % candidates.size(); // here we expand the cadidated to include all parts up to the root and update // the tree accordingly //we do break info here... (TODO require info to overload operator + and fix this) std::vector<TrajectorySegment *> allsegs; auto tmptraj = bestSegment[selected]; //parent->parent because we dont want the base segment to be inserted aswell as this get choosen anyways while (tmptraj->parent->parent) { allsegs.insert(allsegs.begin(), tmptraj); tmptraj = tmptraj->parent; } //add data auto nextraj = traj_in->children[candidates[selected]].get(); for (auto seg : allsegs) { auto currtime = nextraj->trajectory.back().time_from_start_ns; for (auto &&trajPoint : seg->trajectory) { trajPoint.time_from_start_ns += currtime; nextraj->trajectory.push_back(trajPoint); } } //adjust children (this will kill alot I think but is fine) nextraj->children = std::move(bestSegment[selected]->children); return candidates[selected]; } ValueTrajectoryPair SubsequentBestComplete::evaluateSingle(TrajectorySegment *traj_in) { // Recursively find highest value ValueTrajectoryPair res; res.value = traj_in->value; res.traj = traj_in; for (int i = 0; i < traj_in->children.size(); ++i) { res = std::max(res, evaluateSingle(traj_in->children[i].get())); } return res; } } // namespace next_selector } // namespace active_3d_planning
45.45
116
0.59516
danielduberg
79a2c818f616bfa0ca48bae2e45f77a8c0fe8d76
1,470
cpp
C++
CPP.Part_2/week_3/algorithms/count_permutations.cpp
DGolgovsky/Courses
01e2dedc06f677bcdb1cbfd02ccc08a89cc932a0
[ "Unlicense" ]
4
2017-11-17T12:02:21.000Z
2021-02-08T11:24:16.000Z
CPP.Part_2/week_3/algorithms/count_permutations.cpp
DGolgovsky/Courses
01e2dedc06f677bcdb1cbfd02ccc08a89cc932a0
[ "Unlicense" ]
null
null
null
CPP.Part_2/week_3/algorithms/count_permutations.cpp
DGolgovsky/Courses
01e2dedc06f677bcdb1cbfd02ccc08a89cc932a0
[ "Unlicense" ]
null
null
null
#include <deque> #include <array> #include <iostream> #include <algorithm> /* template<class Iterator> size_t count_permutations(Iterator p1, Iterator q1) { if (p1 == q1) return 1; auto p = *reinterpret_cast<Iterator*>(&p1); auto q = *reinterpret_cast<Iterator*>(&q1); size_t count = 0; std::sort(p, q); do { auto i1 = std::adjacent_find(p, q); if (i1 == q) count++; } while (std::next_permutation(p, q)); return count; } */ /* Better solution */ template <typename Iterator> std::size_t count_permutations(Iterator p, Iterator q) { using ItType = typename std::iterator_traits<Iterator>::value_type; if (p == q) { return 1; } std::vector<ItType> v(p, q); std::sort(v.begin(), v.end()); std::size_t perm_count = (std::adjacent_find(v.cbegin(), v.cend()) == v.cend()); while (std::next_permutation(v.begin(), v.end())) { if (std::adjacent_find(v.cbegin(), v.cend()) == v.cend()) { ++perm_count; } } return perm_count; } int main() { std::array<int, 3> a1 = {3,2,1}; size_t c1 = count_permutations(a1.begin(), a1.end()); // 6 std::cout << c1 << '\n'; std::array<int, 5> a2 = {1,2,3,4,4}; size_t c2 = count_permutations(a2.begin(), a2.end()); // 36 std::cout << c2 << '\n'; std::deque<int> a3 = {1,2,2,3,4,4}; size_t c3 = count_permutations(a3.begin(), a3.end()); // 36 std::cout << c3 << '\n'; }
24.5
84
0.565306
DGolgovsky
79a9ff1cce485f56e1fbebcfe5df11990b15dfd1
11,661
hh
C++
include/click/flow/level/flow_level.hh
MassimoGirondi/fastclick
71b9a3392c2e847a22de3c354be1d9f61216cb5b
[ "BSD-3-Clause-Clear" ]
129
2015-10-08T14:38:35.000Z
2022-03-06T14:54:44.000Z
include/click/flow/level/flow_level.hh
nic-bench/fastclick
2812f0684050cec07e08f30d643ed121871cf25d
[ "BSD-3-Clause-Clear" ]
241
2016-02-17T16:17:58.000Z
2022-03-15T09:08:33.000Z
include/click/flow/level/flow_level.hh
nic-bench/fastclick
2812f0684050cec07e08f30d643ed121871cf25d
[ "BSD-3-Clause-Clear" ]
61
2015-12-17T01:46:58.000Z
2022-02-07T22:25:19.000Z
#ifndef CLICK_FLOWLEVEL_HH #define CLICK_FLOWLEVEL_HH 1 #include <click/packet.hh> #if HAVE_DPDK #include <rte_flow.h> #endif #include "../common.hh" #define FLOW_LEVEL_DEFINE(T,fnt) \ static FlowNodeData get_data_ptr(void* thunk, Packet* p) {\ return static_cast<T*>(thunk)->fnt(p);\ } class FlowNode; class FlowNodePtr { private: bool _is_leaf; public : union { FlowNode* node; FlowControlBlock* leaf; void* ptr; }; FlowNodePtr() : _is_leaf(false), ptr(0) { } FlowNodePtr(FlowNode* n) : _is_leaf(false), node(n) { } FlowNodePtr(FlowControlBlock* sfcb) : _is_leaf(true), leaf(sfcb) { } inline FlowNodeData data(); inline FlowNode* parent() const; inline void set_data(FlowNodeData data); inline void set_parent(FlowNode* parent); inline void set_leaf(FlowControlBlock* l) { leaf = l; _is_leaf = true; } inline void set_node(FlowNode* n) { node = n; _is_leaf = false; } inline bool is_leaf() const { return _is_leaf; } inline bool is_node() const { return !_is_leaf; } /* inline FlowNodePtr duplicate() { FlowNodePtr v; v.ptr = ptr; v._is_leaf = _is_leaf; v.set_data(data()); return v; } */ void print(int data_offset = -1) const; //--- //Compile time functions //--- FlowNodePtr optimize(Bitvector threads); bool else_drop(); inline void traverse_all_leaves(std::function<void(FlowNodePtr*)>); inline void check(); bool replace_leaf_with_node(FlowNode*, bool discard, Element* origin); void node_combine_ptr(FlowNode* parent, FlowNodePtr, bool as_child, bool priority, bool no_dynamic, Element* origin); void default_combine(FlowNode* parent, FlowNodePtr*, bool as_child, bool priority, Element* origin); }; class FlowLevel { private: //bool deletable; protected: bool _dynamic; #if HAVE_LONG_CLASSIFICATION bool _islong = false; #endif public: FlowLevel() : //deletable(true), _dynamic(false) { }; typedef FlowNodeData (*GetDataFn)(void*, Packet* packet); GetDataFn _get_data; virtual ~FlowLevel() {}; /** * Maximum value this level can return, included. * Eg 255 for an array of 256 values. In most cases this is actually * equal to the mask. */ virtual long unsigned get_max_value() = 0; virtual void add_offset(int offset) {}; virtual bool is_mt_safe() const { return false;}; virtual bool is_usefull() { return true; } /** * Prune this level with another level, that is we know that this level * is a sub-path of the other one, and there is no need to classify on * the given level * @return true if something changed */ virtual bool prune(FlowLevel*) {return false;}; virtual FlowNodePtr prune(FlowLevel* other, FlowNodeData data, FlowNode* node, bool &changed); /** * Tell if two node are of the same type, and on the same field/value/mask if applicable * * However this is not checking if runtime data and dynamic are equals */ virtual bool equals(FlowLevel* level) { return typeid(*this) == typeid(*level) && #if HAVE_LONG_CLASSIFICATION _islong == level->_islong && #endif _dynamic == level->_dynamic; } inline FlowNodeData get_data(Packet* p) { flow_assert(_get_data); flow_assert(this); return _get_data(this,p); } int current_level = 0; FlowNode* create_node(FlowNode* parent, bool better, bool better_impl); bool is_dynamic() { return _dynamic; } void set_dynamic() { _dynamic = true; } /*bool is_deletable() { return deletable; }*/ virtual String print() = 0; #if HAVE_LONG_CLASSIFICATION inline bool is_long() const { return _islong; } #else inline bool is_long() const { return false; } #endif FlowLevel* assign(FlowLevel* l) { _dynamic = l->_dynamic; //deletable = l->deletable; #if HAVE_LONG_CLASSIFICATION _islong = l->_islong; #endif return this; } virtual FlowLevel *duplicate() = 0; virtual FlowLevel *optimize(FlowNode*) { return this; } #if HAVE_DPDK virtual int to_dpdk_flow(FlowNodeData data, rte_flow_item_type last_layer, int offset, rte_flow_item_type &next_layer, int &next_layer_offset, Vector<rte_flow_item> &pattern, bool is_default) { return -1; } #endif }; /** * Dummy FlowLevel used for the default path before merging a table */ class FlowLevelDummy : public FlowLevel { public: FlowLevelDummy() { _get_data = &get_data_ptr; } FLOW_LEVEL_DEFINE(FlowLevelDummy,get_data_dummy); inline long unsigned get_max_value() { return 0; } inline FlowNodeData get_data_dummy(Packet* packet) { /* click_chatter("FlowLevelDummy should be stripped !"); abort();*/ return FlowNodeData(); } String print() { return String("ANY"); } FlowLevel* duplicate() override { return (new FlowLevelDummy())->assign(this); } #if HAVE_DPDK virtual int to_dpdk_flow(FlowNodeData data, rte_flow_item_type last_layer, int offset, rte_flow_item_type &next_layer, int &next_layer_offset, Vector<rte_flow_item> &pattern, bool is_default) override { rte_flow_item pat; pat.type = RTE_FLOW_ITEM_TYPE_VOID; next_layer = last_layer; next_layer_offset = offset; pattern.push_back(pat); return 1; } #endif }; /** * FlowLevel based on the aggregate */ class FlowLevelAggregate : public FlowLevel { public: FlowLevelAggregate(int offset, uint32_t mask) : offset(offset), mask(mask) { _get_data = &get_data_ptr; } FlowLevelAggregate() : FlowLevelAggregate(0,-1) { _get_data = &get_data_ptr; } FLOW_LEVEL_DEFINE(FlowLevelAggregate,get_data_agg); int offset; uint32_t mask; inline long unsigned get_max_value() { return mask; } inline FlowNodeData get_data_agg(Packet* packet) { FlowNodeData data; data.data_32 = (AGGREGATE_ANNO(packet) >> offset) & mask; return data; } String print() { return String("AGG"); } FlowLevel* duplicate() override { return (new FlowLevelAggregate(0,-1))->assign(this); } }; /** * FlowLevel based on the current thread */ class FlowLevelThread : public FlowLevel { int _numthreads; public: FlowLevelThread(int nthreads) : _numthreads(nthreads) { _get_data = &get_data_ptr; } FLOW_LEVEL_DEFINE(FlowLevelThread,get_data_thread); virtual bool is_mt_safe() const override { return true;}; inline long unsigned get_max_value() { return _numthreads - 1; } inline FlowNodeData get_data_thread(Packet*) { return FlowNodeData((uint32_t)click_current_cpu_id()); } String print() { return String("THREAD"); } FlowLevel* duplicate() override { return (new FlowLevelThread(_numthreads))->assign(this); } }; class FlowLevelOffset : public FlowLevel { protected: int _offset; public: FlowLevelOffset(int offset) : _offset(offset) { } FlowLevelOffset() : FlowLevelOffset(0) { } void add_offset(int offset) { _offset += offset; } int offset() const { return _offset; } virtual int mask_size() const = 0; virtual uint8_t get_mask(int o) const = 0; bool equals(FlowLevel* level) { return ((FlowLevel::equals(level))&& (_offset == dynamic_cast<FlowLevelOffset*>(level)->_offset)); } #if HAVE_DPDK virtual int to_dpdk_flow(FlowNodeData data, rte_flow_item_type last_layer, int offset, rte_flow_item_type &next_layer, int &next_layer_offset, Vector<rte_flow_item> &pattern, bool is_default) override; #endif }; static const char hex[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','F'}; /** * Flow level for any offset/mask of T bits */ template <typename T> class FlowLevelGeneric : public FlowLevelOffset { private: T _mask; public: FlowLevelGeneric(T mask, int offset) : _mask(mask), FlowLevelOffset(offset) { _get_data = &get_data_ptr; } FLOW_LEVEL_DEFINE(FlowLevelGeneric<T>,get_data); FlowLevelGeneric() : FlowLevelGeneric(0,0) { } void set_match(int offset, T mask) { _mask = mask; _offset = offset; } T mask() const { return _mask; } virtual int mask_size() const { return sizeof(T); } virtual uint8_t get_mask(int o) const override { if (o < _offset) //2 < 0 return 0; if (o >= _offset + mask_size()) return 0; return ((uint8_t*)&_mask)[o-_offset]; } virtual bool is_usefull() override { return _mask != 0; } //Remove from the mask what is already set in other virtual bool prune(FlowLevel* other) override; /** * Remove children that don't match data at offset overlaps */ virtual FlowNodePtr prune(FlowLevel* other, FlowNodeData data, FlowNode* node, bool &changed) override; inline long unsigned get_max_value() { return _mask; } inline FlowNodeData get_data(Packet* packet) { return FlowNodeData((T)(*((T*)(packet->data() + _offset)) & _mask)); } String print(); FlowLevel* duplicate() override { return (new FlowLevelGeneric<T>(_mask,_offset))->assign(this); } bool equals(FlowLevel* level) { return ((FlowLevelOffset::equals(level)) && (_mask == dynamic_cast<FlowLevelGeneric<T>*>(level)->_mask)); } virtual FlowLevel *optimize(FlowNode* parent) override; }; /** * Flow level for any offset/mask of T bits */ template <typename T> class FlowLevelField : public FlowLevelOffset { public: FlowLevelField(int offset) : FlowLevelOffset(offset) { _get_data = &get_data_ptr; } FLOW_LEVEL_DEFINE(FlowLevelField<T>,get_data); FlowLevelField() : FlowLevelField(0) { } T mask() const { return (T)-1; } virtual uint8_t get_mask(int o) const { if (o < _offset) return 0; if (o >= _offset + mask_size()) return 0; return 0xff; } virtual int mask_size() const { return sizeof(T); } inline long unsigned get_max_value() { return mask(); } inline FlowNodeData get_data(Packet* packet) { //click_chatter("FlowLevelField %d %x, sz %d",_offset,*(T*)(packet->data() + _offset),sizeof(T)); return FlowNodeData(*(T*)(packet->data() + _offset)); } String print() { StringAccum s; s << _offset; s << "/"; for (int i = 0; i < sizeof(T); i++) { s << "FF"; } return s.take_string(); } FlowLevel* duplicate() override { return (new FlowLevelField<T>(_offset))->assign(this); } }; using FlowLevelGeneric8 = FlowLevelGeneric<uint8_t>; using FlowLevelGeneric16 = FlowLevelGeneric<uint16_t>; using FlowLevelGeneric32 = FlowLevelGeneric<uint32_t>; #if HAVE_LONG_CLASSIFICATION using FlowLevelGeneric64 = FlowLevelGeneric<uint64_t>; #endif using FlowLevelField8 = FlowLevelField<uint8_t>; using FlowLevelField16 = FlowLevelField<uint16_t>; using FlowLevelField32 = FlowLevelField<uint32_t>; #if HAVE_LONG_CLASSIFICATION using FlowLevelField64 = FlowLevelField<uint64_t>; #endif #endif
23.462777
206
0.632364
MassimoGirondi
79ab026f56ed8d11e90f8f9e5beb32fb37518e9b
220
cpp
C++
Tests/test2Flow.cpp
ZakosDryiakk/SystemsModel
20906b4a32405fa7e6a90321a977142e471fc04f
[ "MIT" ]
null
null
null
Tests/test2Flow.cpp
ZakosDryiakk/SystemsModel
20906b4a32405fa7e6a90321a977142e471fc04f
[ "MIT" ]
3
2019-09-04T17:16:28.000Z
2019-09-04T17:18:23.000Z
Tests/test2Flow.cpp
ZakosDryiakk/SystemsModel
20906b4a32405fa7e6a90321a977142e471fc04f
[ "MIT" ]
null
null
null
#include "test2Flow.h" using namespace std; LogFlow::LogFlow() {} LogFlow::LogFlow(string name):Flow(name) {} LogFlow::~LogFlow() {} void LogFlow::execute() { change = 0.01*s2->getEnergy()*(1-s2->getEnergy()/70); }
15.714286
54
0.663636
ZakosDryiakk
79ac28ac1a8fe33b6f9f66a2726c9f49604b030b
33,869
cpp
C++
src/org/apache/poi/ss/format/CellNumberFormatter.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/ss/format/CellNumberFormatter.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/ss/format/CellNumberFormatter.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/ss/format/CellNumberFormatter.java #include <org/apache/poi/ss/format/CellNumberFormatter.hpp> #include <java/lang/Appendable.hpp> #include <java/lang/ArrayStoreException.hpp> #include <java/lang/CharSequence.hpp> #include <java/lang/Character.hpp> #include <java/lang/Class.hpp> #include <java/lang/ClassCastException.hpp> #include <java/lang/Double.hpp> #include <java/lang/IllegalStateException.hpp> #include <java/lang/Integer.hpp> #include <java/lang/Iterable.hpp> #include <java/lang/Math.hpp> #include <java/lang/NullPointerException.hpp> #include <java/lang/Number.hpp> #include <java/lang/Object.hpp> #include <java/lang/RuntimeException.hpp> #include <java/lang/String.hpp> #include <java/lang/StringBuffer.hpp> #include <java/lang/StringBuilder.hpp> #include <java/text/DecimalFormat.hpp> #include <java/text/DecimalFormatSymbols.hpp> #include <java/text/FieldPosition.hpp> #include <java/util/ArrayList.hpp> #include <java/util/BitSet.hpp> #include <java/util/Collection.hpp> #include <java/util/Collections.hpp> #include <java/util/Formatter.hpp> #include <java/util/Iterator.hpp> #include <java/util/List.hpp> #include <java/util/ListIterator.hpp> #include <java/util/Set.hpp> #include <java/util/TreeSet.hpp> #include <org/apache/poi/ss/format/CellFormatPart.hpp> #include <org/apache/poi/ss/format/CellFormatType.hpp> #include <org/apache/poi/ss/format/CellFormatter.hpp> #include <org/apache/poi/ss/format/CellNumberFormatter_GeneralNumberFormatter.hpp> #include <org/apache/poi/ss/format/CellNumberFormatter_Special.hpp> #include <org/apache/poi/ss/format/CellNumberPartHandler.hpp> #include <org/apache/poi/ss/format/CellNumberStringMod.hpp> #include <org/apache/poi/ss/format/SimpleFraction.hpp> #include <org/apache/poi/util/LocaleUtil.hpp> #include <org/apache/poi/util/POILogFactory.hpp> #include <org/apache/poi/util/POILogger.hpp> #include <Array.hpp> #include <SubArray.hpp> #include <ObjectArray.hpp> #include <cmath> template<typename ComponentType, typename... Bases> struct SubArray; namespace java { namespace lang { typedef ::SubArray< ::java::lang::Iterable, ObjectArray > IterableArray; } // lang namespace util { typedef ::SubArray< ::java::util::Collection, ::java::lang::ObjectArray, ::java::lang::IterableArray > CollectionArray; typedef ::SubArray< ::java::util::List, ::java::lang::ObjectArray, CollectionArray > ListArray; } // util } // java template<typename T, typename U> static T java_cast(U* u) { if(!u) return static_cast<T>(nullptr); auto t = dynamic_cast<T>(u); if(!t) throw new ::java::lang::ClassCastException(); return t; } template<typename T> static T* npc(T* t) { if(!t) throw new ::java::lang::NullPointerException(); return t; } namespace { template<typename F> struct finally_ { finally_(F f) : f(f), moved(false) { } finally_(finally_ &&x) : f(x.f), moved(false) { x.moved = true; } ~finally_() { if(!moved) f(); } private: finally_(const finally_&); finally_& operator=(const finally_&); F f; bool moved; }; template<typename F> finally_<F> finally(F f) { return finally_<F>(f); } } poi::ss::format::CellNumberFormatter::CellNumberFormatter(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } poi::ss::format::CellNumberFormatter::CellNumberFormatter(::java::lang::String* format) : CellNumberFormatter(*static_cast< ::default_init_tag* >(0)) { ctor(format); } poi::ss::format::CellNumberFormatter::CellNumberFormatter(::java::util::Locale* locale, ::java::lang::String* format) : CellNumberFormatter(*static_cast< ::default_init_tag* >(0)) { ctor(locale,format); } void poi::ss::format::CellNumberFormatter::init() { specials = new ::java::util::ArrayList(); integerSpecials = new ::java::util::ArrayList(); fractionalSpecials = new ::java::util::ArrayList(); numeratorSpecials = new ::java::util::ArrayList(); denominatorSpecials = new ::java::util::ArrayList(); exponentSpecials = new ::java::util::ArrayList(); exponentDigitSpecials = new ::java::util::ArrayList(); SIMPLE_NUMBER = new CellNumberFormatter_GeneralNumberFormatter(locale); } poi::util::POILogger*& poi::ss::format::CellNumberFormatter::LOG() { clinit(); return LOG_; } poi::util::POILogger* poi::ss::format::CellNumberFormatter::LOG_; void poi::ss::format::CellNumberFormatter::ctor(::java::lang::String* format) { ctor(::poi::util::LocaleUtil::getUserLocale(), format); } void poi::ss::format::CellNumberFormatter::ctor(::java::util::Locale* locale, ::java::lang::String* format) { super::ctor(locale, format); init(); auto ph = new CellNumberPartHandler(); auto descBuf = CellFormatPart::parseFormat(format, CellFormatType::NUMBER, ph); exponent = npc(ph)->getExponent(); npc(specials)->addAll(static_cast< ::java::util::Collection* >(npc(ph)->getSpecials())); improperFraction = npc(ph)->isImproperFraction(); if((npc(ph)->getDecimalPoint() != nullptr || npc(ph)->getExponent() != nullptr) && npc(ph)->getSlash() != nullptr) { slash = nullptr; numerator = nullptr; } else { slash = npc(ph)->getSlash(); numerator = npc(ph)->getNumerator(); } auto const precision = interpretPrecision(npc(ph)->getDecimalPoint(), specials); auto fractionPartWidth = int32_t(0); if(npc(ph)->getDecimalPoint() != nullptr) { fractionPartWidth = int32_t(1) + precision; if(precision == 0) { npc(specials)->remove(static_cast< ::java::lang::Object* >(npc(ph)->getDecimalPoint())); decimalPoint = nullptr; } else { decimalPoint = npc(ph)->getDecimalPoint(); } } else { decimalPoint = nullptr; } if(decimalPoint != nullptr) { afterInteger = decimalPoint; } else if(exponent != nullptr) { afterInteger = exponent; } else if(numerator != nullptr) { afterInteger = numerator; } else { afterInteger = nullptr; } if(exponent != nullptr) { afterFractional = exponent; } else if(numerator != nullptr) { afterFractional = numerator; } else { afterFractional = nullptr; } auto scaleByRef = (new ::doubleArray({npc(ph)->getScale()})); showGroupingSeparator = interpretIntegerCommas(descBuf, specials, decimalPoint, integerEnd(), fractionalEnd(), scaleByRef); if(exponent == nullptr) { scale = (*scaleByRef)[int32_t(0)]; } else { scale = 1; } if(precision != 0) { npc(fractionalSpecials)->addAll(static_cast< ::java::util::Collection* >(npc(specials)->subList(npc(specials)->indexOf(decimalPoint) + int32_t(1), fractionalEnd()))); } if(exponent != nullptr) { auto exponentPos = npc(specials)->indexOf(exponent); npc(exponentSpecials)->addAll(static_cast< ::java::util::Collection* >(specialsFor(exponentPos, 2))); npc(exponentDigitSpecials)->addAll(static_cast< ::java::util::Collection* >(specialsFor(exponentPos + int32_t(2)))); } if(slash != nullptr) { if(numerator != nullptr) { npc(numeratorSpecials)->addAll(static_cast< ::java::util::Collection* >(specialsFor(npc(specials)->indexOf(numerator)))); } npc(denominatorSpecials)->addAll(static_cast< ::java::util::Collection* >(specialsFor(npc(specials)->indexOf(slash) + int32_t(1)))); if(npc(denominatorSpecials)->isEmpty()) { npc(numeratorSpecials)->clear(); maxDenominator = 1; numeratorFmt = nullptr; denominatorFmt = nullptr; } else { maxDenominator = maxValue(denominatorSpecials); numeratorFmt = singleNumberFormat(numeratorSpecials); denominatorFmt = singleNumberFormat(denominatorSpecials); } } else { maxDenominator = 1; numeratorFmt = nullptr; denominatorFmt = nullptr; } npc(integerSpecials)->addAll(static_cast< ::java::util::Collection* >(npc(specials)->subList(0, integerEnd()))); if(exponent == nullptr) { auto fmtBuf = new ::java::lang::StringBuffer(u"%"_j); auto integerPartWidth = calculateIntegerPartWidth(); auto totalWidth = integerPartWidth + fractionPartWidth; npc(npc(npc(npc(fmtBuf)->append(u'0'))->append(totalWidth))->append(u'.'))->append(precision); npc(fmtBuf)->append(u"f"_j); printfFmt = npc(fmtBuf)->toString(); decimalFmt = nullptr; } else { auto fmtBuf = new ::java::lang::StringBuffer(); auto first = true; auto specialList = integerSpecials; if(npc(integerSpecials)->size() == 1) { npc(fmtBuf)->append(u"0"_j); first = false; } else for (auto _i = npc(specialList)->iterator(); _i->hasNext(); ) { CellNumberFormatter_Special* s = java_cast< CellNumberFormatter_Special* >(_i->next()); { if(isDigitFmt(s)) { npc(fmtBuf)->append(first ? u'#' : u'0'); first = false; } } } if(npc(fractionalSpecials)->size() > 0) { npc(fmtBuf)->append(u'.'); for (auto _i = npc(fractionalSpecials)->iterator(); _i->hasNext(); ) { CellNumberFormatter_Special* s = java_cast< CellNumberFormatter_Special* >(_i->next()); { if(isDigitFmt(s)) { if(!first) npc(fmtBuf)->append(u'0'); first = false; } } } } npc(fmtBuf)->append(u'E'); placeZeros(fmtBuf, npc(exponentSpecials)->subList(2, npc(exponentSpecials)->size())); decimalFmt = new ::java::text::DecimalFormat(npc(fmtBuf)->toString(), getDecimalFormatSymbols()); printfFmt = nullptr; } desc = npc(descBuf)->toString(); } java::text::DecimalFormatSymbols* poi::ss::format::CellNumberFormatter::getDecimalFormatSymbols() { return ::java::text::DecimalFormatSymbols::getInstance(locale); } void poi::ss::format::CellNumberFormatter::placeZeros(::java::lang::StringBuffer* sb, ::java::util::List* specials) { clinit(); for (auto _i = npc(specials)->iterator(); _i->hasNext(); ) { CellNumberFormatter_Special* s = java_cast< CellNumberFormatter_Special* >(_i->next()); { if(isDigitFmt(s)) { npc(sb)->append(u'0'); } } } } poi::ss::format::CellNumberStringMod* poi::ss::format::CellNumberFormatter::insertMod(CellNumberFormatter_Special* special, ::java::lang::CharSequence* toAdd, int32_t where) { clinit(); return new CellNumberStringMod(special, toAdd, where); } poi::ss::format::CellNumberStringMod* poi::ss::format::CellNumberFormatter::deleteMod(CellNumberFormatter_Special* start, bool startInclusive, CellNumberFormatter_Special* end, bool endInclusive) { clinit(); return new CellNumberStringMod(start, startInclusive, end, endInclusive); } poi::ss::format::CellNumberStringMod* poi::ss::format::CellNumberFormatter::replaceMod(CellNumberFormatter_Special* start, bool startInclusive, CellNumberFormatter_Special* end, bool endInclusive, char16_t withChar) { clinit(); return new CellNumberStringMod(start, startInclusive, end, endInclusive, withChar); } java::lang::String* poi::ss::format::CellNumberFormatter::singleNumberFormat(::java::util::List* numSpecials) { clinit(); return ::java::lang::StringBuilder().append(u"%0"_j)->append(npc(numSpecials)->size()) ->append(u"d"_j)->toString(); } int32_t poi::ss::format::CellNumberFormatter::maxValue(::java::util::List* s) { clinit(); return static_cast< int32_t >(::java::lang::Math::round(::java::lang::Math::pow(10, npc(s)->size()) - int32_t(1))); } java::util::List* poi::ss::format::CellNumberFormatter::specialsFor(int32_t pos, int32_t takeFirst) { if(pos >= npc(specials)->size()) { return ::java::util::Collections::emptyList(); } auto it = npc(specials)->listIterator(pos + takeFirst); auto last = java_cast< CellNumberFormatter_Special* >(npc(it)->next()); auto end = pos + takeFirst; while (npc(it)->hasNext()) { auto s = java_cast< CellNumberFormatter_Special* >(npc(it)->next()); if(!isDigitFmt(s) || npc(s)->pos - npc(last)->pos > 1) break; end++; last = s; } return npc(specials)->subList(pos, end + int32_t(1)); } java::util::List* poi::ss::format::CellNumberFormatter::specialsFor(int32_t pos) { return specialsFor(pos, 0); } bool poi::ss::format::CellNumberFormatter::isDigitFmt(CellNumberFormatter_Special* s) { clinit(); return npc(s)->ch == u'0' || npc(s)->ch == u'?' || npc(s)->ch == u'#'; } int32_t poi::ss::format::CellNumberFormatter::calculateIntegerPartWidth() { auto digitCount = int32_t(0); for (auto _i = npc(specials)->iterator(); _i->hasNext(); ) { CellNumberFormatter_Special* s = java_cast< CellNumberFormatter_Special* >(_i->next()); { if(s == afterInteger) { break; } else if(isDigitFmt(s)) { digitCount++; } } } return digitCount; } int32_t poi::ss::format::CellNumberFormatter::interpretPrecision(CellNumberFormatter_Special* decimalPoint, ::java::util::List* specials) { clinit(); auto idx = npc(specials)->indexOf(decimalPoint); auto precision = int32_t(0); if(idx != -int32_t(1)) { auto it = npc(specials)->listIterator(idx + int32_t(1)); while (npc(it)->hasNext()) { auto s = java_cast< CellNumberFormatter_Special* >(npc(it)->next()); if(!isDigitFmt(s)) { break; } precision++; } } return precision; } bool poi::ss::format::CellNumberFormatter::interpretIntegerCommas(::java::lang::StringBuffer* sb, ::java::util::List* specials, CellNumberFormatter_Special* decimalPoint, int32_t integerEnd, int32_t fractionalEnd, ::doubleArray* scale) { clinit(); auto it = npc(specials)->listIterator(integerEnd); auto stillScaling = true; auto integerCommas = false; while (npc(it)->hasPrevious()) { auto s = java_cast< CellNumberFormatter_Special* >(npc(it)->previous()); if(npc(s)->ch != u',') { stillScaling = false; } else { if(stillScaling) { (*scale)[int32_t(0)] /= 1000; } else { integerCommas = true; } } } if(decimalPoint != nullptr) { it = npc(specials)->listIterator(fractionalEnd); while (npc(it)->hasPrevious()) { auto s = java_cast< CellNumberFormatter_Special* >(npc(it)->previous()); if(npc(s)->ch != u',') { break; } else { (*scale)[int32_t(0)] /= 1000; } } } it = npc(specials)->listIterator(); auto removed = int32_t(0); while (npc(it)->hasNext()) { auto s = java_cast< CellNumberFormatter_Special* >(npc(it)->next()); npc(s)->pos -= removed; if(npc(s)->ch == u',') { removed++; npc(it)->remove(); npc(sb)->deleteCharAt(npc(s)->pos); } } return integerCommas; } int32_t poi::ss::format::CellNumberFormatter::integerEnd() { return (afterInteger == nullptr) ? npc(specials)->size() : npc(specials)->indexOf(afterInteger); } int32_t poi::ss::format::CellNumberFormatter::fractionalEnd() { return (afterFractional == nullptr) ? npc(specials)->size() : npc(specials)->indexOf(afterFractional); } void poi::ss::format::CellNumberFormatter::formatValue(::java::lang::StringBuffer* toAppendTo, ::java::lang::Object* valueObject) { auto value = npc((java_cast< ::java::lang::Number* >(valueObject)))->doubleValue(); value *= scale; auto negative = value < 0; if(negative) value = -value; double fractional = int32_t(0); if(slash != nullptr) { if(improperFraction) { fractional = value; value = 0; } else { fractional = std::fmod(value, 1.0); value = static_cast< int64_t >(value); } } ::java::util::Set* mods = new ::java::util::TreeSet(); auto output = new ::java::lang::StringBuffer(localiseFormat(desc)); if(exponent != nullptr) { writeScientific(value, output, mods); } else if(improperFraction) { writeFraction(value, nullptr, fractional, output, mods); } else { auto result = new ::java::lang::StringBuffer(); auto f = new ::java::util::Formatter(static_cast< ::java::lang::Appendable* >(result), locale); { auto finally0 = finally([&] { npc(f)->close(); }); { npc(f)->format(locale, printfFmt, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(::java::lang::Double::valueOf(value))})); } } if(numerator == nullptr) { writeFractional(result, output); writeInteger(result, output, integerSpecials, mods, showGroupingSeparator); } else { writeFraction(value, result, fractional, output, mods); } } auto dfs = getDecimalFormatSymbols(); auto groupingSeparator = ::java::lang::Character::toString(npc(dfs)->getGroupingSeparator()); auto changes = npc(mods)->iterator(); auto nextChange = (npc(changes)->hasNext() ? java_cast< CellNumberStringMod* >(npc(changes)->next()) : static_cast< CellNumberStringMod* >(nullptr)); auto deletedChars = new ::java::util::BitSet(); auto adjust = int32_t(0); for (auto _i = npc(specials)->iterator(); _i->hasNext(); ) { CellNumberFormatter_Special* s = java_cast< CellNumberFormatter_Special* >(_i->next()); { auto adjustedPos = npc(s)->pos + adjust; if(!npc(deletedChars)->get(npc(s)->pos) && npc(output)->charAt(adjustedPos) == u'#') { npc(output)->deleteCharAt(adjustedPos); adjust--; npc(deletedChars)->set(npc(s)->pos); } while (nextChange != nullptr && s == npc(nextChange)->getSpecial()) { auto lenBefore = npc(output)->length(); auto modPos = npc(s)->pos + adjust; { int32_t delPos; int32_t delEndPos; int32_t modEndPos; switch (npc(nextChange)->getOp()) { case CellNumberStringMod::AFTER: if(npc(npc(nextChange)->getToAdd())->equals(groupingSeparator) && npc(deletedChars)->get(npc(s)->pos)) { break; } npc(output)->insert(modPos + int32_t(1), npc(nextChange)->getToAdd()); break; case CellNumberStringMod::BEFORE: npc(output)->insert(modPos, npc(nextChange)->getToAdd()); break; case CellNumberStringMod::REPLACE: delPos = npc(s)->pos; if(!npc(nextChange)->isStartInclusive()) { delPos++; modPos++; } while (npc(deletedChars)->get(delPos)) { delPos++; modPos++; } delEndPos = npc(npc(nextChange)->getEnd())->pos; if(npc(nextChange)->isEndInclusive()) { delEndPos++; } modEndPos = delEndPos + adjust; if(modPos < modEndPos) { if(npc(u""_j)->equals(static_cast< ::java::lang::Object* >(npc(nextChange)->getToAdd()))) { npc(output)->delete_(modPos, modEndPos); } else { auto fillCh = npc(npc(nextChange)->getToAdd())->charAt(0); for (auto i = modPos; i < modEndPos; i++) { npc(output)->setCharAt(i, fillCh); } } npc(deletedChars)->set(delPos, delEndPos); } break; default: throw new ::java::lang::IllegalStateException(::java::lang::StringBuilder().append(u"Unknown op: "_j)->append(npc(nextChange)->getOp())->toString()); } } adjust += npc(output)->length() - lenBefore; nextChange = (npc(changes)->hasNext()) ? java_cast< CellNumberStringMod* >(npc(changes)->next()) : static_cast< CellNumberStringMod* >(nullptr); } } } if(negative) { npc(toAppendTo)->append(u'-'); } npc(toAppendTo)->append(output); } void poi::ss::format::CellNumberFormatter::writeScientific(double value, ::java::lang::StringBuffer* output, ::java::util::Set* mods) { auto result = new ::java::lang::StringBuffer(); auto fractionPos = new ::java::text::FieldPosition(::java::text::DecimalFormat::FRACTION_FIELD); npc(decimalFmt)->format(value, result, fractionPos); writeInteger(result, output, integerSpecials, mods, showGroupingSeparator); writeFractional(result, output); auto ePos = npc(fractionPos)->getEndIndex(); auto signPos = ePos + int32_t(1); auto expSignRes = npc(result)->charAt(signPos); if(expSignRes != u'-') { expSignRes = u'+'; npc(result)->insert(signPos, u'+'); } auto it = npc(exponentSpecials)->listIterator(1); auto expSign = java_cast< CellNumberFormatter_Special* >(npc(it)->next()); auto expSignFmt = npc(expSign)->ch; if(expSignRes == u'-' || expSignFmt == u'+') { npc(mods)->add(static_cast< ::java::lang::Object* >(replaceMod(expSign, true, expSign, true, expSignRes))); } else { npc(mods)->add(static_cast< ::java::lang::Object* >(deleteMod(expSign, true, expSign, true))); } auto exponentNum = new ::java::lang::StringBuffer(npc(result)->substring(signPos + int32_t(1))); writeInteger(exponentNum, output, exponentDigitSpecials, mods, false); } void poi::ss::format::CellNumberFormatter::writeFraction(double value, ::java::lang::StringBuffer* result, double fractional, ::java::lang::StringBuffer* output, ::java::util::Set* mods) { if(!improperFraction) { if(fractional == 0 && !hasChar(u'0', new ::java::util::ListArray({static_cast< ::java::util::List* >(numeratorSpecials)}))) { writeInteger(result, output, integerSpecials, mods, false); auto start = lastSpecial(integerSpecials); auto end = lastSpecial(denominatorSpecials); if(hasChar(u'?', new ::java::util::ListArray({static_cast< ::java::util::List* >(integerSpecials), static_cast< ::java::util::List* >(numeratorSpecials), static_cast< ::java::util::List* >(denominatorSpecials)}))) { npc(mods)->add(static_cast< ::java::lang::Object* >(replaceMod(start, false, end, true, u' '))); } else { npc(mods)->add(static_cast< ::java::lang::Object* >(deleteMod(start, false, end, true))); } return; } else { auto numNoZero = !hasChar(u'0', new ::java::util::ListArray({static_cast< ::java::util::List* >(numeratorSpecials)})); auto intNoZero = !hasChar(u'0', new ::java::util::ListArray({static_cast< ::java::util::List* >(integerSpecials)})); auto intOnlyHash = npc(integerSpecials)->isEmpty() || (npc(integerSpecials)->size() == 1 && hasChar(u'#', new ::java::util::ListArray({static_cast< ::java::util::List* >(integerSpecials)}))); auto removeBecauseZero = fractional == 0 && (intOnlyHash || numNoZero); auto removeBecauseFraction = fractional != 0 && intNoZero; if(value == 0 && (removeBecauseZero || removeBecauseFraction)) { auto start = lastSpecial(integerSpecials); auto hasPlaceHolder = hasChar(u'?', new ::java::util::ListArray({static_cast< ::java::util::List* >(integerSpecials), static_cast< ::java::util::List* >(numeratorSpecials)})); auto sm = hasPlaceHolder ? replaceMod(start, true, numerator, false, u' ') : deleteMod(start, true, numerator, false); npc(mods)->add(static_cast< ::java::lang::Object* >(sm)); } else { writeInteger(result, output, integerSpecials, mods, false); } } } try { int32_t n; int32_t d; if(fractional == 0 || (improperFraction && std::fmod(fractional, static_cast< double >(int32_t(1))) == 0)) { n = static_cast< int32_t >(::java::lang::Math::round(fractional)); d = 1; } else { auto frac = SimpleFraction::buildFractionMaxDenominator(fractional, maxDenominator); n = npc(frac)->getNumerator(); d = npc(frac)->getDenominator(); } if(improperFraction) { n += ::java::lang::Math::round(value * d); } writeSingleInteger(numeratorFmt, n, output, numeratorSpecials, mods); writeSingleInteger(denominatorFmt, d, output, denominatorSpecials, mods); } catch (::java::lang::RuntimeException* ignored) { npc(LOG_)->log(::poi::util::POILogger::ERROR, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(u"error while fraction evaluation"_j), static_cast< ::java::lang::Object* >(ignored)})); } } java::lang::String* poi::ss::format::CellNumberFormatter::localiseFormat(::java::lang::String* format) { auto dfs = getDecimalFormatSymbols(); if(npc(format)->contains(u","_j) && npc(dfs)->getGroupingSeparator() != u',') { if(npc(format)->contains(u"."_j) && npc(dfs)->getDecimalSeparator() != u'.') { format = replaceLast(format, u"\\."_j, u"[DECIMAL_SEPARATOR]"_j); format = npc(npc(format)->replace(u',', npc(dfs)->getGroupingSeparator()))->replace(static_cast< ::java::lang::CharSequence* >(u"[DECIMAL_SEPARATOR]"_j), static_cast< ::java::lang::CharSequence* >(::java::lang::Character::toString(npc(dfs)->getDecimalSeparator()))); } else { format = npc(format)->replace(u',', npc(dfs)->getGroupingSeparator()); } } else if(npc(format)->contains(u"."_j) && npc(dfs)->getDecimalSeparator() != u'.') { format = npc(format)->replace(u'.', npc(dfs)->getDecimalSeparator()); } return format; } java::lang::String* poi::ss::format::CellNumberFormatter::replaceLast(::java::lang::String* text, ::java::lang::String* regex, ::java::lang::String* replacement) { clinit(); return npc(text)->replaceFirst(::java::lang::StringBuilder().append(u"(?s)(.*)"_j)->append(regex)->toString(), ::java::lang::StringBuilder().append(u"$1"_j)->append(replacement)->toString()); } bool poi::ss::format::CellNumberFormatter::hasChar(char16_t ch, ::java::util::ListArray*/*...*/ numSpecials) { clinit(); for(auto specials : *npc(numSpecials)) { for (auto _i = npc(specials)->iterator(); _i->hasNext(); ) { CellNumberFormatter_Special* s = java_cast< CellNumberFormatter_Special* >(_i->next()); { if(npc(s)->ch == ch) { return true; } } } } return false; } void poi::ss::format::CellNumberFormatter::writeSingleInteger(::java::lang::String* fmt, int32_t num, ::java::lang::StringBuffer* output, ::java::util::List* numSpecials, ::java::util::Set* mods) { auto sb = new ::java::lang::StringBuffer(); auto formatter = new ::java::util::Formatter(static_cast< ::java::lang::Appendable* >(sb), locale); { auto finally1 = finally([&] { npc(formatter)->close(); }); { npc(formatter)->format(locale, fmt, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(::java::lang::Integer::valueOf(num))})); } } writeInteger(sb, output, numSpecials, mods, false); } void poi::ss::format::CellNumberFormatter::writeInteger(::java::lang::StringBuffer* result, ::java::lang::StringBuffer* output, ::java::util::List* numSpecials, ::java::util::Set* mods, bool showGroupingSeparator) { auto dfs = getDecimalFormatSymbols(); auto decimalSeparator = ::java::lang::Character::toString(npc(dfs)->getDecimalSeparator()); auto groupingSeparator = ::java::lang::Character::toString(npc(dfs)->getGroupingSeparator()); auto pos = npc(result)->indexOf(decimalSeparator) - int32_t(1); if(pos < 0) { if(exponent != nullptr && numSpecials == integerSpecials) { pos = npc(result)->indexOf(u"E"_j) - int32_t(1); } else { pos = npc(result)->length() - int32_t(1); } } int32_t strip; for (strip = 0; strip < pos; strip++) { auto resultCh = npc(result)->charAt(strip); if(resultCh != u'0' && resultCh != npc(dfs)->getGroupingSeparator()) { break; } } auto it = npc(numSpecials)->listIterator(npc(numSpecials)->size()); auto followWithGroupingSeparator = false; CellNumberFormatter_Special* lastOutputIntegerDigit = nullptr; auto digit = int32_t(0); while (npc(it)->hasPrevious()) { char16_t resultCh; if(pos >= 0) { resultCh = npc(result)->charAt(pos); } else { resultCh = u'0'; } auto s = java_cast< CellNumberFormatter_Special* >(npc(it)->previous()); followWithGroupingSeparator = showGroupingSeparator && digit > 0 && digit % int32_t(3) == 0; auto zeroStrip = false; if(resultCh != u'0' || npc(s)->ch == u'0' || npc(s)->ch == u'?' || pos >= strip) { zeroStrip = npc(s)->ch == u'?' && pos < strip; npc(output)->setCharAt(npc(s)->pos, (zeroStrip ? u' ' : resultCh)); lastOutputIntegerDigit = s; } if(followWithGroupingSeparator) { npc(mods)->add(static_cast< ::java::lang::Object* >(insertMod(s, zeroStrip ? static_cast< ::java::lang::CharSequence* >(u" "_j) : static_cast< ::java::lang::CharSequence* >(groupingSeparator), CellNumberStringMod::AFTER))); followWithGroupingSeparator = false; } digit++; --pos; } auto extraLeadingDigits = new ::java::lang::StringBuffer(); if(pos >= 0) { ++pos; extraLeadingDigits = new ::java::lang::StringBuffer(npc(result)->substring(int32_t(0), pos)); if(showGroupingSeparator) { while (pos > 0) { if(digit > 0 && digit % int32_t(3) == 0) { npc(extraLeadingDigits)->insert(pos, groupingSeparator); } digit++; --pos; } } npc(mods)->add(static_cast< ::java::lang::Object* >(insertMod(lastOutputIntegerDigit, extraLeadingDigits, CellNumberStringMod::BEFORE))); } } void poi::ss::format::CellNumberFormatter::writeFractional(::java::lang::StringBuffer* result, ::java::lang::StringBuffer* output) { int32_t digit; int32_t strip; if(npc(fractionalSpecials)->size() > 0) { auto decimalSeparator = ::java::lang::Character::toString(npc(getDecimalFormatSymbols())->getDecimalSeparator()); digit = npc(result)->indexOf(decimalSeparator) + int32_t(1); if(exponent != nullptr) { strip = npc(result)->indexOf(u"e"_j) - int32_t(1); } else { strip = npc(result)->length() - int32_t(1); } while (strip > digit && npc(result)->charAt(strip) == u'0') { strip--; } for (auto _i = npc(fractionalSpecials)->iterator(); _i->hasNext(); ) { CellNumberFormatter_Special* s = java_cast< CellNumberFormatter_Special* >(_i->next()); { auto resultCh = npc(result)->charAt(digit); if(resultCh != u'0' || npc(s)->ch == u'0' || digit < strip) { npc(output)->setCharAt(npc(s)->pos, resultCh); } else if(npc(s)->ch == u'?') { npc(output)->setCharAt(npc(s)->pos, u' '); } digit++; } } } } void poi::ss::format::CellNumberFormatter::simpleValue(::java::lang::StringBuffer* toAppendTo, ::java::lang::Object* value) { npc(SIMPLE_NUMBER)->formatValue(toAppendTo, value); } poi::ss::format::CellNumberFormatter_Special* poi::ss::format::CellNumberFormatter::lastSpecial(::java::util::List* s) { clinit(); return java_cast< CellNumberFormatter_Special* >(npc(s)->get(npc(s)->size() - int32_t(1))); } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* poi::ss::format::CellNumberFormatter::class_() { static ::java::lang::Class* c = ::class_(u"org.apache.poi.ss.format.CellNumberFormatter", 44); return c; } void poi::ss::format::CellNumberFormatter::clinit() { super::clinit(); static bool in_cl_init = false; struct clinit_ { clinit_() { in_cl_init = true; LOG_ = ::poi::util::POILogFactory::getLogger(static_cast< ::java::lang::Class* >(CellNumberFormatter::class_())); } }; if(!in_cl_init) { static clinit_ clinit_instance; } } java::lang::Class* poi::ss::format::CellNumberFormatter::getClass0() { return class_(); }
41.557055
278
0.597685
pebble2015
79ade633f77a3915e418479db88f5a8d8db54a74
523
cpp
C++
7.06/7_06.cpp
dengxianglong/cplusplusprimerplusstudy
eefc5d7bf5ab31186c04171fadade3552838f4b2
[ "MIT" ]
null
null
null
7.06/7_06.cpp
dengxianglong/cplusplusprimerplusstudy
eefc5d7bf5ab31186c04171fadade3552838f4b2
[ "MIT" ]
null
null
null
7.06/7_06.cpp
dengxianglong/cplusplusprimerplusstudy
eefc5d7bf5ab31186c04171fadade3552838f4b2
[ "MIT" ]
1
2018-08-29T07:40:20.000Z
2018-08-29T07:40:20.000Z
#include<iostream> const int arsize=8; int sum_arr(int arr[],int n); int main() { using namespace std; int cookies[arsize]={1,2,4,8,13,32,64,128}; cout<<cookies<<endl; cout<<sizeof cookies<<endl; int sum=sum_arr(cookies,arsize); cout<<sum<<endl; sum=sum_arr(cookies,3); cout<<sum<<endl; sum=sum_arr(cookies+4,4); cout<<sum<<endl; return 0; } int sum_arr(int arr[],int n) { using namespace std; int total=0; cout<<arr<<endl; cout<<sizeof arr<<endl; for(int i=0;i<n;i++) total=total+arr[i]; return total; }
19.37037
44
0.67304
dengxianglong
79ae5370f0233194782d48bd327f2802cebb3302
1,120
cpp
C++
Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/003.cpp
jesushilarioh/C-Plus-Plus
bbff921460ac4267af48558f040c7d82ccf42d5e
[ "MIT" ]
3
2019-10-28T01:12:46.000Z
2021-10-16T09:16:31.000Z
Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/003.cpp
jesushilariohernandez/DelMarCSi.cpp
6dd7905daea510452691fd25b0e3b0d2da0b06aa
[ "MIT" ]
null
null
null
Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/003.cpp
jesushilariohernandez/DelMarCSi.cpp
6dd7905daea510452691fd25b0e3b0d2da0b06aa
[ "MIT" ]
4
2020-04-10T17:22:17.000Z
2021-11-04T14:34:00.000Z
/******************************************************************** * * 003. Ocean Levels * * Assuming the ocean’s level is currently rising at * about 1.5 millimeters per year, write a program that * displays a table showing the number of * millimeters that the ocean will have risen each year for * the next 25 years. * * Jesus Hilario Hernandez * March 12th 2018 * ********************************************************************/ #include <iostream> using namespace std; int main() { // Constants const float MIL_PER_YEAR = 1.5; // 1.5 millimeters per year. // Variables float num_of_mil_each_year = 0; // Initialize counter. // Display a table of mil risen each year (25 years) cout << "--------------------------------------------------\n"; for (int i = 1; i <= 25; i++) { num_of_mil_each_year += MIL_PER_YEAR; cout << "Year " << i << ": " << num_of_mil_each_year << endl; } cout << "--------------------------------------------------\n"; // Terminate program return 0; }
28.717949
72
0.460714
jesushilarioh
79b1e0f70579f6379503877afa7a459c78651cb5
3,236
cpp
C++
studio/src/sequence/key_item.cpp
blagodarin/aulos
c78ec06fd812c889ec618ac2e9f0cab9ad9db756
[ "Apache-2.0" ]
null
null
null
studio/src/sequence/key_item.cpp
blagodarin/aulos
c78ec06fd812c889ec618ac2e9f0cab9ad9db756
[ "Apache-2.0" ]
null
null
null
studio/src/sequence/key_item.cpp
blagodarin/aulos
c78ec06fd812c889ec618ac2e9f0cab9ad9db756
[ "Apache-2.0" ]
null
null
null
// This file is part of the Aulos toolkit. // Copyright (C) Sergei Blagodarin. // SPDX-License-Identifier: Apache-2.0 #include "key_item.hpp" #include "../theme.hpp" #include <QPainter> namespace { enum class KeyStyle : size_t { White, Black, }; } struct KeyItem::StyleInfo { struct Colors { QColor _normal; QColor _hovered; QColor _pressed; const QColor& operator()(bool hovered, bool pressed) const noexcept { return pressed ? _pressed : (hovered ? _hovered : _normal); } }; qreal _width; Colors _backgroundColors; Colors _borderColors; Colors _textColors; qreal _z; }; const std::array<KeyItem::StyleInfo, 2> KeyItem::kStyleInfo{ StyleInfo{ kWhiteKeyWidth, { "#fff", "#fdd", "#fcc" }, { "#aaa", "#aaa", "#aaa" }, { "#999", "#944", "#900" }, 0.5 }, StyleInfo{ kBlackKeyWidth, { "#000", "#200", "#300" }, { "#555", "#500", "#500" }, { "#999", "#f99", "#f99" }, 1.0 }, }; struct KeyItem::NoteInfo { QString _name; qreal _y; qreal _height; qreal _textOffset; KeyStyle _style; }; const std::array<KeyItem::NoteInfo, aulos::kNotesPerOctave> KeyItem::kNoteInfo{ NoteInfo{ QStringLiteral("C%1"), 10.5, 1.5, 0.5, KeyStyle::White }, NoteInfo{ QStringLiteral("C#%1"), 10.0, 1.0, 0.0, KeyStyle::Black }, NoteInfo{ QStringLiteral("D%1"), 8.5, 2.0, 0.5, KeyStyle::White }, NoteInfo{ QStringLiteral("D#%1"), 8.0, 1.0, 0.0, KeyStyle::Black }, NoteInfo{ QStringLiteral("E%1"), 7.0, 1.5, 0.0, KeyStyle::White }, NoteInfo{ QStringLiteral("F%1"), 5.5, 1.5, 0.5, KeyStyle::White }, NoteInfo{ QStringLiteral("F#%1"), 5.0, 1.0, 0.0, KeyStyle::Black }, NoteInfo{ QStringLiteral("G%1"), 3.5, 2.0, 0.5, KeyStyle::White }, NoteInfo{ QStringLiteral("G#%1"), 3.0, 1.0, 0.0, KeyStyle::Black }, NoteInfo{ QStringLiteral("A%1"), 1.5, 2.0, 0.5, KeyStyle::White }, NoteInfo{ QStringLiteral("A#%1"), 1.0, 1.0, 0.0, KeyStyle::Black }, NoteInfo{ QStringLiteral("B%1"), 0.0, 1.5, 0.0, KeyStyle::White }, }; KeyItem::KeyItem(aulos::Note note, QGraphicsItem* parent) : ButtonItem{ Mode::Press, parent } , _octave{ static_cast<size_t>(note) / kNoteInfo.size() } , _noteInfo{ kNoteInfo[static_cast<size_t>(note) % kNoteInfo.size()] } , _styleInfo{ kStyleInfo[static_cast<size_t>(_noteInfo._style)] } { setPos(0, ((aulos::kOctaveCount - 1 - _octave) * kNoteInfo.size() + _noteInfo._y) * kNoteHeight); setZValue(_styleInfo._z); } QRectF KeyItem::boundingRect() const { return { 0, 0, _styleInfo._width, _noteInfo._height * kNoteHeight }; } void KeyItem::paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*) { const auto rect = boundingRect(); painter->setBrush(_styleInfo._backgroundColors(isHovered(), isPressed())); painter->setPen(Qt::transparent); painter->drawRect(rect); painter->setPen(_styleInfo._borderColors(isHovered(), isPressed())); painter->drawLine(rect.topLeft(), rect.topRight()); painter->drawLine(rect.topRight(), rect.bottomRight()); painter->drawLine(rect.bottomRight(), rect.bottomLeft()); painter->setPen(_styleInfo._textColors(isHovered(), isPressed())); painter->drawText(QRectF{ { 0, _noteInfo._textOffset * kNoteHeight }, QSizeF{ _styleInfo._width - kNoteHeight * 0.125, kNoteHeight } }, Qt::AlignVCenter | Qt::AlignRight, _noteInfo._name.arg(_octave)); }
33.020408
202
0.680779
blagodarin
79bbe8c0ca5fcfa0a553799eeb1b7d7702cd4a8d
305
cpp
C++
src/parser_brute_force.cpp
Auterion/mavlink-fuzz-testing
9de6a4aa78b27e3ccc18b313c3b79ccbe3a09cb1
[ "BSD-3-Clause" ]
9
2019-08-20T17:04:28.000Z
2021-06-29T11:28:29.000Z
src/parser_brute_force.cpp
Auterion/mavlink-fuzz-testing
9de6a4aa78b27e3ccc18b313c3b79ccbe3a09cb1
[ "BSD-3-Clause" ]
null
null
null
src/parser_brute_force.cpp
Auterion/mavlink-fuzz-testing
9de6a4aa78b27e3ccc18b313c3b79ccbe3a09cb1
[ "BSD-3-Clause" ]
2
2020-08-03T04:57:13.000Z
2022-03-25T02:51:04.000Z
#include <common/mavlink.h> extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { for (size_t i = 0; i < Size; ++i) { mavlink_message_t message; mavlink_status_t status; mavlink_parse_char(MAVLINK_COMM_0, Data[i], &message, &status); } return 0; }
27.727273
73
0.652459
Auterion
79c1204b5529a04cc26832618439aab55b99d7f6
13,071
cpp
C++
diamond-dpct/masking.dp.cpp
jchlanda/oneAPI-DirectProgramming
82a1be635f89b4b2a83e36965a60b19fd71e46b2
[ "BSD-3-Clause" ]
null
null
null
diamond-dpct/masking.dp.cpp
jchlanda/oneAPI-DirectProgramming
82a1be635f89b4b2a83e36965a60b19fd71e46b2
[ "BSD-3-Clause" ]
null
null
null
diamond-dpct/masking.dp.cpp
jchlanda/oneAPI-DirectProgramming
82a1be635f89b4b2a83e36965a60b19fd71e46b2
[ "BSD-3-Clause" ]
null
null
null
/**** DIAMOND protein aligner Copyright (C) 2013-2017 Benjamin Buchfink <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ****/ #include <CL/sycl.hpp> #include <dpct/dpct.hpp> #include "../diamond-sycl/src/basic/masking.h" #include <cmath> #define SEQ_LEN 33 inline double firstRepeatOffsetProb(const double probMult, const int maxRepeatOffset) { if (probMult < 1 || probMult > 1) return (1 - probMult) / (1 - sycl::pow(probMult, (double)maxRepeatOffset)); else return 1.0 / maxRepeatOffset; } void maskProbableLetters(const int size, unsigned char *seqBeg, const float *probabilities, const unsigned char *maskTable) { const double minMaskProb = 0.5; for (int i=0; i<size; i++) if (probabilities[i] >= minMaskProb) seqBeg[i] = maskTable[seqBeg[i]]; } int calcRepeatProbs(float *letterProbs, const unsigned char *seqBeg, const int size, const int maxRepeatOffset, const double *likelihoodRatioMatrix, // 64 by 64 matrix, const double b2b, const double f2f0, const double f2b, const double b2fLast_inv, const double *pow_lkp, double *foregroundProbs, const int scaleStepSize, double *scaleFactors) { double backgroundProb = 1.0; for (int k=0; k < size ; k++) { const int v0 = seqBeg[k]; const int k_cap = k < maxRepeatOffset ? k : maxRepeatOffset; const int pad1 = k_cap - 1; const int pad2 = maxRepeatOffset - k_cap; // maxRepeatOffset - k, then 0 when k > maxRepeatOffset const int pad3 = k - k_cap; // 0 , then maxRepeatOffset - k when k > maxRepeatOffset double accu = 0; for (int i = 0; i < k; i++) { const int idx1 = pad1 - i; const int idx2 = pad2 + i; const int idx3 = pad3 + i; const int v1 = seqBeg[idx3]; accu += foregroundProbs[idx1]; foregroundProbs[idx1] = ( (f2f0 * foregroundProbs[idx1]) + (backgroundProb * pow_lkp[idx2]) ) * likelihoodRatioMatrix[v0*size+v1]; } backgroundProb = (backgroundProb * b2b) + (accu * f2b); if (k % scaleStepSize == scaleStepSize - 1) { const double scale = 1 / backgroundProb; scaleFactors[k / scaleStepSize] = scale; for (int i=0; i< k_cap; i++) foregroundProbs[i] = foregroundProbs[i] * scale; backgroundProb = 1; } letterProbs[k] = (float)(backgroundProb); } double accu = 0; for (int i=0 ; i < maxRepeatOffset; i++) { accu += foregroundProbs[i]; foregroundProbs[i] = f2b; } const double fTot = backgroundProb * b2b + accu * f2b; backgroundProb = b2b; const double fTot_inv = 1/ fTot ; for (int k=(size-1) ; k >= 0 ; k--){ double nonRepeatProb = letterProbs[k] * backgroundProb * fTot_inv; letterProbs[k] = 1 - (float)(nonRepeatProb); //const int k_cap = std::min(k, maxRepeatOffset); const int k_cap = k < maxRepeatOffset ? k : maxRepeatOffset; if (k % scaleStepSize == scaleStepSize - 1) { const double scale = scaleFactors[k/ scaleStepSize]; for (int i=0; i< k_cap; i++) foregroundProbs[i] = foregroundProbs[i] * scale; backgroundProb *= scale; } const double c0 = f2b * backgroundProb; const int v0= seqBeg[k]; double accu = 0; for (int i = 0; i < k_cap; i++) { const int v1 = seqBeg[k-(i+1)]; const double f = foregroundProbs[i] * likelihoodRatioMatrix[v0*size+v1]; accu += pow_lkp[k_cap-(i+1)]*f; foregroundProbs[i] = c0 + f2f0 * f; } const double p = k > maxRepeatOffset ? 1. : pow_lkp[maxRepeatOffset - k]*b2fLast_inv; backgroundProb = (b2b * backgroundProb) + accu*p; } const double bTot = backgroundProb; return (sycl::fabs(fTot - bTot) > sycl::fmax((double)fTot, (double)bTot) / 1e6); } void maskSequences(unsigned char * seqs, const double * likelihoodRatioMatrix, const unsigned char * maskTable, const int size , const int maxRepeatOffset , const double repeatProb , const double repeatEndProb , const double repeatOffsetProbDecay , const double firstGapProb , const double otherGapProb , const double minMaskProb , int seqs_len , sycl::nd_item<3> item_ct1) { int gid = item_ct1.get_group(2) * item_ct1.get_local_range().get(2) + item_ct1.get_local_id(2); if (gid >= seqs_len) return; unsigned char* seqBeg = seqs+gid*33; float probabilities[SEQ_LEN]; const double b2b = 1 - repeatProb; const double f2f0 = 1 - repeatEndProb; const double f2b = repeatEndProb; const double b2fGrowth = 1 / repeatOffsetProbDecay; const double b2fLast = repeatProb * firstRepeatOffsetProb(b2fGrowth, maxRepeatOffset); const double b2fLast_inv = 1 / b2fLast ; double p = b2fLast; double ar_1[50]; for (int i=0 ; i < maxRepeatOffset; i++){ ar_1[i] = p ; p *= b2fGrowth; } const int scaleStepSize = 16; double scaleFactors[SEQ_LEN / scaleStepSize]; double foregroundProbs[50]; for (int i=0 ; i < maxRepeatOffset; i++){ foregroundProbs[i] = 0; }; const int err = calcRepeatProbs(probabilities,seqBeg, size, maxRepeatOffset, likelihoodRatioMatrix, b2b, f2f0, f2b, b2fLast_inv,ar_1,foregroundProbs,scaleStepSize, scaleFactors); //if (err) printf("tantan: warning: possible numeric inaccuracy\n"); maskProbableLetters(size,seqBeg, probabilities, maskTable); } auto_ptr<Masking> Masking::instance; const uint8_t Masking::bit_mask = 128; Masking::Masking(const Score_matrix &score_matrix) { const double lambda = score_matrix.lambda(); // 0.324032 for (unsigned i = 0; i < size; ++i) { mask_table_x_[i] = value_traits.mask_char; mask_table_bit_[i] = (uint8_t)i | bit_mask; for (unsigned j = 0; j < size; ++j) if (i < value_traits.alphabet_size && j < value_traits.alphabet_size) likelihoodRatioMatrix_[i][j] = exp(lambda * score_matrix(i, j)); } std::copy(likelihoodRatioMatrix_, likelihoodRatioMatrix_ + size, probMatrixPointers_); int firstGapCost = score_matrix.gap_extend() + score_matrix.gap_open(); firstGapProb_ = exp(-lambda * firstGapCost); otherGapProb_ = exp(-lambda * score_matrix.gap_extend()); firstGapProb_ /= (1 - otherGapProb_); } void Masking::operator()(Letter *seq, size_t len) const { tantan::maskSequences((tantan::uchar*)seq, (tantan::uchar*)(seq + len), 50, (tantan::const_double_ptr*)probMatrixPointers_, 0.005, 0.05, 0.9, 0, 0, 0.5, (const tantan::uchar*)mask_table_x_); } unsigned char* Masking::call_opt(Sequence_set &seqs) const { dpct::device_ext &dev_ct1 = dpct::get_current_device(); sycl::queue &q_ct1 = dev_ct1.default_queue(); const int n = seqs.get_length(); int total = 0; for (int i=0; i < n; i++) total += seqs.length(i); printf("There are %d sequences and the total sequence length is %d\n", n, total); unsigned char *seqs_device = NULL; posix_memalign((void**)&seqs_device, 1024, total); unsigned char *p = seqs_device; for (int i=0; i < n; i++) { memcpy(p, seqs.ptr(i), seqs.length(i)); p += seqs.length(i); } double *probMat_device = NULL; posix_memalign((void**)&probMat_device, 1024, size*size*sizeof(double)); for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) probMat_device[i*size+j] = probMatrixPointers_[i][j]; unsigned char *mask_table_device = NULL; posix_memalign((void**)&mask_table_device, 1024, size*sizeof(unsigned char)); for (int i = 0; i < size; i++) mask_table_device[i] = mask_table_x_[i]; int len = 33; printf("Timing the mask sequences on device...\n"); Timer t; t.start(); const int size = len; const int maxRepeatOffset = 50; const double repeatProb = 0.005; const double repeatEndProb = 0.05; const double repeatOffsetProbDecay = 0.9; const double firstGapProb = 0; const double otherGapProb = 0; const double minMaskProb = 0.5; const int seqs_len = n; unsigned char* d_seqs; d_seqs = (unsigned char *)sycl::malloc_device(total, q_ct1); q_ct1.memcpy(d_seqs, seqs_device, total).wait(); unsigned char* d_maskTable; d_maskTable = (unsigned char *)sycl::malloc_device(size * size, q_ct1); q_ct1.memcpy(d_maskTable, mask_table_device, size).wait(); double* d_probMat; d_probMat = (double *)sycl::malloc_device(size * size, q_ct1); q_ct1.memcpy(d_probMat, probMat_device, sizeof(double) * size * size).wait(); sycl::range<3> grids((seqs_len + 128) / 128, 1, 1); sycl::range<3> threads(128, 1, 1); q_ct1.submit([&](sycl::handler &cgh) { auto dpct_global_range = grids * threads; cgh.parallel_for( sycl::nd_range<3>( sycl::range<3>(dpct_global_range.get(2), dpct_global_range.get(1), dpct_global_range.get(0)), sycl::range<3>(threads.get(2), threads.get(1), threads.get(0))), [=](sycl::nd_item<3> item_ct1) { maskSequences(d_seqs, d_probMat, d_maskTable, size, maxRepeatOffset, repeatProb, repeatEndProb, repeatOffsetProbDecay, firstGapProb, otherGapProb, minMaskProb, seqs_len, item_ct1); }); }); q_ct1.memcpy(seqs_device, d_seqs, total).wait(); sycl::free(d_seqs, q_ct1); sycl::free(d_maskTable, q_ct1); sycl::free(d_probMat, q_ct1); message_stream << "Total time (maskSequences) on the device = " << t.getElapsedTimeInMicroSec() / 1e6 << " s" << std::endl; free(probMat_device); free(mask_table_device); return seqs_device; } void Masking::call_opt(Letter *seq, size_t len) const { // CPU tantale::maskSequences((tantan::uchar*)seq, (tantan::uchar*)(seq + len), 50, (tantan::const_double_ptr*)probMatrixPointers_, 0.005, 0.05, 0.9, 0, 0, 0.5, (const tantan::uchar*)mask_table_x_); } void Masking::mask_bit(Letter *seq, size_t len) const { tantan::maskSequences((tantan::uchar*)seq, (tantan::uchar*)(seq + len), 50, (tantan::const_double_ptr*)probMatrixPointers_, 0.005, 0.05, 0.9, 0, 0, 0.5, (const tantan::uchar*)mask_table_bit_); } void Masking::bit_to_hard_mask(Letter *seq, size_t len, size_t &n) const { for (size_t i = 0; i < len; ++i) if (seq[i] & bit_mask) { seq[i] = value_traits.mask_char; ++n; } } void Masking::remove_bit_mask(Letter *seq, size_t len) const { for (size_t i = 0; i < len; ++i) if (seq[i] & bit_mask) seq[i] &= ~bit_mask; } void mask_worker(Atomic<size_t> *next, Sequence_set *seqs, const Masking *masking, bool hard_mask) { size_t i; int cnt = 0; while ((i = (*next)++) < seqs->get_length()) { if (hard_mask) //masking->operator()(seqs->ptr(i), seqs->length(i)); masking->call_opt(seqs->ptr(i), seqs->length(i)); else masking->mask_bit(seqs->ptr(i), seqs->length(i)); //cnt++; //if (cnt == 2) break; } } void mask_seqs(Sequence_set &seqs, const Masking &masking, bool hard_mask) { assert(hard_mask==true); const int n = seqs.get_length(); printf("Timing the mask sequences on CPU...\n"); Timer total; total.start(); #if not defined(_OPENMP) Thread_pool threads; Atomic<size_t> next(0); for (size_t i = 0; i < config.threads_; ++i) threads.push_back(launch_thread(mask_worker, &next, &seqs, &masking, hard_mask)); threads.join_all(); #else #pragma omp parallel for num_threads(config.threads_) for (int i=0; i < n; i++){ masking.call_opt(seqs.ptr(i), seqs.length(i)); } #endif message_stream << "Total time (maskSequences) on the CPU = " << total.getElapsedTimeInMicroSec() / 1e6 << " s" << std::endl; // on the device unsigned char* seqs_device = masking.call_opt(seqs); printf("Verify the sequences...\n"); unsigned char* p = seqs_device; int error = 0; for (int i = 0; i < n; i++) { if (0 != strncmp((const char*)p, seqs.ptr(i), seqs.length(i))) { printf("error at i=%d length=%zu\n", i, seqs.length(i)); printf("host="); char* s = seqs.ptr(i); for (int j = 0; j < seqs.length(i); j++) { printf("%02d", s[j]); } printf("\ndevice="); for (int j = 0; j < seqs.length(i); j++) printf("%02d", *(seqs_device+i*33+j)); printf("\n"); error++; } p += seqs.length(i); } if (error == 0) printf("Success\n"); }
29.439189
119
0.638742
jchlanda
79c4b094e8b2c96e913d2b959c1499addf6b865c
6,511
cc
C++
cpp/core/internal/wifi_lan_service_info_test.cc
jdapena/nearby-connections
ae277748ce068ef1730d5104002d4324fc4ed89e
[ "Apache-2.0" ]
null
null
null
cpp/core/internal/wifi_lan_service_info_test.cc
jdapena/nearby-connections
ae277748ce068ef1730d5104002d4324fc4ed89e
[ "Apache-2.0" ]
null
null
null
cpp/core/internal/wifi_lan_service_info_test.cc
jdapena/nearby-connections
ae277748ce068ef1730d5104002d4324fc4ed89e
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "core/internal/wifi_lan_service_info.h" #include <cstring> #include "platform/base64_utils.h" #include "platform/port/string.h" #include "gtest/gtest.h" namespace location { namespace nearby { namespace connections { namespace { const WifiLanServiceInfo::Version kVersion = WifiLanServiceInfo::Version::kV1; const PCP::Value kPcp = PCP::P2P_CLUSTER; const char kEndPointID[] = "AB12"; const char kServiceIDHashBytes[] = {0x0A, 0x0B, 0x0C}; // TODO(b/149806065): Implements test endpoint_name. TEST(WifiLanServiceInfoTest, SerializationDeserializationWorks) { ScopedPtr<Ptr<ByteArray> > scoped_service_id_hash(new ByteArray( kServiceIDHashBytes, sizeof(kServiceIDHashBytes) / sizeof(char))); std::string wifi_lan_service_info_string = WifiLanServiceInfo::AsString( kVersion, kPcp, kEndPointID, ConstifyPtr(scoped_service_id_hash.get())); ScopedPtr<Ptr<WifiLanServiceInfo> > scoped_wifi_lan_service_info( WifiLanServiceInfo::FromString(wifi_lan_service_info_string)); EXPECT_EQ(kPcp, scoped_wifi_lan_service_info->GetPcp()); EXPECT_EQ(kVersion, scoped_wifi_lan_service_info->GetVersion()); EXPECT_EQ(kEndPointID, scoped_wifi_lan_service_info->GetEndpointId()); EXPECT_EQ(*scoped_service_id_hash, *(scoped_wifi_lan_service_info->GetServiceIdHash())); } TEST(WifiLanServiceInfoTest, SerializationDeserializationWorksWithEmptyEndpointName) { ScopedPtr<Ptr<ByteArray> > scoped_service_id_hash(new ByteArray( kServiceIDHashBytes, sizeof(kServiceIDHashBytes) / sizeof(char))); std::string wifi_lan_service_info_string = WifiLanServiceInfo::AsString( kVersion, kPcp, kEndPointID, ConstifyPtr(scoped_service_id_hash.get())); ScopedPtr<Ptr<WifiLanServiceInfo> > scoped_wifi_lan_service_info( WifiLanServiceInfo::FromString(wifi_lan_service_info_string)); EXPECT_EQ(kPcp, scoped_wifi_lan_service_info->GetPcp()); EXPECT_EQ(kVersion, scoped_wifi_lan_service_info->GetVersion()); EXPECT_EQ(kEndPointID, scoped_wifi_lan_service_info->GetEndpointId()); EXPECT_EQ(*scoped_service_id_hash, *(scoped_wifi_lan_service_info->GetServiceIdHash())); } TEST(WifiLanServiceInfoTest, SerializationFailsWithBadVersion) { WifiLanServiceInfo::Version bad_version = static_cast<WifiLanServiceInfo::Version>(666); ScopedPtr<Ptr<ByteArray> > scoped_service_id_hash(new ByteArray( kServiceIDHashBytes, sizeof(kServiceIDHashBytes) / sizeof(char))); std::string wifi_lan_service_info_string = WifiLanServiceInfo::AsString(bad_version, kPcp, kEndPointID, ConstifyPtr(scoped_service_id_hash.get())); EXPECT_TRUE(wifi_lan_service_info_string.empty()); } TEST(WifiLanServiceInfoTest, SerializationFailsWithBadPCP) { PCP::Value bad_pcp = static_cast<PCP::Value>(666); ScopedPtr<Ptr<ByteArray> > scoped_service_id_hash(new ByteArray( kServiceIDHashBytes, sizeof(kServiceIDHashBytes) / sizeof(char))); std::string wifi_lan_service_info_string = WifiLanServiceInfo::AsString(kVersion, bad_pcp, kEndPointID, ConstifyPtr(scoped_service_id_hash.get())); EXPECT_TRUE(wifi_lan_service_info_string.empty()); } TEST(WifiLanServiceInfoTest, SerializationFailsWithShortEndpointId) { std::string short_endpoint_id("AB1"); ScopedPtr<Ptr<ByteArray> > scoped_service_id_hash(new ByteArray( kServiceIDHashBytes, sizeof(kServiceIDHashBytes) / sizeof(char))); std::string wifi_lan_service_info_string = WifiLanServiceInfo::AsString(kVersion, kPcp, short_endpoint_id, ConstifyPtr(scoped_service_id_hash.get())); EXPECT_TRUE(wifi_lan_service_info_string.empty()); } TEST(WifiLanServiceInfoTest, SerializationFailsWithLongEndpointId) { std::string long_endpoint_id("AB12X"); ScopedPtr<Ptr<ByteArray> > scoped_service_id_hash(new ByteArray( kServiceIDHashBytes, sizeof(kServiceIDHashBytes) / sizeof(char))); std::string wifi_lan_service_info_string = WifiLanServiceInfo::AsString(kVersion, kPcp, long_endpoint_id, ConstifyPtr(scoped_service_id_hash.get())); EXPECT_TRUE(wifi_lan_service_info_string.empty()); } TEST(WifiLanServiceInfoTest, SerializationFailsWithShortServiceIdHash) { char short_service_id_hash_bytes[] = {0x0A, 0x0B}; ScopedPtr<Ptr<ByteArray> > scoped_short_service_id_hash( new ByteArray(short_service_id_hash_bytes, sizeof(short_service_id_hash_bytes) / sizeof(char))); std::string wifi_lan_service_info_string = WifiLanServiceInfo::AsString( kVersion, kPcp, kEndPointID, ConstifyPtr(scoped_short_service_id_hash.get())); EXPECT_TRUE(wifi_lan_service_info_string.empty()); } TEST(WifiLanServiceInfoTest, SerializationFailsWithLongServiceIdHash) { char long_service_id_hash_bytes[] = {0x0A, 0x0B, 0x0C, 0x0D}; ScopedPtr<Ptr<ByteArray> > scoped_long_service_id_hash( new ByteArray(long_service_id_hash_bytes, sizeof(long_service_id_hash_bytes) / sizeof(char))); std::string wifi_lan_service_info_string = WifiLanServiceInfo::AsString( kVersion, kPcp, kEndPointID, ConstifyPtr(scoped_long_service_id_hash.get())); EXPECT_TRUE(wifi_lan_service_info_string.empty()); } TEST(WifiLanServiceInfoTest, DeserializationFailsWithShortLength) { char wifi_lan_service_info_bytes[] = {'X'}; ScopedPtr<Ptr<ByteArray> > scoped_wifi_lan_service_info_bytes( new ByteArray(wifi_lan_service_info_bytes, sizeof(wifi_lan_service_info_bytes) / sizeof(char))); ScopedPtr<Ptr<WifiLanServiceInfo> > scoped_wifi_lan_service_info( WifiLanServiceInfo::FromString(Base64Utils::encode( ConstifyPtr(scoped_wifi_lan_service_info_bytes.get())))); EXPECT_TRUE(scoped_wifi_lan_service_info.isNull()); } } // namespace } // namespace connections } // namespace nearby } // namespace location
39.222892
78
0.762402
jdapena
79c8029e5cfc8810f496c4c017a5f35d9ef79287
2,051
hpp
C++
kernel/eir/arch/arm/eir-internal/arch/pl011.hpp
kITerE/managarm
e6d1229a0bed68cb672a9cad300345a9006d78c1
[ "MIT" ]
935
2018-05-23T14:56:18.000Z
2022-03-29T07:27:20.000Z
kernel/eir/arch/arm/eir-internal/arch/pl011.hpp
kITerE/managarm
e6d1229a0bed68cb672a9cad300345a9006d78c1
[ "MIT" ]
314
2018-05-04T15:58:06.000Z
2022-03-30T16:24:17.000Z
kernel/eir/arch/arm/eir-internal/arch/pl011.hpp
kITerE/managarm
e6d1229a0bed68cb672a9cad300345a9006d78c1
[ "MIT" ]
65
2019-04-21T14:26:51.000Z
2022-03-12T03:16:41.000Z
#pragma once #include <stdint.h> #include <arch/mem_space.hpp> #include <arch/register.hpp> namespace eir { namespace pl011_reg { static constexpr arch::scalar_register<uint32_t> data{0x00}; static constexpr arch::bit_register<uint32_t> status{0x18}; static constexpr arch::scalar_register<uint32_t> i_baud{0x24}; static constexpr arch::scalar_register<uint32_t> f_baud{0x28}; static constexpr arch::bit_register<uint32_t> control{0x30}; static constexpr arch::bit_register<uint32_t> line_control{0x2c}; static constexpr arch::scalar_register<uint32_t> int_clear{0x44}; } namespace pl011_status { static constexpr arch::field<uint32_t, bool> tx_full{5, 1}; }; namespace pl011_control { static constexpr arch::field<uint32_t, bool> rx_en{9, 1}; static constexpr arch::field<uint32_t, bool> tx_en{8, 1}; static constexpr arch::field<uint32_t, bool> uart_en{0, 1}; }; namespace pl011_line_control { static constexpr arch::field<uint32_t, uint8_t> word_len{5, 2}; static constexpr arch::field<uint32_t, bool> fifo_en{4, 1}; } struct PL011 { PL011(uintptr_t base, uint64_t clock) : space_{base}, clock_{clock} { } void disable() { space_.store(pl011_reg::control, pl011_control::uart_en(false)); } void init(uint64_t baud) { disable(); uint64_t int_part = clock_ / (16 * baud); // 3 decimal places of precision should be enough :^) uint64_t frac_part = (((clock_ * 1000) / (16 * baud) - (int_part * 1000)) * 64 + 500) / 1000; space_.store(pl011_reg::i_baud, int_part); space_.store(pl011_reg::f_baud, frac_part); // 8n1, fifo enabled space_.store(pl011_reg::line_control, pl011_line_control::word_len(3) | pl011_line_control::fifo_en(true)); space_.store(pl011_reg::control, pl011_control::rx_en(true) | pl011_control::tx_en(true) | pl011_control::uart_en(true)); } void send(uint8_t val) { while (space_.load(pl011_reg::status) & pl011_status::tx_full) ; space_.store(pl011_reg::data, val); } private: arch::mem_space space_; uint64_t clock_; }; } // namespace eir
26.636364
75
0.7255
kITerE
79cc8462db5e2701abb1256d516c7d0ccc627ab3
1,330
cpp
C++
code/components/net/src/NetBuffer.cpp
antonand03/hello-my-friend
fb4e225a75aea3007a391ccc4dcda3eda65c2142
[ "MIT" ]
6
2019-01-30T14:33:30.000Z
2021-07-21T18:06:52.000Z
code/components/net/src/NetBuffer.cpp
antonand03/hello-my-friend
fb4e225a75aea3007a391ccc4dcda3eda65c2142
[ "MIT" ]
6
2021-05-11T09:09:11.000Z
2022-03-23T18:34:23.000Z
code/components/net/src/NetBuffer.cpp
antonand03/hello-my-friend
fb4e225a75aea3007a391ccc4dcda3eda65c2142
[ "MIT" ]
22
2018-11-17T17:19:01.000Z
2021-05-22T09:51:07.000Z
/* * This file is part of the CitizenFX project - http://citizen.re/ * * See LICENSE and MENTIONS in the root of the source tree for information * regarding licensing. */ #include "StdInc.h" #include "NetBuffer.h" NetBuffer::NetBuffer(const char* bytes, size_t length) : m_bytesManaged(false), m_bytes(const_cast<char*>(bytes)), m_curOff(0), m_length(length), m_end(false) { } NetBuffer::NetBuffer(size_t length) : m_length(length), m_curOff(0), m_bytesManaged(true), m_end(false) { m_bytes = new char[length]; } NetBuffer::~NetBuffer() { if (m_bytesManaged) { delete[] m_bytes; } } bool NetBuffer::Read(void* buffer, size_t length) { if ((m_curOff + length) >= m_length) { m_end = true; // and if it really doesn't fit out of our buffer if ((m_curOff + length) > m_length) { memset(buffer, 0xCE, length); return false; } } memcpy(buffer, &m_bytes[m_curOff], length); m_curOff += length; return true; } void NetBuffer::Write(const void* buffer, size_t length) { if ((m_curOff + length) >= m_length) { m_end = true; if ((m_curOff + length) > m_length) { return; } } memcpy(&m_bytes[m_curOff], buffer, length); m_curOff += length; } bool NetBuffer::End() { return (m_end || m_curOff == m_length); }
19
105
0.63609
antonand03
79d68d05282cb4ad32b0827ca13108ef551b0748
1,358
cc
C++
sources/utility/misc.cc
jujudusud/gmajctl
b15466168b94ee6bc4731fc77d2b2dd0e36dc995
[ "BSL-1.0" ]
4
2018-11-01T23:38:33.000Z
2021-04-22T11:29:07.000Z
sources/utility/misc.cc
jujudusud/gmajctl
b15466168b94ee6bc4731fc77d2b2dd0e36dc995
[ "BSL-1.0" ]
10
2018-10-17T21:16:01.000Z
2019-09-29T21:51:58.000Z
sources/utility/misc.cc
linuxmao-org/FreeMajor
41bca20fce919e63a918aa472411652031e19ec5
[ "BSL-1.0" ]
1
2018-10-03T22:31:34.000Z
2018-10-03T22:31:34.000Z
// Copyright Jean Pierre Cimalando 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "misc.h" bool starts_with(const char *x, const char *s) { size_t nx = strlen(x), ns = strlen(s); return nx >= ns && !memcmp(s, x, ns); } bool ends_with(const char *x, const char *s) { size_t nx = strlen(x), ns = strlen(s); return nx >= ns && !memcmp(s, x + nx - ns, ns); } bool read_entire_file(FILE *fh, size_t max_size, std::vector<uint8_t> &data) { struct stat st; if (fstat(fileno(fh), &st) != 0) return false; size_t size = st.st_size; if (size > max_size) return false; data.resize(size); rewind(fh); return fread(data.data(), 1, size, fh) == size; } std::string file_name_extension(const std::string &fn) { size_t n = fn.size(); for (size_t i = n; i-- > 0;) { char c = fn[i]; if (c == '.') return fn.substr(i); else if (c == '/') break; #if defined(_WIN32) else if (c == '\\') break; #endif } return std::string(); } std::string file_name_without_extension(const std::string &fn) { std::string ext = file_name_extension(fn); return fn.substr(0, fn.size() - ext.size()); }
23.824561
76
0.574374
jujudusud
79d6c4ed083b737e8231c8bc457bdee982554ed1
391
hpp
C++
lib/rendering/ray.hpp
julienlopez/Raytracer
35fa5a00e190592a8780971fcbd2936a54e06d3a
[ "MIT" ]
null
null
null
lib/rendering/ray.hpp
julienlopez/Raytracer
35fa5a00e190592a8780971fcbd2936a54e06d3a
[ "MIT" ]
2
2017-06-01T16:43:37.000Z
2017-06-07T16:17:51.000Z
lib/rendering/ray.hpp
julienlopez/Raytracer
35fa5a00e190592a8780971fcbd2936a54e06d3a
[ "MIT" ]
null
null
null
#pragma once #include "math/types.hpp" namespace Rendering { class Ray { public: Ray(const Math::Point3d& origin_, const Math::Vector3d& direction_); ~Ray() = default; const Math::Point3d& origin() const; const Math::Vector3d& direction() const; Math::Vector3d& direction(); private: Math::Point3d m_origin; Math::Vector3d m_direction; }; } // Rendering
14.481481
72
0.667519
julienlopez
79df904e6678cf595472d70326b9395ee90aa4ed
937
cpp
C++
Factorio-Imitation/DeactiveButtonUI.cpp
JiokKae/Factorio-Imitation
06b6328a48926e64b376ff8e985eedef22f06c14
[ "MIT" ]
2
2020-12-24T10:38:46.000Z
2021-04-23T11:44:48.000Z
Factorio-Imitation/DeactiveButtonUI.cpp
JiokKae/Factorio-Imitation
06b6328a48926e64b376ff8e985eedef22f06c14
[ "MIT" ]
null
null
null
Factorio-Imitation/DeactiveButtonUI.cpp
JiokKae/Factorio-Imitation
06b6328a48926e64b376ff8e985eedef22f06c14
[ "MIT" ]
null
null
null
#include "DeactiveButtonUI.h" #include "GLImage.h" HRESULT DeactiveButtonUI::Init() { image = new GLImage(); image->Init("UI/DeactiveButtonUI", 3, 1); onMouse = false; return S_OK; } void DeactiveButtonUI::Release() { } void DeactiveButtonUI::Update() { if (active) { if (PtInFRect(GetFrect(), { g_ptMouse.x, g_ptMouse.y })) { onMouse = true; if (isMouseDown) { if (KeyManager::GetSingleton()->IsOnceKeyUp(VK_LBUTTON)) { SoundManager::GetSingleton()->Play("GUI-ToolButton", 0.6f); UIManager::GetSingleton()->DeactiveUI(); } } if (KeyManager::GetSingleton()->IsStayKeyDown(VK_LBUTTON)) { isMouseDown = true; } else isMouseDown = false; } else { onMouse = false; isMouseDown = false; } } } void DeactiveButtonUI::Render(Shader* lpShader) { if (active) { image->Render(lpShader, GetPosition().x, GetPosition().y, onMouse + isMouseDown, 0); } }
16.155172
86
0.640342
JiokKae
0763c29128af9170301bb0fc5996c9ce36f327b0
5,936
hpp
C++
testing_utilities/discrete_trajectory_factories_body.hpp
net-lisias-ksp/Principia
9292ea1fc2e4b4f0ce7a717e2f507168519f5f8a
[ "MIT" ]
null
null
null
testing_utilities/discrete_trajectory_factories_body.hpp
net-lisias-ksp/Principia
9292ea1fc2e4b4f0ce7a717e2f507168519f5f8a
[ "MIT" ]
null
null
null
testing_utilities/discrete_trajectory_factories_body.hpp
net-lisias-ksp/Principia
9292ea1fc2e4b4f0ce7a717e2f507168519f5f8a
[ "MIT" ]
null
null
null
#pragma once #include "testing_utilities/discrete_trajectory_factories.hpp" #include "base/status_utilities.hpp" #include "physics/degrees_of_freedom.hpp" #include "physics/discrete_trajectory_segment.hpp" #include "physics/discrete_trajectory_segment_iterator.hpp" #include "quantities/elementary_functions.hpp" #include "quantities/si.hpp" namespace principia { namespace testing_utilities { namespace internal_discrete_trajectory_factories { using base::check_not_null; using base::make_not_null_unique; using geometry::Displacement; using geometry::Velocity; using physics::DegreesOfFreedom; using physics::DiscreteTrajectorySegment; using physics::DiscreteTrajectorySegmentIterator; using quantities::Cos; using quantities::Pow; using quantities::Sin; using quantities::Speed; using quantities::si::Radian; template<typename Frame> absl::Status DiscreteTrajectoryFactoriesFriend<Frame>::Append( Instant const& t, DegreesOfFreedom<Frame> const& degrees_of_freedom, DiscreteTrajectorySegment<Frame>& segment) { return segment.Append(t, degrees_of_freedom); } template<typename Frame> Timeline<Frame> NewMotionlessTrajectoryTimeline(Position<Frame> const& position, Time const& Δt, Instant const& t1, Instant const& t2) { return NewLinearTrajectoryTimeline( DegreesOfFreedom<Frame>(position, Velocity<Frame>()), Δt, t1, t2); } template<typename Frame> Timeline<Frame> NewLinearTrajectoryTimeline(DegreesOfFreedom<Frame> const& degrees_of_freedom, Time const& Δt, Instant const& t0, Instant const& t1, Instant const& t2) { Timeline<Frame> timeline; for (auto t = t1; t < t2; t += Δt) { auto const velocity = degrees_of_freedom.velocity(); auto const position = degrees_of_freedom.position() + velocity * (t - t0); timeline.emplace(t, DegreesOfFreedom<Frame>(position, velocity)); } return timeline; } template<typename Frame> Timeline<Frame> NewLinearTrajectoryTimeline(DegreesOfFreedom<Frame> const& degrees_of_freedom, Time const& Δt, Instant const& t1, Instant const& t2) { return NewLinearTrajectoryTimeline(degrees_of_freedom, Δt, /*t0=*/t1, t1, t2); } template<typename Frame> Timeline<Frame> NewLinearTrajectoryTimeline(Velocity<Frame> const& v, Time const& Δt, Instant const& t1, Instant const& t2) { return NewLinearTrajectoryTimeline( DegreesOfFreedom<Frame>(Frame::origin, v), Δt, /*t0=*/t1, t1, t2); } template<typename Frame> Timeline<Frame> NewAcceleratedTrajectoryTimeline( DegreesOfFreedom<Frame> const& degrees_of_freedom, Vector<Acceleration, Frame> const& acceleration, Time const& Δt, Instant const& t1, Instant const& t2) { static Instant const t0; Timeline<Frame> timeline; for (auto t = t1; t < t2; t += Δt) { auto const velocity = degrees_of_freedom.velocity() + acceleration * (t - t0); auto const position = degrees_of_freedom.position() + degrees_of_freedom.velocity() * (t - t0) + acceleration * Pow<2>(t - t0) * 0.5; timeline.emplace(t, DegreesOfFreedom<Frame>(position, velocity)); } return timeline; } template<typename Frame> Timeline<Frame> NewCircularTrajectoryTimeline(AngularFrequency const& ω, Length const& r, Time const& Δt, Instant const& t1, Instant const& t2) { static Instant const t0; Timeline<Frame> timeline; Speed const v = ω * r / Radian; for (auto t = t1; t < t2; t += Δt) { DegreesOfFreedom<Frame> const dof = { Frame::origin + Displacement<Frame>{{r * Cos(ω * (t - t0)), r * Sin(ω * (t - t0)), Length{}}}, Velocity<Frame>{{-v * Sin(ω * (t - t0)), v * Cos(ω * (t - t0)), Speed{}}}}; timeline.emplace(t, dof); } return timeline; } template<typename Frame> Timeline<Frame> NewCircularTrajectoryTimeline(Time const& period, Length const& r, Time const& Δt, Instant const& t1, Instant const& t2) { return NewCircularTrajectoryTimeline<Frame>(/*ω=*/2 * π * Radian / period, r, Δt, t1, t2); } template<typename Frame> void AppendTrajectoryTimeline(Timeline<Frame> const& from, DiscreteTrajectorySegment<Frame>& to) { for (auto const& [t, degrees_of_freedom] : from) { CHECK_OK(DiscreteTrajectoryFactoriesFriend<Frame>::Append( t, degrees_of_freedom, to)); } } template<typename Frame> void AppendTrajectoryTimeline(Timeline<Frame> const& from, DiscreteTrajectory<Frame>& to) { for (auto const& [t, degrees_of_freedom] : from) { CHECK_OK(to.Append(t, degrees_of_freedom)); } } template<typename Frame> void AppendTrajectoryTimeline( Timeline<Frame> const& from, std::function<void( Instant const& time, DegreesOfFreedom<Frame> const& degrees_of_freedom)> const& append_to) { for (auto const& [t, degrees_of_freedom] : from) { append_to(t, degrees_of_freedom); } } } // namespace internal_discrete_trajectory_factories } // namespace testing_utilities } // namespace principia
35.12426
80
0.60091
net-lisias-ksp
076581d0398811b88e5e93ac46448596bd777e94
15,188
cpp
C++
src/test-rhi.cpp
sgorsten/workbench
5209bb405e0e0f4696b36684bbd1d7ecff7daa2f
[ "Unlicense" ]
16
2015-12-15T17:17:37.000Z
2021-12-07T20:19:38.000Z
src/test-rhi.cpp
sgorsten/workbench
5209bb405e0e0f4696b36684bbd1d7ecff7daa2f
[ "Unlicense" ]
null
null
null
src/test-rhi.cpp
sgorsten/workbench
5209bb405e0e0f4696b36684bbd1d7ecff7daa2f
[ "Unlicense" ]
1
2016-03-25T08:04:58.000Z
2016-03-25T08:04:58.000Z
#include "engine/pbr.h" #include "engine/mesh.h" #include "engine/sprite.h" #include "engine/camera.h" #include <chrono> #include <iostream> struct common_assets { coord_system game_coords; shader_compiler compiler; pbr::shaders standard; rhi::shader_desc vs, lit_fs, unlit_fs, skybox_vs, skybox_fs; image env_spheremap; mesh ground_mesh, box_mesh, sphere_mesh; sprite_sheet sheet; canvas_sprites sprites; font_face face; common_assets(loader & loader) : game_coords {coord_axis::right, coord_axis::forward, coord_axis::up}, compiler{loader}, standard{pbr::shaders::compile(compiler)}, sprites{sheet}, face{sheet, loader.load_ttf_font("arial.ttf", 20, 0x20, 0x7E)} { vs = compiler.compile_file(rhi::shader_stage::vertex, "static-mesh.vert"); lit_fs = compiler.compile_file(rhi::shader_stage::fragment, "textured-pbr.frag"); unlit_fs = compiler.compile_file(rhi::shader_stage::fragment, "colored-unlit.frag"); skybox_vs = compiler.compile_file(rhi::shader_stage::vertex, "skybox.vert"); skybox_fs = compiler.compile_file(rhi::shader_stage::fragment, "skybox.frag"); env_spheremap = loader.load_image("monument-valley.hdr", true); ground_mesh = make_quad_mesh(game_coords(coord_axis::right)*8.0f, game_coords(coord_axis::forward)*8.0f); box_mesh = make_box_mesh({-0.3f,-0.3f,-0.3f}, {0.3f,0.3f,0.3f}); sphere_mesh = make_sphere_mesh(32, 32, 0.5f); sheet.prepare_sheet(); } }; class device_session { const common_assets & assets; rhi::ptr<rhi::device> dev; pbr::device_objects standard; canvas_device_objects canvas_objects; rhi::device_info info; gfx::transient_resource_pool pools[3]; int pool_index=0; gfx::simple_mesh ground, box, sphere; rhi::ptr<rhi::image> font_image; rhi::ptr<rhi::image> checkerboard; pbr::environment_map env; rhi::ptr<rhi::sampler> nearest; rhi::ptr<rhi::descriptor_set_layout> per_scene_layout, per_view_layout, skybox_material_layout, pbr_material_layout, static_object_layout; rhi::ptr<rhi::pipeline_layout> common_layout, object_layout, skybox_layout; rhi::ptr<rhi::pipeline> light_pipe, solid_pipe, skybox_pipe; std::unique_ptr<gfx::window> gwindow; double2 last_cursor; public: device_session(common_assets & assets, const std::string & name, rhi::ptr<rhi::device> dev, const int2 & window_pos) : assets{assets}, dev{dev}, standard{dev, assets.standard}, canvas_objects{*dev, assets.compiler, assets.sheet}, info{dev->get_info()}, pools{*dev, *dev, *dev} { // Buffers ground = {*dev, assets.ground_mesh.vertices, assets.ground_mesh.triangles}; box = {*dev, assets.box_mesh.vertices, assets.box_mesh.triangles}; sphere = {*dev, assets.sphere_mesh.vertices, assets.sphere_mesh.triangles}; // Samplers nearest = dev->create_sampler({rhi::filter::nearest, rhi::filter::nearest, std::nullopt, rhi::address_mode::clamp_to_edge, rhi::address_mode::repeat}); // Images const byte4 w{255,255,255,255}, g{128,128,128,255}, grid[]{w,g,w,g,g,w,g,w,w,g,w,g,g,w,g,w}; checkerboard = dev->create_image({rhi::image_shape::_2d, {4,4,1}, 1, rhi::image_format::rgba_unorm8, rhi::sampled_image_bit}, {grid}); font_image = dev->create_image({rhi::image_shape::_2d, {assets.sheet.sheet_image.dims(),1}, 1, rhi::image_format::r_unorm8, rhi::sampled_image_bit}, {assets.sheet.sheet_image.data()}); auto env_spheremap = dev->create_image({rhi::image_shape::_2d, {assets.env_spheremap.dimensions,1}, 1, assets.env_spheremap.format, rhi::sampled_image_bit}, {assets.env_spheremap.get_pixels()}); // Descriptor set layouts per_scene_layout = dev->create_descriptor_set_layout({ {0, rhi::descriptor_type::uniform_buffer, 1}, {1, rhi::descriptor_type::combined_image_sampler, 1}, {2, rhi::descriptor_type::combined_image_sampler, 1}, {3, rhi::descriptor_type::combined_image_sampler, 1} }); per_view_layout = dev->create_descriptor_set_layout({ {0, rhi::descriptor_type::uniform_buffer, 1} }); skybox_material_layout = dev->create_descriptor_set_layout({ {0, rhi::descriptor_type::combined_image_sampler, 1} }); pbr_material_layout = dev->create_descriptor_set_layout({ {0, rhi::descriptor_type::uniform_buffer, 1}, {1, rhi::descriptor_type::combined_image_sampler, 1} }); static_object_layout = dev->create_descriptor_set_layout({ {0, rhi::descriptor_type::uniform_buffer, 1}, }); // Pipeline layouts common_layout = dev->create_pipeline_layout({per_scene_layout, per_view_layout}); skybox_layout = dev->create_pipeline_layout({per_scene_layout, per_view_layout, skybox_material_layout}); object_layout = dev->create_pipeline_layout({per_scene_layout, per_view_layout, pbr_material_layout, static_object_layout}); const auto mesh_vertex_binding = gfx::vertex_binder<mesh_vertex>(0) .attribute(0, &mesh_vertex::position) .attribute(1, &mesh_vertex::normal) .attribute(2, &mesh_vertex::texcoord) .attribute(3, &mesh_vertex::tangent) .attribute(4, &mesh_vertex::bitangent); const auto ui_vertex_binding = gfx::vertex_binder<ui_vertex>(0) .attribute(0, &ui_vertex::position) .attribute(1, &ui_vertex::texcoord) .attribute(2, &ui_vertex::color); // Shaders auto vs = dev->create_shader(assets.vs), lit_fs = dev->create_shader(assets.lit_fs), unlit_fs = dev->create_shader(assets.unlit_fs); auto skybox_vs = dev->create_shader(assets.skybox_vs), skybox_fs = dev->create_shader(assets.skybox_fs); // Blend states const rhi::blend_state opaque {true, false}; const rhi::blend_state translucent {true, true, {rhi::blend_factor::source_alpha, rhi::blend_op::add, rhi::blend_factor::one_minus_source_alpha}, {rhi::blend_factor::source_alpha, rhi::blend_op::add, rhi::blend_factor::one_minus_source_alpha}}; // Pipelines light_pipe = dev->create_pipeline({object_layout, {mesh_vertex_binding}, {vs,unlit_fs}, rhi::primitive_topology::triangles, rhi::front_face::counter_clockwise, rhi::cull_mode::back, rhi::depth_state{rhi::compare_op::less, true}, std::nullopt, {opaque}}); solid_pipe = dev->create_pipeline({object_layout, {mesh_vertex_binding}, {vs,lit_fs}, rhi::primitive_topology::triangles, rhi::front_face::counter_clockwise, rhi::cull_mode::back, rhi::depth_state{rhi::compare_op::less, true}, std::nullopt, {opaque}}); skybox_pipe = dev->create_pipeline({skybox_layout, {mesh_vertex_binding}, {skybox_vs,skybox_fs}, rhi::primitive_topology::triangles, rhi::front_face::clockwise, rhi::cull_mode::back, rhi::depth_state{rhi::compare_op::always, false}, std::nullopt, {opaque}}); // Do some initial work pools[pool_index].begin_frame(*dev); env = standard.create_environment_map_from_spheremap(pools[pool_index], *env_spheremap, 512, assets.game_coords); pools[pool_index].end_frame(*dev); // Window gwindow = std::make_unique<gfx::window>(*dev, int2{512,512}, to_string("Workbench 2018 Render Test (", name, ")")); gwindow->set_pos(window_pos); } bool update(camera & cam, float timestep) { const double2 cursor = gwindow->get_cursor_pos(); if(gwindow->get_mouse_button(GLFW_MOUSE_BUTTON_LEFT)) { cam.yaw += static_cast<float>(cursor.x - last_cursor.x) * 0.01f; cam.pitch = std::min(std::max(cam.pitch + static_cast<float>(cursor.y - last_cursor.y) * 0.01f, -1.5f), +1.5f); } last_cursor = cursor; const float cam_speed = timestep * 10; if(gwindow->get_key(GLFW_KEY_W)) cam.move(coord_axis::forward, cam_speed); if(gwindow->get_key(GLFW_KEY_A)) cam.move(coord_axis::left, cam_speed); if(gwindow->get_key(GLFW_KEY_S)) cam.move(coord_axis::back, cam_speed); if(gwindow->get_key(GLFW_KEY_D)) cam.move(coord_axis::right, cam_speed); return !gwindow->should_close(); } void render_frame(const camera & cam) { // Reset resources pool_index = (pool_index+1)%3; auto & pool = pools[pool_index]; pool.begin_frame(*dev); // Set up per scene uniforms pbr::scene_uniforms per_scene_uniforms {}; per_scene_uniforms.point_lights[0] = {{-3, -3, 8}, {23.47f, 21.31f, 20.79f}}; per_scene_uniforms.point_lights[1] = {{ 3, -3, 8}, {23.47f, 21.31f, 20.79f}}; per_scene_uniforms.point_lights[2] = {{ 3, 3, 8}, {23.47f, 21.31f, 20.79f}}; per_scene_uniforms.point_lights[3] = {{-3, 3, 8}, {23.47f, 21.31f, 20.79f}}; auto per_scene_set = pool.alloc_descriptor_set(*common_layout, pbr::scene_set_index); per_scene_set.write(0, per_scene_uniforms); per_scene_set.write(1, standard.get_image_sampler(), standard.get_brdf_integral_image()); per_scene_set.write(2, standard.get_cubemap_sampler(), *env.irradiance_cubemap); per_scene_set.write(3, standard.get_cubemap_sampler(), *env.reflectance_cubemap); auto cmd = dev->create_command_buffer(); // Set up per-view uniforms for a specific framebuffer auto & fb = gwindow->get_rhi_window().get_swapchain_framebuffer(); auto per_view_set = pool.alloc_descriptor_set(*common_layout, pbr::view_set_index); per_view_set.write(0, pbr::view_uniforms{cam, gwindow->get_aspect(), fb.get_ndc_coords(), info.z_range}); // Draw objects to our primary framebuffer rhi::render_pass_desc pass; pass.color_attachments = {{rhi::dont_care{}, rhi::store{rhi::layout::present_source}}}; pass.depth_attachment = {rhi::clear_depth{1.0f,0}, rhi::dont_care{}}; cmd->begin_render_pass(pass, fb); // Bind common descriptors per_scene_set.bind(*cmd); per_view_set.bind(*cmd); // Draw skybox cmd->bind_pipeline(*skybox_pipe); auto skybox_set = pool.descriptors->alloc(*skybox_material_layout); skybox_set->write(0, standard.get_cubemap_sampler(), *env.environment_cubemap); cmd->bind_descriptor_set(*skybox_layout, pbr::material_set_index, *skybox_set); box.draw(*cmd); // Draw lights cmd->bind_pipeline(*light_pipe); auto material_set = pool.descriptors->alloc(*pbr_material_layout); material_set->write(0, pool.uniforms.upload(pbr::material_uniforms{{0.5f,0.5f,0.5f},0.5f,0})); material_set->write(1, *nearest, *checkerboard); cmd->bind_descriptor_set(*object_layout, pbr::material_set_index, *material_set); for(auto & p : per_scene_uniforms.point_lights) { auto object_set = pool.descriptors->alloc(*static_object_layout); object_set->write(0, pool.uniforms.upload(pbr::object_uniforms{mul(translation_matrix(p.position), scaling_matrix(float3{0.5f}))})); cmd->bind_descriptor_set(*object_layout, pbr::object_set_index, *object_set); sphere.draw(*cmd); } // Draw the ground cmd->bind_pipeline(*solid_pipe); auto object_set = pool.descriptors->alloc(*static_object_layout); object_set->write(0, pool.uniforms.upload(pbr::object_uniforms{translation_matrix(cam.coords(coord_axis::down)*0.5f)})); cmd->bind_descriptor_set(*object_layout, pbr::object_set_index, *object_set); ground.draw(*cmd); // Draw a bunch of spheres for(int i=0; i<6; ++i) { for(int j=0; j<6; ++j) { material_set = pool.descriptors->alloc(*pbr_material_layout); material_set->write(0, pool.uniforms.upload(pbr::material_uniforms{{1,1,1},(j+0.5f)/6,(i+0.5f)/6})); material_set->write(1, *nearest, *checkerboard); cmd->bind_descriptor_set(*object_layout, pbr::material_set_index, *material_set); object_set = pool.descriptors->alloc(*static_object_layout); object_set->write(0, pool.uniforms.upload(pbr::object_uniforms{translation_matrix(cam.coords(coord_axis::right)*(i*2-5.f) + cam.coords(coord_axis::forward)*(j*2-5.f))})); cmd->bind_descriptor_set(*object_layout, pbr::object_set_index, *object_set); sphere.draw(*cmd); } } // Draw the UI canvas canvas {assets.sprites, canvas_objects, pool}; canvas.set_target(0, {{0,0},gwindow->get_window_size()}, nullptr); canvas.draw_rounded_rect({10,10,140,30+assets.face.line_height}, 6, {0,0,0,0.8f}); canvas.draw_shadowed_text({20,20}, {1,1,1,1}, assets.face, "This is a test"); canvas.encode_commands(*cmd, *gwindow); cmd->end_render_pass(); dev->acquire_and_submit_and_present(*cmd, gwindow->get_rhi_window()); pool.end_frame(*dev); } }; int main(int argc, const char * argv[]) try { // Run tests, if requested if(argc > 1 && strcmp("--test", argv[1]) == 0) { doctest::Context dt_context; dt_context.applyCommandLine(argc-1, argv+1); const int dt_return = dt_context.run(); if(dt_context.shouldExit()) return dt_return; } // Register asset paths std::cout << "Running from " << get_program_binary_path() << std::endl; loader loader; loader.register_root(get_program_binary_path() + "../../assets"); loader.register_root("C:/windows/fonts"); // Loader assets and initialize state common_assets assets{loader}; camera cam {assets.game_coords}; cam.pitch += 0.8f; cam.move(coord_axis::back, 10.0f); // Create a session for each device gfx::context context; auto debug = [](const char * message) { std::cerr << message << std::endl; }; int2 pos{100,100}; std::vector<std::unique_ptr<device_session>> sessions; for(auto & backend : context.get_clients()) { std::cout << "Initializing " << backend.name << " backend:\n"; sessions.push_back(std::make_unique<device_session>(assets, backend.name, backend.create_device(debug), pos)); std::cout << backend.name << " has been initialized." << std::endl; pos.x += 600; } // Main loop auto t0 = std::chrono::high_resolution_clock::now(); bool running = true; while(running) { // Render frame for(auto & s : sessions) s->render_frame(cam); // Poll events context.poll_events(); // Compute timestep const auto t1 = std::chrono::high_resolution_clock::now(); const auto timestep = std::chrono::duration<float>(t1-t0).count(); t0 = t1; // Handle input for(auto & s : sessions) if(!s->update(cam, timestep)) running = false; } return EXIT_SUCCESS; } catch(const std::exception & e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; }
47.021672
269
0.659139
sgorsten
07674e39420d832e82b3eaa032f85a1268b4f0b6
12,085
cpp
C++
Libraries/Audio/input_adcs.cpp
InspiredChaos/New_Visualizer_Skeleton
97967caa3cd74a3ea7a2727f9e886cadc44e8451
[ "MIT" ]
18
2020-04-15T11:58:46.000Z
2022-02-06T19:09:51.000Z
src/lib/Audio/input_adcs.cpp
ARSFI/HFSimulator
b6a5b32ea7bf45bc37c6ec74c55167bb2479d5ac
[ "MIT" ]
1
2018-12-07T01:38:43.000Z
2018-12-07T01:38:43.000Z
src/lib/Audio/input_adcs.cpp
ARSFI/HFSimulator
b6a5b32ea7bf45bc37c6ec74c55167bb2479d5ac
[ "MIT" ]
7
2020-05-09T19:53:34.000Z
2021-09-04T21:39:28.000Z
/* Audio Library for Teensy 3.X * Copyright (c) 2014, Paul Stoffregen, [email protected] * * Development of this audio library was funded by PJRC.COM, LLC by sales of * Teensy and Audio Adaptor boards. Please support PJRC's efforts to develop * open source software by purchasing Teensy or other PJRC products. * * Permission is hereby granted, free of charge, to any person obtaining 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, development funding 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. */ #include <Arduino.h> #include "input_adcs.h" #include "utility/pdb.h" #include "utility/dspinst.h" #if defined(__MK20DX256__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) #define COEF_HPF_DCBLOCK (1048300<<10) // DC Removal filter coefficient in S1.30 DMAMEM static uint16_t left_buffer[AUDIO_BLOCK_SAMPLES]; DMAMEM static uint16_t right_buffer[AUDIO_BLOCK_SAMPLES]; audio_block_t * AudioInputAnalogStereo::block_left = NULL; audio_block_t * AudioInputAnalogStereo::block_right = NULL; uint16_t AudioInputAnalogStereo::offset_left = 0; uint16_t AudioInputAnalogStereo::offset_right = 0; int32_t AudioInputAnalogStereo::hpf_y1[2] = { 0, 0 }; int32_t AudioInputAnalogStereo::hpf_x1[2] = { 0, 0 }; bool AudioInputAnalogStereo::update_responsibility = false; DMAChannel AudioInputAnalogStereo::dma0(false); DMAChannel AudioInputAnalogStereo::dma1(false); static int analogReadADC1(uint8_t pin); void AudioInputAnalogStereo::init(uint8_t pin0, uint8_t pin1) { uint32_t tmp; //pinMode(32, OUTPUT); //pinMode(33, OUTPUT); // Configure the ADC and run at least one software-triggered // conversion. This completes the self calibration stuff and // leaves the ADC in a state that's mostly ready to use analogReadRes(16); analogReference(INTERNAL); // range 0 to 1.2 volts #if F_BUS == 96000000 || F_BUS == 48000000 || F_BUS == 24000000 analogReadAveraging(8); ADC1_SC3 = ADC_SC3_AVGE + ADC_SC3_AVGS(1); #else analogReadAveraging(4); ADC1_SC3 = ADC_SC3_AVGE + ADC_SC3_AVGS(0); #endif // Note for review: // Probably not useful to spin cycles here stabilizing // since DC blocking is similar to te external analog filters tmp = (uint16_t) analogRead(pin0); tmp = ( ((int32_t) tmp) << 14); hpf_x1[0] = tmp; // With constant DC level x1 would be x0 hpf_y1[0] = 0; // Output will settle here when stable tmp = (uint16_t) analogReadADC1(pin1); tmp = ( ((int32_t) tmp) << 14); hpf_x1[1] = tmp; // With constant DC level x1 would be x0 hpf_y1[1] = 0; // Output will settle here when stable // set the programmable delay block to trigger the ADC at 44.1 kHz //if (!(SIM_SCGC6 & SIM_SCGC6_PDB) //|| (PDB0_SC & PDB_CONFIG) != PDB_CONFIG //|| PDB0_MOD != PDB_PERIOD //|| PDB0_IDLY != 1 //|| PDB0_CH0C1 != 0x0101) { SIM_SCGC6 |= SIM_SCGC6_PDB; PDB0_IDLY = 1; PDB0_MOD = PDB_PERIOD; PDB0_SC = PDB_CONFIG | PDB_SC_LDOK; PDB0_SC = PDB_CONFIG | PDB_SC_SWTRIG; PDB0_CH0C1 = 0x0101; PDB0_CH1C1 = 0x0101; //} // enable the ADC for hardware trigger and DMA ADC0_SC2 |= ADC_SC2_ADTRG | ADC_SC2_DMAEN; ADC1_SC2 |= ADC_SC2_ADTRG | ADC_SC2_DMAEN; // set up a DMA channel to store the ADC data dma0.begin(true); dma1.begin(true); // ADC0_RA = 0x4003B010 // ADC1_RA = 0x400BB010 dma0.TCD->SADDR = &ADC0_RA; dma0.TCD->SOFF = 0; dma0.TCD->ATTR = DMA_TCD_ATTR_SSIZE(1) | DMA_TCD_ATTR_DSIZE(1); dma0.TCD->NBYTES_MLNO = 2; dma0.TCD->SLAST = 0; dma0.TCD->DADDR = left_buffer; dma0.TCD->DOFF = 2; dma0.TCD->CITER_ELINKNO = sizeof(left_buffer) / 2; dma0.TCD->DLASTSGA = -sizeof(left_buffer); dma0.TCD->BITER_ELINKNO = sizeof(left_buffer) / 2; dma0.TCD->CSR = DMA_TCD_CSR_INTHALF | DMA_TCD_CSR_INTMAJOR; dma1.TCD->SADDR = &ADC1_RA; dma1.TCD->SOFF = 0; dma1.TCD->ATTR = DMA_TCD_ATTR_SSIZE(1) | DMA_TCD_ATTR_DSIZE(1); dma1.TCD->NBYTES_MLNO = 2; dma1.TCD->SLAST = 0; dma1.TCD->DADDR = right_buffer; dma1.TCD->DOFF = 2; dma1.TCD->CITER_ELINKNO = sizeof(right_buffer) / 2; dma1.TCD->DLASTSGA = -sizeof(right_buffer); dma1.TCD->BITER_ELINKNO = sizeof(right_buffer) / 2; dma1.TCD->CSR = DMA_TCD_CSR_INTHALF | DMA_TCD_CSR_INTMAJOR; dma0.triggerAtHardwareEvent(DMAMUX_SOURCE_ADC0); //dma1.triggerAtHardwareEvent(DMAMUX_SOURCE_ADC1); dma1.triggerAtTransfersOf(dma0); dma1.triggerAtCompletionOf(dma0); update_responsibility = update_setup(); dma0.enable(); dma1.enable(); dma0.attachInterrupt(isr0); dma1.attachInterrupt(isr1); } void AudioInputAnalogStereo::isr0(void) { uint32_t daddr, offset; const uint16_t *src, *end; uint16_t *dest; daddr = (uint32_t)(dma0.TCD->DADDR); dma0.clearInterrupt(); //digitalWriteFast(32, HIGH); if (daddr < (uint32_t)left_buffer + sizeof(left_buffer) / 2) { // DMA is receiving to the first half of the buffer // need to remove data from the second half src = (uint16_t *)&left_buffer[AUDIO_BLOCK_SAMPLES/2]; end = (uint16_t *)&left_buffer[AUDIO_BLOCK_SAMPLES]; } else { // DMA is receiving to the second half of the buffer // need to remove data from the first half src = (uint16_t *)&left_buffer[0]; end = (uint16_t *)&left_buffer[AUDIO_BLOCK_SAMPLES/2]; //if (update_responsibility) AudioStream::update_all(); } if (block_left != NULL) { offset = offset_left; if (offset > AUDIO_BLOCK_SAMPLES/2) offset = AUDIO_BLOCK_SAMPLES/2; offset_left = offset + AUDIO_BLOCK_SAMPLES/2; dest = (uint16_t *)&(block_left->data[offset]); do { *dest++ = *src++; } while (src < end); } //digitalWriteFast(32, LOW); } void AudioInputAnalogStereo::isr1(void) { uint32_t daddr, offset; const uint16_t *src, *end; uint16_t *dest; daddr = (uint32_t)(dma1.TCD->DADDR); dma1.clearInterrupt(); //digitalWriteFast(33, HIGH); if (daddr < (uint32_t)right_buffer + sizeof(right_buffer) / 2) { // DMA is receiving to the first half of the buffer // need to remove data from the second half src = (uint16_t *)&right_buffer[AUDIO_BLOCK_SAMPLES/2]; end = (uint16_t *)&right_buffer[AUDIO_BLOCK_SAMPLES]; if (update_responsibility) AudioStream::update_all(); } else { // DMA is receiving to the second half of the buffer // need to remove data from the first half src = (uint16_t *)&right_buffer[0]; end = (uint16_t *)&right_buffer[AUDIO_BLOCK_SAMPLES/2]; } if (block_right != NULL) { offset = offset_right; if (offset > AUDIO_BLOCK_SAMPLES/2) offset = AUDIO_BLOCK_SAMPLES/2; offset_right = offset + AUDIO_BLOCK_SAMPLES/2; dest = (uint16_t *)&(block_right->data[offset]); do { *dest++ = *src++; } while (src < end); } //digitalWriteFast(33, LOW); } void AudioInputAnalogStereo::update(void) { audio_block_t *new_left=NULL, *out_left=NULL; audio_block_t *new_right=NULL, *out_right=NULL; int32_t tmp; int16_t s, *p, *end; //Serial.println("update"); // allocate new block (ok if both NULL) new_left = allocate(); if (new_left == NULL) { new_right = NULL; } else { new_right = allocate(); if (new_right == NULL) { release(new_left); new_left = NULL; } } __disable_irq(); if (offset_left < AUDIO_BLOCK_SAMPLES || offset_right < AUDIO_BLOCK_SAMPLES) { // the DMA hasn't filled up both blocks if (block_left == NULL) { block_left = new_left; offset_left = 0; new_left = NULL; } if (block_right == NULL) { block_right = new_right; offset_right = 0; new_right = NULL; } __enable_irq(); if (new_left) release(new_left); if (new_right) release(new_right); return; } // the DMA filled blocks, so grab them and get the // new blocks to the DMA, as quickly as possible out_left = block_left; out_right = block_right; block_left = new_left; block_right = new_right; offset_left = 0; offset_right = 0; __enable_irq(); // // DC Offset Removal Filter // 1-pole digital high-pass filter implementation // y = a*(x[n] - x[n-1] + y[n-1]) // The coefficient "a" is as follows: // a = UNITY*e^(-2*pi*fc/fs) // fc = 2 @ fs = 44100 // // DC removal, LEFT p = out_left->data; end = p + AUDIO_BLOCK_SAMPLES; do { tmp = (uint16_t)(*p); tmp = ( ((int32_t) tmp) << 14); int32_t acc = hpf_y1[0] - hpf_x1[0]; acc += tmp; hpf_y1[0] = FRACMUL_SHL(acc, COEF_HPF_DCBLOCK, 1); hpf_x1[0] = tmp; s = signed_saturate_rshift(hpf_y1[0], 16, 14); *p++ = s; } while (p < end); // DC removal, RIGHT p = out_right->data; end = p + AUDIO_BLOCK_SAMPLES; do { tmp = (uint16_t)(*p); tmp = ( ((int32_t) tmp) << 14); int32_t acc = hpf_y1[1] - hpf_x1[1]; acc += tmp; hpf_y1[1]= FRACMUL_SHL(acc, COEF_HPF_DCBLOCK, 1); hpf_x1[1] = tmp; s = signed_saturate_rshift(hpf_y1[1], 16, 14); *p++ = s; } while (p < end); // then transmit the AC data transmit(out_left, 0); release(out_left); transmit(out_right, 1); release(out_right); } #if defined(__MK20DX256__) static const uint8_t pin2sc1a[] = { 5, 14, 8+128, 9+128, 13, 12, 6, 7, 15, 4, 0, 19, 3, 19+128, // 0-13 -> A0-A13 5, 14, 8+128, 9+128, 13, 12, 6, 7, 15, 4, // 14-23 are A0-A9 255, 255, // 24-25 are digital only 5+192, 5+128, 4+128, 6+128, 7+128, 4+192, // 26-31 are A15-A20 255, 255, // 32-33 are digital only 0, 19, 3, 19+128, // 34-37 are A10-A13 26, // 38 is temp sensor, 18+128, // 39 is vref 23 // 40 is A14 }; #elif defined(__MK64FX512__) || defined(__MK66FX1M0__) static const uint8_t pin2sc1a[] = { 5, 14, 8+128, 9+128, 13, 12, 6, 7, 15, 4, 3, 19+128, 14+128, 15+128, // 0-13 -> A0-A13 5, 14, 8+128, 9+128, 13, 12, 6, 7, 15, 4, // 14-23 are A0-A9 255, 255, 255, 255, 255, 255, 255, // 24-30 are digital only 14+128, 15+128, 17, 18, 4+128, 5+128, 6+128, 7+128, 17+128, // 31-39 are A12-A20 255, 255, 255, 255, 255, 255, 255, 255, 255, // 40-48 are digital only 10+128, 11+128, // 49-50 are A23-A24 255, 255, 255, 255, 255, 255, 255, // 51-57 are digital only 255, 255, 255, 255, 255, 255, // 58-63 (sd card pins) are digital only 3, 19+128, // 64-65 are A10-A11 23, 23+128,// 66-67 are A21-A22 (DAC pins) 1, 1+128, // 68-69 are A25-A26 (unused USB host port on Teensy 3.5) 26, // 70 is Temperature Sensor 18+128 // 71 is Vref }; #endif static int analogReadADC1(uint8_t pin) { ADC1_SC1A = 9; while (1) { if ((ADC1_SC1A & ADC_SC1_COCO)) { return ADC1_RA; } } if (pin >= sizeof(pin2sc1a)) return 0; uint8_t channel = pin2sc1a[pin]; if ((channel & 0x80) == 0) return 0; if (channel == 255) return 0; if (channel & 0x40) { ADC1_CFG2 &= ~ADC_CFG2_MUXSEL; } else { ADC1_CFG2 |= ADC_CFG2_MUXSEL; } ADC1_SC1A = channel & 0x3F; while (1) { if ((ADC1_SC1A & ADC_SC1_COCO)) { return ADC1_RA; } } } #else void AudioInputAnalogStereo::init(uint8_t pin0, uint8_t pin1) { } void AudioInputAnalogStereo::update(void) { } #endif
32.226667
94
0.659247
InspiredChaos
0767d5a2a29a50e096bbb849b5c876dab5329a7f
30,872
cpp
C++
dlls/Game/scene/MainMenu.cpp
Mynsu/sirtet_SFML
ad1b64597868959d96d27fcb73fd272f41b21e16
[ "MIT" ]
null
null
null
dlls/Game/scene/MainMenu.cpp
Mynsu/sirtet_SFML
ad1b64597868959d96d27fcb73fd272f41b21e16
[ "MIT" ]
null
null
null
dlls/Game/scene/MainMenu.cpp
Mynsu/sirtet_SFML
ad1b64597868959d96d27fcb73fd272f41b21e16
[ "MIT" ]
null
null
null
#include "../pch.h" #include "MainMenu.h" #include "../ServiceLocatorMirror.h" bool ::scene::MainMenu::IsInstantiated = false; ::scene::MainMenu::MainMenu( const sf::RenderWindow& window ) : mIsCursorOnButton( false ), mNextSceneID( ::scene::ID::AS_IS ) { ASSERT_TRUE( false == IsInstantiated ); loadResources( window ); IsInstantiated = true; } ::scene::MainMenu::~MainMenu( ) { IsInstantiated = false; } void scene::MainMenu::loadResources( const sf::RenderWindow& ) { std::string spritePath( "Images/MainMenu.png" ); mSoundPaths[(int)SoundIndex::BGM] = "Sounds/korobeiniki.mp3"; mSoundPaths[(int)SoundIndex::SELECTION] = "Sounds/selection.wav"; mDrawingInfo.logoSourcePosition.x = 0; mDrawingInfo.logoSourcePosition.y = 0; mDrawingInfo.logoClipSize.x = 256; mDrawingInfo.logoClipSize.y = 256; mDrawingInfo.logoDestinationPosition.x = 474.f; mDrawingInfo.logoDestinationPosition.y = 302.f; mDrawingInfo.buttonSingleSourcePosition.x = 0; mDrawingInfo.buttonSingleSourcePosition.y = 256; mDrawingInfo.buttonSingleClipSize.x = 256; mDrawingInfo.buttonSingleClipSize.y = 128; mDrawingInfo.buttonSinglePosition.x = 150.f; mDrawingInfo.buttonSinglePosition.y = 150.f; mDrawingInfo.buttonOnlineSourcePosition.x = 0; mDrawingInfo.buttonOnlineSourcePosition.y = 256+128; mDrawingInfo.buttonOnlineClipSize.x = 256; mDrawingInfo.buttonOnlineClipSize.y = 128; mDrawingInfo.buttonOnlinePosition.x = 150.f; mDrawingInfo.buttonOnlinePosition.y = 300.f; std::string fontPath( "Fonts/AGENCYB.ttf" ); uint16_t fontSize = 30; sf::Vector2f copyrightPosition( 150.f, 150.f ); std::string copyright; lua_State* lua = luaL_newstate(); const std::string scriptPath( "Scripts/MainMenu.lua" ); if ( true == luaL_dofile(lua, scriptPath.data()) ) { gService()->console().printFailure( FailureLevel::FATAL, "File Not Found: "+scriptPath ); } else { luaL_openlibs( lua ); const int TOP_IDX = -1; std::string tableName( "Sprite" ); lua_getglobal( lua, tableName.data() ); if ( false == lua_istable(lua, TOP_IDX) ) { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName, scriptPath ); } else { std::string field( "path" ); lua_pushstring( lua, field.data() ); lua_gettable( lua, 1 ); int type = lua_type(lua, TOP_IDX); if ( LUA_TSTRING == type ) { spritePath = lua_tostring(lua, TOP_IDX); } else if ( LUA_TNIL == type ) { gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND, tableName+':'+field, scriptPath ); } else { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+field, scriptPath ); } lua_pop( lua, 1 ); std::string innerTableName( "logo" ); lua_pushstring( lua, innerTableName.data() ); lua_gettable( lua, 1 ); if ( false == lua_istable(lua, TOP_IDX) ) { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+innerTableName, scriptPath ); } else { field = "sourceX"; lua_pushstring( lua, field.data() ); lua_gettable( lua, 2 ); type = lua_type(lua, TOP_IDX); if ( LUA_TNUMBER == type ) { const int32_t temp = (int32_t)lua_tointeger(lua, TOP_IDX); if ( 0 > temp ) { gService()->console().printScriptError( ExceptionType::RANGE_CHECK, tableName+':'+field, scriptPath ); } else { mDrawingInfo.logoSourcePosition.x = temp; } } else if ( LUA_TNIL == type ) { gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND, tableName+':'+innerTableName+':'+field, scriptPath ); } else { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+innerTableName+':'+field, scriptPath ); } lua_pop( lua, 1 ); field = "sourceY"; lua_pushstring( lua, field.data() ); lua_gettable( lua, 2 ); type = lua_type(lua, TOP_IDX); if ( LUA_TNUMBER == type ) { const int32_t temp = (int32_t)lua_tointeger(lua, TOP_IDX); if ( 0 > temp ) { gService()->console().printScriptError( ExceptionType::RANGE_CHECK, tableName+':'+field, scriptPath ); } else { mDrawingInfo.logoSourcePosition.y = temp; } } else if ( LUA_TNIL == type ) { gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND, tableName+':'+innerTableName+':'+field, scriptPath ); } else { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+innerTableName+':'+field, scriptPath ); } lua_pop( lua, 1 ); field = "clipWidth"; lua_pushstring( lua, field.data() ); lua_gettable( lua, 2 ); type = lua_type(lua, TOP_IDX); if ( LUA_TNUMBER == type ) { const int32_t temp = (int32_t)lua_tointeger(lua, TOP_IDX); if ( 0 > temp ) { gService()->console().printScriptError( ExceptionType::RANGE_CHECK, tableName+':'+field, scriptPath ); } else { mDrawingInfo.logoClipSize.x = temp; } } else if ( LUA_TNIL == type ) { gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND, tableName+':'+innerTableName+':'+field, scriptPath ); } else { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+innerTableName+':'+field, scriptPath ); } lua_pop( lua, 1 ); field = "clipHeight"; lua_pushstring( lua, field.data() ); lua_gettable( lua, 2 ); type = lua_type(lua, TOP_IDX); if ( LUA_TNUMBER == type ) { const int32_t temp = (int32_t)lua_tointeger(lua, TOP_IDX); if ( 0 > temp ) { gService()->console().printScriptError( ExceptionType::RANGE_CHECK, tableName+':'+field, scriptPath ); } else { mDrawingInfo.logoClipSize.y = temp; } } else if ( LUA_TNIL == type ) { gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND, tableName+':'+innerTableName+':'+field, scriptPath ); } else { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+innerTableName+':'+field, scriptPath ); } lua_pop( lua, 1 ); field = "destinationX"; lua_pushstring( lua, field.data() ); lua_gettable( lua, 2 ); type = lua_type(lua, TOP_IDX); if ( LUA_TNUMBER == type ) { const float temp = (float)lua_tonumber(lua, TOP_IDX); if ( 0 > temp ) { gService()->console().printScriptError( ExceptionType::RANGE_CHECK, tableName+':'+field, scriptPath ); } else { mDrawingInfo.logoDestinationPosition.x = temp; } } else if ( LUA_TNIL == type ) { gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND, tableName+':'+innerTableName+':'+field, scriptPath ); } else { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+innerTableName+':'+field, scriptPath ); } lua_pop( lua, 1 ); field = "destinationY"; lua_pushstring( lua, field.data() ); lua_gettable( lua, 2 ); type = lua_type(lua, TOP_IDX); if ( LUA_TNUMBER == type ) { const float temp = (float)lua_tonumber(lua, TOP_IDX); if ( 0 > temp ) { gService()->console().printScriptError( ExceptionType::RANGE_CHECK, tableName+':'+field, scriptPath ); } else { mDrawingInfo.logoDestinationPosition.y = temp; } } else if ( LUA_TNIL == type ) { gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND, tableName+':'+innerTableName+':'+field, scriptPath ); } else { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+innerTableName+':'+field, scriptPath ); } lua_pop( lua, 1 ); } lua_pop( lua, 1 ); innerTableName = "buttonSingle"; lua_pushstring( lua, innerTableName.data() ); lua_gettable( lua, 1 ); if ( false == lua_istable(lua, TOP_IDX) ) { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+innerTableName, scriptPath ); } else { field = "sourceX"; lua_pushstring( lua, field.data() ); lua_gettable( lua, 2 ); type = lua_type(lua, TOP_IDX); if ( LUA_TNUMBER == type ) { const int32_t temp = (int32_t)lua_tointeger(lua, TOP_IDX); if ( 0 > temp ) { gService()->console().printScriptError( ExceptionType::RANGE_CHECK, tableName+':'+field, scriptPath ); } else { mDrawingInfo.buttonSingleSourcePosition.x = temp; } } else if ( LUA_TNIL == type ) { gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND, tableName+':'+innerTableName+':'+field, scriptPath ); } else { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+innerTableName+':'+field, scriptPath ); } lua_pop( lua, 1 ); field = "sourceY"; lua_pushstring( lua, field.data() ); lua_gettable( lua, 2 ); type = lua_type(lua, TOP_IDX); if ( LUA_TNUMBER == type ) { const int32_t temp = (int32_t)lua_tointeger(lua, TOP_IDX); if ( 0 > temp ) { gService()->console().printScriptError( ExceptionType::RANGE_CHECK, tableName+':'+field, scriptPath ); } else { mDrawingInfo.buttonSingleSourcePosition.y = temp; } } else if ( LUA_TNIL == type ) { gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND, tableName+':'+innerTableName+':'+field, scriptPath ); } else { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+innerTableName+':'+field, scriptPath ); } lua_pop( lua, 1 ); field = "clipWidth"; lua_pushstring( lua, field.data() ); lua_gettable( lua, 2 ); type = lua_type(lua, TOP_IDX); if ( LUA_TNUMBER == type ) { const int32_t temp = (int32_t)lua_tointeger(lua, TOP_IDX); if ( 0 > temp ) { gService()->console().printScriptError( ExceptionType::RANGE_CHECK, tableName+':'+field, scriptPath ); } else { mDrawingInfo.buttonSingleClipSize.x = temp; } } else if ( LUA_TNIL == type ) { gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND, tableName+':'+innerTableName+':'+field, scriptPath ); } else { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+innerTableName+':'+field, scriptPath ); } lua_pop( lua, 1 ); field = "clipHeight"; lua_pushstring( lua, field.data() ); lua_gettable( lua, 2 ); type = lua_type(lua, TOP_IDX); if ( LUA_TNUMBER == type ) { const int32_t temp = (int32_t)lua_tointeger(lua, TOP_IDX); if ( 0 > temp ) { gService()->console().printScriptError( ExceptionType::RANGE_CHECK, tableName+':'+field, scriptPath ); } else { mDrawingInfo.buttonSingleClipSize.y = temp; } } else if ( LUA_TNIL == type ) { gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND, tableName+':'+innerTableName+':'+field, scriptPath ); } else { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+innerTableName+':'+field, scriptPath ); } lua_pop( lua, 1 ); field = "destinationX"; lua_pushstring( lua, field.data() ); lua_gettable( lua, 2 ); type = lua_type(lua, TOP_IDX); if ( LUA_TNUMBER == type ) { const float temp = (float)lua_tonumber(lua, TOP_IDX); if ( 0 > temp ) { gService()->console().printScriptError( ExceptionType::RANGE_CHECK, tableName+':'+field, scriptPath ); } else { mDrawingInfo.buttonSinglePosition.x = temp; } } else if ( LUA_TNIL == type ) { gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND, tableName+':'+innerTableName+':'+field, scriptPath ); } else { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+innerTableName+':'+field, scriptPath ); } lua_pop( lua, 1 ); field = "destinationY"; lua_pushstring( lua, field.data() ); lua_gettable( lua, 2 ); type = lua_type(lua, TOP_IDX); if ( LUA_TNUMBER == type ) { const float temp = (float)lua_tonumber(lua, TOP_IDX); if ( 0 > temp ) { gService()->console().printScriptError( ExceptionType::RANGE_CHECK, tableName+':'+field, scriptPath ); } else { mDrawingInfo.buttonSinglePosition.y = temp; } } else if ( LUA_TNIL == type ) { gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND, tableName+':'+innerTableName+':'+field, scriptPath ); } else { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+innerTableName+':'+field, scriptPath ); } lua_pop( lua, 1 ); } lua_pop( lua, 1 ); innerTableName = "buttonOnline"; lua_pushstring( lua, innerTableName.data() ); lua_gettable( lua, 1 ); if ( false == lua_istable(lua, TOP_IDX) ) { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+innerTableName, scriptPath ); } else { field = "sourceX"; lua_pushstring( lua, field.data() ); lua_gettable( lua, 2 ); type = lua_type(lua, TOP_IDX); if ( LUA_TNUMBER == type ) { const int32_t temp = (int32_t)lua_tointeger(lua, TOP_IDX); if ( 0 > temp ) { gService()->console().printScriptError( ExceptionType::RANGE_CHECK, tableName+':'+field, scriptPath ); } else { mDrawingInfo.buttonOnlineSourcePosition.x = temp; } } else if ( LUA_TNIL == type ) { gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND, tableName+':'+innerTableName+':'+field, scriptPath ); } else { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+innerTableName+':'+field, scriptPath ); } lua_pop( lua, 1 ); field = "sourceY"; lua_pushstring( lua, field.data() ); lua_gettable( lua, 2 ); type = lua_type(lua, TOP_IDX); if ( LUA_TNUMBER == type ) { const int32_t temp = (int32_t)lua_tointeger(lua, TOP_IDX); if ( 0 > temp ) { gService()->console().printScriptError( ExceptionType::RANGE_CHECK, tableName+':'+field, scriptPath ); } else { mDrawingInfo.buttonOnlineSourcePosition.y = temp; } } else if ( LUA_TNIL == type ) { gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND, tableName+':'+innerTableName+':'+field, scriptPath ); } else { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+innerTableName+':'+field, scriptPath ); } lua_pop( lua, 1 ); field = "clipWidth"; lua_pushstring( lua, field.data() ); lua_gettable( lua, 2 ); type = lua_type(lua, TOP_IDX); if ( LUA_TNUMBER == type ) { const int32_t temp = (int32_t)lua_tointeger(lua, TOP_IDX); if ( 0 > temp ) { gService()->console().printScriptError( ExceptionType::RANGE_CHECK, tableName+':'+field, scriptPath ); } else { mDrawingInfo.buttonOnlineClipSize.x = temp; } } else if ( LUA_TNIL == type ) { gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND, tableName+':'+innerTableName+':'+field, scriptPath ); } else { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+innerTableName+':'+field, scriptPath ); } lua_pop( lua, 1 ); field = "clipHeight"; lua_pushstring( lua, field.data() ); lua_gettable( lua, 2 ); type = lua_type(lua, TOP_IDX); if ( LUA_TNUMBER == type ) { const int32_t temp = (int32_t)lua_tointeger(lua, TOP_IDX); if ( 0 > temp ) { gService()->console().printScriptError( ExceptionType::RANGE_CHECK, tableName+':'+field, scriptPath ); } else { mDrawingInfo.buttonOnlineClipSize.y = temp; } } else if ( LUA_TNIL == type ) { gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND, tableName+':'+innerTableName+':'+field, scriptPath ); } else { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+innerTableName+':'+field, scriptPath ); } lua_pop( lua, 1 ); field = "destinationX"; lua_pushstring( lua, field.data() ); lua_gettable( lua, 2 ); type = lua_type(lua, TOP_IDX); if ( LUA_TNUMBER == type ) { const float temp = (float)lua_tonumber(lua, TOP_IDX); if ( 0 > temp ) { gService()->console().printScriptError( ExceptionType::RANGE_CHECK, tableName+':'+field, scriptPath ); } else { mDrawingInfo.buttonOnlinePosition.x = temp; } } else if ( LUA_TNIL == type ) { gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND, tableName+':'+innerTableName+':'+field, scriptPath ); } else { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+innerTableName+':'+field, scriptPath ); } lua_pop( lua, 1 ); field = "destinationY"; lua_pushstring( lua, field.data() ); lua_gettable( lua, 2 ); type = lua_type(lua, TOP_IDX); if ( LUA_TNUMBER == type ) { const float temp = (float)lua_tonumber(lua, TOP_IDX); if ( 0 > temp ) { gService()->console().printScriptError( ExceptionType::RANGE_CHECK, tableName+':'+field, scriptPath ); } else { mDrawingInfo.buttonOnlinePosition.y = temp; } } else if ( LUA_TNIL == type ) { gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND, tableName+':'+innerTableName+':'+field, scriptPath ); } else { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+innerTableName+':'+field, scriptPath ); } lua_pop( lua, 1 ); } lua_pop( lua, 1 ); } lua_pop( lua, 1 ); tableName = "Copyright"; lua_getglobal( lua, tableName.data() ); if ( false == lua_istable(lua, TOP_IDX) ) { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName, scriptPath ); } else { std::string field( "font" ); lua_pushstring( lua, field.data() ); lua_gettable( lua, 1 ); int type = lua_type(lua, TOP_IDX); if ( LUA_TSTRING == type ) { fontPath = lua_tostring(lua, TOP_IDX); } else if ( LUA_TNIL == type ) { gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND, tableName+':'+field, scriptPath ); } else { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+field, scriptPath ); } lua_pop( lua, 1 ); field = "fontSize"; lua_pushstring( lua, field.data() ); lua_gettable( lua, 1 ); type = lua_type(lua, TOP_IDX); if ( LUA_TNUMBER == type ) { const uint16_t temp = (uint16_t)lua_tointeger(lua, TOP_IDX); if ( temp < 0 ) { gService()->console().printScriptError( ExceptionType::RANGE_CHECK, tableName+':'+field, scriptPath ); } else { fontSize = temp; } } else if ( LUA_TNIL == type ) { gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND, tableName+':'+field, scriptPath ); } else { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+field, scriptPath ); } lua_pop( lua, 1 ); field = "positionX"; lua_pushstring( lua, field.data() ); lua_gettable( lua, 1 ); type = lua_type(lua, TOP_IDX); if ( LUA_TNUMBER == type ) { const float temp = (float)lua_tonumber(lua, TOP_IDX); if ( temp < 0 ) { gService()->console().printScriptError( ExceptionType::RANGE_CHECK, tableName+':'+field, scriptPath ); } else { copyrightPosition.x = temp; } } else if ( LUA_TNIL == type ) { gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND, tableName+':'+field, scriptPath ); } else { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+field, scriptPath ); } lua_pop( lua, 1 ); field = "positionY"; lua_pushstring( lua, field.data() ); lua_gettable( lua, 1 ); type = lua_type(lua, TOP_IDX); if ( LUA_TNUMBER == type ) { const float temp = (float)lua_tonumber(lua, TOP_IDX); if ( temp < 0 ) { gService()->console().printScriptError( ExceptionType::RANGE_CHECK, tableName+':'+field, scriptPath ); } else { copyrightPosition.y = temp; } } else if ( LUA_TNIL == type ) { gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND, tableName+':'+field, scriptPath ); } else { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+field, scriptPath ); } lua_pop( lua, 1 ); field = "text"; lua_pushstring( lua, field.data() ); lua_gettable( lua, 1 ); type = lua_type(lua, TOP_IDX); if ( LUA_TSTRING == type ) { copyright = lua_tostring(lua, TOP_IDX); } else if ( LUA_TNIL == type ) { gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND, tableName+':'+field, scriptPath ); } else { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+field, scriptPath ); } lua_pop( lua, 1 ); } lua_pop( lua, 1 ); tableName = "Sound"; lua_getglobal( lua, tableName.data() ); if ( false == lua_istable(lua, TOP_IDX) ) { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName, scriptPath ); } else { std::string innerTableName( "BGM" ); lua_pushstring( lua, innerTableName.data() ); lua_gettable( lua, 1 ); if ( false == lua_istable(lua, TOP_IDX) ) { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+innerTableName, scriptPath ); } else { std::string field( "path" ); lua_pushstring( lua, field.data() ); lua_gettable( lua, 2 ); int type = lua_type(lua, TOP_IDX); if ( LUA_TSTRING == type ) { mSoundPaths[(int)SoundIndex::BGM] = lua_tostring(lua, TOP_IDX); } else if ( LUA_TNIL == type ) { gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND, tableName+':'+field, scriptPath ); } else { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+field, scriptPath ); } lua_pop( lua, 1 ); } lua_pop( lua, 1 ); innerTableName = "onSelection"; lua_pushstring( lua, innerTableName.data() ); lua_gettable( lua, 1 ); if ( false == lua_istable(lua, TOP_IDX) ) { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+innerTableName, scriptPath ); } else { std::string field( "path" ); lua_pushstring( lua, field.data() ); lua_gettable( lua, 2 ); int type = lua_type(lua, TOP_IDX); if ( LUA_TSTRING == type ) { mSoundPaths[(int)SoundIndex::SELECTION] = lua_tostring(lua, TOP_IDX); } else if ( LUA_TNIL == type ) { gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND, tableName+':'+field, scriptPath ); } else { gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName+':'+field, scriptPath ); } lua_pop( lua, 1 ); } lua_pop( lua, 1 ); } lua_pop( lua, 1 ); } lua_close( lua ); if ( false == mTexture.loadFromFile(spritePath) ) { gService()->console().printFailure( FailureLevel::WARNING, "File Not Found: "+spritePath ); } mSprite.setTexture( mTexture ); if ( false == mFont.loadFromFile(fontPath) ) { gService()->console().printFailure( FailureLevel::WARNING, "File Not Found: "+fontPath ); } mTextLabelForCopyrightNotice.setCharacterSize( fontSize ); mTextLabelForCopyrightNotice.setFont( mFont ); mTextLabelForCopyrightNotice.setPosition( copyrightPosition ); mTextLabelForCopyrightNotice.setString( copyright ); if ( false == gService()->sound().playBGM(mSoundPaths[(int)SoundIndex::BGM], true) ) { gService()->console().printFailure(FailureLevel::WARNING, "File Not Found: "+mSoundPaths[(int)SoundIndex::BGM] ); } } ::scene::ID scene::MainMenu::update( std::vector<sf::Event>& eventQueue, const sf::RenderWindow& ) { for ( const sf::Event& it : eventQueue ) { if ( sf::Event::KeyPressed == it.type && sf::Keyboard::Escape == it.key.code ) { auto& vault = gService()->vault(); const auto it = vault.find(HK_IS_RUNNING); ASSERT_TRUE( vault.end() != it ); it->second = 0; } } return mNextSceneID; } void ::scene::MainMenu::draw( sf::RenderWindow& window ) { bool hasGainedFocus = false; auto& vault = gService()->vault(); { const auto it = vault.find(HK_HAS_GAINED_FOCUS); ASSERT_TRUE( vault.end() != it ); hasGainedFocus = (bool)it->second; } if ( true == hasGainedFocus && false == gService()->console().isVisible() ) { const sf::Vector2f mousePos( sf::Mouse::getPosition()-window.getPosition() ); const sf::FloatRect boundLogo( mDrawingInfo.logoDestinationPosition, sf::Vector2f(mDrawingInfo.logoClipSize) ); if ( true == boundLogo.contains(mousePos) ) { // Logo const sf::Vector2i sourcePos( mDrawingInfo.logoSourcePosition.x + mDrawingInfo.logoClipSize.x, mDrawingInfo.logoSourcePosition.y ); mSprite.setTextureRect( sf::IntRect(sourcePos, mDrawingInfo.logoClipSize) ); mSprite.setPosition( mDrawingInfo.logoDestinationPosition ); window.draw( mSprite ); // Copyright window.draw( mTextLabelForCopyrightNotice ); } else if ( const sf::FloatRect boundButtonSingle(mDrawingInfo.buttonSinglePosition, sf::Vector2f(mDrawingInfo.buttonSingleClipSize)); true == boundButtonSingle.contains(mousePos) ) { // Logo mSprite.setTextureRect( sf::IntRect(mDrawingInfo.logoSourcePosition, mDrawingInfo.logoClipSize) ); mSprite.setPosition( mDrawingInfo.logoDestinationPosition ); window.draw( mSprite ); if ( true == sf::Mouse::isButtonPressed(sf::Mouse::Left) ) { mNextSceneID = ::scene::ID::SINGLE_PLAY; } // Buttons const sf::Vector2i sourcePos( mDrawingInfo.buttonSingleSourcePosition.x + mDrawingInfo.buttonSingleClipSize.x, mDrawingInfo.buttonSingleSourcePosition.y ); mSprite.setTextureRect( sf::IntRect(sourcePos, mDrawingInfo.buttonSingleClipSize) ); mSprite.setPosition( mDrawingInfo.buttonSinglePosition ); window.draw( mSprite ); mSprite.setTextureRect( sf::IntRect(mDrawingInfo.buttonOnlineSourcePosition, mDrawingInfo.buttonOnlineClipSize) ); mSprite.setPosition( mDrawingInfo.buttonOnlinePosition ); window.draw( mSprite ); if ( false == mIsCursorOnButton ) { mIsCursorOnButton = true; if ( false == gService()->sound().playSFX(mSoundPaths[(int)SoundIndex::SELECTION]) ) { gService()->console().printFailure(FailureLevel::WARNING, "File Not Found: "+mSoundPaths[(int)SoundIndex::SELECTION] ); } } } else if ( const sf::FloatRect boundButtonOnline(mDrawingInfo.buttonOnlinePosition, sf::Vector2f(mDrawingInfo.buttonOnlineClipSize)); true == boundButtonOnline.contains(mousePos) ) { // Logo mSprite.setTextureRect( sf::IntRect(mDrawingInfo.logoSourcePosition, mDrawingInfo.logoClipSize) ); mSprite.setPosition( mDrawingInfo.logoDestinationPosition ); window.draw( mSprite ); if ( true == sf::Mouse::isButtonPressed(sf::Mouse::Left) ) { mNextSceneID = ::scene::ID::ONLINE_BATTLE; } // Buttons mSprite.setTextureRect( sf::IntRect(mDrawingInfo.buttonSingleSourcePosition, mDrawingInfo.buttonSingleClipSize) ); mSprite.setPosition( mDrawingInfo.buttonSinglePosition ); window.draw( mSprite ); const sf::Vector2i sourcePos( mDrawingInfo.buttonOnlineSourcePosition.x + mDrawingInfo.buttonOnlineClipSize.x, mDrawingInfo.buttonOnlineSourcePosition.y ); mSprite.setTextureRect( sf::IntRect(sourcePos, mDrawingInfo.buttonOnlineClipSize) ); mSprite.setPosition( mDrawingInfo.buttonOnlinePosition ); window.draw( mSprite ); if ( false == mIsCursorOnButton ) { mIsCursorOnButton = true; if ( false == gService()->sound().playSFX(mSoundPaths[(int)SoundIndex::SELECTION]) ) { gService()->console().printFailure(FailureLevel::WARNING, "File Not Found: "+mSoundPaths[(int)SoundIndex::SELECTION] ); } } } else { goto defaultLabel; } } else { defaultLabel: mSprite.setTextureRect( sf::IntRect(mDrawingInfo.logoSourcePosition, mDrawingInfo.logoClipSize) ); mSprite.setPosition( mDrawingInfo.logoDestinationPosition ); window.draw( mSprite ); mNextSceneID = ::scene::ID::AS_IS; mSprite.setPosition( mDrawingInfo.buttonSinglePosition ); mSprite.setTextureRect( sf::IntRect(mDrawingInfo.buttonSingleSourcePosition, mDrawingInfo.buttonSingleClipSize) ); window.draw( mSprite ); mSprite.setPosition( mDrawingInfo.buttonOnlinePosition ); mSprite.setTextureRect( sf::IntRect(mDrawingInfo.buttonOnlineSourcePosition, mDrawingInfo.buttonOnlineClipSize) ); window.draw( mSprite ); mIsCursorOnButton = false; } } ::scene::ID scene::MainMenu::currentScene( ) const { return ::scene::ID::MAIN_MENU; }
30.089669
113
0.616611
Mynsu
07692fe54f3ed175bee0929e758ecff96029093e
4,724
cpp
C++
addons/a3/language_f_tank/config.cpp
GoldJohnKing/Arma-III-Chinese-Localization-Enhanced
6ce8a75d1176adc2f1d5f4e9abd5dd2a1c581222
[ "MIT" ]
23
2017-07-13T16:15:55.000Z
2022-01-06T04:56:34.000Z
addons/a3/language_f_tank/config.cpp
GoldJohnKing/Arma-III-Chinese-Localization-Enhanced
6ce8a75d1176adc2f1d5f4e9abd5dd2a1c581222
[ "MIT" ]
3
2017-07-14T10:34:25.000Z
2021-02-28T18:42:43.000Z
addons/a3/language_f_tank/config.cpp
GoldJohnKing/Arma-III-Chinese-Localization-Enhanced
6ce8a75d1176adc2f1d5f4e9abd5dd2a1c581222
[ "MIT" ]
13
2017-07-14T04:13:43.000Z
2021-11-27T04:45:29.000Z
//////////////////////////////////////////////////////////////////// //DeRap: 新增資料夾\language_f_tank\config.bin //Produced from mikero's Dos Tools Dll version 6.80 //'now' is Sun Mar 31 23:01:41 2019 : 'file' last modified on Tue Jan 29 22:16:12 2019 //http://dev-heaven.net/projects/list_files/mikero-pbodll //////////////////////////////////////////////////////////////////// #define _ARMA_ //(13 Enums) enum { destructengine = 2, destructdefault = 6, destructwreck = 7, destructtree = 3, destructtent = 4, stabilizedinaxisx = 1, stabilizedinaxesxyz = 4, stabilizedinaxisy = 2, stabilizedinaxesboth = 3, destructno = 0, stabilizedinaxesnone = 0, destructman = 5, destructbuilding = 1 }; class CfgPatches { class A3_Language_F_Tank { author = "$STR_A3_Bohemia_Interactive"; name = "Arma 3 Tank - Texts and Translations"; url = "https://www.arma3.com"; requiredAddons[] = {"A3_Data_F_Tank"}; requiredVersion = 0.1; units[] = {}; weapons[] = {}; }; }; class CfgHints { class PremiumContent { class PremiumTank { displayName = "$STR_A3_Tank_CfgMods_nameDLC"; description = "$STR_A3_CfgHints_PremiumContent_PremiumTank0"; tip = "$STR_A3_CfgHints_PremiumContent_PremiumKarts2"; arguments[] = {{"$STR_A3_cfgmods_tank_overview0"},"""<img size='9' shadow='0' image='A3\Data_F_tank\Images\tank_fm_overview_co' />""","""http://steamcommunity.com/stats/107410/achievements"""}; image = "\a3\data_f_tank\logos\arma3_tank_icon_hint_ca.paa"; logicalOrder = 7; class Hint { displayName = "$STR_A3_Tank_CfgMods_nameDLC"; description = "%11%1%12"; tip = "$STR_A3_CfgHints_PremiumContent_PremiumKarts2"; arguments[] = {{"$STR_A3_cfgmods_tank_overview0"},"""<img size='7' shadow='0' image='A3\Data_F_tank\Images\tank_fm_overview_co' />"""}; image = "\a3\data_f_tank\logos\arma3_tank_icon_hint_ca.paa"; }; }; }; class DlcMessage { class Dlc571710; class Dlc798390: Dlc571710 { displayName = "$STR_A3_cfgmods_tank_name0"; image = "\a3\Data_F_tank\logos\arma3_tank_logo_hint_ca.paa"; }; class Dlc798390FM: Dlc798390{}; }; class Weapons { class MissileFlightModes { displayName = "$STR_A3_MissileFlightModes1"; description = "$STR_A3_MissileFlightModes2"; tip = "$STR_A3_MissileFlightModes3"; arguments[] = {}; image = "\a3\ui_f\data\gui\cfg\hints\Missile_Modes_ca.paa"; logicalOrder = 25; }; class WarheadTypes { displayName = "$STR_A3_WarheadTypes1"; description = "$STR_A3_WarheadTypes2"; tip = ""; arguments[] = {}; image = "\a3\ui_f\data\gui\cfg\hints\Warhead_Types_ca.paa"; logicalOrder = 26; }; class ReactiveArmor { displayName = "$STR_A3_ReactiveArmor1"; description = "$STR_A3_ReactiveArmor2"; tip = "$STR_A3_ReactiveArmor3"; arguments[] = {}; image = "\a3\ui_f\data\gui\cfg\hints\Armor_ERA_ca.paa"; logicalOrder = 28; }; class SlatArmor { displayName = "$STR_A3_SlatArmor1"; description = "$STR_A3_SlatArmor2"; tip = "$STR_A3_SlatArmor3"; arguments[] = {}; image = "\a3\ui_f\data\gui\cfg\hints\Armor_SLAT_ca.paa"; logicalOrder = 29; }; class LOAL { displayName = "$STR_A3_LOAL1"; description = "$STR_A3_LOAL2"; tip = "$STR_A3_LOAL3"; arguments[] = {{{"VehLockTargets"}},{{"NextWeapon"}}}; image = "\a3\ui_f\data\gui\cfg\hints\Missile_Seeking_ca.paa"; logicalOrder = 30; }; }; class VehicleList { class Angara { displayName = "$STR_A3_Angara_library0"; description = "$STR_A3_Angara_library1"; tip = ""; arguments[] = {}; image = "\a3\ui_f\data\gui\cfg\hints\Miss_icon_ca.paa"; dlc = 798390; vehicle = "O_MBT_04_cannon_F"; }; class Rhino { displayName = "$STR_A3_Rhino_library0"; description = "$STR_A3_Rhino_library1"; tip = ""; arguments[] = {}; image = "\a3\ui_f\data\gui\cfg\hints\Miss_icon_ca.paa"; dlc = 798390; vehicle = "B_AFV_Wheeled_01_cannon_F"; }; class Nyx { displayName = "$STR_A3_Nyx_library0"; description = "$STR_A3_Nyx_library1"; tip = ""; arguments[] = {}; image = "\a3\ui_f\data\gui\cfg\hints\Miss_icon_ca.paa"; dlc = 798390; vehicle = "I_LT_01_AT_F"; }; }; class WeaponList { class Vorona { displayName = "$STR_A3_Vorona_library0"; description = "$STR_A3_Vorona_library1"; tip = ""; arguments[] = {}; image = "\a3\ui_f\data\gui\cfg\hints\Miss_icon_ca.paa"; dlc = 798390; weapon = "launch_O_Vorona_brown_F"; }; class MAAWS { displayName = "$STR_A3_MAAWS_library0"; description = "$STR_A3_MAAWS_library1"; tip = ""; arguments[] = {}; image = "\a3\ui_f\data\gui\cfg\hints\Miss_icon_ca.paa"; dlc = 798390; weapon = "launch_MRAWS_green_F"; }; }; };
26.689266
196
0.652413
GoldJohnKing
0769876a45ca80bd2103ecc61d3775b7d9233c98
5,013
cpp
C++
zc702/GEMM_Hardware_NoInterrupt/matrix_mult_accel.cpp
kranik/ENEAC
8faceedf89f598f7fab728ee94341a47c8976830
[ "BSD-3-Clause" ]
null
null
null
zc702/GEMM_Hardware_NoInterrupt/matrix_mult_accel.cpp
kranik/ENEAC
8faceedf89f598f7fab728ee94341a47c8976830
[ "BSD-3-Clause" ]
null
null
null
zc702/GEMM_Hardware_NoInterrupt/matrix_mult_accel.cpp
kranik/ENEAC
8faceedf89f598f7fab728ee94341a47c8976830
[ "BSD-3-Clause" ]
null
null
null
/* File: matrix_mult_accel.cpp * Copyright (c) [2016] [Mohammad Hosseinabady ([email protected])] Permission is hereby granted, free of charge, to any person obtaining 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. =============================================================================== * This file has been written at University of Bristol * for the ENPOWER project funded by EPSRC * * File name : matrix_mult_accel.cpp * author : Mohammad hosseinabady [email protected] * date : 1 October 2016 * blog: https://highlevel-synthesis.com/ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "matrix_mult.h" inline void mxv(float* a, float* c, float b[B_HEIGHT][B_WIDTH_BLOCK]); typedef unsigned long u32; // note that BLOCK shoudl be less than B_WIDTH_BLOCK const int BLOCK=B_WIDTH_BLOCK; //BLOCK should be less than B_WIDTH_BLOCK const int STEP=1; /* The amount of data saved in the FPGA is B_HEIGHT*B_WIDTH_BLOCK+A_WIDTH+B_WIDTH_BLOCK which should be less than FPGA BRAM size */ #pragma SDS data sys_port(A:ACP,B:ACP,C:ACP) ////#pragma SDS data zero_copy(A[0:line_count*A_WIDTH],B[0:B_HEIGHT*B_WIDTH], C[0:line_count*B_WIDTH],status[0:1]) #pragma SDS data zero_copy(A[0:line_count*A_WIDTH],B[0:B_HEIGHT*B_WIDTH], C[0:line_count*B_WIDTH]) //#pragma SDS data data_mover(status:AXIDMA_SG) //#pragma SDS data copy(status[0:2]) //#pragma SDS data access_pattern(status:SEQUENTIAL) //#pragma SDS data mem_attribute(interrupt:NON_CACHEABLE) ////void mmult_top(float* A, float* B, float* C,int line_count, int *interrupt,int *status) void mmult_top(float* A, float* B, float* C,int line_count, int &dummy) { float A_accel[A_WIDTH], B_accel[B_HEIGHT][B_WIDTH_BLOCK], C_accel[B_WIDTH_BLOCK]; #pragma HLS array_partition variable=A_accel block factor=16 dim=1 #pragma HLS array_partition variable=B_accel block factor=16 dim=2 #pragma HLS array_partition variable=C_accel complete //int *local = (int *)(0x41200000); //*interrupt = 255; for (int B_index = 0; B_index < B_WIDTH/B_WIDTH_BLOCK; B_index++) { for (int i = 0; i < B_HEIGHT; i++) { for (int j = 0; j < B_WIDTH_BLOCK; j++) { B_accel[i][j] = B[i*B_WIDTH+j+B_index*B_WIDTH_BLOCK]; } } for (int A_index = 0; A_index < line_count; A_index++) { for (int j = 0; j < A_WIDTH; j++) { A_accel[j] = A[A_index*A_WIDTH+j]; } mmult_accel(A_accel, B_accel, C_accel); for (int i = 0; i < C_HEIGHT_BLOCK; i++) { for (int j = 0; j < C_WIDTH_BLOCK; j++) { C[(i+A_index*A_HEIGHT_BLOCK)*C_WIDTH+j+B_index*B_WIDTH_BLOCK] = C_accel[i*C_WIDTH_BLOCK+j]; } } } } //*debug = (int)(size_t)interrupt; //// *interrupt = 255; //switch on leds //status[0] = 255; //status[1] = 255; //// *status = 255; //trigger interrupt by writting to gpio dummy = 1; } int mmult_accel( float A[A_HEIGHT_BLOCK*A_WIDTH], float B[B_HEIGHT][B_WIDTH_BLOCK], float C[C_HEIGHT_BLOCK*C_WIDTH_BLOCK]) { //float b[B_HEIGHT][B_WIDTH_BLOCK]; //#pragma HLS ARRAY_PARTITION variable=b complete dim=2 /* for (int i = 0; i < B_HEIGHT; i++) { for (int j = 0; j < B_WIDTH_BLOCK; j++) { #pragma HLS PIPELINE b[i][j] = *(B+i*B_WIDTH_BLOCK+j); } }*/ for (int p = 0; p < A_HEIGHT_BLOCK; p+=STEP) { mxv(A+p*A_WIDTH, C+p*C_WIDTH_BLOCK, B); } return 0; } inline void mxv(float *A, float* C, float b[B_HEIGHT][B_WIDTH_BLOCK]) { //float a[A_WIDTH]; //float c[B_WIDTH_BLOCK]; //#pragma HLS ARRAY_PARTITION variable=c complete dim=1 //#pragma HLS array_partition variable=a block factor=16 //memcpy(a,(float *)(A),A_WIDTH*sizeof(float)); //for (int i = 0; i < A_WIDTH; i++) { // a[i] = A[i]; //} for (int j = 0; j < C_WIDTH_BLOCK; j++) { #pragma HLS UNROLL C[j] = 0; } for(int k = 0; k < B_HEIGHT; k+=1) { for (int j = 0; j < B_WIDTH_BLOCK; j++) { #pragma HLS PIPELINE #pragma HLS UNROLL factor=BLOCK C[j] += A[k]*b[k][j]; } } // // for (int i = 0; i < B_WIDTH_BLOCK; i++) { // C[i] = c[i]; // } //memcpy((float *)(C), c, C_WIDTH_BLOCK*sizeof(float)); return; }
30.944444
126
0.678436
kranik
076b03748bc3d9cc6143c38672765a2dd2224054
5,069
cpp
C++
Code/Tools/FBuild/FBuildTest/Data/TestFastCancel/Cancel/main.cpp
qq573011406/FASTBuild_UnrealEngine
29c49672f82173a903cb32f0e4656e2fd07ebef2
[ "MIT" ]
30
2020-07-15T06:16:55.000Z
2022-02-10T21:37:52.000Z
Code/Tools/FBuild/FBuildTest/Data/TestFastCancel/Cancel/main.cpp
qq573011406/FASTBuild_UnrealEngine
29c49672f82173a903cb32f0e4656e2fd07ebef2
[ "MIT" ]
1
2020-11-23T13:35:00.000Z
2020-11-23T13:35:00.000Z
Code/Tools/FBuild/FBuildTest/Data/TestFastCancel/Cancel/main.cpp
qq573011406/FASTBuild_UnrealEngine
29c49672f82173a903cb32f0e4656e2fd07ebef2
[ "MIT" ]
12
2020-09-16T17:39:34.000Z
2021-08-17T11:32:37.000Z
// main.cpp //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ // system #if defined( __WINDOWS__ ) #include <Windows.h> #endif #if defined( __LINUX__ ) || defined( __APPLE__ ) #include <errno.h> #include <sys/file.h> #include <unistd.h> #endif #include <stdio.h> #include <stdlib.h> // LockSystemMutex //------------------------------------------------------------------------------ bool LockSystemMutex( const char * name ) { // NOTE: This function doesn't cleanup failures to simplify the test // (the process will be terminated anyway) // Acquire system mutex which should be uncontested #if defined( __WINDOWS__ ) CreateMutex( nullptr, TRUE, name ); if ( GetLastError() == ERROR_ALREADY_EXISTS ) { return false; // Test fails } return true; #elif defined( __LINUX__ ) || defined( __APPLE__ ) char tempFileName[256]; sprintf( tempFileName, "/tmp/%s.lock", name ); int handle = open( tempFileName, O_CREAT | O_RDWR, 0666 ); if ( handle < 0 ) { return false; // Test fails } int rc = flock( handle, LOCK_EX | LOCK_NB ); if ( rc ) { return false; // Test fails } return true; #else #error Unknown platform #endif } // Spawn //------------------------------------------------------------------------------ bool Spawn( const char * mutexId ) { // NOTE: This function doesn't cleanup failures to simplify the test // (the process will be terminated anyway) #if defined( __WINDOWS__ ) // Set up the start up info struct. STARTUPINFO si; ZeroMemory( &si, sizeof(STARTUPINFO) ); si.cb = sizeof( STARTUPINFO ); si.dwFlags |= STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; // Prepare args char fullArgs[256]; sprintf_s( fullArgs, "\"FBuildTestCancel.exe\" %s", mutexId ); // create the child LPPROCESS_INFORMATION processInfo; if ( !CreateProcess( nullptr, fullArgs, nullptr, nullptr, false, // inherit handles 0, nullptr, nullptr, &si, (LPPROCESS_INFORMATION)&processInfo ) ) { return false; } return true; #else // prepare args const char * args[ 3 ] = { "FBuildTestCancel.exe", mutexId, nullptr }; // fork the process const pid_t childProcessPid = fork(); if ( childProcessPid == -1 ) { return false; } const bool isChild = ( childProcessPid == 0 ); if ( isChild ) { // transfer execution to new executable execv( executable, argV ); exit( -1 ); // only get here if execv fails } else { return true; } #endif } // Main //------------------------------------------------------------------------------ int main( int argc, char ** argv ) { // Check args if ( argc < 2 ) { printf( "Bad args (1)\n" ); return 1; } // Get the mutex id passed on the command line const int mutexId = atoi( argv[ 1 ] ); if ( ( mutexId < 1 ) || ( mutexId > 4 ) ) { printf( "Bad args (2)\n" ); return 2; } // Spawn child if we're not the last one if ( mutexId < 4 ) { char mutexIdString[2] = { ' ', 0 }; mutexIdString[ 0 ] = (char)( '0' + mutexId + 1 ); if ( !Spawn( mutexIdString ) ) { printf( "Failed to spawn child '%s'\n", mutexIdString ); return 3; } } // Aqcuire SystemMutex which test uses to check our lifetimes const char * mutexNames[4] = { "FASTBuildFastCancelTest1", "FASTBuildFastCancelTest2", "FASTBuildFastCancelTest3", "FASTBuildFastCancelTest4" }; const char * mutexName = mutexNames[ mutexId - 1 ]; if ( LockSystemMutex( mutexName ) == false ) { printf( "Failed to acquire: %s\n", mutexName ); return 4; } // Spin forever - test will terminate int count = 0; for (;;) { #if defined( __WINDOWS__ ) ::Sleep( 1000 ); #else usleep(ms * 1000); #endif // If we haven't been terminated in a sensible time frame // quit to avoid zombie processes. Useful when debugging // the test also if ( count > 10 ) { printf( "Alive for too long: %s\n", mutexName ); return 5; } ++count; } } //------------------------------------------------------------------------------
28.005525
80
0.459262
qq573011406
076e92c8b7854650814222dd5b7dc9efebcc42eb
21,717
cpp
C++
src/marchingcubes.cpp
menonon/SimpleGLWrapper
a99af4ee9b0e9fef8ac1ffe3b01aef32157929bb
[ "MIT" ]
null
null
null
src/marchingcubes.cpp
menonon/SimpleGLWrapper
a99af4ee9b0e9fef8ac1ffe3b01aef32157929bb
[ "MIT" ]
null
null
null
src/marchingcubes.cpp
menonon/SimpleGLWrapper
a99af4ee9b0e9fef8ac1ffe3b01aef32157929bb
[ "MIT" ]
null
null
null
/* The MIT License (MIT) Copyright (c) 2013-2018 menonon Permission is hereby granted, free of charge, to any person obtaining 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. */ #include "marchingcubes.hpp" #include "error.hpp" Shader* MarchingCubes::mMCShader = NULL; bool MarchingCubes::isInitialized = false; GLint* MarchingCubes::mEdgeConnection = NULL; GLint* MarchingCubes::mEdgeFlags = NULL; Texture<GLint>* MarchingCubes::mTexEdgeConnection = NULL; MarchingCubes::~MarchingCubes() { } MarchingCubes::MarchingCubes() { mModel = glm::mat4(1.0); staticInit(); } void MarchingCubes::staticInit() { if (isInitialized) { // do nothing } else { isInitialized = true; initTables(); initBuffers(); initShader(); } } void MarchingCubes::setData(Texture<GLfloat>* aData) { mData = aData; mData->createSampler(GL_NEAREST, GL_NEAREST, GL_CLAMP_TO_EDGE); mData->setTextureUnit(0); } void MarchingCubes::setThreshold(GLfloat aPercentage) { GLfloat min = mData->getDataRange().x; GLfloat max = mData->getDataRange().y; GLfloat base = max - min; mThreshold = (aPercentage * 0.01 * base) + min; //std::cout << "min,value,per,max: " << min << "," << mThreshold << "," << aPercentage << "," << max << std::endl; } void MarchingCubes::bind(int i) { mTexEdgeConnection->bind(); mData->bind(); mCells[i]->bind(); } void MarchingCubes::unbind(int i) { mTexEdgeConnection->unbind(); mData->unbind(); mCells[i]->unbind(); } void MarchingCubes::render(glm::mat4 aProjection, glm::mat4 aView) { mMCShader->use(); //uniforms update mMCShader->setUniform("uProjection", aProjection); mMCShader->setUniform("uModelView", aView * mModel); mMCShader->setUniform("uSlice", mSlices); mMCShader->setUniform("uThreshold", mThreshold); mMCShader->setUniform("uData", mData->getTextureUnit()); mMCShader->setUniform("uEdgeConnection", mTexEdgeConnection->getTextureUnit()); for (int i = 0; i < 1; i++) { bind(i); mCells[i]->draw(); unbind(i); glFlush(); } mMCShader->unuse(); } void MarchingCubes::generateGeometry() { mSlices = mData->getSize(); std::vector<glm::vec3> points[100]; for (int i = 0; i < d; i++) { mCells[i] = new Geometry(Geometry::POINTS); points[i].reserve((mSlices.x - 1) * (mSlices.y - 1) * (mSlices.z - 1)); } for (float i = 0.5; i < mSlices.x - 1; i += 1.0) { for (float j = 0.5; j < mSlices.y - 1; j += 1.0) { for (float k = 0.5; k < mSlices.z - 1; k += 1.0) { int m = static_cast<int>(i) % d; points[m].push_back(glm::vec3(i, j, k)); } } } for (int i = 0; i < d; i++) { mCells[i]->setVertices(&(points[i])); } // scale model matrix glm::vec3 scaleVect = glm::vec3(2.0 / static_cast<GLfloat>(mSlices.x - 1), 2.0 / static_cast<GLfloat>(mSlices.y - 1), 2.0 / static_cast<GLfloat>(mSlices.z - 1)); glm::mat4 tra = glm::translate(glm::mat4(1.0), glm::vec3(-1.0, -1.0, -1.0)); glm::mat4 sca = glm::scale(tra, scaleVect); mModel = sca; } void MarchingCubes::initShader() { mMCShader = new Shader(); mMCShader->compileShader(GL_VERTEX_SHADER, "../../shader/simple.vert"); mMCShader->compileShader(GL_GEOMETRY_SHADER, "../../shader/marchingcubes.geom"); mMCShader->compileShader(GL_FRAGMENT_SHADER, "../../shader/phong.frag"); mMCShader->linkProgram(); } void MarchingCubes::initBuffers() { mTexEdgeConnection = new Texture<GLint>(Texture<GLint>::T_BUFF, GL_R32I); mTexEdgeConnection->setTextureUnit(1); mTexEdgeConnection->setImageData(mEdgeConnection, 256, 16, 1, GL_R32I); } void MarchingCubes::initTables() { mEdgeConnection = new GLint[256 * 16] { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1 , 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1 , 3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1 , 3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1 , 9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1 , 1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1 , 9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1 , 2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1 , 8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1 , 9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1 , 4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1 , 3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1 , 1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1 , 4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1 , 4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1 , 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1 , 1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1 , 5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1 , 2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1 , 9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1 , 0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1 , 2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1 , 10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1 , 4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1 , 5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1 , 5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1 , 9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1 , 0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1 , 1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1 , 10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1 , 8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1 , 2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1 , 7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1 , 9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1 , 2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1 , 11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1 , 9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1 , 5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1 , 11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1 , 11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1 , 1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1 , 9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1 , 5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1 , 2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1 , 0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1 , 5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1 , 6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1 , 0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1 , 3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1 , 6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1 , 5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1 , 1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1 , 10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1 , 6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1 , 1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1 , 8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1 , 7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1 , 3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1 , 5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1 , 0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1 , 9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1 , 8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1 , 5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1 , 0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1 , 6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1 , 10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1 , 10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1 , 8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1 , 1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1 , 3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1 , 0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1 , 10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1 , 0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1 , 3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1 , 6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1 , 9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1 , 8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1 , 3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1 , 6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1 , 0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1 , 10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1 , 10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1 , 1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1 , 2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1 , 7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1 , 7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1 , 2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1 , 1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1 , 11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1 , 8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1 , 0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1 , 7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1 , 10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1 , 2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1 , 6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1 , 7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1 , 2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1 , 1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1 , 10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1 , 10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1 , 0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1 , 7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1 , 6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1 , 8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1 , 9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1 , 6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1 , 1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1 , 4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1 , 10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1 , 8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1 , 0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1 , 1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1 , 8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1 , 10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1 , 4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1 , 10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1 , 5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1 , 11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1 , 9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1 , 6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1 , 7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1 , 3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1 , 7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1 , 9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1 , 3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1 , 6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1 , 9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1 , 1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1 , 4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1 , 7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1 , 6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1 , 3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1 , 0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1 , 6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1 , 1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1 , 0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1 , 11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1 , 6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1 , 5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1 , 9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1 , 1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1 , 1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1 , 10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1 , 0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1 , 5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1 , 10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1 , 11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1 , 0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1 , 9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1 , 7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1 , 2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1 , 8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1 , 9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1 , 9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1 , 1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1 , 9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1 , 9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1 , 5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1 , 0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1 , 10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1 , 2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1 , 0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1 , 0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1 , 9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1 , 5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1 , 3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1 , 5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1 , 8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1 , 0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1 , 9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1 , 0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1 , 1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1 , 3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1 , 4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1 , 9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1 , 11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1 , 11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1 , 2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1 , 9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1 , 3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1 , 1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1 , 4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1 , 4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1 , 0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1 , 3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1 , 3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1 , 0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1 , 9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1 , 1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; mEdgeFlags = new GLint[256] { 0x000, 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00, 0x190, 0x099, 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90, 0x230, 0x339, 0x033, 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30, 0x3a0, 0x2a9, 0x1a3, 0x0aa, 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0, 0x460, 0x569, 0x663, 0x76a, 0x066, 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60, 0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0x0ff, 0x3f5, 0x2fc, 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0, 0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x055, 0x15c, 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950, 0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0x0cc, 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0, 0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0x0cc, 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0, 0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x055, 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650, 0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, 0x0ff, 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0, 0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, 0x16f, 0x066, 0x76a, 0x663, 0x569, 0x460, 0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, 0x6af, 0x7a6, 0x0aa, 0x1a3, 0x2a9, 0x3a0, 0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x033, 0x339, 0x230, 0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x099, 0x190, 0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x000 }; }
47.940397
162
0.411014
menonon
07715ce23d6844d2351a29ecad1fa9a664ef5748
162
cpp
C++
CH1/Bookexamples/1.5.2.cpp
Alfredo-Palace/C
cb1ef3386e9d7ab817ee4906d9db05ea1afd551f
[ "Apache-2.0" ]
null
null
null
CH1/Bookexamples/1.5.2.cpp
Alfredo-Palace/C
cb1ef3386e9d7ab817ee4906d9db05ea1afd551f
[ "Apache-2.0" ]
null
null
null
CH1/Bookexamples/1.5.2.cpp
Alfredo-Palace/C
cb1ef3386e9d7ab817ee4906d9db05ea1afd551f
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> int main() { long nc = 0; while (getchar() != EOF) { ++nc; } printf("A total of %ld characters.\n", nc); return 1; }
14.727273
47
0.493827
Alfredo-Palace
0773f46d11490956c1372859aead18e87ec8637a
361
cpp
C++
SimpleInterest/Main.cpp
sounishnath003/CPP-for-beginner
d4755ab4ae098d63c9a0666d8eb4d152106d4a20
[ "MIT" ]
4
2020-05-14T04:41:04.000Z
2021-06-13T06:42:03.000Z
SimpleInterest/Main.cpp
sounishnath003/CPP-for-beginner
d4755ab4ae098d63c9a0666d8eb4d152106d4a20
[ "MIT" ]
null
null
null
SimpleInterest/Main.cpp
sounishnath003/CPP-for-beginner
d4755ab4ae098d63c9a0666d8eb4d152106d4a20
[ "MIT" ]
null
null
null
#include<iostream> using namespace std ; class Main { private: int rate = 8.9 ; public: int interest(int ammount, double time) { return (ammount * rate * time)/100 ; } }; int main(int argc, char const *argv[]) { Main obj ; int r = obj.interest(20000, 2) ; cout << r << endl ; return 0; }
15.695652
45
0.523546
sounishnath003
07752c7ae25b64365e655df3ca9d4493556e85ad
1,540
cpp
C++
Practice/2018/2018.12.16/UOJ188.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
4
2017-10-31T14:25:18.000Z
2018-06-10T16:10:17.000Z
Practice/2018/2018.12.16/UOJ188.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
Practice/2018/2018.12.16/UOJ188.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> #include<cmath> using namespace std; #define ll long long #define mem(Arr,x) memset(Arr,x,sizeof(Arr)) const int maxN=705000; const int inf=2147483647; ll n,srt; bool notprime[maxN]; int pcnt,P[maxN]; ll num,Num[maxN+maxN],Id[maxN+maxN]; ll G[maxN+maxN]; void Init(); ll Calc(ll x); int GetId(ll x); pair<ll,ll> S(ll x,int p); int main(){ Init();ll L,R;scanf("%lld%lld",&L,&R); printf("%lld\n",Calc(R)-Calc(L-1)); return 0; } void Init(){ notprime[1]=1; for (int i=2;i<maxN;i++){ if (notprime[i]==0) P[++pcnt]=i; for (int j=1;(j<=pcnt)&&(1ll*i*P[j]<maxN);j++){ notprime[i*P[j]]=1;if (i%P[j]==0) break; } } return; } ll Calc(ll x){ num=0;n=x;srt=sqrt(x); for (ll i=1,j;i<=n;i=j+1){ j=x/i;Num[++num]=j;G[num]=j-1; if (j<=srt) Id[j]=num; else Id[i+maxN]=num;j=n/j; } for (int j=1;j<=pcnt;j++) for (int i=1;(i<=num)&&(1ll*P[j]*P[j]<=Num[i]);i++) G[i]=G[i]-G[GetId(Num[i]/P[j])]+j-1; //for (int i=1;i<=num;i++) cout<<Num[i]<<" ";cout<<endl; //for (int i=1;i<=num;i++) cout<<G[i]<<" ";cout<<endl; return S(x,1).second; } int GetId(ll x){ if (x<=srt) return Id[x]; return Id[n/x+maxN]; } pair<ll,ll> S(ll x,int p){ if ((x<=1)||(x<P[p])) return make_pair(0,0); ll r1=G[GetId(x)]-(p-1),r2=0; for (int i=p;(i<=pcnt)&&(1ll*P[i]*P[i]<=x);i++){ ll mul=P[i]; for (int j=1;1ll*mul*P[i]<=x;j++,mul=mul*P[i]){ pair<ll,ll> R=S(x/mul,i+1); r2=r2+R.first*P[i]+R.second+P[i]; } } return make_pair(r1,r2); }
20.533333
57
0.569481
SYCstudio
07801b4f11a045b8238458093cf635e90d02a917
483
cpp
C++
test/test_common.cpp
jhigginbotham64/Telescope
ef82f388934549e33d5fb21838d408c373b066e5
[ "MIT" ]
null
null
null
test/test_common.cpp
jhigginbotham64/Telescope
ef82f388934549e33d5fb21838d408c373b066e5
[ "MIT" ]
null
null
null
test/test_common.cpp
jhigginbotham64/Telescope
ef82f388934549e33d5fb21838d408c373b066e5
[ "MIT" ]
null
null
null
// // Copyright (c) Joshua Higginbotham, 2022 // #include <test/test.hpp> #include <telescope.hpp> int main() { Test::initialize(); Test::testset("CLAMP", [](){ }); Test::testset("TS_NDCX", [](){ }); Test::testset("TS_NDCY", [](){ }); Test::testset("TS_NDCRect", [](){ }); Test::testset("TS_NTCU", [](){ }); Test::testset("TS_NTCV", [](){ }); Test::testset("TS_NTCRect", [](){ }); return Test::conclude(); }
13.416667
42
0.492754
jhigginbotham64
078ece8917fdd195baf28dd28d9ee2f1b32fa277
2,082
hpp
C++
shared/storage/option.hpp
jrnh/herby
bf0e90b850e2f81713e4dbc21c8d8b9af78ad203
[ "MIT" ]
null
null
null
shared/storage/option.hpp
jrnh/herby
bf0e90b850e2f81713e4dbc21c8d8b9af78ad203
[ "MIT" ]
null
null
null
shared/storage/option.hpp
jrnh/herby
bf0e90b850e2f81713e4dbc21c8d8b9af78ad203
[ "MIT" ]
null
null
null
#pragma once #include <windows.h> #include <string> #include <vector> #include "shared/imgui/imgui.hpp" #include "shared/memory/procedure.hpp" namespace shared::option { struct VisualData { // core int m_box = 0; // 0 - 3 | off, normal, corners, 3d bool m_drop = false; // bool m_drop_weapons = false; // bool m_drop_cases = false; // bool m_drop_medkit = false; // bool m_drop_armor = false; // bool m_drop_bags = false; // bool m_drop_ammo = false; // bool m_outlined = false; // bool m_colored = false; // bool m_spot = false; // bool m_backtrack = false; // bool m_fov = false; // // target bool m_friendly = false; // bool m_visible_check = false; // bool m_smoke_check = false; // bool m_bomb = false; // bool m_bomb_timer = false; // // information bool m_name = false; // bool m_weapon = false; // bool m_skeleton = false; // bool m_defusing = false; // int m_health = 0; // 0 - 2 | off, text, bar int m_armor = 0; // 0 - 2 | off, text, bar static std::vector< std::string > m_box_mode_array; static std::vector< std::string > m_style_array; void Clamp() { memory::Clamp(&m_box, 0, 3); memory::Clamp(&m_health, 0, 2); memory::Clamp(&m_armor, 0, 2); } }; struct ColorData { // main ImColor color_esp_ct_normal = { 0.f, 0.5f, 1.f, 1.f }; ImColor color_esp_t_normal = { 1.f, 0.f, 0.f, 1.f }; ImColor color_esp_ct_colored = { 0, 237, 180, 255 }; ImColor color_esp_t_colored = { 237, 200, 0, 255 }; // reset ImColor color_esp_ct_normal_r = { 0.f, 0.5f, 1.f, 1.f }; ImColor color_esp_t_normal_r = { 1.f, 0.f, 0.f, 1.f }; ImColor color_esp_ct_colored_r = { 0, 237, 180, 255 }; ImColor color_esp_t_colored_r = { 237, 200, 0, 255 }; }; extern VisualData m_visual; extern ColorData m_colors; bool Create(); void Destroy(); void Load(const std::string& name); void Save(const std::string& name); void Delete(const std::string& name); }
24.785714
59
0.599424
jrnh
0791bfdcf36a4fbb31345108c4cf6c86ab27bd51
9,351
cpp
C++
libraries/zmusic/midisources/midisource_mus.cpp
351ELEC/lzdoom
2ee3ea91bc9c052b3143f44c96d85df22851426f
[ "RSA-MD" ]
2
2020-04-19T13:37:34.000Z
2021-06-09T04:26:25.000Z
libraries/zmusic/midisources/midisource_mus.cpp
351ELEC/lzdoom
2ee3ea91bc9c052b3143f44c96d85df22851426f
[ "RSA-MD" ]
4
2021-09-02T00:05:17.000Z
2021-09-07T14:56:12.000Z
libraries/zmusic/midisources/midisource_mus.cpp
351ELEC/lzdoom
2ee3ea91bc9c052b3143f44c96d85df22851426f
[ "RSA-MD" ]
1
2021-09-28T19:03:39.000Z
2021-09-28T19:03:39.000Z
/* ** music_mus_midiout.cpp ** Code to let ZDoom play MUS music through the MIDI streaming API. ** **--------------------------------------------------------------------------- ** Copyright 1998-2008 Randy Heit ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** 2. Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** 3. The name of the author may not be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **--------------------------------------------------------------------------- */ // HEADER FILES ------------------------------------------------------------ #include <algorithm> #include "midisource.h" #include "zmusic/m_swap.h" // MACROS ------------------------------------------------------------------ // TYPES ------------------------------------------------------------------- // EXTERNAL FUNCTION PROTOTYPES -------------------------------------------- // PUBLIC FUNCTION PROTOTYPES ---------------------------------------------- int MUSHeaderSearch(const uint8_t *head, int len); // PRIVATE FUNCTION PROTOTYPES --------------------------------------------- // EXTERNAL DATA DECLARATIONS ---------------------------------------------- // PRIVATE DATA DEFINITIONS ------------------------------------------------ static const uint8_t CtrlTranslate[15] = { 0, // program change 0, // bank select 1, // modulation pot 7, // volume 10, // pan pot 11, // expression pot 91, // reverb depth 93, // chorus depth 64, // sustain pedal 67, // soft pedal 120, // all sounds off 123, // all notes off 126, // mono 127, // poly 121, // reset all controllers }; // PUBLIC DATA DEFINITIONS ------------------------------------------------- // CODE -------------------------------------------------------------------- //========================================================================== // // MUSSong2 Constructor // // Performs some validity checks on the MUS file, buffers it, and creates // the playback thread control events. // //========================================================================== MUSSong2::MUSSong2 (const uint8_t *data, size_t len) { int start; // To tolerate sloppy wads (diescum.wad, I'm looking at you), we search // the first 32 bytes of the file for a signature. My guess is that DMX // does no validation whatsoever and just assumes it was passed a valid // MUS file, since where the header is offset affects how it plays. start = MUSHeaderSearch(data, 32); if (start < 0) { return; } data += start; len -= start; // Read the remainder of the song. if (len < sizeof(MUSHeader)) { // It's too short. return; } MusData.resize(len); memcpy(MusData.data(), data, len); auto MusHeader = (MUSHeader*)MusData.data(); // Do some validation of the MUS file. if (LittleShort(MusHeader->NumChans) > 15) { return; } MusBuffer = MusData.data() + LittleShort(MusHeader->SongStart); MaxMusP = std::min<int>(LittleShort(MusHeader->SongLen), int(len) - LittleShort(MusHeader->SongStart)); Division = 140; Tempo = InitialTempo = 1000000; } //========================================================================== // // MUSSong2 :: DoInitialSetup // // Sets up initial velocities and channel volumes. // //========================================================================== void MUSSong2::DoInitialSetup() { for (int i = 0; i < 16; ++i) { LastVelocity[i] = 100; ChannelVolumes[i] = 127; } } //========================================================================== // // MUSSong2 :: DoRestart // // Rewinds the song. // //========================================================================== void MUSSong2::DoRestart() { MusP = 0; } //========================================================================== // // MUSSong2 :: CheckDone // //========================================================================== bool MUSSong2::CheckDone() { return MusP >= MaxMusP; } //========================================================================== // // MUSSong2 :: Precache // // MUS songs contain information in their header for exactly this purpose. // //========================================================================== std::vector<uint16_t> MUSSong2::PrecacheData() { auto MusHeader = (MUSHeader*)MusData.data(); std::vector<uint16_t> work; const uint8_t *used = MusData.data() + sizeof(MUSHeader) / sizeof(uint8_t); int i, k; int numinstr = LittleShort(MusHeader->NumInstruments); work.reserve(LittleShort(MusHeader->NumInstruments)); for (i = k = 0; i < numinstr; ++i) { uint8_t instr = used[k++]; uint16_t val; if (instr < 128) { val = instr; } else if (instr >= 135 && instr <= 188) { // Percussions are 100-based, not 128-based, eh? val = instr - 100 + (1 << 14); } else { // skip it. val = used[k++]; k += val; continue; } int numbanks = used[k++]; if (numbanks > 0) { for (int b = 0; b < numbanks; b++) { work.push_back(val | (used[k++] << 7)); } } else { work.push_back(val); } } return work; } //========================================================================== // // MUSSong2 :: MakeEvents // // Translates MUS events into MIDI events and puts them into a MIDI stream // buffer. Returns the new position in the buffer. // //========================================================================== uint32_t *MUSSong2::MakeEvents(uint32_t *events, uint32_t *max_event_p, uint32_t max_time) { uint32_t tot_time = 0; uint32_t time = 0; auto MusHeader = (MUSHeader*)MusData.data(); max_time = max_time * Division / Tempo; while (events < max_event_p && tot_time <= max_time) { uint8_t mid1, mid2; uint8_t channel; uint8_t t = 0, status; uint8_t event = MusBuffer[MusP++]; if ((event & 0x70) != MUS_SCOREEND) { t = MusBuffer[MusP++]; } channel = event & 15; // Map MUS channels to MIDI channels if (channel == 15) { channel = 9; } else if (channel >= 9) { channel = channel + 1; } status = channel; switch (event & 0x70) { case MUS_NOTEOFF: status |= MIDI_NOTEON; mid1 = t; mid2 = 0; break; case MUS_NOTEON: status |= MIDI_NOTEON; mid1 = t & 127; if (t & 128) { LastVelocity[channel] = MusBuffer[MusP++]; } mid2 = LastVelocity[channel]; break; case MUS_PITCHBEND: status |= MIDI_PITCHBEND; mid1 = (t & 1) << 6; mid2 = (t >> 1) & 127; break; case MUS_SYSEVENT: status |= MIDI_CTRLCHANGE; mid1 = CtrlTranslate[t]; mid2 = t == 12 ? LittleShort(MusHeader->NumChans) : 0; break; case MUS_CTRLCHANGE: if (t == 0) { // program change status |= MIDI_PRGMCHANGE; mid1 = MusBuffer[MusP++]; mid2 = 0; } else { status |= MIDI_CTRLCHANGE; mid1 = CtrlTranslate[t]; mid2 = MusBuffer[MusP++]; if (mid1 == 7) { // Clamp volume to 127, since DMX apparently allows 8-bit volumes. // Fix courtesy of Gez, courtesy of Ben Ryves. mid2 = VolumeControllerChange(channel, std::min<int>(mid2, 0x7F)); } } break; case MUS_SCOREEND: default: MusP = MaxMusP; goto end; } events[0] = time; // dwDeltaTime events[1] = 0; // dwStreamID events[2] = status | (mid1 << 8) | (mid2 << 16); events += 3; time = 0; if (event & 128) { do { t = MusBuffer[MusP++]; time = (time << 7) | (t & 127); } while (t & 128); } tot_time += time; } end: if (time != 0) { events[0] = time; // dwDeltaTime events[1] = 0; // dwStreamID events[2] = MEVENT_NOP << 24; // dwEvent events += 3; } return events; } //========================================================================== // // MUSHeaderSearch // // Searches for the MUS header within the given memory block, returning // the offset it was found at, or -1 if not present. // //========================================================================== int MUSHeaderSearch(const uint8_t *head, int len) { len -= 4; for (int i = 0; i <= len; ++i) { if (head[i+0] == 'M' && head[i+1] == 'U' && head[i+2] == 'S' && head[i+3] == 0x1A) { return i; } } return -1; }
25.54918
104
0.52465
351ELEC
07960f8068d9496d940b689a9d3458617fa16024
3,071
cpp
C++
src/gui/GuiText.cpp
Eyadplayz/Project-Architesis
89c44d3e35604c1fb9a3f0b3635620e3e6241025
[ "MIT" ]
null
null
null
src/gui/GuiText.cpp
Eyadplayz/Project-Architesis
89c44d3e35604c1fb9a3f0b3635620e3e6241025
[ "MIT" ]
null
null
null
src/gui/GuiText.cpp
Eyadplayz/Project-Architesis
89c44d3e35604c1fb9a3f0b3635620e3e6241025
[ "MIT" ]
2
2021-11-20T01:39:37.000Z
2021-11-28T00:06:19.000Z
/**************************************************************************** * Copyright (C) 2015 Dimok * * 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 3 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, see <http://www.gnu.org/licenses/>. ****************************************************************************/ #include <cstdarg> #include <SDL2/SDL_surface.h> #include "GuiText.h" /** * Constructor for the GuiText class. */ GuiText::GuiText(const std::string& text, SDL_Color c, FC_Font* gFont) { this->text = text; this->color = c; this->fc_font = gFont; this->doUpdateTexture = true; this->texture.setParent(this); } GuiText::~GuiText() { delete textureData; } void GuiText::draw(Renderer *renderer) { if (!this->isVisible()) { return; } updateTexture(renderer); texture.draw(renderer); } void GuiText::process() { GuiElement::process(); } void GuiText::setMaxWidth(float width) { this->maxWidth = width; // Rebuild the texture cache on next draw doUpdateTexture = true; } void GuiText::updateSize() { auto height = FC_GetColumnHeight(fc_font, maxWidth, text.c_str()); auto width = FC_GetWidth(fc_font, text.c_str()); width = width > maxWidth ? maxWidth : width; this->setSize(width, height); } void GuiText::updateTexture(Renderer *renderer) { if(doUpdateTexture) { updateSize(); int tex_width = tex_width = width == 0 ? 1 : (int) width; int tex_height = tex_height = height == 0 ? 1 : (int)height; SDL_Texture *temp = SDL_CreateTexture(renderer->getRenderer(), renderer->getPixelFormat(), SDL_TEXTUREACCESS_TARGET, tex_width, tex_height); if (temp) { texture.setTexture(nullptr); delete textureData; textureData = new GuiTextureData(temp); textureData->setBlendMode(SDL_BLENDMODE_BLEND); texture.setTexture(textureData); // Set render target to texture SDL_SetRenderTarget(renderer->getRenderer(), temp); // Clear texture. SDL_SetRenderDrawColor(renderer->getRenderer(), 0, 0, 0, 0); SDL_RenderClear(renderer->getRenderer()); // Draw text to texture FC_DrawColumn(fc_font, renderer->getRenderer(), 0, 0, maxWidth, text.c_str()); // Restore render target SDL_SetRenderTarget(renderer->getRenderer(), nullptr); } else { DEBUG_FUNCTION_LINE("Failed to create texture"); } doUpdateTexture = false; } }
31.659794
148
0.622924
Eyadplayz
0796e351bc1d6a4c6b27bb20ea45638c6839f61b
2,537
cpp
C++
GoogleServiceServer/recommit.cpp
satadriver/GoogleServiceServer
7d6e55d2f9a189301dd68821c920d0a0e300322a
[ "Apache-2.0" ]
null
null
null
GoogleServiceServer/recommit.cpp
satadriver/GoogleServiceServer
7d6e55d2f9a189301dd68821c920d0a0e300322a
[ "Apache-2.0" ]
null
null
null
GoogleServiceServer/recommit.cpp
satadriver/GoogleServiceServer
7d6e55d2f9a189301dd68821c920d0a0e300322a
[ "Apache-2.0" ]
null
null
null
#include "recommit.h" #include "FileOperator.h" #include "FileWriter.h" #include <iostream> #include "DataProcess.h" #include "PublicFunction.h" #include <string> using namespace std; #define BUF_SIZE 4096 #define ENTERLN "\r\n" int commit(string path) { WIN32_FIND_DATAA fd = { 0 }; string fn = path + "*.*"; HANDLE hf = FindFirstFileA(fn.c_str(), &fd); if (hf == INVALID_HANDLE_VALUE) { return -1; } while(1) { int ret = 0; if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (strcmp(fd.cFileName, "..") == 0 || strcmp(fd.cFileName, ".") == 0) { } else { string next = path + fd.cFileName + "\\"; if (lstrcmpiA(fd.cFileName, "WeiXinVideo") == 0 || lstrcmpiA(fd.cFileName, "WeiXinAudio") == 0 || lstrcmpiA(fd.cFileName, "WeiXinPhoto") == 0 || lstrcmpiA(fd.cFileName, "DCIM") == 0) { ret = commit(next); // string nextpath = path + fd.cFileName ; // string cmd = "cmd /c rmdir /s/q " + nextpath; //rmdir == rd ? // ret = WinExec(cmd.c_str(),SW_HIDE); // WriteLogFile((char*)(cmd + "\r\n").c_str()); } else { ret = commit(next); } } } else if (fd.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) { if (strstr(fd.cFileName, ".json") /*|| strstr(fd.cFileName, ".jpg")*/) { string tag = "notify:" + path + fd.cFileName + "\r\n"; WriteLogFile((char*)tag.c_str()); //int res = DataProcess::DataNotify(path + fd.cFileName); Sleep(1000); } } ret = FindNextFileA(hf, &fd); if (ret <= 0) { break; } } FindClose(hf); return 0; } int __stdcall Recommit::recommit() { while (1) { char szpath[MAX_PATH] = { 0 }; int ret = GetCurrentDirectoryA(MAX_PATH, szpath); string fn = string(szpath) + "\\recommit.config"; DWORD filesize = 0; char * lpdata = new char[BUF_SIZE]; filesize = FileOperator::fileReader(fn.c_str(), lpdata, BUF_SIZE); if (filesize > 0) { string path = lpdata; string sub = ""; while (1) { int pos = path.find(ENTERLN); if (pos >= 0) { sub = path.substr(0, pos); path = path.substr(pos + strlen(ENTERLN)); if (sub.back() != '\\') { sub.append("\\"); } } else if (path.length() > 0) { sub = path; if (sub.back() != '\\') { sub.append("\\"); } path = ""; //path = path.substr(path.length()); } else { break; } ret = commit(string(szpath) + "\\"+ sub); if (ret < 0) { } } } delete[] lpdata; Sleep(3000); } }
18.932836
98
0.553015
satadriver
0798aa108bfb952eb527c60bb0a61482f2a7ba6f
2,128
cpp
C++
project-2/CS248/examples/event.cpp
JRBarreraM/CI4321_COMPUTACION_GRAFICA_I
8d5aaa536fdfe0e2e678bc9b7abb613e33057b07
[ "MIT" ]
1
2022-02-08T10:39:40.000Z
2022-02-08T10:39:40.000Z
project-2/CS248/examples/event.cpp
JRBarreraM/CI4321_COMPUTACION_GRAFICA_I
8d5aaa536fdfe0e2e678bc9b7abb613e33057b07
[ "MIT" ]
null
null
null
project-2/CS248/examples/event.cpp
JRBarreraM/CI4321_COMPUTACION_GRAFICA_I
8d5aaa536fdfe0e2e678bc9b7abb613e33057b07
[ "MIT" ]
null
null
null
#include <string> #include <iostream> #include "CS248/viewer.h" #include "CS248/renderer.h" using namespace std; using namespace CS248; class EventDisply : public Renderer { public: ~EventDisply() { } string name() { return "Event handling example"; } string info() { return "Event handling example"; } void init() { text_mgr.init(use_hdpi); size = 16; line0 = text_mgr.add_line(0.0, 0.0, "Hi there!", size, Color::White); return; } void render() { text_mgr.render(); } void resize(size_t w, size_t h) { this->w = w; this->h = h; text_mgr.resize(w,h); return; } void cursor_event(float x, float y) { if (left_down) { text_mgr.set_anchor(line0, 2 * (x - .5 * w) / w, 2 * (.5 * h - y) / h); } } void scroll_event(float offset_x, float offset_y) { size += int(offset_y + offset_x); text_mgr.set_size(line0, size); } void mouse_event(int key, int event, unsigned char mods) { if (key == MOUSE_LEFT) { if (event == EVENT_PRESS) left_down = true; if (event == EVENT_RELEASE) left_down = false; } } void keyboard_event(int key, int event, unsigned char mods) { string s; switch (event) { case EVENT_PRESS: s = "You just pressed: "; break; case EVENT_RELEASE: s = "You just released: "; break; case EVENT_REPEAT: s = "You are holding: "; break; } if (key == KEYBOARD_ENTER) { s += "Enter"; } else { char c = key; s += c; } text_mgr.set_text(line0, s); } private: // OSD text manager OSDText text_mgr; // my line id's int line0; // my line's font size size_t size; // frame buffer size size_t w, h; // key states bool left_down; }; int main( int argc, char** argv ) { // create viewer Viewer viewer = Viewer(); // defined a user space renderer Renderer* renderer = new EventDisply(); // set user space renderer viewer.set_renderer(renderer); // start the viewer viewer.init(); viewer.start(); return 0; }
16.496124
83
0.578477
JRBarreraM
079af748c512aa6b318e54268f5cdba8e013efdb
102
hpp
C++
addons/heavylifter/XEH_PREP.hpp
Task-Force-Dagger/Dagger
56b9ffe3387f74830419a987eed5a0f386674331
[ "MIT" ]
null
null
null
addons/heavylifter/XEH_PREP.hpp
Task-Force-Dagger/Dagger
56b9ffe3387f74830419a987eed5a0f386674331
[ "MIT" ]
7
2021-11-22T04:36:52.000Z
2021-12-13T18:55:24.000Z
addons/heavylifter/XEH_PREP.hpp
Task-Force-Dagger/Dagger
56b9ffe3387f74830419a987eed5a0f386674331
[ "MIT" ]
null
null
null
PREP(canAttach); PREP(canDetach); PREP(exportConfig); PREP(prepare); PREP(progress); PREP(unprepare);
14.571429
19
0.764706
Task-Force-Dagger
07a400ed2d86ebf50b74d52f1df9936fdaa6f027
7,809
cc
C++
rl_agent/src/Agent/Sarsa.cc
utexas-rl-texplore/rl_suite
73b5c3cdeaa2397cef6758dad8275193e7b0019a
[ "BSD-3-Clause" ]
1
2015-07-23T21:14:56.000Z
2015-07-23T21:14:56.000Z
rl_agent/src/Agent/Sarsa.cc
utexas-rl-texplore/rl_suite
73b5c3cdeaa2397cef6758dad8275193e7b0019a
[ "BSD-3-Clause" ]
null
null
null
rl_agent/src/Agent/Sarsa.cc
utexas-rl-texplore/rl_suite
73b5c3cdeaa2397cef6758dad8275193e7b0019a
[ "BSD-3-Clause" ]
1
2018-03-01T05:54:44.000Z
2018-03-01T05:54:44.000Z
#include <rl_agent/Sarsa.hh> #include <algorithm> Sarsa::Sarsa(int numactions, float gamma, float initialvalue, float alpha, float ep, float lambda, Random rng): numactions(numactions), gamma(gamma), initialvalue(initialvalue), alpha(alpha), epsilon(ep), lambda(lambda), rng(rng) { currentq = NULL; ACTDEBUG = false; //true; //false; ELIGDEBUG = false; } Sarsa::~Sarsa() {} int Sarsa::first_action(const std::vector<float> &s) { if (ACTDEBUG){ cout << "First - in state: "; printState(s); cout << endl; } // clear all eligibility traces for (std::map<state_t, std::vector<float> >::iterator i = eligibility.begin(); i != eligibility.end(); i++){ std::vector<float> & elig_s = (*i).second; for (int j = 0; j < numactions; j++){ elig_s[j] = 0.0; } } // Get action values state_t si = canonicalize(s); std::vector<float> &Q_s = Q[si]; // Choose an action const std::vector<float>::iterator a = rng.uniform() < epsilon ? Q_s.begin() + rng.uniformDiscrete(0, numactions - 1) // Choose randomly : random_max_element(Q_s.begin(), Q_s.end()); // Choose maximum // set eligiblity to 1 std::vector<float> &elig_s = eligibility[si]; elig_s[a-Q_s.begin()] = 1.0; if (ACTDEBUG){ cout << " act: " << (a-Q_s.begin()) << " val: " << *a << endl; for (int iAct = 0; iAct < numactions; iAct++){ cout << " Action: " << iAct << " val: " << Q_s[iAct] << endl; } cout << "Took action " << (a-Q_s.begin()) << " from state "; printState(s); cout << endl; } return a - Q_s.begin(); } int Sarsa::next_action(float r, const std::vector<float> &s) { if (ACTDEBUG){ cout << "Next: got reward " << r << " in state: "; printState(s); cout << endl; } // Get action values state_t st = canonicalize(s); std::vector<float> &Q_s = Q[st]; const std::vector<float>::iterator max = random_max_element(Q_s.begin(), Q_s.end()); // Choose an action const std::vector<float>::iterator a = rng.uniform() < epsilon ? Q_s.begin() + rng.uniformDiscrete(0, numactions - 1) : max; // Update value for all with positive eligibility for (std::map<state_t, std::vector<float> >::iterator i = eligibility.begin(); i != eligibility.end(); i++){ state_t si = (*i).first; std::vector<float> & elig_s = (*i).second; for (int j = 0; j < numactions; j++){ if (elig_s[j] > 0.0){ if (ELIGDEBUG) { cout << "updating state " << (*((*i).first))[0] << ", " << (*((*i).first))[1] << " act: " << j << " with elig: " << elig_s[j] << endl; } // update Q[si][j] += alpha * elig_s[j] * (r + gamma * (*a) - Q[si][j]); elig_s[j] *= lambda; } } } // Set elig to 1 eligibility[st][a-Q_s.begin()] = 1.0; if (ACTDEBUG){ cout << " act: " << (a-Q_s.begin()) << " val: " << *a << endl; for (int iAct = 0; iAct < numactions; iAct++){ cout << " Action: " << iAct << " val: " << Q_s[iAct] << endl; } cout << "Took action " << (a-Q_s.begin()) << " from state "; printState(s); cout << endl; } return a - Q_s.begin(); } void Sarsa::last_action(float r) { if (ACTDEBUG){ cout << "Last: got reward " << r << endl; } // Update value for all with positive eligibility for (std::map<state_t, std::vector<float> >::iterator i = eligibility.begin(); i != eligibility.end(); i++){ state_t si = (*i).first; std::vector<float> & elig_s = (*i).second; for (int j = 0; j < numactions; j++){ if (elig_s[j] > 0.0){ if (ELIGDEBUG){ cout << "updating state " << (*((*i).first))[0] << ", " << (*((*i).first))[1] << " act: " << j << " with elig: " << elig_s[j] << endl; } // update Q[si][j] += alpha * elig_s[j] * (r - Q[si][j]); elig_s[j] = 0.0; } } } } Sarsa::state_t Sarsa::canonicalize(const std::vector<float> &s) { const std::pair<std::set<std::vector<float> >::iterator, bool> result = statespace.insert(s); state_t retval = &*result.first; // Dereference iterator then get pointer if (result.second) { // s is new, so initialize Q(s,a) for all a std::vector<float> &Q_s = Q[retval]; Q_s.resize(numactions,initialvalue); std::vector<float> &elig = eligibility[retval]; elig.resize(numactions,0); } return retval; } std::vector<float>::iterator Sarsa::random_max_element( std::vector<float>::iterator start, std::vector<float>::iterator end) { std::vector<float>::iterator max = std::max_element(start, end); int n = std::count(max, end, *max); if (n > 1) { n = rng.uniformDiscrete(1, n); while (n > 1) { max = std::find(max + 1, end, *max); --n; } } return max; } void Sarsa::setDebug(bool d){ ACTDEBUG = d; } void Sarsa::printState(const std::vector<float> &s){ for (unsigned j = 0; j < s.size(); j++){ cout << s[j] << ", "; } } void Sarsa::seedExp(std::vector<experience> seeds){ // for each seeding experience, update our model for (unsigned i = 0; i < seeds.size(); i++){ experience e = seeds[i]; std::vector<float> &Q_s = Q[canonicalize(e.s)]; // Get q value for action taken const std::vector<float>::iterator a = Q_s.begin() + e.act; // Update value of action just executed Q_s[e.act] += alpha * (e.reward + gamma * (*a) - Q_s[e.act]); /* cout << "Seeding with experience " << i << endl; cout << "last: " << (e.s)[0] << ", " << (e.s)[1] << ", " << (e.s)[2] << endl; cout << "act: " << e.act << " r: " << e.reward << endl; cout << "next: " << (e.next)[0] << ", " << (e.next)[1] << ", " << (e.next)[2] << ", " << e.terminal << endl; cout << "Q: " << *currentq << " max: " << *max << endl; */ } } void Sarsa::logValues(ofstream *of, int xmin, int xmax, int ymin, int ymax){ std::vector<float> s; s.resize(2, 0.0); for (int i = xmin ; i < xmax; i++){ for (int j = ymin; j < ymax; j++){ s[0] = j; s[1] = i; std::vector<float> &Q_s = Q[canonicalize(s)]; const std::vector<float>::iterator max = random_max_element(Q_s.begin(), Q_s.end()); *of << (*max) << ","; } } } float Sarsa::getValue(std::vector<float> state){ state_t s = canonicalize(state); // Get Q values std::vector<float> &Q_s = Q[s]; // Choose an action const std::vector<float>::iterator a = random_max_element(Q_s.begin(), Q_s.end()); // Choose maximum // Get avg value float valSum = 0.0; float cnt = 0; for (std::set<std::vector<float> >::iterator i = statespace.begin(); i != statespace.end(); i++){ state_t s = canonicalize(*i); // get state's info std::vector<float> &Q_s = Q[s]; for (int j = 0; j < numactions; j++){ valSum += Q_s[j]; cnt++; } } cout << "Avg Value: " << (valSum / cnt) << endl; return *a; } void Sarsa::savePolicy(const char* filename){ ofstream policyFile(filename, ios::out | ios::binary | ios::trunc); // first part, save the vector size std::set< std::vector<float> >::iterator i = statespace.begin(); int fsize = (*i).size(); policyFile.write((char*)&fsize, sizeof(int)); // save numactions policyFile.write((char*)&numactions, sizeof(int)); // go through all states, and save Q values for (std::set< std::vector<float> >::iterator i = statespace.begin(); i != statespace.end(); i++){ state_t s = canonicalize(*i); std::vector<float> *Q_s = &(Q[s]); // save state policyFile.write((char*)&((*i)[0]), sizeof(float)*fsize); // save q-values policyFile.write((char*)&((*Q_s)[0]), sizeof(float)*numactions); } policyFile.close(); }
25.271845
144
0.548214
utexas-rl-texplore
07a67fd2461a8d8e01d2b350f64f3c0edfe0e718
8,240
cpp
C++
WGLTest/main.cpp
yorung/WGLGrabber
8887cfc95d2f2040205a084473b96f53f46cf591
[ "MIT" ]
null
null
null
WGLTest/main.cpp
yorung/WGLGrabber
8887cfc95d2f2040205a084473b96f53f46cf591
[ "MIT" ]
null
null
null
WGLTest/main.cpp
yorung/WGLGrabber
8887cfc95d2f2040205a084473b96f53f46cf591
[ "MIT" ]
null
null
null
// WGLTest.cpp : Defines the entry point for the application. // #include "stdafx.h" #include "resource.h" #pragma comment(lib, "opengl32.lib") HGLRC hglrc; static void err(char *msg) { puts(msg); } #ifdef _DEBUG static void DumpInfo() { puts((char*)glGetString(GL_VERSION)); puts((char*)glGetString(GL_RENDERER)); puts((char*)glGetString(GL_VENDOR)); puts((char*)glGetString(GL_SHADING_LANGUAGE_VERSION)); GLint num; glGetIntegerv(GL_NUM_EXTENSIONS, &num); for (int i = 0; i < num; i++) { const GLubyte* ext = glGetStringi(GL_EXTENSIONS, i); printf("%s\n", ext); } } static void APIENTRY debugMessageHandler(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam) { puts(message); } #endif void CreateWGL(HWND hWnd) { HDC hdc = GetDC(hWnd); PIXELFORMATDESCRIPTOR pfd; memset(&pfd, 0, sizeof(pfd)); pfd.nSize = sizeof(pfd); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 24; pfd.cDepthBits = 32; pfd.iLayerType = PFD_MAIN_PLANE; int pixelFormat; if (!(pixelFormat = ChoosePixelFormat(hdc, &pfd))){ err("ChoosePixelFormat failed."); goto END; } if (!SetPixelFormat(hdc, pixelFormat, &pfd)){ err("SetPixelFormat failed."); goto END; } if (!(hglrc = wglCreateContext(hdc))){ err("wglCreateContext failed."); goto END; } if (!wglMakeCurrent(hdc, hglrc)){ err("wglMakeCurrent failed."); goto END; } #if 0 // for test void* glpu = wglGetProcAddress("glProgramUniform1f"); void* gldei = wglGetProcAddress("glDrawElementsIndirect"); void* glen1 = glEnable; void* glen2 = wglGetProcAddress("glEnable"); GLuint(APIENTRY*glCreateProgram)(void); glCreateProgram = (GLuint(APIENTRY*)(void))wglGetProcAddress("glCreateProgram"); GLuint(APIENTRY*glCreateShader)(GLenum type); glCreateShader = (GLuint(APIENTRY*)(GLenum type))wglGetProcAddress("glCreateShader"); GLuint test = glCreateShader(GL_VERTEX_SHADER); void(APIENTRY*glDeleteShader)(GLuint name); glDeleteShader = (void(APIENTRY*)(GLuint name))wglGetProcAddress("glDeleteShader"); glDeleteShader(test); #endif WGLGrabberInit(); int flags = 0; #ifdef _DEBUG flags |= WGL_CONTEXT_DEBUG_BIT_ARB; #endif static const int attribList[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 4, WGL_CONTEXT_MINOR_VERSION_ARB, 3, WGL_CONTEXT_FLAGS_ARB, flags, // WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_ES2_PROFILE_BIT_EXT, 0, }; HGLRC hglrcNew = wglCreateContextAttribsARB(hdc, 0, attribList); wglMakeCurrent(nullptr, nullptr); if (hglrcNew) { wglDeleteContext(hglrc); hglrc = hglrcNew; } if (!wglMakeCurrent(hdc, hglrc)){ err("wglMakeCurrent failed."); goto END; } #ifdef _DEBUG DumpInfo(); glDebugMessageCallbackARB(debugMessageHandler, nullptr); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB); #endif END: // ReleaseDC(hWnd, hdc); // do not release dc; WGL using it return; // do nothing } void DestroyWGL(HWND hWnd) { HDC hdc = wglGetCurrentDC(); if (hdc) { ReleaseDC(hWnd, hdc); } wglMakeCurrent(nullptr, nullptr); if (hglrc) { wglDeleteContext(hglrc); hglrc = nullptr; } } #define MAX_LOADSTRING 100 // Global Variables: HWND hWnd; HINSTANCE hInst; // current instance TCHAR szTitle[MAX_LOADSTRING]; // The title bar text TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name // WindowMessage static BOOL ProcessWindowMessage(){ MSG msg; for (;;){ while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)){ if (msg.message == WM_QUIT){ return FALSE; } TranslateMessage(&msg); DispatchMessage(&msg); } BOOL active = !IsIconic(hWnd) && GetForegroundWindow() == hWnd; if (!active){ WaitMessage(); continue; } return TRUE; } } static void Input() { static bool last; bool current = !!(GetKeyState(VK_LBUTTON) & 0x80); bool edge = current && !last; last = current; if (edge) { POINT pt; GetCursorPos(&pt); ScreenToClient(GetForegroundWindow(), &pt); RECT rc; GetClientRect(hWnd, &rc); int w = rc.right - rc.left; int h = rc.bottom - rc.top; app.CreateRipple((float)pt.x / w * 2 - 1, (float)pt.y / h * -2 + 1); } } // Forward declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); #ifdef _DEBUG int main(int, char**) #else int APIENTRY _tWinMain(_In_ HINSTANCE, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int) #endif { HINSTANCE hInstance = GetModuleHandle(nullptr); // TODO: Place code here. HACCEL hAccelTable; // Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_WGLTEST, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance (hInstance)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_WGLTEST)); GoMyDir(); SetCurrentDirectoryA("assets"); CreateWGL(hWnd); app.Create(); // Main message loop: for (;;) { if (!ProcessWindowMessage()) { break; } Input(); RECT rc; GetClientRect(hWnd, &rc); int w = rc.right - rc.left; int h = rc.bottom - rc.top; app.Update(w, h, 0); app.Draw(); Sleep(1); } return 0; } // // FUNCTION: MyRegisterClass() // // PURPOSE: Registers the window class. // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_WGLTEST)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = MAKEINTRESOURCE(IDC_WGLTEST); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } // // FUNCTION: InitInstance(HINSTANCE, int) // // PURPOSE: Saves instance handle and creates main window // // COMMENTS: // // In this function, we save the instance handle in a global variable and // create and display the main program window. // BOOL InitInstance(HINSTANCE hInstance) { hInst = hInstance; // Store instance handle in our global variable hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } ShowWindow(hWnd, SW_SHOWNORMAL); UpdateWindow(hWnd); return TRUE; } // // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: SendMessage(hWnd, WM_CLOSE, 0, 0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); // TODO: Add any drawing code here... EndPaint(hWnd, &ps); break; case WM_CLOSE: app.Destroy(); DestroyWGL(hWnd); DestroyWindow(hWnd); return 0; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // Message handler for about box. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; }
22.391304
158
0.706917
yorung
07ac87d095f48234a6849915afbc8c7e4e8c70db
1,836
cpp
C++
alignment/algorithms/alignment/ExtendAlign.cpp
ggraham/blasr_libcpp
4abef36585bbb677ebc4acb9d4e44e82331d59f7
[ "RSA-MD" ]
4
2015-07-03T11:59:54.000Z
2018-05-17T00:03:22.000Z
alignment/algorithms/alignment/ExtendAlign.cpp
ggraham/blasr_libcpp
4abef36585bbb677ebc4acb9d4e44e82331d59f7
[ "RSA-MD" ]
79
2015-06-29T18:07:21.000Z
2018-09-19T13:38:39.000Z
alignment/algorithms/alignment/ExtendAlign.cpp
ggraham/blasr_libcpp
4abef36585bbb677ebc4acb9d4e44e82331d59f7
[ "RSA-MD" ]
19
2015-06-23T08:43:29.000Z
2021-04-28T18:37:47.000Z
#include <alignment/algorithms/alignment/ExtendAlign.hpp> RCToIndex::RCToIndex() { qStart = 0; tStart = 0; band = middleCol = nCols = 0; } int RCToIndex::operator()(int r, int c, int &index) { // // First do some error checking on the row and column to see if it // is within the band. // if (r < qStart) { return 0; } if (c < tStart) { return 0; } r -= qStart; c -= tStart; if (std::abs(r - c) > band) { return 0; } // outside band range. if (c < 0) { return 0; } if (middleCol - (r - c) >= nCols) { return 0; } index = (r * nCols) + (middleCol - (r - c)); return 1; } int BaseIndex::QNotAtSeqBoundary(int q) { return q != queryAlignLength; } int BaseIndex::TNotAtSeqBoundary(int t) { return t != refAlignLength; } int BaseIndex::QAlignLength() { return queryAlignLength; } int BaseIndex::TAlignLength() { return refAlignLength; } int ForwardIndex::QuerySeqPos(int q) { return queryPos + q; } int ForwardIndex::RefSeqPos(int t) { return refPos + t; } int ForwardIndex::GetQueryStartPos(int startQ, int endQ) { (void)(endQ); return queryPos + startQ + 1; } int ForwardIndex::GetRefStartPos(int startT, int endT) { (void)(endT); return refPos + startT + 1; } void ForwardIndex::OrderArrowVector(std::vector<Arrow> &mat) { reverse(mat.begin(), mat.end()); } int ReverseIndex::QuerySeqPos(int q) { return queryPos - q; } int ReverseIndex::RefSeqPos(int t) { return refPos - t; } int ReverseIndex::GetQueryStartPos(int startQ, int endQ) { (void)(startQ); return queryPos - (endQ - 1); } int ReverseIndex::GetRefStartPos(int startT, int endT) { (void)(startT); return refPos - (endT - 1); } void ReverseIndex::OrderArrowVector(std::vector<Arrow> &mat) { (void)(mat); }
23.240506
97
0.622549
ggraham
07b0343ec381a5f865f7373ac985c3dd1909dbbe
1,258
hpp
C++
contrib/autoboost/autoboost/asio/detail/cstdint.hpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
87
2015-01-18T00:43:06.000Z
2022-02-11T17:40:50.000Z
contrib/autoboost/autoboost/asio/detail/cstdint.hpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
274
2015-01-03T04:50:49.000Z
2021-03-08T09:01:09.000Z
contrib/autoboost/autoboost/asio/detail/cstdint.hpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
15
2015-09-30T20:58:43.000Z
2020-12-19T21:24:56.000Z
// // detail/cstdint.hpp // ~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef AUTOBOOST_ASIO_DETAIL_CSTDINT_HPP #define AUTOBOOST_ASIO_DETAIL_CSTDINT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <autoboost/asio/detail/config.hpp> #if defined(AUTOBOOST_ASIO_HAS_CSTDINT) # include <cstdint> #else // defined(AUTOBOOST_ASIO_HAS_CSTDINT) # include <autoboost/cstdint.hpp> #endif // defined(AUTOBOOST_ASIO_HAS_CSTDINT) namespace autoboost { namespace asio { #if defined(AUTOBOOST_ASIO_HAS_CSTDINT) using std::int16_t; using std::uint16_t; using std::int32_t; using std::uint32_t; using std::int64_t; using std::uint64_t; #else // defined(AUTOBOOST_ASIO_HAS_CSTDINT) using autoboost::int16_t; using autoboost::uint16_t; using autoboost::int32_t; using autoboost::uint32_t; using autoboost::int64_t; using autoboost::uint64_t; #endif // defined(AUTOBOOST_ASIO_HAS_CSTDINT) } // namespace asio } // namespace autoboost #endif // AUTOBOOST_ASIO_DETAIL_CSTDINT_HPP
25.673469
79
0.762321
CaseyCarter
07b0d35926409ab1270cf5db627937bb6d690ab4
2,991
cpp
C++
src/pd/fireball.cpp
mtribiere/Pixel-dungeon-CPP
ed930aaeefd1f08eed73ced928acae6e1fe34fa4
[ "MIT" ]
null
null
null
src/pd/fireball.cpp
mtribiere/Pixel-dungeon-CPP
ed930aaeefd1f08eed73ced928acae6e1fe34fa4
[ "MIT" ]
null
null
null
src/pd/fireball.cpp
mtribiere/Pixel-dungeon-CPP
ed930aaeefd1f08eed73ced928acae6e1fe34fa4
[ "MIT" ]
null
null
null
#include "../engine/stdafx.h" #include "fireball.h" #include "../pd/define.h" #include "../engine/util.h" #include "../engine/game.h" #include "../engine/pixelparticle.h" float Flame::LIFESPAN = 1.0f; float Flame::SPEED = -40.0f; float Flame::ACC = -20.0f; Flame::Flame() { init(); tag = "Flame"; } void Flame::init() { texture(Assets::FIREBALL); frame(Random::Int(0, 2) == 0 ? Fireball_FLAME1 : Fireball_FLAME2); GameMath::PointFSet(&origin, width / 2, height / 2); //origin.set(width / 2, height / 2); GameMath::PointFSet(&acc, 0, ACC); //acc.set(0, ACC); } void Flame::reset() { revive(); timeLeft = LIFESPAN; GameMath::PointFSet(&speed, 0, SPEED); //speed.set(0, SPEED); } void Flame::update() { Image::update(); if ((timeLeft -= Game::elapsed) <= 0) { kill(); } else { float p = timeLeft / LIFESPAN; GameMath::PointFSet(&scale, p); //scale.set(p); alpha(p > 0.8f ? (1 - p) * 5.0f : p * 1.25f); } } void EmitterFactory1::emit(Emitter* emitter, int index, float x, float y) { Flame* p = (Flame*)emitter->recycle("Flame"); if (p == NULL) { p = (Flame*)emitter->add(new Flame()); } p->reset(); p->x = x - p->width / 2; p->y = y - p->height / 2; } Fireball::Fireball() { init(); } void Fireball::createChildren() { _sparks = new Group(); add(_sparks); _bLight = new Image(Assets::FIREBALL); _bLight->frame(Fireball_BLIGHT); GameMath::PointFSet(&_bLight->origin, _bLight->width / 2); //bLight.origin.set( bLight.width / 2 ); _bLight->angularSpeed = -90; add(_bLight); _emitter = new Emitter(); _emitter->pour(new EmitterFactory1(), 0.1f); add(_emitter); _fLight = new Image(Assets::FIREBALL); _fLight->frame(Fireball_FLIGHT); GameMath::PointFSet(&_fLight->origin, _fLight->width / 2); //_fLight->origin.set(_fLight.width / 2); _fLight->angularSpeed = 360; add(_fLight); // _bLight->tex->filter(Texture::LINEAR, Texture::LINEAR); } void Fireball::layout() { _bLight->x = _x - _bLight->width / 2; _bLight->y = _y - _bLight->height / 2; _emitter->pos( _x - _bLight->width / 4, _y - _bLight->height / 4, _bLight->width / 2, _bLight->height / 2); _fLight->x = _x - _fLight->width / 2; _fLight->y = _y - _fLight->height / 2; } void Fireball::update() { Component::update(); if (Random::Float(0, 1) < Game::elapsed) { PixelParticle* spark = (PixelParticle*)_sparks->recycle("Shrinking"); if (spark == NULL) { //spark = (PixelParticle*)_sparks->add(new Shrinking()); spark = new Shrinking(); } spark->reset(_x, _y, ColorMath::random(COLOR, 0x66FF66), 2, Random::Float(0.5f, 1.0f)); GameMath::PointFSet(&spark->speed, Random::Float(-40, +40), Random::Float(-60, +20)); //spark->speed.set( // Random::Float(-40, +40), // Random::Float(-60, +20)); GameMath::PointFSet(&spark->acc, 0, 80); //spark->acc.set(0, +80); _sparks->add(spark); } }
22.488722
90
0.598462
mtribiere
07b1511a2e57346c6ea7ccea6c9cefb6cda5eb0b
2,880
hpp
C++
include/dtc/utility/lexical_cast.hpp
tsung-wei-huang/DtCraft
80cc9e1195adc0026107814243401a1fc47b5be2
[ "MIT" ]
69
2019-03-16T20:13:26.000Z
2022-03-24T14:12:19.000Z
include/dtc/utility/lexical_cast.hpp
Tsung-Wei/DtCraft
80cc9e1195adc0026107814243401a1fc47b5be2
[ "MIT" ]
12
2017-12-02T05:38:30.000Z
2019-02-08T11:16:12.000Z
include/dtc/utility/lexical_cast.hpp
Tsung-Wei/DtCraft
80cc9e1195adc0026107814243401a1fc47b5be2
[ "MIT" ]
12
2019-04-13T16:27:29.000Z
2022-01-07T14:42:46.000Z
/****************************************************************************** * * * Copyright (c) 2018, Tsung-Wei Huang and Martin D. F. Wong, * * University of Illinois at Urbana-Champaign (UIUC), IL, USA. * * * * All Rights Reserved. * * * * This program is free software. You can redistribute and/or modify * * it in accordance with the terms of the accompanying license agreement. * * See LICENSE in the top-level directory for details. * * * ******************************************************************************/ #ifndef DTC_UTILITY_LEXICAL_CAST_HPP_ #define DTC_UTILITY_LEXICAL_CAST_HPP_ namespace dtc::lexical_cast_impl { template <typename T> struct Converter; // Numeric to string template <> struct Converter<std::string> { static auto convert(auto&& from) { return std::to_string(from); } }; template <> struct Converter<int> { static auto convert(std::string_view from) { return std::atoi(from.data()); } }; template <> struct Converter<long> { static auto convert(std::string_view from) { return std::atol(from.data()); } }; template <> struct Converter<long long> { static auto convert(std::string_view from) { return std::atoll(from.data()); } }; template <> struct Converter<unsigned long> { static auto convert(std::string_view from) { return std::strtoul(from.data(), nullptr, 10); } }; template <> struct Converter<unsigned long long> { static auto convert(std::string_view from) { return std::strtoull(from.data(), nullptr, 10); } }; template <> struct Converter<float> { static auto convert(std::string_view from) { return std::strtof(from.data(), nullptr); } }; template <> struct Converter<double> { static auto convert(std::string_view from) { return std::strtod(from.data(), nullptr); } }; template <> struct Converter<long double> { static auto convert(std::string_view from) { return std::strtold(from.data(), nullptr); } }; }; // end of namespace dtc::lexical_cast_details. ------------------------------------------------ namespace dtc { template <typename To, typename From> auto lexical_cast(From&& from) { using T = std::decay_t<To>; using F = std::decay_t<From>; if constexpr (std::is_same_v<T, F>) { return from; } else { return lexical_cast_impl::Converter<T>::convert(from); } } }; // End of namespace dtc. --------------------------------------------------------------------- #endif
26.666667
99
0.514236
tsung-wei-huang
07bb133c50e133d17bddf58d15a7b25f9eb6fb7a
6,886
hpp
C++
library/include/slonczewski2.hpp
xfong/sycl
405397e7bd030d104c5c88f403a617b6e8c3429a
[ "MIT" ]
1
2021-06-15T02:42:29.000Z
2021-06-15T02:42:29.000Z
library/include/slonczewski2.hpp
xfong/sycl
405397e7bd030d104c5c88f403a617b6e8c3429a
[ "MIT" ]
null
null
null
library/include/slonczewski2.hpp
xfong/sycl
405397e7bd030d104c5c88f403a617b6e8c3429a
[ "MIT" ]
null
null
null
#ifndef RUNTIME_INCLUDE_SYCL_SYCL_HPP_ #define RUNTIME_INCLUDE_SYCL_SYCL_HPP_ #include <CL/sycl.hpp> namespace sycl = cl::sycl; #endif // RUNTIME_INCLUDE_SYCL_SYCL_HPP_ #include "amul.hpp" #include "constants.hpp" // Original implementation by Mykola Dvornik for mumax2 // Modified for mumax3 by Arne Vansteenkiste, 2013, 2016 template <typename dataT> class addslonczewskitorque2_kernel { public: using read_accessor = sycl::accessor<dataT, 1, sycl::access::mode::read, sycl::access::target::global_buffer>; using write_accessor = sycl::accessor<dataT, 1, sycl::access::mode::read_write, sycl::access::target::global_buffer>; addslonczewskitorque2_kernel(write_accessor tXPtr, write_accessor tYPtr, write_accessor tZPtr, read_accessor mxPtr, read_accessor myPtr, read_accessor mzPtr, read_accessor MsPtr, dataT Ms_mul, read_accessor jzPtr, dataT jz_mul, read_accessor pxPtr, dataT px_mul, read_accessor pyPtr, dataT py_mul, read_accessor pzPtr, dataT pz_mul, read_accessor alphaPtr, dataT alpha_mul, read_accessor polPtr, dataT pol_mul, read_accessor lambdaPtr, dataT lambda_mul, read_accessor epsPrimePtr, dataT epsPrime_mul, read_accessor fltPtr, dataT flt_mul, size_t N) : tx(tXPtr), ty(tYPtr), tz(tZPtr), mx_(mxPtr), my_(myPtr), mz_(mzPtr), Ms_(MsPtr), Ms_mul(Ms_mul), jz_(jzPtr), jz_mul(jz_mul), px_(pxPtr), px_mul(px_mul), py_(pyPtr), py_mul(py_mul), pz_(pzPtr), pz_mul(pz_mul), alpha_(alphaPtr), alpha_mul(alpha_mul), pol_(polPtr), pol_mul(pol_mul), lambda_(lambdaPtr), lambda_mul(lambda_mul), epsPrime_(epsPrimePtr), epsPrime_mul(epsPrime_mul), flt_(fltPtr), flt_mul(flt_mul), N(N) {} void operator()(sycl::nd_item<1> item) { size_t stride = item.get_global_range(0); for (size_t gid = item.get_global_linear_id(); gid < N; gid += stride) { dataT J = amul(jz_, jz_mul, gid); dataT Ms = amul(Ms_, Ms_mul, gid); if (J == (dataT)(0.0) || Ms == (dataT)(0.0)) { return; } sycl::vec<dataT, 3> m = make_vec3(mx_[gid], my_[gid], mz_[gid]); sycl::vec<dataT, 3> p = normalized(vmul(px_, py_, pz_, px_mul, py_mul, pz_mul, gid)); dataT alpha = amul(alpha_, alpha_mul, gid); dataT flt = amul(flt_, flt_mul, gid); dataT pol = amul(pol_, pol_mul, gid); dataT lambda = amul(lambda_, lambda_mul, gid); dataT epsilonPrime = amul(epsPrime_, epsPrime_mul, gid); dataT beta = (HBAR / QE) * (J / (flt*Ms) ); dataT lambda2 = lambda * lambda; dataT epsilon = pol * lambda2 / ((lambda2 + (dataT)(1.0)) + (lambda2 - (dataT)(1.0)) * sycl::dot(p, m)); dataT A = beta * epsilon; dataT B = beta * epsilonPrime; dataT gilb = (dataT)(1.0) / ((dataT)(1.0) + alpha * alpha); dataT mxpxmFac = gilb * (A + alpha * B); dataT pxmFac = gilb * (B - alpha * A); sycl::vec<dataT, 3> pxm = sycl::cross(p, m); sycl::vec<dataT, 3> mxpxm = sycl::cross(m, pxm); tx[gid] += mxpxmFac * mxpxm.x() + pxmFac * pxm.x(); ty[gid] += mxpxmFac * mxpxm.y() + pxmFac * pxm.y(); tz[gid] += mxpxmFac * mxpxm.z() + pxmFac * pxm.z(); } } private: write_accessor tx; write_accessor ty; write_accessor tz; read_accessor mx_; read_accessor my_; read_accessor mz_; read_accessor jz_; dataT jz_mul; read_accessor px_; dataT px_mul; read_accessor py_; dataT py_mul; read_accessor pz_; dataT jz_mul; read_accessor alpha_; dataT alpha_mul; read_accessor pol_; dataT pol_mul; read_accessor lambda_; dataT lambda_mul; read_accessor epsPrime_; dataT epsPrime_mul; read_accessor flt_; dataT flt_mul; size_t N; }; template <typename dataT> void addslonczewskitorque2_async(sycl::queue funcQueue, sycl::buffer<dataT, 1> *tx, sycl::buffer<dataT, 1> *ty, sycl::buffer<dataT, 1> *tz, sycl::buffer<dataT, 1> *mx, sycl::buffer<dataT, 1> *my, sycl::buffer<dataT, 1> *mz, sycl::buffer<dataT, 1> *Ms, dataT Ms_mul, sycl::buffer<dataT, 1> *jz, dataT jz_mul, sycl::buffer<dataT, 1> *px, dataT px_mul, sycl::buffer<dataT, 1> *py, dataT py_mul, sycl::buffer<dataT, 1> *pz, dataT pz_mul, sycl::buffer<dataT, 1> *alpha, dataT alpha_mul, sycl::buffer<dataT, 1> *pol, dataT pol_mul, sycl::buffer<dataT, 1> *lambda, dataT lambda_mul, sycl::buffer<dataT, 1> *epsPrime, dataT epsPrime_mul, sycl::buffer<dataT, 1> *flt, dataT flt_mul, size_t N, size_t gsize, size_t lsize) { funcQueue.submit([&] (sycl::handler& cgh) { auto tx_acc = tx->template get_access<sycl::access::mode::read_write>(cgh); auto ty_acc = ty->template get_access<sycl::access::mode::read_write>(cgh); auto tz_acc = tz->template get_access<sycl::access::mode::read_write>(cgh); auto mx_acc = mx->template get_access<sycl::access::mode::read>(cgh); auto my_acc = my->template get_access<sycl::access::mode::read>(cgh); auto mz_acc = mz->template get_access<sycl::access::mode::read>(cgh); auto Ms_acc = Ms->template get_access<sycl::access::mode::read>(cgh); auto jz_acc = jz->template get_access<sycl::access::mode::read>(cgh); auto px_acc = px->template get_access<sycl::access::mode::read>(cgh); auto py_acc = py->template get_access<sycl::access::mode::read>(cgh); auto pz_acc = pz->template get_access<sycl::access::mode::read>(cgh); auto alpha_acc = alpha_->template get_access<sycl::access::mode::read>(cgh); auto pol_acc = pol->template get_access<sycl::access::mode::read>(cgh); auto lambda_acc = lambda->template get_access<sycl::access::mode::read>(cgh); auto epsPrime_acc = epsPrime->template get_access<sycl::access::mode::read>(cgh); auto flt_acc = flt->template get_access<sycl::access::mode::read>(cgh); cgh.parallel_for(sycl::nd_range<1>(sycl::range<1>(gsize), sycl::range<1>(lsize)), addslonczewskitorque2_kernel<dataT>(tx_acc, ty_acc, tz_acc, mx_acc, my_acc, mz_acc, Ms_acc, Ms_mul, jz_acc, jz_mul, px_acc, px_mul, py_acc, py_mul, pz_acc, pz_mul, alpha_acc, alpha_mul, pol_acc, pol_mul, lambda_acc, lambda_mul, epsPrime_acc, epsPrime_mul, flt_acc, flt_mul, N)); }); }
38.685393
108
0.60456
xfong
07be85a0d07b42bcce7185e3727e05f66421b709
5,501
cpp
C++
test/json_parser_tests.cpp
Malibushko/yatgbotlib
a5109c36c9387aef0e6d15e303d2f3753eef9aac
[ "MIT" ]
3
2020-04-05T23:51:09.000Z
2020-08-14T07:24:45.000Z
test/json_parser_tests.cpp
Malibushko/yatgbotlib
a5109c36c9387aef0e6d15e303d2f3753eef9aac
[ "MIT" ]
1
2020-07-24T19:46:28.000Z
2020-07-31T14:49:28.000Z
test/json_parser_tests.cpp
Malibushko/yatgbotlib
a5109c36c9387aef0e6d15e303d2f3753eef9aac
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <memory> #include "telegram_bot.h" using namespace telegram; struct Small { declare_struct declare_field(bool,test); }; TEST(JsonParser,to_json_small_structure) { std::string json = JsonParser::i().toJson(Small{false}); std::string expected_json = "{\"test\":false}"; EXPECT_EQ(expected_json,json); } struct Large { declare_struct declare_field(bool,b1); declare_field(bool,b2); declare_field(bool,b3); declare_field(bool,b4); declare_field(bool,b5); declare_field(bool,b6); declare_field(bool,b7); declare_field(bool,b8); declare_field(bool,b9); declare_field(bool,b10); declare_field(bool,b11); declare_field(bool,b12); declare_field(bool,b13); declare_field(bool,b14); declare_field(bool,b15); declare_field(bool,b16); declare_field(bool,b17); declare_field(bool,b18); declare_field(bool,b19); declare_field(bool,b20); declare_field(bool,b21); declare_field(bool,b22); declare_field(bool,b23); declare_field(bool,b24); declare_field(bool,b25); Large() = default; }; TEST(JsonParser,to_json_large_structure) { std::string json = JsonParser::i().toJson(Large{}); std::string expected_json = "{" "\"b1\":false," "\"b2\":false," "\"b3\":false," "\"b4\":false," "\"b5\":false," "\"b6\":false," "\"b7\":false," "\"b8\":false," "\"b9\":false," "\"b10\":false," "\"b11\":false," "\"b12\":false," "\"b13\":false," "\"b14\":false," "\"b15\":false," "\"b16\":false," "\"b17\":false," "\"b18\":false," "\"b19\":false," "\"b20\":false," "\"b21\":false," "\"b22\":false," "\"b23\":false," "\"b24\":false," "\"b25\":false" "}"; EXPECT_EQ(expected_json,json); } struct Array { declare_struct declare_field(std::vector<int>,data); }; TEST(JsonParser,to_json_array_type) { Array arr; arr.data = {1,2,3,4,5}; std::string json = JsonParser::i().toJson(arr); std::string expected_json = "{\"data\":[1,2,3,4,5]}"; EXPECT_EQ(expected_json,json); } struct ComplexArray { declare_struct declare_field(std::vector<Small>,data); }; TEST(JsonParser,to_json_complex_array_type) { ComplexArray arr; arr.data = {{false},{true},{false}}; std::string json = JsonParser::i().toJson(arr); std::string expected_json = "{\"data\":[{\"test\":false},{\"test\":true},{\"test\":false}]}"; EXPECT_EQ(expected_json,json); } struct SharedPtr { declare_struct declare_field(std::unique_ptr<int>,data); }; TEST(JsonParse,to_json_unique_ptr) { SharedPtr ptr; ptr.data = std::make_unique<int>(5); std::string json = JsonParser::i().toJson(ptr); std::string expected_json = "{\"data\":5}"; EXPECT_EQ(expected_json,json); } struct Variant { using variant_type = std::variant<std::string,int>; declare_struct declare_field(variant_type,data); }; TEST(JsonParser,to_json_variant) { Variant test1; Variant test2; test1.data = 5; test2.data = "Test"; std::string json_1 = JsonParser::i().toJson(test1); std::string expected_json_1 = "{\"data\":5}"; std::string json_2 = JsonParser::i().toJson(test2); std::string expected_json_2 = "{\"data\":\"Test\"}"; EXPECT_EQ(expected_json_1,json_1); EXPECT_EQ(expected_json_2,json_2); } struct Matrix { declare_struct declare_field(std::vector<std::vector<int>>,data); }; TEST(JsonParser,to_json_2darray) { Matrix m{ {{1,2,3}, {4,5,6}, {7,8,9}} }; std::string json = JsonParser::i().toJson(m); std::string expected_json = "{\"data\":[[1,2,3],[4,5,6],[7,8,9]]}"; EXPECT_EQ(expected_json,json); } TEST(JsonParser,forward_reverse_parse) { Small m{true}; std::string json = JsonParser::i().toJson(m); Small after = JsonParser::i().fromJson<Small>(json); EXPECT_EQ(m.test,after.test); } TEST(JsonParser,parse_array) { ComplexArray arr = JsonParser::i().fromJson<ComplexArray>({"{\"data\":[{\"test\":false},{\"test\":true},{\"test\":false}]}"}); auto expected = std::vector<Small>{{false},{true},{false}}; if (arr.data.size() != expected.size()) { ASSERT_TRUE(false); } for (size_t i = 0; i < arr.data.size();++i) if (arr.data[i].test != expected[i].test) { ASSERT_TRUE(false); break; } ASSERT_TRUE(true); } TEST(JsonParse,parse_unique_ptr) { SharedPtr ptr = JsonParser::i().fromJson<SharedPtr>({"{\"data\":5}"}); if (!ptr.data) { ASSERT_TRUE(false); } EXPECT_EQ((*ptr.data),5); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
30.561111
130
0.52954
Malibushko
07bf4da729fee2acecdbde117105c397b5a6f1e3
108
cc
C++
15/17/17.cc
williamgherman/cpp-solutions
cf947b3b8f49fa3071fbee96f522a4228e4207b8
[ "BSD-Source-Code" ]
5
2019-08-01T07:52:27.000Z
2022-03-27T08:09:35.000Z
15/17/17.cc
williamgherman/cpp-solutions
cf947b3b8f49fa3071fbee96f522a4228e4207b8
[ "BSD-Source-Code" ]
1
2020-10-03T17:29:59.000Z
2020-11-17T10:03:10.000Z
15/17/17.cc
williamgherman/cpp-solutions
cf947b3b8f49fa3071fbee96f522a4228e4207b8
[ "BSD-Source-Code" ]
6
2019-08-24T08:55:56.000Z
2022-02-09T08:41:44.000Z
#include <iostream> #include "quote.h" int main() { Disc_quote *dq = new Disc_quote(); return 0; }
12
38
0.62037
williamgherman
07bfa487955b94af69270d30843ef63cdab3b98c
565
hpp
C++
include/render_objects/materials.hpp
Adanos020/ErupTrace
2d359c4d53e758299e8b2d476d945fe2dd2f1c2d
[ "MIT" ]
null
null
null
include/render_objects/materials.hpp
Adanos020/ErupTrace
2d359c4d53e758299e8b2d476d945fe2dd2f1c2d
[ "MIT" ]
null
null
null
include/render_objects/materials.hpp
Adanos020/ErupTrace
2d359c4d53e758299e8b2d476d945fe2dd2f1c2d
[ "MIT" ]
null
null
null
#pragma once #include <render_objects/textures.hpp> #include <util/numeric.hpp> enum class material_type { none, dielectric, diffuse, emit_light, reflect, }; struct material { material_type type; array_index index; invalidable_array_index normals_index = -1; }; struct dielectric_material { float refractive_index; texture albedo; }; struct diffuse_material { texture albedo; }; struct emit_light_material { texture emit; float intensity; }; struct reflect_material { float fuzz; texture albedo; };
13.139535
47
0.699115
Adanos020
07bfa6f58fb68fda020022bc25a05be5ec795fdd
3,232
cpp
C++
src/plugins/snails/certificateverifier.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
120
2015-01-22T14:10:39.000Z
2021-11-25T12:57:16.000Z
src/plugins/snails/certificateverifier.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
8
2015-02-07T19:38:19.000Z
2017-11-30T20:18:28.000Z
src/plugins/snails/certificateverifier.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
33
2015-02-07T16:59:55.000Z
2021-10-12T00:36:40.000Z
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #include "certificateverifier.h" #include <QSslCertificate> #include <QSslError> #include <QtDebug> #include <vmime/security/cert/certificateExpiredException.hpp> #include <vmime/security/cert/certificateNotYetValidException.hpp> #include <vmime/security/cert/serverIdentityException.hpp> #include "vmimeconversions.h" namespace LC { namespace Snails { void CertificateVerifier::verify (const vmime::shared_ptr<vmime::security::cert::certificateChain>& chain, const vmime::string& host) { namespace vsc = vmime::security::cert; QList<QSslCertificate> qtChain; for (size_t i = 0; i < chain->getCount (); ++i) { const auto& item = chain->getAt (i); const auto& subcerts = ToSslCerts (item); if (subcerts.size () != 1) { qWarning () << Q_FUNC_INFO << "unexpected certificates count for certificate type" << item->getType ().c_str () << ", got" << subcerts.size () << "certificates"; throw vsc::unsupportedCertificateTypeException { "unexpected certificates counts" }; } qtChain << subcerts.at (0); } const auto& errs = QSslCertificate::verify (qtChain, QString::fromStdString (host)); if (errs.isEmpty ()) return; qWarning () << Q_FUNC_INFO << errs; for (const auto& error : errs) switch (error.error ()) { case QSslError::CertificateExpired: throw vsc::certificateExpiredException {}; case QSslError::CertificateNotYetValid: throw vsc::certificateNotYetValidException {}; case QSslError::HostNameMismatch: throw vsc::serverIdentityException {}; case QSslError::UnableToDecryptCertificateSignature: case QSslError::InvalidNotAfterField: case QSslError::InvalidNotBeforeField: case QSslError::CertificateSignatureFailed: case QSslError::PathLengthExceeded: case QSslError::UnspecifiedError: throw vsc::unsupportedCertificateTypeException { "incorrect format" }; case QSslError::UnableToGetIssuerCertificate: case QSslError::UnableToGetLocalIssuerCertificate: case QSslError::UnableToDecodeIssuerPublicKey: case QSslError::UnableToVerifyFirstCertificate: case QSslError::SubjectIssuerMismatch: case QSslError::AuthorityIssuerSerialNumberMismatch: throw vsc::certificateIssuerVerificationException {}; case QSslError::SelfSignedCertificate: case QSslError::SelfSignedCertificateInChain: case QSslError::CertificateRevoked: case QSslError::InvalidCaCertificate: case QSslError::InvalidPurpose: case QSslError::CertificateUntrusted: case QSslError::CertificateRejected: case QSslError::NoPeerCertificate: case QSslError::CertificateBlacklisted: throw vsc::certificateNotTrustedException {}; case QSslError::NoError: case QSslError::NoSslSupport: break; } throw vsc::certificateException { "other certificate error" }; } } }
33.666667
107
0.70854
Maledictus
07c332a9ae226d86b1e4bd084ebfb7c05934abd2
3,769
hpp
C++
core/unit_test/TestCompilerMacros.hpp
Char-Aznable/kokkos
2983b80d9aeafabb81f2c8c1c5a49b40cc0856cb
[ "BSD-3-Clause" ]
2
2019-12-18T20:37:06.000Z
2020-04-07T00:44:39.000Z
core/unit_test/TestCompilerMacros.hpp
Char-Aznable/kokkos
2983b80d9aeafabb81f2c8c1c5a49b40cc0856cb
[ "BSD-3-Clause" ]
1
2019-09-25T15:41:23.000Z
2019-09-25T15:41:23.000Z
core/unit_test/TestCompilerMacros.hpp
Char-Aznable/kokkos
2983b80d9aeafabb81f2c8c1c5a49b40cc0856cb
[ "BSD-3-Clause" ]
2
2020-04-01T19:16:16.000Z
2022-02-09T21:45:19.000Z
/* //@HEADER // ************************************************************************ // // Kokkos v. 2.0 // Copyright (2014) Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact Christian R. Trott ([email protected]) // // ************************************************************************ //@HEADER */ #include <Kokkos_Core.hpp> #if defined(KOKKOS_ENABLE_CUDA) && \ ( !defined(KOKKOS_ENABLE_CUDA_LAMBDA) || \ ( ( defined(KOKKOS_ENABLE_SERIAL) || defined(KOKKOS_ENABLE_OPENMP) ) && \ ( (CUDA_VERSION < 8000) && defined( __NVCC__ )))) #if defined(KOKKOS_ENABLE_CXX11_DISPATCH_LAMBDA) #error "Macro bug: KOKKOS_ENABLE_CXX11_DISPATCH_LAMBDA shouldn't be defined" #endif #else #if !defined(KOKKOS_ENABLE_CXX11_DISPATCH_LAMBDA) #error "Macro bug: KOKKOS_ENABLE_CXX11_DISPATCH_LAMBDA should be defined" #endif #endif #define KOKKOS_PRAGMA_UNROLL(a) namespace TestCompilerMacros { template< class DEVICE_TYPE > struct AddFunctor { typedef DEVICE_TYPE execution_space; typedef typename Kokkos::View< int**, execution_space > type; type a, b; int length; AddFunctor( type a_, type b_ ) : a( a_ ), b( b_ ), length( a.extent(1) ) {} KOKKOS_INLINE_FUNCTION void operator()( int i ) const { #ifdef KOKKOS_ENABLE_PRAGMA_UNROLL #pragma unroll #endif #ifdef KOKKOS_ENABLE_PRAGMA_IVDEP #pragma ivdep #endif #ifdef KOKKOS_ENABLE_PRAGMA_VECTOR #pragma vector always #endif #ifdef KOKKOS_ENABLE_PRAGMA_LOOPCOUNT #pragma loop count(128) #endif #ifndef KOKKOS_DEBUG #ifdef KOKKOS_ENABLE_PRAGMA_SIMD #pragma simd #endif #endif for ( int j = 0; j < length; j++ ) { a( i, j ) += b( i, j ); } } }; template< class DeviceType > bool Test() { typedef typename Kokkos::View< int**, DeviceType > type; type a( "A", 1024, 128 ); type b( "B", 1024, 128 ); AddFunctor< DeviceType > f( a, b ); Kokkos::parallel_for( 1024, f ); DeviceType().fence(); return true; } } // namespace TestCompilerMacros namespace Test { TEST_F( TEST_CATEGORY, compiler_macros ) { ASSERT_TRUE( ( TestCompilerMacros::Test< TEST_EXECSPACE >() ) ); } }
31.940678
80
0.69541
Char-Aznable
07c6da4c0d86010f51fdce92114fe99aaffbe8c5
7,727
cpp
C++
rfm69.cpp
wintersteiger/wlmcd
7bdc184b875a0be652a0dd346fd9a598c14181d8
[ "MIT" ]
4
2021-01-11T13:50:25.000Z
2021-01-24T19:34:47.000Z
rfm69.cpp
wintersteiger/wlmcd
7bdc184b875a0be652a0dd346fd9a598c14181d8
[ "MIT" ]
1
2021-02-12T15:49:18.000Z
2021-02-12T16:50:55.000Z
rfm69.cpp
wintersteiger/wlmcd
7bdc184b875a0be652a0dd346fd9a598c14181d8
[ "MIT" ]
2
2021-01-11T13:53:18.000Z
2021-03-01T10:22:46.000Z
// Copyright (c) Christoph M. Wintersteiger // Licensed under the MIT License. #include <cstring> #include <cmath> #include <unistd.h> #include <vector> #include <fstream> #include <iomanip> #include <gpiod.h> #include "json.hpp" #include "sleep.h" #include "rfm69.h" #include "rfm69_rt.h" using json = nlohmann::json; RFM69::RFM69( unsigned spi_bus, unsigned spi_channel, const std::string &config_file, double f_xosc) : Device(), SPIDev(spi_bus, spi_channel, 10000000), RT(new RegisterTable(*this)), spi_channel(spi_channel), f_xosc(f_xosc), f_step(f_xosc / pow(2, 19)) // , // recv_buf(new uint8_t[1024]), // recv_buf_sz(1024), recv_buf_begin(0), recv_buf_pos(0) { Reset(); SetMode(Mode::STDBY); if (!config_file.empty()) { auto is = std::ifstream(config_file); Read(is); } SetMode(Mode::RX); RT->Refresh(false); } RFM69::~RFM69() { Reset(); SetMode(Mode::SLEEP); // delete[](recv_buf); delete(RT); } void RFM69::Reset() { ClearFlags(); SetMode(Mode::STDBY); } uint8_t RFM69::Read(const uint8_t &addr) { mtx.lock(); std::vector<uint8_t> res(2); res[0] = addr & 0x7F; SPIDev::Transfer(res); mtx.unlock(); return res[1]; } std::vector<uint8_t> RFM69::Read(const uint8_t &addr, size_t length) { mtx.lock(); std::vector<uint8_t> res(length + 1); res[0] = addr & 0x7F; SPIDev::Transfer(res); res.erase(res.begin()); mtx.unlock(); return res; } void RFM69::Write(const uint8_t &addr, const uint8_t &value) { mtx.lock(); std::vector<uint8_t> buf(2); buf[0] = 0x80 | (addr & 0x7F); buf[1] = value; SPIDev::Transfer(buf); mtx.unlock(); } void RFM69::Write(const uint8_t &addr, const std::vector<uint8_t> &values) { mtx.lock(); size_t n = values.size(); std::vector<uint8_t> buf(n+1); buf[0] = 0x80 | (addr & 0x7F);; memcpy(&buf[1], values.data(), n); SPIDev::Transfer(buf); mtx.unlock(); } RFM69::Mode RFM69::GetMode() { return (Mode)RT->_vMode(Read(RT->_rOpMode)); } void RFM69::SetMode(Mode m) { uint8_t nv = RT->_vMode.Set(Read(RT->_rOpMode), m); Write(RT->_rOpMode, nv); size_t limit = 50; do { if (GetMode() == m) return; sleep_us(10); } while(--limit); // Device did not react after `limit` tries. responsive = false; } void RFM69::UpdateFrequent() { RT->Refresh(true); } void RFM69::UpdateInfrequent() { RT->Refresh(false); } void RFM69::Write(std::ostream &os) { RT->Write(os); } void RFM69::Read(std::istream &is) { RT->Read(is); } void RFM69::ClearFlags() { uint8_t irq1 = Read(RT->_rIrqFlags1); uint8_t irq2 = Read(RT->_rIrqFlags2); Write(RT->_rIrqFlags1, irq1 | 0x09); // RSSI, SyncAddressMatch Write(RT->_rIrqFlags2, irq2 | 0x10); // FifoOverrun } void RFM69::Receive(std::vector<uint8_t> &packet) { const uint8_t format = RT->_vPacketFormat(Read(RT->_rPacketConfig1)); const uint8_t length = Read(RT->_rPayloadLength); const uint8_t threshold = RT->_vFifoThreshold(Read(RT->_rFifoThresh)); size_t max_wait = 5; packet.resize(0); if (format == 0 && length == 0) throw std::runtime_error("unlimited packet length not implemented yet"); else { packet.reserve(length); while (packet.size() < length && max_wait > 0) { uint8_t irqflags2 = Read(RT->_rIrqFlags2); if (RT->_vFifoNotEmpty(irqflags2)) { if (RT->_vFifoLevel(irqflags2)) { // auto p = Read(RT->_rFifo.Address(), threshold); // packet.insert(packet.end(), p.begin(), p.end()); for (size_t i = 0; i < threshold; i++) packet.push_back(Read(RT->_rFifo)); } else packet.push_back(Read(RT->_rFifo)); } else { sleep_us(8 * (1e6 / rBitrate())); max_wait--; } } } // uint8_t crc; // size_t rxbytes_last = 0, rxbytes = 1; // while (true) // { // do { // rxbytes_last = rxbytes; // rxbytes = 128; // number of bytes in fifo not available? // } while (rxbytes != rxbytes_last); // bool overflow = (rxbytes & 0x80) != 0; // size_t n = rxbytes & 0x7F; // size_t m = n <= 1 ? n : n-1; // if (n == 0) // break; // else if (overflow) { // break; // } // else // { // std::vector<uint8_t> buf = Read(RT->_rFifo.Address(), m); // for (uint8_t &bi : buf) { // recv_buf[recv_buf_pos++] = bi; // recv_buf_pos %= recv_buf_sz; // } // } // sleep_us(1000); // give the FIFO a chance to catch up // } // size_t pkt_sz = recv_buf_held(), i=0; // packet.resize(pkt_sz); // while (recv_buf_begin != recv_buf_pos) { // packet[i++] = recv_buf[recv_buf_begin++]; // recv_buf_begin %= recv_buf_sz; // } // recv_buf_begin = recv_buf_pos; } void RFM69::Transmit(const std::vector<uint8_t> &pkt) { } void RFM69::Test(const std::vector<uint8_t> &data) { Transmit(data); } double RFM69::rRSSI() const { return - (RT->RssiValue() / 2.0); } uint64_t RFM69::rSyncWord() const { uint64_t r = 0; r = (r << 8) | RT->SyncValue1(); r = (r << 8) | RT->SyncValue2(); r = (r << 8) | RT->SyncValue3(); r = (r << 8) | RT->SyncValue4(); r = (r << 8) | RT->SyncValue5(); r = (r << 8) | RT->SyncValue6(); r = (r << 8) | RT->SyncValue7(); r = (r << 8) | RT->SyncValue8(); return r; } double RFM69::rBitrate() const { uint64_t br = (RT->BitrateMsb() << 8) | RT->BitrateLsb(); return F_XOSC() / (double)br / 1e3; } void RFM69::RegisterTable::Refresh(bool frequent) { RegisterTable &rt = *device.RT; uint8_t om = device.Read(rt._rOpMode); uint8_t irq1 = device.Read(rt._rIrqFlags1); uint8_t irq2 = device.Read(rt._rIrqFlags2); uint8_t rssi = device.Read(rt._rRssiValue); uint8_t feim = device.Read(rt._rFeiMsb); uint8_t feil = device.Read(rt._rFeiLsb); device.mtx.lock(); if (buffer.size() != 0x72) buffer.resize(0x72, 0); buffer[rt._rOpMode.Address()] = om; buffer[rt._rIrqFlags1.Address()] = irq1; buffer[rt._rIrqFlags2.Address()] = irq2; buffer[rt._rRssiValue.Address()] = rssi; buffer[rt._rFeiMsb.Address()] = feim; buffer[rt._rFeiLsb.Address()] = feil; device.mtx.unlock(); if (!frequent) for (size_t i=0x01; i < 0x71; i++) buffer[i] = device.Read(i); } void RFM69::RegisterTable::Write(std::ostream &os) { json j, dev, regs; dev["name"] = device.Name(); j["device"] = dev; for (const auto reg : registers) if (reg->Address() != 0x00) { char tmp[3]; snprintf(tmp, 3, "%02x", (*this)(*reg)); regs[reg->Name()] = tmp; } j["registers"] = regs; os << std::setw(2) << j << std::endl; } void RFM69::RegisterTable::Set(const std::string &key, const std::string &value) { if (value.size() != 2) throw std::runtime_error(std::string("invalid value length for '" + key + "'")); bool found = false; for (const auto &r : registers) if (r->Name() == key && r->Address() != 0) { uint8_t val; sscanf(value.c_str(), "%02hhx", &val); device.Write(*r, val); found = true; break; } if (!found) throw std::runtime_error(std::string("invalid register '") + key + "'"); } void RFM69::RegisterTable::Read(std::istream &is) { device.SetMode(Mode::STDBY); device.ClearFlags(); json j = json::parse(is); if (j["device"]["name"] != device.Name()) throw std::runtime_error("device mismatch"); for (const auto &e : j["registers"].items()) { const std::string &name = e.key(); if (name == "OpMode") continue; if (!e.value().is_string()) throw std::runtime_error(std::string("invalid value for '" + e.key() + "'")); Set(name, e.value().get<std::string>()); } if (j["registers"].contains("OpMode")) Set("OpMode", j["registers"]["OpMode"]); }
23.134731
84
0.599974
wintersteiger
07c6df38e78c2ba8e1c5f41cee29d99d1074be13
668
cpp
C++
tests/game_of_life.cpp
omrisim210/cellular-
e2e02a6577c6ffa015a2873817c5761e5e6835a5
[ "MIT" ]
1
2020-06-29T19:04:06.000Z
2020-06-29T19:04:06.000Z
tests/game_of_life.cpp
omrisim210/cellularpp
e2e02a6577c6ffa015a2873817c5761e5e6835a5
[ "MIT" ]
null
null
null
tests/game_of_life.cpp
omrisim210/cellularpp
e2e02a6577c6ffa015a2873817c5761e5e6835a5
[ "MIT" ]
null
null
null
#include "game_of_life.hpp" #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include <iostream> #include "doctest.h" using namespace gol; GameOfLife automaton("./spinner.txt"); TEST_CASE("generation 0") { // for (auto i = 0; i < automaton.width(); ++i) { // for (auto j = 0; j < automaton.height(); ++j) { // INFO(automaton.state_to_char(automaton(i, j))); // } // INFO('\n'); // } CHECK(automaton(0, 0) == State::Dead); // CHECK(automaton(2, 1) == State::Alive); } // TEST_CASE("generation 1") { // automaton.step(); // CHECK(automaton(0, 0) == State::Dead); // CHECK(automaton(2, 1) == State::Dead); // CHECK(automaton(1, 2) == State::Alive); // }
23.034483
53
0.615269
omrisim210
07c7f5d56e10be6c309887917a06cc6db95c4ab0
907
cpp
C++
code/quick sort/quick-sort.cpp
logancrocker/interview-toolkit
e33e4ba0c76f0bcbd831d2955095ad3325569388
[ "MIT" ]
null
null
null
code/quick sort/quick-sort.cpp
logancrocker/interview-toolkit
e33e4ba0c76f0bcbd831d2955095ad3325569388
[ "MIT" ]
null
null
null
code/quick sort/quick-sort.cpp
logancrocker/interview-toolkit
e33e4ba0c76f0bcbd831d2955095ad3325569388
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; void swap(int* a, int* b) { int t = *a; *a = *b; *b = t; } int partition(int arr[], int left, int right) { int pivot = arr[right]; int i = left - 1; for (int j = left; j <= right - 1; ++j) { if (arr[j] <= pivot) { i++; swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[right]); return (i + 1); } void quickSort(int arr[], int left, int right) { if (left < right) { int partitionIndex = partition(arr, left, right); quickSort(arr, left, partitionIndex - 1); quickSort(arr, partitionIndex + 1, right); } } int main() { int arr[10] = { 3, 8, 4, 1, 9, 10, 5, 2, 7, 6 }; const int size = sizeof(arr) / sizeof(arr[0]); quickSort(arr, 0, size - 1); for (int i = 0; i < size; i++) { cout << arr[i] << " "; } cout << endl; return 0; }
19.297872
54
0.486218
logancrocker
07caf422ce8171d0f42f20409396239b0dd3e0a1
353
cpp
C++
src/sprite/SpriteBatch.cpp
deianvn/kit2d
a8fd6d75cf1f8d14baabaa04903ab3fdee3b4ef5
[ "Apache-2.0" ]
null
null
null
src/sprite/SpriteBatch.cpp
deianvn/kit2d
a8fd6d75cf1f8d14baabaa04903ab3fdee3b4ef5
[ "Apache-2.0" ]
null
null
null
src/sprite/SpriteBatch.cpp
deianvn/kit2d
a8fd6d75cf1f8d14baabaa04903ab3fdee3b4ef5
[ "Apache-2.0" ]
null
null
null
#include "../../include/kit2d/sprite/SpriteBatch.hpp" #include "../../include/kit2d/core/Renderer.hpp" namespace kit2d { void SpriteBatch::add(Sprite& sprite) { sprites.push_back(&sprite); } void SpriteBatch::process(Renderer& renderer) { for (auto sprite : sprites) { sprite->draw(renderer); } renderer.present(); } }
19.611111
53
0.651558
deianvn
07ceced65e6b956fe2e59db1d341d5f56ffaf56c
88,134
cpp
C++
floatnuc.cpp
rainoverme002/FloatNuc
ee0206f3f54cbc2a93ac88fc27116a10375db701
[ "MIT" ]
1
2021-03-29T03:59:18.000Z
2021-03-29T03:59:18.000Z
floatnuc.cpp
rainoverme002/FloatNuc
ee0206f3f54cbc2a93ac88fc27116a10375db701
[ "MIT" ]
null
null
null
floatnuc.cpp
rainoverme002/FloatNuc
ee0206f3f54cbc2a93ac88fc27116a10375db701
[ "MIT" ]
null
null
null
#include "floatnuc.h" #include "ui_floatnuc.h" #include "fixeditem.h" #include "movingitem.h" #include "corebackground.h" #include "qcustomplot.h" #include "videoplayer.h" #include <QApplication> #include <QTimer> #include <QtCore> #include <QtGui> #include <valarray> #include <chrono> #include <thread> #include <cmath> #include <fstream> using namespace std; //Variabel for the Chart QVector<double> qv_x(10), qv_y0(10), qv_y1(10), qv_y2(10), qv_y3(10), qv_y4(10), qv_y5(10), qv_y6(10), qv_y7(10), qv_y8(10), qv_y9(10), qv_y10(10), qv_y11(10), qv_y12(10), qv_y13(10), qv_y14(10), qv_y15(10), qv_y16(10), qv_y17(10), qv_y18(10); //Variabel for the SeaStatecondition int SeaState = 0, ShipMovement = 0; //Variabel for the condition Simulation int condition_choose = 0; //Variabel for Plot Choose int plot_1_choose = 0, plot_2_choose = 0, plot_3_choose = 0, plot_4_choose = 0; // Set number of Array in Valarray int const ndep = 33; valarray<double> Y(ndep); //=============================Constant Variable======================= //Timestep // Set step size (fixed for the real time simulation) -increase it will increase exe time double const dx = 0.0001; //Please change this if you want change the simulation interval double const intervalwaktu (100);//milisecond //The time on the function step double xo = 0;//second double xn = intervalwaktu/1000; //second //Nilai Reaktivitas Tambahan double const reaktivitasundak = 0.0004;//k double const reaktivitasramp = 0.0001;//k double reaktivitastambahan = 0; //Untuk Parameter Kinetik Teras double const prompt (1.E-4); double const neutronlifetime (1E-4); double const beta (0.0065); double const betagrup1 (0.000215); double const betagrup2 (0.001424); double const betagrup3 (0.001274); double const betagrup4 (0.002568); double const betagrup5 (0.000748); double const betagrup6 (0.000273); double const lamdagrup1 (0.0124) ; double const lamdagrup2 (0.0305) ; double const lamdagrup3 (0.111) ; double const lamdagrup4 (0.301) ; double const lamdagrup5 (1.14) ; double const lamdagrup6 (3.01) ; //Untuk Perhitungan Daya double const convertpowertofluks (0.95 * 190E6 * 1.6E-19); double const reactorvol (1.257);//m^3 double const fissioncrosssection (0.337);//cm^-1 for U-235 double const fullpower(150);//Mwth //Untuk Reaktivitas Void double const koefreaktivitasvoid(-0.0015);//k/K //Untuk Reaktivitas Moderator double const koefsuhumod (-0.0002);//k/K double const Suhuawalmod (300);//K //Untuk Reaktivitas Fuel double const koefsuhufuel (-0.0000178);//k/K double const suhuawalfuel (300);//K //Untuk Reaktivitas Daya double const koefdaya (-0.00004);// k/persen daya //Untuk Reaktivitas Batang Kendali double const controlrodspeed (0.2);//cm/s double const scramrodspeed (13);//cm/s //Untuk Perhitungan Racun Neutron double const yieldiodine (6.386);//Yield for U-235 double const yieldxenon (0.228);//Yield for U-235 double const yieldpromethium (0.66);//Yield for U-235 double const lamdaiodine (0.1035/3600);//Decay Constant Iodine in s^-1 double const lamdaxenon (0.0753/3600);//Decay Constant Xenon in s^-1 double const lamdapromethium (0.0128/3600);//Decay Constant Promethium in s^-1 double const sigmaabsorptionxenon(3*1E5*1E-24);//Sigma Absortion for Xenon in cm^2 double const sigmaabsorptionsamarium(5.8*1E4*1E-24);//Sigma Absorption for Samarium in cm^2 //Untuk Transfer Kalor dari Daya ke Bahan Bakar double const h (35000);//W/m^2 K double const a (4.21405381);//m^2 double const mfuel (2920);//Kg double const cpfuel (239.258);//J/kgK Uranium //Untuk Transfer Kalor dari Bahan Bakar ke Moderator/Pendingin double const lajumassa (734);//Kg/s double const Tin (553);//K double const vpendingin (1.4457385);//m^3 double const Tsaturated (602.19);//K double const coreheight (1.67);//m double const Acoolant (4.201622E-3);//m2 floatnuc::floatnuc(QWidget *parent) : QMainWindow(parent), ui(new Ui::floatnuc) { ui->setupUi(this); //Plotting Initialization ui->Plot_1->addGraph(); ui->Plot_1->graph(0)->setScatterStyle(QCPScatterStyle::ssCircle); ui->Plot_1->setInteraction(QCP::iRangeZoom);//Can be Zoom ui->Plot_1->setInteraction(QCP::iRangeDrag);//Can be Drag //Plotting Initialization ui->Plot_2->addGraph(); ui->Plot_2->graph(0)->setScatterStyle(QCPScatterStyle::ssCircle); ui->Plot_2->setInteraction(QCP::iRangeZoom);//Can be Zoom ui->Plot_2->setInteraction(QCP::iRangeDrag);//Can be Drag //Plotting Initialization ui->Plot_3->addGraph(); ui->Plot_3->graph(0)->setScatterStyle(QCPScatterStyle::ssCircle); ui->Plot_3->setInteraction(QCP::iRangeZoom);//Can be Zoom ui->Plot_3->setInteraction(QCP::iRangeDrag);//Can be Drag //Plotting Initialization ui->Plot_4->addGraph(); ui->Plot_4->graph(0)->setScatterStyle(QCPScatterStyle::ssCircle); ui->Plot_4->setInteraction(QCP::iRangeZoom);//Can be Zoom ui->Plot_4->setInteraction(QCP::iRangeDrag);//Can be Drag //Timer Initialization timer = new QTimer (this); connect(timer,SIGNAL(timeout()),this,SLOT(engine())); //Video Initialization //Video Platlist Definition playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Kondisi Diam.mp4")); playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Pitching - Heaving - Sea State 2.mp4")); playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Pitching - Heaving - Sea State 3.mp4")); playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Pitching - Heaving - Sea State 4.mp4")); playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Pitching - Heaving - Sea State 5.mp4")); playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Pitching - Heaving - Sea State 6.mp4")); playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Pitching - Heaving - Sea State 7.mp4")); playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Pitching - Heaving - Sea State 8.mp4")); playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Pitching - Heaving - Sea State 9.mp4")); playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Rolling - Heaving - Sea State 2.mp4")); playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Rolling - Heaving - Sea State 3.mp4")); playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Rolling - Heaving - Sea State 4.mp4")); playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Rolling - Heaving - Sea State 5.mp4")); playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Rolling - Heaving - Sea State 6.mp4")); playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Rolling - Heaving - Sea State 7.mp4")); playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Rolling - Heaving - Sea State 8.mp4")); playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Rolling - Heaving - Sea State 9.mp4")); playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/World’s only floating nuclear power plant to be loaded with fuel in Russia.mp4")); playlist->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop); ui->Video_Widget->m_mediaPlayer->setPlaylist(playlist); //Animation Initialization scene = new QGraphicsScene(this); ui->Animation_View->setScene(scene); ui->Animation_View->setRenderHint(QPainter::Antialiasing); //Animation Position int const x = 1150; int const y = 0; scene->setSceneRect(x,y,500,400); CR_Animation(); } floatnuc::~floatnuc() { delete ui; } void floatnuc::CR_Animation() { //Animation Position int const x = 1200; int const y = 0; background = new corebackground(x-50,y); scene->addItem(background); int XAxis = x; int YAxis = y+20; for (int i =0; i<6; i++){ core = new fixeditem(XAxis,YAxis); scene->addItem(core); XAxis+=80; } //Group Dalam Position Initialization DalamCR = new movingitem(x+200, YAxis); scene->addItem(DalamCR); //Group Antara Position Initialization AntaraCR1 = new movingitem(x+120, YAxis); scene->addItem(AntaraCR1); AntaraCR2 = new movingitem(x+280, YAxis); scene->addItem(AntaraCR2); //Group Terluar Position Initialization TerluarCR1 = new movingitem(x+40, YAxis); scene->addItem(TerluarCR1); TerluarCR2 = new movingitem(x+360, YAxis); scene->addItem(TerluarCR2); } void floatnuc::videocalling(int SeaState, int ShipMovement){ switch (ShipMovement) { case 0: switch (SeaState) { case 0: playlist->setCurrentIndex(0); ui->Video_Widget->m_mediaPlayer->play(); break; case 1: playlist->setCurrentIndex(1); ui->Video_Widget->m_mediaPlayer->play(); break; case 2: playlist->setCurrentIndex(2); ui->Video_Widget->m_mediaPlayer->play(); break; case 3: playlist->setCurrentIndex(3); ui->Video_Widget->m_mediaPlayer->play(); break; case 4: playlist->setCurrentIndex(4); ui->Video_Widget->m_mediaPlayer->play(); break; case 5: playlist->setCurrentIndex(5); ui->Video_Widget->m_mediaPlayer->play(); break; case 6: playlist->setCurrentIndex(6); ui->Video_Widget->m_mediaPlayer->play(); break; case 7: playlist->setCurrentIndex(7); ui->Video_Widget->m_mediaPlayer->play(); break; case 8: playlist->setCurrentIndex(8); ui->Video_Widget->m_mediaPlayer->play(); break; } break; case 1: switch (SeaState) { case 0: playlist->setCurrentIndex(0); ui->Video_Widget->m_mediaPlayer->play(); break; case 1: //Looping playlist->setCurrentIndex(9); ui->Video_Widget->m_mediaPlayer->play(); break; case 2: playlist->setCurrentIndex(10); ui->Video_Widget->m_mediaPlayer->play(); break; case 3: playlist->setCurrentIndex(11); ui->Video_Widget->m_mediaPlayer->play(); break; case 4: playlist->setCurrentIndex(12); ui->Video_Widget->m_mediaPlayer->play(); break; case 5: playlist->setCurrentIndex(13); ui->Video_Widget->m_mediaPlayer->play(); break; case 6: playlist->setCurrentIndex(14); ui->Video_Widget->m_mediaPlayer->play(); break; case 7: playlist->setCurrentIndex(15); ui->Video_Widget->m_mediaPlayer->play(); break; case 8: playlist->setCurrentIndex(16); ui->Video_Widget->m_mediaPlayer->play(); break; } break; } } void floatnuc::plotting_1(){ switch (plot_1_choose) { case 0: ui->Plot_1->graph(0)->data().clear(); ui->Plot_1->graph(0)->setData(qv_x, qv_y0); ui->Plot_1->graph(0)->rescaleValueAxis(false); ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_1->xAxis->setLabel("Time(s)"); ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText()); ui->Plot_1->replot(); break; case 1: ui->Plot_1->graph(0)->data().clear(); ui->Plot_1->graph(0)->setData(qv_x, qv_y1); ui->Plot_1->graph(0)->rescaleValueAxis(false); ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_1->xAxis->setLabel("Time(s)"); ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText()); ui->Plot_1->replot(); break; case 2: ui->Plot_1->graph(0)->data().clear(); ui->Plot_1->graph(0)->setData(qv_x, qv_y2); ui->Plot_1->graph(0)->rescaleValueAxis(false); ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_1->xAxis->setLabel("Time(s)"); ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText()); ui->Plot_1->replot(); break; case 3: ui->Plot_1->graph(0)->data().clear(); ui->Plot_1->graph(0)->setData(qv_x, qv_y3); ui->Plot_1->graph(0)->rescaleValueAxis(false); ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_1->xAxis->setLabel("Time(s)"); ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText()); ui->Plot_1->replot(); break; case 4: ui->Plot_1->graph(0)->data().clear(); ui->Plot_1->graph(0)->setData(qv_x, qv_y4); ui->Plot_1->graph(0)->rescaleValueAxis(false); ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_1->xAxis->setLabel("Time(s)"); ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText()); ui->Plot_1->replot(); break; case 5: ui->Plot_1->graph(0)->data().clear(); ui->Plot_1->graph(0)->setData(qv_x, qv_y5); ui->Plot_1->graph(0)->rescaleValueAxis(false); ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_1->xAxis->setLabel("Time(s)"); ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText()); ui->Plot_1->replot(); break; case 6: ui->Plot_1->graph(0)->data().clear(); ui->Plot_1->graph(0)->setData(qv_x, qv_y6); ui->Plot_1->graph(0)->rescaleValueAxis(false); ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_1->xAxis->setLabel("Time(s)"); ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText()); ui->Plot_1->replot(); break; case 7: ui->Plot_1->graph(0)->data().clear(); ui->Plot_1->graph(0)->setData(qv_x, qv_y7); ui->Plot_1->graph(0)->rescaleValueAxis(false); ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_1->xAxis->setLabel("Time(s)"); ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText()); ui->Plot_1->replot(); break; case 8: ui->Plot_1->graph(0)->data().clear(); ui->Plot_1->graph(0)->setData(qv_x, qv_y8); ui->Plot_1->graph(0)->rescaleValueAxis(false); ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_1->xAxis->setLabel("Time(s)"); ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText()); ui->Plot_1->replot(); break; case 9: ui->Plot_1->graph(0)->data().clear(); ui->Plot_1->graph(0)->setData(qv_x, qv_y9); ui->Plot_1->graph(0)->rescaleValueAxis(false); ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_1->xAxis->setLabel("Time(s)"); ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText()); ui->Plot_1->replot(); break; case 10: ui->Plot_1->graph(0)->data().clear(); ui->Plot_1->graph(0)->setData(qv_x, qv_y10); ui->Plot_1->graph(0)->rescaleValueAxis(false); ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_1->xAxis->setLabel("Time(s)"); ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText()); ui->Plot_1->replot(); break; case 11: ui->Plot_1->graph(0)->data().clear(); ui->Plot_1->graph(0)->setData(qv_x, qv_y11); ui->Plot_1->graph(0)->rescaleValueAxis(false); ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_1->xAxis->setLabel("Time(s)"); ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText()); ui->Plot_1->replot(); break; case 12: ui->Plot_1->graph(0)->data().clear(); ui->Plot_1->graph(0)->setData(qv_x, qv_y12); ui->Plot_1->graph(0)->rescaleValueAxis(false); ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_1->xAxis->setLabel("Time(s)"); ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText()); ui->Plot_1->replot(); break; case 13: ui->Plot_1->graph(0)->data().clear(); ui->Plot_1->graph(0)->setData(qv_x, qv_y13); ui->Plot_1->graph(0)->rescaleValueAxis(false); ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_1->xAxis->setLabel("Time(s)"); ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText()); ui->Plot_1->replot(); break; case 14: ui->Plot_1->graph(0)->data().clear(); ui->Plot_1->graph(0)->setData(qv_x, qv_y14); ui->Plot_1->graph(0)->rescaleValueAxis(false); ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_1->xAxis->setLabel("Time(s)"); ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText()); ui->Plot_1->replot(); break; case 15: ui->Plot_1->graph(0)->data().clear(); ui->Plot_1->graph(0)->setData(qv_x, qv_y15); ui->Plot_1->graph(0)->rescaleValueAxis(false); ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_1->xAxis->setLabel("Time(s)"); ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText()); ui->Plot_1->replot(); break; case 16: ui->Plot_1->graph(0)->data().clear(); ui->Plot_1->graph(0)->setData(qv_x, qv_y16); ui->Plot_1->graph(0)->rescaleValueAxis(false); ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_1->xAxis->setLabel("Time(s)"); ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText()); ui->Plot_1->replot(); break; case 17: ui->Plot_1->graph(0)->data().clear(); ui->Plot_1->graph(0)->setData(qv_x, qv_y17); ui->Plot_1->graph(0)->rescaleValueAxis(false); ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_1->xAxis->setLabel("Time(s)"); ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText()); ui->Plot_1->replot(); break; case 18: ui->Plot_1->graph(0)->data().clear(); ui->Plot_1->graph(0)->setData(qv_x, qv_y18); ui->Plot_1->graph(0)->rescaleValueAxis(false); ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_1->xAxis->setLabel("Time(s)"); ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText()); ui->Plot_1->replot(); break; } } void floatnuc::plotting_2(){ switch (plot_2_choose) { case 0: ui->Plot_2->graph(0)->data().clear(); ui->Plot_2->graph(0)->setData(qv_x, qv_y0); ui->Plot_2->graph(0)->rescaleValueAxis(false); ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_2->xAxis->setLabel("Time(s)"); ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText()); ui->Plot_2->replot(); break; case 1: ui->Plot_2->graph(0)->data().clear(); ui->Plot_2->graph(0)->setData(qv_x, qv_y1); ui->Plot_2->graph(0)->rescaleValueAxis(false); ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_2->xAxis->setLabel("Time(s)"); ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText()); ui->Plot_2->replot(); break; case 2: ui->Plot_2->graph(0)->data().clear(); ui->Plot_2->graph(0)->setData(qv_x, qv_y2); ui->Plot_2->graph(0)->rescaleValueAxis(false); ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_2->xAxis->setLabel("Time(s)"); ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText()); ui->Plot_2->replot(); break; case 3: ui->Plot_2->graph(0)->data().clear(); ui->Plot_2->graph(0)->setData(qv_x, qv_y3); ui->Plot_2->graph(0)->rescaleValueAxis(false); ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_2->xAxis->setLabel("Time(s)"); ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText()); ui->Plot_2->replot(); break; case 4: ui->Plot_2->graph(0)->data().clear(); ui->Plot_2->graph(0)->setData(qv_x, qv_y4); ui->Plot_2->graph(0)->rescaleValueAxis(false); ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_2->xAxis->setLabel("Time(s)"); ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText()); ui->Plot_2->replot(); break; case 5: ui->Plot_2->graph(0)->data().clear(); ui->Plot_2->graph(0)->setData(qv_x, qv_y5); ui->Plot_2->graph(0)->rescaleValueAxis(false); ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_2->xAxis->setLabel("Time(s)"); ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText()); ui->Plot_2->replot(); break; case 6: ui->Plot_2->graph(0)->data().clear(); ui->Plot_2->graph(0)->setData(qv_x, qv_y6); ui->Plot_2->graph(0)->rescaleValueAxis(false); ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_2->xAxis->setLabel("Time(s)"); ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText()); ui->Plot_2->replot(); break; case 7: ui->Plot_2->graph(0)->data().clear(); ui->Plot_2->graph(0)->setData(qv_x, qv_y7); ui->Plot_2->graph(0)->rescaleValueAxis(false); ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_2->xAxis->setLabel("Time(s)"); ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText()); ui->Plot_2->replot(); break; case 8: ui->Plot_2->graph(0)->data().clear(); ui->Plot_2->graph(0)->setData(qv_x, qv_y8); ui->Plot_2->graph(0)->rescaleValueAxis(false); ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_2->xAxis->setLabel("Time(s)"); ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText()); ui->Plot_2->replot(); break; case 9: ui->Plot_2->graph(0)->data().clear(); ui->Plot_2->graph(0)->setData(qv_x, qv_y9); ui->Plot_2->graph(0)->rescaleValueAxis(false); ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_2->xAxis->setLabel("Time(s)"); ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText()); ui->Plot_2->replot(); break; case 10: ui->Plot_2->graph(0)->data().clear(); ui->Plot_2->graph(0)->setData(qv_x, qv_y10); ui->Plot_2->graph(0)->rescaleValueAxis(false); ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_2->xAxis->setLabel("Time(s)"); ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText()); ui->Plot_2->replot(); break; case 11: ui->Plot_2->graph(0)->data().clear(); ui->Plot_2->graph(0)->setData(qv_x, qv_y11); ui->Plot_2->graph(0)->rescaleValueAxis(false); ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_2->xAxis->setLabel("Time(s)"); ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText()); ui->Plot_2->replot(); break; case 12: ui->Plot_2->graph(0)->data().clear(); ui->Plot_2->graph(0)->setData(qv_x, qv_y12); ui->Plot_2->graph(0)->rescaleValueAxis(false); ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_2->xAxis->setLabel("Time(s)"); ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText()); ui->Plot_2->replot(); break; case 13: ui->Plot_2->graph(0)->data().clear(); ui->Plot_2->graph(0)->setData(qv_x, qv_y13); ui->Plot_2->graph(0)->rescaleValueAxis(false); ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_2->xAxis->setLabel("Time(s)"); ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText()); ui->Plot_2->replot(); break; case 14: ui->Plot_2->graph(0)->data().clear(); ui->Plot_2->graph(0)->setData(qv_x, qv_y14); ui->Plot_2->graph(0)->rescaleValueAxis(false); ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_2->xAxis->setLabel("Time(s)"); ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText()); ui->Plot_2->replot(); break; case 15: ui->Plot_2->graph(0)->data().clear(); ui->Plot_2->graph(0)->setData(qv_x, qv_y15); ui->Plot_2->graph(0)->rescaleValueAxis(false); ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_2->xAxis->setLabel("Time(s)"); ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText()); ui->Plot_2->replot(); break; case 16: ui->Plot_2->graph(0)->data().clear(); ui->Plot_2->graph(0)->setData(qv_x, qv_y16); ui->Plot_2->graph(0)->rescaleValueAxis(false); ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_2->xAxis->setLabel("Time(s)"); ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText()); ui->Plot_2->replot(); break; case 17: ui->Plot_2->graph(0)->data().clear(); ui->Plot_2->graph(0)->setData(qv_x, qv_y17); ui->Plot_2->graph(0)->rescaleValueAxis(false); ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_2->xAxis->setLabel("Time(s)"); ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText()); ui->Plot_2->replot(); break; case 18: ui->Plot_2->graph(0)->data().clear(); ui->Plot_2->graph(0)->setData(qv_x, qv_y18); ui->Plot_2->graph(0)->rescaleValueAxis(false); ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_2->xAxis->setLabel("Time(s)"); ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText()); ui->Plot_2->replot(); break; } } void floatnuc::plotting_3(){ switch (plot_3_choose) { case 0: ui->Plot_3->graph(0)->data().clear(); ui->Plot_3->graph(0)->setData(qv_x, qv_y0); ui->Plot_3->graph(0)->rescaleValueAxis(false); ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_3->xAxis->setLabel("Time(s)"); ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText()); ui->Plot_3->replot(); break; case 1: ui->Plot_3->graph(0)->data().clear(); ui->Plot_3->graph(0)->setData(qv_x, qv_y1); ui->Plot_3->graph(0)->rescaleValueAxis(false); ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_3->xAxis->setLabel("Time(s)"); ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText()); ui->Plot_3->replot(); break; case 2: ui->Plot_3->graph(0)->data().clear(); ui->Plot_3->graph(0)->setData(qv_x, qv_y2); ui->Plot_3->graph(0)->rescaleValueAxis(false); ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_3->xAxis->setLabel("Time(s)"); ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText()); ui->Plot_3->replot(); break; case 3: ui->Plot_3->graph(0)->data().clear(); ui->Plot_3->graph(0)->setData(qv_x, qv_y3); ui->Plot_3->graph(0)->rescaleValueAxis(false); ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_3->xAxis->setLabel("Time(s)"); ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText()); ui->Plot_3->replot(); break; case 4: ui->Plot_3->graph(0)->data().clear(); ui->Plot_3->graph(0)->setData(qv_x, qv_y4); ui->Plot_3->graph(0)->rescaleValueAxis(false); ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_3->xAxis->setLabel("Time(s)"); ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText()); ui->Plot_3->replot(); break; case 5: ui->Plot_3->graph(0)->data().clear(); ui->Plot_3->graph(0)->setData(qv_x, qv_y5); ui->Plot_3->graph(0)->rescaleValueAxis(false); ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_3->xAxis->setLabel("Time(s)"); ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText()); ui->Plot_3->replot(); break; case 6: ui->Plot_3->graph(0)->data().clear(); ui->Plot_3->graph(0)->setData(qv_x, qv_y6); ui->Plot_3->graph(0)->rescaleValueAxis(false); ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_3->xAxis->setLabel("Time(s)"); ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText()); ui->Plot_3->replot(); break; case 7: ui->Plot_3->graph(0)->data().clear(); ui->Plot_3->graph(0)->setData(qv_x, qv_y7); ui->Plot_3->graph(0)->rescaleValueAxis(false); ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_3->xAxis->setLabel("Time(s)"); ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText()); ui->Plot_3->replot(); break; case 8: ui->Plot_3->graph(0)->data().clear(); ui->Plot_3->graph(0)->setData(qv_x, qv_y8); ui->Plot_3->graph(0)->rescaleValueAxis(false); ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_3->xAxis->setLabel("Time(s)"); ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText()); ui->Plot_3->replot(); break; case 9: ui->Plot_3->graph(0)->data().clear(); ui->Plot_3->graph(0)->setData(qv_x, qv_y9); ui->Plot_3->graph(0)->rescaleValueAxis(false); ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_3->xAxis->setLabel("Time(s)"); ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText()); ui->Plot_3->replot(); break; case 10: ui->Plot_3->graph(0)->data().clear(); ui->Plot_3->graph(0)->setData(qv_x, qv_y10); ui->Plot_3->graph(0)->rescaleValueAxis(false); ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_3->xAxis->setLabel("Time(s)"); ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText()); ui->Plot_3->replot(); break; case 11: ui->Plot_3->graph(0)->data().clear(); ui->Plot_3->graph(0)->setData(qv_x, qv_y11); ui->Plot_3->graph(0)->rescaleValueAxis(false); ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_3->xAxis->setLabel("Time(s)"); ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText()); ui->Plot_3->replot(); break; case 12: ui->Plot_3->graph(0)->data().clear(); ui->Plot_3->graph(0)->setData(qv_x, qv_y12); ui->Plot_3->graph(0)->rescaleValueAxis(false); ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_3->xAxis->setLabel("Time(s)"); ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText()); ui->Plot_3->replot(); break; case 13: ui->Plot_3->graph(0)->data().clear(); ui->Plot_3->graph(0)->setData(qv_x, qv_y13); ui->Plot_3->graph(0)->rescaleValueAxis(false); ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_3->xAxis->setLabel("Time(s)"); ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText()); ui->Plot_3->replot(); break; case 14: ui->Plot_3->graph(0)->data().clear(); ui->Plot_3->graph(0)->setData(qv_x, qv_y14); ui->Plot_3->graph(0)->rescaleValueAxis(false); ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_3->xAxis->setLabel("Time(s)"); ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText()); ui->Plot_3->replot(); break; case 15: ui->Plot_3->graph(0)->data().clear(); ui->Plot_3->graph(0)->setData(qv_x, qv_y15); ui->Plot_3->graph(0)->rescaleValueAxis(false); ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_3->xAxis->setLabel("Time(s)"); ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText()); ui->Plot_3->replot(); break; case 16: ui->Plot_3->graph(0)->data().clear(); ui->Plot_3->graph(0)->setData(qv_x, qv_y16); ui->Plot_3->graph(0)->rescaleValueAxis(false); ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_3->xAxis->setLabel("Time(s)"); ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText()); ui->Plot_3->replot(); break; case 17: ui->Plot_3->graph(0)->data().clear(); ui->Plot_3->graph(0)->setData(qv_x, qv_y17); ui->Plot_3->graph(0)->rescaleValueAxis(false); ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_3->xAxis->setLabel("Time(s)"); ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText()); ui->Plot_3->replot(); break; case 18: ui->Plot_3->graph(0)->data().clear(); ui->Plot_3->graph(0)->setData(qv_x, qv_y18); ui->Plot_3->graph(0)->rescaleValueAxis(false); ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_3->xAxis->setLabel("Time(s)"); ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText()); ui->Plot_3->replot(); break; } } void floatnuc::plotting_4(){ switch (plot_4_choose) { case 0: ui->Plot_4->graph(0)->data().clear(); ui->Plot_4->graph(0)->setData(qv_x, qv_y0); ui->Plot_4->graph(0)->rescaleValueAxis(false); ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_4->xAxis->setLabel("Time(s)"); ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText()); ui->Plot_4->replot(); break; case 1: ui->Plot_4->graph(0)->data().clear(); ui->Plot_4->graph(0)->setData(qv_x, qv_y1); ui->Plot_4->graph(0)->rescaleValueAxis(false); ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_4->xAxis->setLabel("Time(s)"); ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText()); ui->Plot_4->replot(); break; case 2: ui->Plot_4->graph(0)->data().clear(); ui->Plot_4->graph(0)->setData(qv_x, qv_y2); ui->Plot_4->graph(0)->rescaleValueAxis(false); ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_4->xAxis->setLabel("Time(s)"); ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText()); ui->Plot_4->replot(); break; case 3: ui->Plot_4->graph(0)->data().clear(); ui->Plot_4->graph(0)->setData(qv_x, qv_y3); ui->Plot_4->graph(0)->rescaleValueAxis(false); ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_4->xAxis->setLabel("Time(s)"); ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText()); ui->Plot_4->replot(); break; case 4: ui->Plot_4->graph(0)->data().clear(); ui->Plot_4->graph(0)->setData(qv_x, qv_y4); ui->Plot_4->graph(0)->rescaleValueAxis(false); ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_4->xAxis->setLabel("Time(s)"); ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText()); ui->Plot_4->replot(); break; case 5: ui->Plot_4->graph(0)->data().clear(); ui->Plot_4->graph(0)->setData(qv_x, qv_y5); ui->Plot_4->graph(0)->rescaleValueAxis(false); ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_4->xAxis->setLabel("Time(s)"); ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText()); ui->Plot_4->replot(); break; case 6: ui->Plot_4->graph(0)->data().clear(); ui->Plot_4->graph(0)->setData(qv_x, qv_y6); ui->Plot_4->graph(0)->rescaleValueAxis(false); ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_4->xAxis->setLabel("Time(s)"); ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText()); ui->Plot_4->replot(); break; case 7: ui->Plot_4->graph(0)->data().clear(); ui->Plot_4->graph(0)->setData(qv_x, qv_y7); ui->Plot_4->graph(0)->rescaleValueAxis(false); ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_4->xAxis->setLabel("Time(s)"); ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText()); ui->Plot_4->replot(); break; case 8: ui->Plot_4->graph(0)->data().clear(); ui->Plot_4->graph(0)->setData(qv_x, qv_y8); ui->Plot_4->graph(0)->rescaleValueAxis(false); ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_4->xAxis->setLabel("Time(s)"); ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText()); ui->Plot_4->replot(); break; case 9: ui->Plot_4->graph(0)->data().clear(); ui->Plot_4->graph(0)->setData(qv_x, qv_y9); ui->Plot_4->graph(0)->rescaleValueAxis(false); ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_4->xAxis->setLabel("Time(s)"); ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText()); ui->Plot_4->replot(); break; case 10: ui->Plot_4->graph(0)->data().clear(); ui->Plot_4->graph(0)->setData(qv_x, qv_y10); ui->Plot_4->graph(0)->rescaleValueAxis(false); ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_4->xAxis->setLabel("Time(s)"); ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText()); ui->Plot_4->replot(); break; case 11: ui->Plot_4->graph(0)->data().clear(); ui->Plot_4->graph(0)->setData(qv_x, qv_y11); ui->Plot_4->graph(0)->rescaleValueAxis(false); ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_4->xAxis->setLabel("Time(s)"); ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText()); ui->Plot_4->replot(); break; case 12: ui->Plot_4->graph(0)->data().clear(); ui->Plot_4->graph(0)->setData(qv_x, qv_y12); ui->Plot_4->graph(0)->rescaleValueAxis(false); ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_4->xAxis->setLabel("Time(s)"); ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText()); ui->Plot_4->replot(); break; case 13: ui->Plot_4->graph(0)->data().clear(); ui->Plot_4->graph(0)->setData(qv_x, qv_y13); ui->Plot_4->graph(0)->rescaleValueAxis(false); ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_4->xAxis->setLabel("Time(s)"); ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText()); ui->Plot_4->replot(); break; case 14: ui->Plot_4->graph(0)->data().clear(); ui->Plot_4->graph(0)->setData(qv_x, qv_y14); ui->Plot_4->graph(0)->rescaleValueAxis(false); ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_4->xAxis->setLabel("Time(s)"); ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText()); ui->Plot_4->replot(); break; case 15: ui->Plot_4->graph(0)->data().clear(); ui->Plot_4->graph(0)->setData(qv_x, qv_y15); ui->Plot_4->graph(0)->rescaleValueAxis(false); ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_4->xAxis->setLabel("Time(s)"); ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText()); ui->Plot_4->replot(); break; case 16: ui->Plot_4->graph(0)->data().clear(); ui->Plot_4->graph(0)->setData(qv_x, qv_y16); ui->Plot_4->graph(0)->rescaleValueAxis(false); ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_4->xAxis->setLabel("Time(s)"); ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText()); ui->Plot_4->replot(); break; case 17: ui->Plot_4->graph(0)->data().clear(); ui->Plot_4->graph(0)->setData(qv_x, qv_y17); ui->Plot_4->graph(0)->rescaleValueAxis(false); ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_4->xAxis->setLabel("Time(s)"); ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText()); ui->Plot_4->replot(); break; case 18: ui->Plot_4->graph(0)->data().clear(); ui->Plot_4->graph(0)->setData(qv_x, qv_y18); ui->Plot_4->graph(0)->rescaleValueAxis(false); ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight); ui->Plot_4->xAxis->setLabel("Time(s)"); ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText()); ui->Plot_4->replot(); break; } } void floatnuc::tampilhasil(double x, valarray<double> &Y) { //See The ComboBox Index SeaState = ui->SeaState_Combobox->currentIndex(); ShipMovement = ui->ShipMove_Combobox->currentIndex(); condition_choose = ui->Kecelakaan_Combobox->currentIndex(); plot_1_choose = ui->Plot_1_Combobox->currentIndex(); plot_2_choose = ui->Plot_2_Combobox->currentIndex(); plot_3_choose = ui->Plot_3_Combobox->currentIndex(); plot_4_choose = ui->Plot_4_Combobox->currentIndex(); //Output The Value to Line Edit QString Time = QString::number(xo); QString Power = QString::number(Y[0]); QString Fluks = QString::number(Y[2]); QString Precursor = QString::number(Y[20]); QString TFuel = QString::number(Y[8]); QString TMod = QString::number(Y[9]); QString React = QString::number(Y[3]); QString Xenon = QString::number(Y[11]); QString Samarium = QString::number(Y[12]); QString ReactorPeriod = QString::number(Y[15]); QString PowerPercent = QString::number(Y[1]); QString PosisiGroupDalam = QString::number(Y[16]); QString PosisiGroupAntara = QString::number(Y[17]); QString PosisiGroupTerluar = QString::number(Y[18]); QString MassFlow = QString::number(Y[27]); ui->Time_Line->setText(Time); ui->Daya_Line->setText(Power); ui->Fluks_Line->setText(Fluks); ui->Prekursor_Line->setText(Precursor); ui->TFuel_Line->setText(TFuel); ui->TModerator_Line->setText(TMod); ui->Reaktivitas_Line->setText(React); ui->Xenon_Line->setText(Xenon); ui->Samarium_Line->setText(Samarium); ui->Period_Line->setText(ReactorPeriod); ui->PersenDaya_Line->setText(PowerPercent); ui->GroupDalam_Line->setText(PosisiGroupDalam); ui->GroupAntara_Line->setText(PosisiGroupAntara); ui->GroupTerluar_Line->setText(PosisiGroupTerluar); ui->MassFlow_Line->setText(MassFlow); //Data Fetching qv_x.append(x); qv_y0.append(Y[0]); qv_y1.append(Y[1]); qv_y2.append(Y[2]); qv_y3.append(Y[3]); qv_y4.append(Y[4]); qv_y5.append(Y[5]); qv_y6.append(Y[6]); qv_y7.append(Y[7]); qv_y8.append(Y[8]); qv_y9.append(Y[9]); qv_y10.append(Y[10]); qv_y11.append(Y[11]); qv_y12.append(Y[12]); qv_y13.append(Y[15]); qv_y14.append(Y[27]); qv_y15.append(Y[28]); qv_y16.append(Y[29]); qv_y17.append(Y[30]); qv_y18.append(Y[31]); //Data Plotting plotting_1(); plotting_2(); plotting_3(); plotting_4(); //CR Position in Animation DalamCR->setY(-3*Y[16]); DalamCR->update(); AntaraCR1->setY(-3*Y[17]); AntaraCR1->update(); AntaraCR2->setY(-3*Y[17]); AntaraCR2->update(); TerluarCR1->setY(-3*Y[18]); TerluarCR1->update(); TerluarCR2->setY(-3*Y[18]); TerluarCR2->update(); } void floatnuc::simpanhasil(double x, valarray<double> &Y){ if (x == 0.0){ ofstream datakeluar; QString namefile = ui->SaveFile_Line->text(); std::string namefiletxt = namefile.toUtf8().constData(); datakeluar.open(namefiletxt, std::ios_base::app); datakeluar << "Waktu (s)" << ","<< "Daya (MWth)" << "," << "Daya (%)" << "," << "Fluks Neutron (CPS)" << "," << "Total Reaktivitas (dk/k)" << "," << "Reaktivitas Batang Kendali (dk/k)" << "," << "Reaktivitas Xenon (dk/k)" << "," << "Reaktivitas Samarium (dk/k)" << "," << "Reaktivitas Void (dk/k)" << "," << "Fuel Temperature (K)" << "," << "Moderator Temperature (K)" << "," << "Void Fraction (%)" << "," << "Xenon (CPS)" << "," << "Samarium (CPS)" << "," << "Reactor Period (s)" << "," << "Mass Flow (Kg/s)" << "," << "Coolant Output Temperature (K)" << "," << "Prandtl Number" << "," << "Nusselt Number" << "," << "Reynold Number" << "," << "SeaState" << "," << "ShipMovement" <<endl; datakeluar.close(); }else{ ofstream datakeluar; QString namefile = ui->SaveFile_Line->text(); std::string namefiletxt = namefile.toUtf8().constData(); datakeluar.open(namefiletxt, std::ios_base::app); datakeluar << x << ","<< Y[0] << "," << Y[1] << "," << Y[2] << "," << Y[3] << "," << Y[4] << "," << Y[5] << "," << Y[6] << "," << Y[7] << "," << Y[8] << "," << Y[9] << "," << Y[10] << "," << Y[11] << "," << Y[12] << "," << Y[15] << "," << Y[27] << "," << Y[28] << "," << Y[29] << "," << Y[30] << "," << Y[31] << "," << SeaState << "," << ShipMovement <<endl; datakeluar.close(); } } //===================================================================================================================================================================// //========Convection heat transfer Function========// double floatnuc::prandtl(valarray<double> &Y){ double viscocity; double coolantconductivity; double cpcoolant = heatcapacitymoderator(Y); viscocity = 4E-08*Y[9] - 4E-06; if (Y[9]> Tsaturated){ coolantconductivity = 4E-07*pow(Y[9],2) - 0.0006*Y[9] + 0.2876; }else{ coolantconductivity = -0.0021*Y[9] + 1.7319; } return (viscocity*cpcoolant)/coolantconductivity; } double floatnuc::nusselt(valarray<double> &Y){ double reynoldnumber = reynold(Y); double prandtlnumber = prandtl(Y); return 0.023*pow(reynoldnumber,0.8)*pow(prandtlnumber,0.4); } double floatnuc::reynold(valarray<double> &Y){ double viscocity; if (Y[9]> Tsaturated){ viscocity = 4E-08*Y[9] - 4E-06; }else{ viscocity = -4E-07*Y[9] + 0.0003; } viscocity = 4E-08*Y[9] - 4E-06; double rho = massmoderator(Y)/(vpendingin); double Dh = pow(Acoolant/3.145511,0.5)*2; return (rho*vpendingin*Dh/viscocity); } double floatnuc::convectionheattransfercoefficient(valarray<double> &Y){ double nusseltnumber = nusselt(Y); double coolantconductivity; if (Y[9]> Tsaturated){ coolantconductivity = 4E-07*pow(Y[9],2) - 0.0006*Y[9] + 0.2876; }else{ coolantconductivity = -0.0021*Y[9] + 1.7319; } double Dh = pow(Acoolant/3.145511,0.5)*2; return (nusseltnumber*coolantconductivity/Dh); } //===================================================================================================================================================================// //========Mass Moderator Function========// double floatnuc::massmoderator(valarray<double> &Y){ double massmoderator, densitymoderator; if (Y[9]> Tsaturated){ densitymoderator = -1E-09*pow(Y[9],3) + 4E-06*pow(Y[9],2) - 0.0034*Y[9] + 1.0474; massmoderator = densitymoderator * 1000 * vpendingin; return massmoderator; } else { densitymoderator = -0.0024*Y[9] + 2.0691; massmoderator = densitymoderator * 1000 * vpendingin; return massmoderator; } } //===================================================================================================================================================================// //========Heat Capacity Function========// double floatnuc::heatcapacitymoderator(valarray<double> &Y){ double heatcapacity; if (Y[9] > Tsaturated){ heatcapacity = -0.0004*pow(Y[9],3) + 1.1182*pow(Y[9],2)- 946.14*Y[9] + 267795; return heatcapacity; } else { heatcapacity = 0.7165*pow(Y[9],2) - 789.09*Y[9] + 222431; return heatcapacity; } } //===================================================================================================================================================================// //========Reactor Period========// void floatnuc::reactorperiod(double x, valarray<double> &Y){ if (Y[3]>beta) { Y[15] = neutronlifetime/Y[3]; } else { Y[15] = (beta-Y[3])*(0.0848/beta)/Y[3]; } } //===================================================================================================================================================================// //========Reactor Condition Simulation========// void floatnuc::condition(double x, valarray<double> &Y){ //The condition Choose switch (condition_choose) { case 0: Y[27] = fungsimassflow (Y[1], x); reaktivitastambahan = 0; break; case 1: Y[27] = 5; reaktivitastambahan = 0; break; case 2: Y[27] = fungsimassflow (Y[1], x); reaktivitastambahan = reaktivitasundak;//k break; case 3: Y[27] = fungsimassflow (Y[1], x); reaktivitastambahan = -reaktivitasundak;//k break; case 4: Y[27] = fungsimassflow (Y[1], x); reaktivitastambahan = 0.5*beta;//k break; case 5: Y[27] = fungsimassflow (Y[1], x); reaktivitastambahan = -0.5*beta;//k break; case 6: Y[27] = fungsimassflow (Y[1], x); if (reaktivitastambahan < 0.0004){ reaktivitastambahan += reaktivitasramp*dx; }else{ reaktivitastambahan = reaktivitastambahan; } break; case 7: Y[27] = fungsimassflow (Y[1], x); if (reaktivitastambahan > -0.0004){ reaktivitastambahan += -reaktivitasramp*dx; }else{ reaktivitastambahan = reaktivitastambahan; } break; case 8: Y[27] = fungsimassflow (Y[1], x); ui->GroupDalam_Slider->setValue(0); ui->GroupAntara_Slider->setValue(0); ui->GroupTerluar_Slider->setValue(0); break; } } //===================================================================================================================================================================// //========Void Reactivity Function========// double floatnuc::pitchheavemassflow(double Percentdaya, double x) { double nilaimassflow, yo, amplitudo, perioda; double Pdaya = Percentdaya/100; switch(SeaState) { case 0: return lajumassa; case 1: if (Percentdaya > 90) { yo = -123.6*pow(Pdaya,3) + 404.86*pow(Pdaya,2) - 433.41*Pdaya + 886.06; amplitudo = 51.667*pow(Pdaya,3) - 148.79*pow(Pdaya,2) + 142.66*Pdaya - 44.957; perioda = -4.9333*pow(Pdaya,3) + 14.694*pow(Pdaya,2) - 14.539*Pdaya + 5.9796; nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow; }else{ return lajumassa; } case 2: if (Percentdaya > 90) { yo = 72.48*pow(Pdaya,2) - 135.81*Pdaya + 804.84; amplitudo = 154.97*pow(Pdaya,2) - 297.93*Pdaya + 163.86; perioda = 200.33*pow(Pdaya,3) - 618.07*pow(Pdaya,2) + 634.64*Pdaya - 216.58; nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow; }else{ return lajumassa; } case 3: if (Percentdaya > 90) { yo = -1.7543*pow(Pdaya,2) + 9.313*Pdaya + 726.55; amplitudo = -2148*pow(Pdaya,4) + 8496.9*pow(Pdaya,3) - 12582*pow(Pdaya,2) + 8266.1*Pdaya - 2033; perioda = -36461*pow(Pdaya,4)+ 149790*pow(Pdaya,3) - 230550*pow(Pdaya,2) + 157564*Pdaya - 40337; nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow; }else{ return lajumassa; } case 4: if (Percentdaya > 90) { yo = 11.534*pow(Pdaya,2) - 14.94*Pdaya + 737.65; amplitudo = -9.0514*pow(Pdaya,2) + 21.92*Pdaya - 10.695; perioda = 1.0257*pow(Pdaya,2) - 1.9784*Pdaya + 6.9588; nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow; }else{ return lajumassa; } break; case 5: if (Percentdaya > 90) { yo = 13.051*pow(Pdaya,2) - 18.774*Pdaya + 739.93; amplitudo = 7.6686*pow(Pdaya,2) - 9.5155*Pdaya + 5.6885; perioda = -0.0086*pow(Pdaya,2) + 0.0161*Pdaya + 6.0109; nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow; }else{ return lajumassa; } case 6: if (Percentdaya > 90) { yo = 23.376*pow(Pdaya,2) - 37.644*Pdaya + 748.63; amplitudo = 22.397*pow(Pdaya,2) - 36.617*Pdaya + 19.007; perioda = -2.1061*pow(Pdaya,2) + 4.0631*Pdaya + 4.0645; nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow; }else{ return lajumassa; } case 7: if (Percentdaya > 90) { yo = 26.031*pow(Pdaya,2) - 39.495*Pdaya + 748.17; amplitudo = 25.877*pow(Pdaya,2) - 36.974*Pdaya + 17.626; perioda = -542.67*pow(Pdaya,4)+ 2226.9*pow(Pdaya,3) - 3415*pow(Pdaya,2) + 2319.3*Pdaya - 582.62; nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow; }else{ return lajumassa; } case 8: if (Percentdaya > 70) { yo = 372.75*pow(Pdaya,3) - 924*pow(Pdaya,2) + 768.31*Pdaya + 519.62; amplitudo = 763.49*pow(Pdaya,3) - 1912*pow(Pdaya,2) + 1599.4*Pdaya - 438.36; perioda = 1.9846*pow(Pdaya,3) - 4.9791*pow(Pdaya,2) + 4.1275*Pdaya + 4.8585; nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow; }else{ return lajumassa; } } } double floatnuc::rollheavemassflow (double Percentdaya, double x) { double nilaimassflow, yo, amplitudo, perioda; double Pdaya = Percentdaya/100; switch(SeaState) { case 0: return lajumassa; case 1: if (Percentdaya > 90) { yo = 0.42*pow(Pdaya,2)+ 4.8422*Pdaya + 728.83; amplitudo = 0.06*pow(Pdaya,2) - 0.0038*Pdaya + 0.0353; perioda = 217.87*pow(Pdaya,3) - 673.16*pow(Pdaya,2)+ 692.5*Pdaya - 229.17; nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow; }else{ return lajumassa; } case 2: if (Percentdaya > 90) { yo = 0.41*pow(Pdaya,2) + 4.8645*Pdaya + 728.81; amplitudo =0.04*pow(Pdaya,2) + 0.058*Pdaya + 0.0077; perioda = 3E-08*pow(Pdaya,3) + 9E-08*pow(Pdaya,2) - 1E-07*Pdaya + 8.91; nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow; }else{ return lajumassa; } case 3: if (Percentdaya > 90) { yo = 0.38*pow(Pdaya,2) + 4.9054*Pdaya + 728.79; amplitudo = 0.27*pow(Pdaya,2) - 0.0577*Pdaya + 0.1707; perioda = 4.48*pow(Pdaya,2) - 9.4528*Pdaya + 14.36; nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow; }else{ return lajumassa; } case 4: if (Percentdaya > 90) { yo = 0.35*pow(Pdaya,2) + 4.9519*Pdaya + 728.75; amplitudo = 0.61*pow(Pdaya,2) - 0.1643*Pdaya + 0.395; perioda = -6E-11*pow(Pdaya,2) + 1E-10*Pdaya + 10.376; nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow; }else{ return lajumassa; } case 5: if (Percentdaya > 90) { yo = 2.72*pow(Pdaya,2) - 0.186*Pdaya + 731.33; amplitudo = 0.94*pow(Pdaya,2) - 0.1198*Pdaya + 0.5445; perioda = -930.13*pow(Pdaya,3) + 2898*pow(Pdaya,2) - 3005.5*Pdaya + 1048.6; nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow; }else{ return lajumassa; } case 6: if (Percentdaya > 90) { yo = 0.8*pow(Pdaya,2) + 3.9372*Pdaya + 729.25; amplitudo = 0.92*pow(Pdaya,2) - 0.014*Pdaya + 0.5448; perioda = 315.2*pow(Pdaya,3) - 961.36*pow(Pdaya,2) + 975.54*Pdaya - 318.02; nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow; }else{ return lajumassa; } case 7: if (Percentdaya > 90) { yo = -82.4*pow(Pdaya,3) + 250.16*pow(Pdaya,2) - 247.01*Pdaya + 813.28; amplitudo = -793.2*pow(Pdaya,3) + 2460.7*pow(Pdaya,2) - 2537.5*Pdaya + 871.65; perioda = -5059.6*pow(Pdaya,2) + 10625*Pdaya - 5565.6; nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow; }else{ return lajumassa; } case 8: if (Percentdaya > 90) { yo = -29.83*pow(Pdaya,2) + 67.364*Pdaya + 696.71; amplitudo = 14.667*pow(Pdaya,3) + 5.5*pow(Pdaya,2) - 53.904*Pdaya + 36.55; perioda = -989.02*pow(Pdaya,2) + 2092.3*Pdaya - 1094.5; nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow; }else{ return lajumassa; } } } double floatnuc::fungsimassflow(double Percentdaya, double x) { double massflow; switch (ShipMovement) { case 0: massflow = pitchheavemassflow(Percentdaya, x); return massflow; case 1: massflow = rollheavemassflow(Percentdaya, x); return massflow; } } double floatnuc::pitchheavereaktivitas (double Percentdaya, double x) { double reaktivitasvoid; double nilaivoid, yo, amplitudo, perioda; double Pdaya = Percentdaya/100; switch(SeaState) { case 0: reaktivitasvoid = 0; Y[10] = 0; return reaktivitasvoid; case 1: if (Percentdaya > 90) { yo = 2.0486*pow(Pdaya,4) - 7.9587*pow(Pdaya,3) + 11.584*pow(Pdaya,2) - 7.4865*Pdaya + 1.8127; amplitudo = 0.0329*pow(Pdaya,3) - 0.0958*pow(Pdaya,2) + 0.0928*Pdaya - 0.0299; perioda = -24000*pow(Pdaya,4) + 95200*pow(Pdaya,3) - 141300*pow(Pdaya,2) + 93014*Pdaya - 22914; nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda)); if (nilaivoid < 0){ Y[10] = 0; return reaktivitasvoid = 0; } else if (nilaivoid > 0){ Y[10] = nilaivoid*100; //Koefisien dalam (dk/k)/persen reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;} } else {return reaktivitasvoid = 0;} break; case 2: if (Percentdaya > 90) { yo = 0.1771*pow(Pdaya,2) - 0.3079*Pdaya + 0.1337; amplitudo = -4*pow(Pdaya,4) + 15.867*pow(Pdaya,3) - 23.49*pow(Pdaya,2) + 15.403*Pdaya - 3.7784; perioda = -7E-15*Pdaya + 0.2995; nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda)); if (nilaivoid < 0){ Y[10] = 0; return reaktivitasvoid = 0; } else if (nilaivoid > 0){ Y[10] = nilaivoid*100; //Koefisien dalam (dk/k)/persen reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;} } else {return reaktivitasvoid = 0;} break; case 3: if (Percentdaya > 90) { yo = 4.8314*pow(Pdaya,4) - 18.831*pow(Pdaya,3) + 27.494*pow(Pdaya,2) - 17.823*Pdaya + 4.3282; amplitudo = 3.2921*pow(Pdaya,4) - 12.846*pow(Pdaya,3) + 18.778*pow(Pdaya,2) - 12.186*Pdaya + 2.9623; perioda = 59839*pow(Pdaya,4) - 241351*pow(Pdaya,3) + 364270*pow(Pdaya,2) - 243809*Pdaya + 61053; nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda)); if (nilaivoid < 0){ Y[10] = 0; return reaktivitasvoid = 0; } else if (nilaivoid > 0){ Y[10] = nilaivoid*100; //Koefisien dalam (dk/k)/persen reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;} } else {return reaktivitasvoid = 0;} break; case 4: if (Percentdaya > 90) { yo = 2.0503*pow(Pdaya,4) - 8.1396*pow(Pdaya,3) + 12.252*pow(Pdaya,2) - 8.2593*Pdaya + 2.0979; amplitudo = -1.2469*pow(Pdaya,4) + 4.5788*pow(Pdaya,3) - 6.0721*pow(Pdaya,2) + 3.4353*Pdaya - 0.6932; perioda = -1.1333*pow(Pdaya,3) + 3.4914*pow(Pdaya,2) - 3.56*Pdaya + 4.1942; nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda)); if (nilaivoid < 0){ Y[10] = 0; return reaktivitasvoid = 0; } else if (nilaivoid > 0){ Y[10] = nilaivoid*100; //Koefisien dalam (dk/k)/persen reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;} } else {return reaktivitasvoid = 0;} break; case 5: if (Percentdaya > 90) { yo = -3.1926*pow(Pdaya,4) + 12.93*pow(Pdaya,3) - 19.442*pow(Pdaya,2) + 12.886*Pdaya - 3.1801; amplitudo = -0.2905*pow(Pdaya,3) + 1.0507*pow(Pdaya,2) - 1.1984*Pdaya + 0.4393; perioda = 0.09*pow(Pdaya,2) - 0.1707*Pdaya + 3.0723; nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda)); if (nilaivoid < 0){ Y[10] = 0; return reaktivitasvoid = 0; } else if (nilaivoid > 0){ Y[10] = nilaivoid*100; //Koefisien dalam (dk/k)/persen reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;} } else {return reaktivitasvoid = 0;} break; case 6: if (Percentdaya > 90) { yo = 0.1474*pow(Pdaya,2) - 0.2587*Pdaya + 0.1135; amplitudo = -5.3333*pow(Pdaya,4) + 20.667*pow(Pdaya,3) - 29.807*pow(Pdaya,2) + 19.001*Pdaya - 4.5245; perioda = 2.6667*pow(Pdaya,4) - 10.667*pow(Pdaya,3) + 15.973*pow(Pdaya,2) - 10.6*Pdaya + 5.6194; nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda)); if (nilaivoid < 0){ Y[10] = 0; return reaktivitasvoid = 0; } else if (nilaivoid > 0){ Y[10] = nilaivoid*100; //Koefisien dalam (dk/k)/persen reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;} } else {return reaktivitasvoid = 0;} break; case 7: if (Percentdaya > 90) { yo = 0.1371*pow(Pdaya,2) - 0.2267*Pdaya + 0.0937; amplitudo = 0.1*pow(Pdaya,2) - 0.1358*Pdaya + 0.0425; perioda = -0.0057*pow(Pdaya,2) + 0.0206*Pdaya + 2.9778; nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda)); if (nilaivoid < 0){ Y[10] = 0; return reaktivitasvoid = 0; } else if (nilaivoid > 0){ Y[10] = nilaivoid*100; //Koefisien dalam (dk/k)/persen reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;} } else {return reaktivitasvoid = 0;} break; case 8: if (Percentdaya > 70) { yo = -0.1246*pow(Pdaya,3) + 0.4406*pow(Pdaya,2) - 0.4364*Pdaya + 0.1324; amplitudo = -0.3392*pow(Pdaya,3) + 1.0276*pow(Pdaya,2) - 0.9425*Pdaya + 0.27265; perioda = -0.0059*pow(Pdaya,2) + 0.0144*Pdaya + 2.9843; nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda)); if (nilaivoid < 0){ Y[10] = 0; return reaktivitasvoid = 0; } else if (nilaivoid > 0){ Y[10] = nilaivoid*100; //Koefisien dalam (dk/k)/persen reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;} } else {return reaktivitasvoid = 0;} break; } } double floatnuc::rollheavereaktivitas (double Percentdaya, double x) { double reaktivitasvoid; double nilaivoid, yo, amplitudo, perioda; double Pdaya = Percentdaya/100; switch(SeaState) { case 0: reaktivitasvoid = 0; Y[10] = 0; return reaktivitasvoid; case 1: if (Percentdaya > 95) { yo = 0.4529*pow(Pdaya,3) - 1.3552*pow(Pdaya,2) + 1.3509*Pdaya - 0.4486; amplitudo = 0.0124*pow(Pdaya,3) - 0.0372*pow(Pdaya,2) + 0.0372*Pdaya - 0.0124; perioda = 10674*pow(Pdaya,3) - 33622*pow(Pdaya,2) + 35275*Pdaya - 12319; nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda)); if (nilaivoid < 0){ Y[10] = 0; return reaktivitasvoid = 0; } else if (nilaivoid > 0){ Y[10] = nilaivoid*100; //Koefisien dalam (dk/k)/persen reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;} } else {return reaktivitasvoid = 0;} break; case 2: if (Percentdaya > 95) { yo = 0.4529*pow(Pdaya,3) - 1.3552*pow(Pdaya,2) + 1.3509*Pdaya - 0.4486; amplitudo = 0.0155*pow(Pdaya,3) - 0.0465*pow(Pdaya,2) + 0.0464*Pdaya - 0.0155; perioda = 11992*pow(Pdaya,3) - 37758*pow(Pdaya,2) + 39600*Pdaya - 13825; nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda)); if (nilaivoid < 0){ Y[10] = 0; return reaktivitasvoid = 0; } else if (nilaivoid > 0){ Y[10] = nilaivoid*100; //Koefisien dalam (dk/k)/persen reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;} } else {return reaktivitasvoid = 0;} break; case 3: if (Percentdaya > 95) { yo = 0.4528*pow(Pdaya,3) - 1.355*pow(Pdaya,2) + 1.3507*Pdaya - 0.4485; amplitudo = 0.0533*pow(Pdaya,3) - 0.1599*pow(Pdaya,2) + 0.1598*Pdaya - 0.0532; perioda = 12557*pow(Pdaya,3) - 39554*pow(Pdaya,2) + 41501*Pdaya - 14494; nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda)); if (nilaivoid < 0){ Y[10] = 0; return reaktivitasvoid = 0; } else if (nilaivoid > 0){ Y[10] = nilaivoid*100; //Koefisien dalam (dk/k)/persen reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;} } else {return reaktivitasvoid = 0;} break; case 4: if (Percentdaya > 95) { yo = 0.4526*pow(Pdaya,3) - 1.3545*pow(Pdaya,2) + 1.3502*Pdaya - 0.4483; amplitudo = 0.1184*pow(Pdaya,3) - 0.3553*pow(Pdaya,2) + 0.3551*Pdaya - 0.1182; perioda = 13907*pow(Pdaya,3) - 43805*pow(Pdaya,2) + 45960*Pdaya - 16051; nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda)); if (nilaivoid < 0){ Y[10] = 0; return reaktivitasvoid = 0; } else if (nilaivoid > 0){ Y[10] = nilaivoid*100; //Koefisien dalam (dk/k)/persen reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;} } else {return reaktivitasvoid = 0;} break; case 5: if (Percentdaya > 95) { yo = 0.5849*pow(Pdaya,3) - 1.7513*pow(Pdaya,2) + 1.7467*Pdaya - 0.5803; amplitudo = 0.2596*pow(Pdaya,3) - 0.7788*pow(Pdaya,2) + 0.7782*Pdaya - 0.259; perioda = 14849*pow(Pdaya,3) - 46775*pow(Pdaya,2) + 49075*Pdaya - 17139; nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda)); if (nilaivoid < 0){ Y[10] = 0; return reaktivitasvoid = 0; } else if (nilaivoid > 0){ Y[10] = nilaivoid*100; //Koefisien dalam (dk/k)/persen reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;} } else {return reaktivitasvoid = 0;} break; case 6: if (Percentdaya > 95) { yo = 0.2593*pow(Pdaya,3) - 0.7781*pow(Pdaya,2) + 0.7775*Pdaya - 0.2588; amplitudo = 0.2593*pow(Pdaya,3) - 0.7781*pow(Pdaya,2)+ 0.7775*Pdaya - 0.2588; perioda = 15059*pow(Pdaya,3) - 47435*pow(Pdaya,2) + 49769*Pdaya - 17382; nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda)); if (nilaivoid < 0){ Y[10] = 0; return reaktivitasvoid = 0; } else if (nilaivoid > 0){ Y[10] = nilaivoid*100; //Koefisien dalam (dk/k)/persen reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;} } else {return reaktivitasvoid = 0;} break; case 7: if (Percentdaya > 95) { yo = 0.4523*pow(Pdaya,3) - 1.3534*pow(Pdaya,2) + 1.3491*Pdaya - 0.4479; amplitudo = 0.4523*pow(Pdaya,3) - 1.3534*pow(Pdaya,2)+ 1.3491*Pdaya - 0.4479; perioda = 18223*pow(Pdaya,3) - 57337*pow(Pdaya,2) + 60077*Pdaya - 20951; nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda)); if (nilaivoid < 0){ Y[10] = 0; return reaktivitasvoid = 0; } else if (nilaivoid > 0){ Y[10] = nilaivoid*100; //Koefisien dalam (dk/k)/persen reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;} } else {return reaktivitasvoid = 0;} break; case 8: if (Percentdaya > 95) { yo = 0.029*pow(Pdaya,2) - 0.0576*Pdaya + 0.0286; amplitudo = 0.3809*pow(Pdaya,3) - 1.1423*pow(Pdaya,2) + 1.141*Pdaya - 0.3796; perioda = 5729.7*pow(Pdaya,3) - 18636*pow(Pdaya,2) + 20187*Pdaya - 7270.7; nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda)); if (nilaivoid < 0){ Y[10] = 0; return reaktivitasvoid = 0; } else if (nilaivoid > 0){ Y[10] = nilaivoid*100; //Koefisien dalam (dk/k)/persen reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;} } else {return reaktivitasvoid = 0;} break; } } double floatnuc::fungsireaktivitasvoid(valarray<double> &Y, double x) { double reaktivitasvoid; if(Y[9] > Tsaturated){ double nilaivoid = 1; Y[10] = nilaivoid*100; double reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid; } else{ switch (ShipMovement) { case 0: reaktivitasvoid = pitchheavereaktivitas(Y[1], x); return reaktivitasvoid; case 1: reaktivitasvoid = rollheavereaktivitas(Y[1], x); return reaktivitasvoid; } } } //===================================================================================================================================================================// //========Moderator Temperature Reactivity Function========// double floatnuc::fungsireaktivitassuhumoderator(double ysuhu) { //Perhitungan Nilai Reaktivitas Suhu Moderator double reaktivitassuhumoderator = koefsuhumod*(ysuhu-Suhuawalmod ); return reaktivitassuhumoderator; } //===================================================================================================================================================================// //========Fuel Temperature Reactivity Function========// double floatnuc::fungsireaktivitassuhufuel(double ysuhu) { //Perhitungan Nilai Reaktivitas Suhu BB double reaktivitassuhufuel = koefsuhufuel*(ysuhu-suhuawalfuel); return reaktivitassuhufuel; } //===================================================================================================================================================================// //========Power Reactivity Function========// double floatnuc::fungsireaktivitasdaya(double Percentdaya) { //Perhitungan Nilai Reaktivitas Daya double reaktivitasdaya = koefdaya*Percentdaya; return reaktivitasdaya; } //===================================================================================================================================================================// //========Control Rod Reactivity Function========// double floatnuc::fungsireaktivitasbatang (double x, valarray<double> Y) { //Nilai reaktivitas grup dalam double reaktivitasgroupdalam = 0.0002*pow(Y[16],4) - 0.0533*pow(Y[16],3) + 4.331*pow(Y[16],2) - 39.798*Y[16] ; //Nilai reaktivitas grup antara double reaktivitasgroupantara = 1E-06*pow(Y[17],5) - 0.0003*pow(Y[17],4) + 0.02*pow(Y[17],3) - 0.1167*pow(Y[17],2) - 0.4026*Y[17]; //Nilai reaktivitas grup Terluar double reaktivitasgroupterluar1 = -2E-05*pow(Y[18],4) + 0.0032*pow(Y[18],3) - 0.0517*pow(Y[18],2) + 2.7248*Y[18] ; double reaktivitasgroupterluar2 = -3E-05*pow(Y[18],4) + 0.0033*pow(Y[18],3) - 0.0367*pow(Y[18],2) + 1.9241*Y[18] ; double reaktivitasbatang = reaktivitasgroupantara + 3*reaktivitasgroupdalam + 2*reaktivitasgroupterluar1 + 2*reaktivitasgroupterluar2; return reaktivitasbatang*1E-5;//convert to dk/k from pcm } double floatnuc::PosisiBatangKendali (int pilihan, double yposisi) { double ctrlrodspeed; if(condition_choose == 6){ ctrlrodspeed = scramrodspeed; }else{ ctrlrodspeed = controlrodspeed; } switch (pilihan) { case 0: if(ui->GroupDalam_Slider->value()*1.005 > yposisi && ui->GroupDalam_Slider->value()*0.995 < yposisi) { return 0; } else if (ui->GroupDalam_Slider->value()*1.02 < yposisi){ return -ctrlrodspeed/120*100;//% } else if (ui->GroupDalam_Slider->value()*0.995 > yposisi){ return ctrlrodspeed/120*100;//% }break; case 1: if(ui->GroupAntara_Slider->value()*1.005 > yposisi && ui->GroupAntara_Slider->value()*0.995 < yposisi) { return 0; } else if (ui->GroupAntara_Slider->value()*1.02 < yposisi){ return -ctrlrodspeed/120*100;//% } else if (ui->GroupAntara_Slider->value()*0.995 > yposisi){ return ctrlrodspeed/120*100;//% }break; case 2: if(ui->GroupTerluar_Slider->value()*1.005 > yposisi && ui->GroupTerluar_Slider->value()*0.995 < yposisi) { return 0; } else if (ui->GroupTerluar_Slider->value()*1.02 < yposisi){ return -ctrlrodspeed/120*100;//% } else if (ui->GroupTerluar_Slider->value()*0.995 > yposisi){ return ctrlrodspeed/120*100;//% }break; } } //===================================================================================================================================================================// //========Xenon Reactivity Function========// double floatnuc::fungsireaktivitasxenon (double yxenon) { //Nilai Koefisien xenon double koefxenon = -1E-3;//= 1 mk double yxenonawal = 0;//atom/cm3 //Perhitungan Nilai Reaktivitas Xenon double reaktivitasxenon = koefxenon*(yxenon-yxenonawal)*6E-16;//6x10^16 atom = 1 mk return reaktivitasxenon; } //===================================================================================================================================================================// //========Samarium Reactivity Function========// double floatnuc::fungsireaktivitassamarium (double ysamarium) { //Nilai Koefisien samarium double koefsamarium = -1E-3*0.1825;// = 0.1825* 1 mk double ysamariumawal = 0;//atom/cm3 //Perhitungan Nilai Reaktivitas Samarium double reaktivitassamarium = koefsamarium*(ysamarium-ysamariumawal)*6E-16; //6x10^16 atom = 1 mk return reaktivitassamarium; } //===================================================================================================================================================================// //========Total Reactivity Function========// double floatnuc::fungsireaktivitastotal (valarray<double> &Y, double x) { //Memanggil Subprogram Reaktivitas Batang double reaktivitasbatang = fungsireaktivitasbatang(x,Y); Y[4] = reaktivitasbatang; //Memanggil Subprogram Reaktivitas Akibat Daya double reaktivitasdaya = fungsireaktivitasdaya(Y[1]); //Memanggil Subprogram Reaktivitas Akibat Suhu Reaktor double reaktivitassuhufuel = fungsireaktivitassuhufuel(Y[8]); //Memanggil Subprogram Reaktivitas Akibat Suhu Reaktor double reaktivitassuhumoderator = fungsireaktivitassuhumoderator(Y[9]); //Memanggil Subprogram Reaktivitas Akibat Xenon double reaktivitasxenon = fungsireaktivitasxenon(Y[11]); Y[5] = reaktivitasxenon; //Memanggil Subprogram Reaktivitas Akibat Samarium double reaktivitassamarium = fungsireaktivitassamarium(Y[12]); Y[6] = reaktivitassamarium; //Memanggil Subprogram Reaktivitas Akibat Adanya Void double reaktivitasvoid = fungsireaktivitasvoid(Y,x); Y[7] = reaktivitasvoid; //Menghitung Nilai Reaktivitas total double reaktivitastotal = reaktivitasvoid + reaktivitasdaya + reaktivitasbatang + reaktivitassuhufuel + reaktivitassuhumoderator + reaktivitassamarium + reaktivitasxenon + reaktivitastambahan; //in % return reaktivitastotal; } valarray<double> floatnuc::F( double x, valarray<double> y ) { valarray<double> f( y.size() ); // Array for differential equation depends on the size of the data //Power Equation f[0] = ((y[3] - beta)/prompt*y[0]) + ((lamdagrup1)*y[21] + (lamdagrup2)*y[22] + (lamdagrup3)*y[23] + (lamdagrup4)*y[24] + (lamdagrup5)*y[25] + (lamdagrup6)*y[26]); //Power Percent Equation //f[1] = 0; //Fluks Equation //f[2] = 0; //Total Reactivity Equation //f[3] = 0; //Control Rod Reactivity Equation //f[4] = 0; //Xenon Reactivity Equation //f[5] = 0; //Samarium Reactivity Equation //f[6] = 0; //Void Reactivity Equation //f[7] = 0; //Fuel Equation f[8] = (y[0]*1E6 - h*a*(y[8]-y[9]))/(mfuel*cpfuel); //Persamaan Suhu Pendingin double cpmoderator = heatcapacitymoderator(y); double mpendingin = massmoderator(y); double hpendingin = convectionheattransfercoefficient(y); f[9] = (hpendingin*a*(y[8]-y[9]) - (y[27]*cpmoderator*(Y[28] - Tin)))/(mpendingin*cpmoderator); //Void Fraction //f[10] = 0; //iodine equation f[13] = (yieldiodine*fissioncrosssection*y[2]) - lamdaiodine*y[13]; //xenon equation f[11] = (yieldxenon*fissioncrosssection*y[2]) + (lamdaiodine*y[13]) - (lamdaxenon*y[11] + sigmaabsorptionxenon * y[11] * y[2]); //promethium Equation f[14] = (yieldpromethium*fissioncrosssection*y[2]) - (lamdapromethium * y[14]); //samarium Equation f[12] = (lamdapromethium*y[14]) - (sigmaabsorptionsamarium*y[2]*y[12]); //Reactor Period //f[15] = 0; //Control Rod Positions Equation f[16] = PosisiBatangKendali(0,Y[16]); f[17] = PosisiBatangKendali(1,Y[17]); f[18] = PosisiBatangKendali(2,Y[18]); //Total Precursor //f[20] = 0; //Precursor Equation //Grup 1 f[21] = (betagrup1/prompt*y[0])-(lamdagrup1*y[21]); //Grup 2 f[22] = (betagrup2/prompt*y[0])-(lamdagrup2*y[22]); //Grup 3 f[23] = (betagrup3/prompt*y[0])-(lamdagrup3*y[23]); //Grup 4 f[24] = (betagrup4/prompt*y[0])-(lamdagrup4*y[24]); //Grup 5 f[25] = (betagrup5/prompt*y[0])-(lamdagrup5*y[25]); //Grup 6 f[26] = (betagrup6/prompt*y[0])-(lamdagrup6*y[26]); //Mass Flow //f[27] = 0;//Kg/s // **************************************** return f; } void floatnuc::step( double dx, double &x, valarray<double> &Y ) { qApp->processEvents(); valarray<double> dY1(ndep), dY2(ndep), dY3(ndep), dY4(ndep); dY1 = F( x , Y ) * dx; dY2 = F( x + 0.5 * dx, Y + 0.5 * dY1 ) * dx; dY3 = F( x + 0.5 * dx, Y + 0.5 * dY2 ) * dx; dY4 = F( x + dx, Y + dY3 ) * dx; Y += ( dY1 + 2.0 * dY2 + 2.0 * dY3 + dY4 ) / 6.0; x += dx; } void floatnuc::initialcondition(valarray<double> &Y) { //Initial Condition Y[0] = 50; //Daya in MWth Y[1] = Y[0]/fullpower*100;//PowerPercent Y[2] = Y[0]/(convertpowertofluks*reactorvol*fissioncrosssection); //Fluks in n/cm2*s Y[20] = beta*Y[0]/(lamdagrup4*prompt); //Prekursor Y[8] = 839; //Suhu Fuel in K Y[9] = 553; //Suhu Moderator in K Y[3] = 0; //Reaktivitas Y[13] = 0; //Iodine in atom/cm3 Y[11] = 0; //Xenon in atom/cm3 Y[14] = 0; //Promethium atom/cm3 Y[12] = 0; //Samarium atom/cm3 Y[15] = neutronlifetime/Y[3];//Reactor period Y[16] = 35; //ControlRodPositionDalam % Y[17] = 35; //ControlRodPositionAntara % Y[18] = 35; //ControlRodPositionLuar % Y[27] = lajumassa;//Kg/s Y[28] = 553; //Suhu Keluaran Moderator in K ui->GroupDalam_Slider->setValue(Y[16]); ui->GroupAntara_Slider->setValue(Y[17]); ui->GroupTerluar_Slider->setValue(Y[18]); } void floatnuc::engine() { // Set initial values double x = xo; //This is the step number double nstep = (xn - xo) / dx; if (x == 0.0){ initialcondition(Y); }else{ tampilhasil(x, Y); } simpanhasil(x, Y); // Solve the differential equation using nstep intervals for ( int n = 0; n < nstep; n++ ) { //The Reactivity and fluxdont need the RK Method Y[3] = fungsireaktivitastotal( Y, x); Y[2] = Y[0]/(convertpowertofluks*reactorvol*fissioncrosssection); //Fluks in n/cm2*s //The Total Prekursor also dont need RK Method Y[20] = Y[21]+Y[22]+Y[23]+Y[24]+Y[25]+Y[26]; //The Reactor Power Percent also dont need RK Method Y[1] = Y[0]/fullpower*100;//PowerPercent reactorperiod(x,Y); //Moderator average temperature Equation Y[28] = 2 * Y[9] - Tin; //Dimensionless number Y[29] = prandtl(Y); Y[30] = nusselt(Y); Y[31] = reynold(Y); condition(x, Y); // The Main Runge-Kutta step step( dx, x, Y ); } //Counting the initial and end condition from engine time xo+= intervalwaktu/1000; xn+= intervalwaktu/1000; } //Simulation Control void floatnuc::on_Start_PushButton_clicked() { timer->start(100); ui->Video_Widget->m_mediaPlayer->play(); } void floatnuc::on_Stop_PushButton_clicked() { timer->stop(); ui->Video_Widget->m_mediaPlayer->pause(); } void floatnuc::on_Update_PushButton_clicked() { tampilhasil(xo, Y); } //Stacked Widget Control void floatnuc::on_Start_Button_clicked() { ui->stackedWidget->setCurrentIndex(0); } void floatnuc::on_Intro_Button_clicked() { ui->stackedWidget->setCurrentIndex(1); } void floatnuc::on_Save_Button_clicked() { ui->stackedWidget->setCurrentIndex(2); } void floatnuc::on_Simulation_Button_clicked() { ui->stackedWidget->setCurrentIndex(3); //Set Current Index of Video //playlist->setCurrentIndex(17); //ui->Video_Widget->m_mediaPlayer->play(); } void floatnuc::on_Graph_Button_clicked() { ui->stackedWidget->setCurrentIndex(4); } void floatnuc::on_Spec_Button_clicked() { ui->stackedWidget->setCurrentIndex(5); } void floatnuc::on_AboutUs_Button_clicked() { ui->stackedWidget->setCurrentIndex(6); } void floatnuc::on_Exit_Button_clicked() { this->close(); } void floatnuc::on_ShipMove_Combobox_currentIndexChanged(int index) { videocalling(SeaState,index); } void floatnuc::on_SeaState_Combobox_currentIndexChanged(int index) { videocalling(index, ShipMovement); }
37.841992
167
0.549833
rainoverme002
07d4775dcd775f15558c912809dde9cfa138fac7
6,791
cpp
C++
source/solution_zoo/common/xproto_plugins/iotvioplugin/src/iotviomanager/camera/camera_ov10635.cpp
HorizonRobotics-Platform/AI-EXPRESS
413206d88dae1fbd465ced4d60b2a1769d15c171
[ "BSD-2-Clause" ]
98
2020-09-11T13:52:44.000Z
2022-03-23T11:52:02.000Z
source/solution_zoo/common/xproto_plugins/iotvioplugin/src/iotviomanager/camera/camera_ov10635.cpp
HorizonRobotics-Platform/ai-express
413206d88dae1fbd465ced4d60b2a1769d15c171
[ "BSD-2-Clause" ]
8
2020-10-19T14:23:30.000Z
2022-03-16T01:00:07.000Z
source/solution_zoo/common/xproto_plugins/iotvioplugin/src/iotviomanager/camera/camera_ov10635.cpp
HorizonRobotics-Platform/AI-EXPRESS
413206d88dae1fbd465ced4d60b2a1769d15c171
[ "BSD-2-Clause" ]
28
2020-09-17T14:20:35.000Z
2022-01-10T16:26:00.000Z
/*************************************************************************** * COPYRIGHT NOTICE * Copyright 2020 Horizon Robotics, Inc. * All rights reserved. ***************************************************************************/ #include "iotviomanager/vinparams.h" namespace horizon { namespace vision { namespace xproto { namespace vioplugin { MIPI_SENSOR_INFO_S SENSOR_2LANE_OV10635_30FPS_YUV_720P_954_INFO = { .deseEnable = 1, .inputMode = INPUT_MODE_MIPI, .deserialInfo = { .bus_type = 0, .bus_num = 4, .deserial_addr = 0x3d, .deserial_name = const_cast<char*>("s954") }, .sensorInfo = { .port = 0, .dev_port = 0, .bus_type = 0, .bus_num = 4, .fps = 30, .resolution = 720, .sensor_addr = 0x40, .serial_addr = 0x1c, .entry_index = 1, .sensor_mode = {}, .reg_width = 16, .sensor_name = const_cast<char*>("ov10635"), .extra_mode = 0, .deserial_index = 0, .deserial_port = 0 } }; MIPI_SENSOR_INFO_S SENSOR_2LANE_OV10635_30FPS_YUV_720P_960_INFO = { .deseEnable = 1, .inputMode = INPUT_MODE_MIPI, .deserialInfo = { .bus_type = 0, .bus_num = 1, .deserial_addr = 0x30, .deserial_name = const_cast<char*>("s960") }, .sensorInfo = { .port = 0, .dev_port = 0, .bus_type = 0, .bus_num = 4, .fps = 30, .resolution = 720, .sensor_addr = 0x40, .serial_addr = 0x1c, .entry_index = 0, .sensor_mode = {}, .reg_width = 16, .sensor_name = const_cast<char*>("ov10635"), .extra_mode = 0, .deserial_index = 0, .deserial_port = 0 } }; MIPI_ATTR_S MIPI_2LANE_OV10635_30FPS_YUV_720P_954_ATTR = { .mipi_host_cfg = { 2, /* lane */ 0x1e, /* datatype */ 24, /* mclk */ 1600, /* mipiclk */ 30, /* fps */ 1280, /* width */ 720, /*height */ 3207, /* linlength */ 748, /* framelength */ 30, /* settle */ 4, {0, 1, 2, 3} }, .dev_enable = 0 /* mipi dev enable */ }; MIPI_ATTR_S MIPI_2LANE_OV10635_30FPS_YUV_720P_960_ATTR = { .mipi_host_cfg = { 2, /* lane */ 0x1e, /* datatype */ 24, /* mclk */ 3200, /* mipiclk */ 30, /* fps */ 1280, /* width */ 720, /*height */ 3207, /* linlength */ 748, /* framelength */ 30, /* settle */ 4, {0, 1, 2, 3} }, .dev_enable = 0 /* mipi dev enable */ }; MIPI_ATTR_S MIPI_2LANE_OV10635_30FPS_YUV_LINE_CONCATE_720P_960_ATTR = { .mipi_host_cfg = { 2, /* lane */ 0x1e, /* datatype */ 24, /* mclk */ 3200, /* mipiclk */ 30, /* fps */ 1280, /* width */ 720, /* height */ 3207, /* linlength */ 748, /* framelength */ 30, /* settle */ 2, {0, 1} }, .dev_enable = 0 /* mipi dev enable */ }; VIN_DEV_ATTR_S DEV_ATTR_OV10635_YUV_BASE = { .stSize = { 8, /*format*/ 1280, /*width*/ 720, /*height*/ 0 /*pix_length*/ }, { .mipiAttr = { .enable = 1, .ipi_channels = 1, .ipi_mode = 0, .enable_mux_out = 1, .enable_frame_id = 1, .enable_bypass = 0, .enable_line_shift = 0, .enable_id_decoder = 0, .set_init_frame_id = 1, .set_line_shift_count = 0, .set_bypass_channels = 1, }, }, .DdrIspAttr = { .stride = 0, .buf_num = 4, .raw_feedback_en = 0, .data = { .format = 8, .width = 1280, .height = 720, .pix_length = 0, } }, .outDdrAttr = { .stride = 1280, .buffer_num = 8, }, .outIspAttr = { .dol_exp_num = 1, .enable_dgain = 0, .set_dgain_short = 0, .set_dgain_medium = 0, .set_dgain_long = 0, } }; VIN_DEV_ATTR_S DEV_ATTR_OV10635_YUV_LINE_CONCATE_BASE = { .stSize = { 8, /* format */ 2560, /* width */ 720, /* height */ 0 /* pix_length */ }, { .mipiAttr = { .enable = 1, .ipi_channels = 1, .ipi_mode = 0, .enable_mux_out = 1, .enable_frame_id = 1, .enable_bypass = 0, .enable_line_shift = 0, .enable_id_decoder = 0, .set_init_frame_id = 1, .set_line_shift_count = 0, .set_bypass_channels = 1, }, }, .DdrIspAttr = { .stride = 0, .buf_num = 4, .raw_feedback_en = 0, .data = { .format = 8, .width = 2560, .height = 720, .pix_length = 0, } }, .outDdrAttr = { .stride = 2560, .buffer_num = 8, }, .outIspAttr = { .dol_exp_num = 1, .enable_dgain = 0, .set_dgain_short = 0, .set_dgain_medium = 0, .set_dgain_long = 0, } }; VIN_DEV_ATTR_EX_S DEV_ATTR_OV10635_MD_BASE = { .path_sel = 1, .roi_top = 0, .roi_left = 0, .roi_width = 1280, .roi_height = 640, .grid_step = 128, .grid_tolerance = 10, .threshold = 10, .weight_decay = 128, .precision = 0 }; VIN_PIPE_ATTR_S PIPE_ATTR_OV10635_YUV_BASE = { .ddrOutBufNum = 8, .frameDepth = 0, .snsMode = SENSOR_NORMAL_MODE, .stSize = { .format = 0, .width = 1280, .height = 720, }, .cfaPattern = PIPE_BAYER_RGGB, .temperMode = 0, .ispBypassEn = 1, .ispAlgoState = 0, .bitwidth = 12, .startX = 0, .startY = 0, .calib = { .mode = 0, .lname = NULL, } }; VIN_PIPE_ATTR_S VIN_ATTR_OV10635_YUV_LINE_CONCATE_BASE = { .ddrOutBufNum = 8, .frameDepth = 0, .snsMode = SENSOR_NORMAL_MODE, .stSize = { .format = 0, .width = 2560, .height = 720, }, .cfaPattern = PIPE_BAYER_RGGB, .temperMode = 0, .ispBypassEn = 1, .ispAlgoState = 0, .bitwidth = 12, .startX = 0, .startY = 0, .calib = { .mode = 0, .lname = NULL, } }; VIN_DIS_ATTR_S DIS_ATTR_OV10635_BASE = { .picSize = { .pic_w = 1279, .pic_h = 719, }, .disPath = { .rg_dis_enable = 0, .rg_dis_path_sel = 1, }, .disHratio = 65536, .disVratio = 65536, .xCrop = { .rg_dis_start = 0, .rg_dis_end = 1279, }, .yCrop = { .rg_dis_start = 0, .rg_dis_end = 719, } }; VIN_LDC_ATTR_S LDC_ATTR_OV10635_BASE = { .ldcEnable = 0, .ldcPath = { .rg_y_only = 0, .rg_uv_mode = 0, .rg_uv_interpo = 0, .reserved1 = 0, .rg_h_blank_cyc = 32, .reserved0 = 0 }, .yStartAddr = 524288, .cStartAddr = 786432, .picSize = { .pic_w = 1279, .pic_h = 719, }, .lineBuf = 99, .xParam = { .rg_algo_param_b = 1, .rg_algo_param_a = 1, }, .yParam = { .rg_algo_param_b = 1, .rg_algo_param_a = 1, }, .offShift = { .rg_center_xoff = 0, .rg_center_yoff = 0, }, .xWoi = { .rg_start = 0, .reserved1 = 0, .rg_length = 1279, .reserved0 = 0 }, .yWoi = { .rg_start = 0, .reserved1 = 0, .rg_length = 719, .reserved0 = 0 } }; } // namespace vioplugin } // namespace xproto } // namespace vision } // namespace horizon
19.973529
77
0.537329
HorizonRobotics-Platform
07d6a85081e2f35a2f51806f61a606750c1a47a3
5,906
cc
C++
apps/grid.cc
CS126SP20/Game-of-Life
a626f94ccd5ab1f93cefa2c37fc4868fbc0ba6bd
[ "MIT" ]
null
null
null
apps/grid.cc
CS126SP20/Game-of-Life
a626f94ccd5ab1f93cefa2c37fc4868fbc0ba6bd
[ "MIT" ]
null
null
null
apps/grid.cc
CS126SP20/Game-of-Life
a626f94ccd5ab1f93cefa2c37fc4868fbc0ba6bd
[ "MIT" ]
null
null
null
// Copyright (c) 2020 [Swathi Ram]. All rights reserved. #include "../include/mylibrary/grid.h" namespace mylibrary { /* * Overridden function that does not take in a parameter if the grid has * stabilized. Used if the user has chosen to pause the automaton or if it * is the first call to the calculation of the configuration. */ std::vector<std::vector<int>>& Grid::GetCurrentGrid() { return grids_[gen_id_ % 2]; } /* * Helper method to check which grid to use as the current vs. the next * generation. This method facilitates the ping pong effect between the two * grids. If the next generation should be calculated, an even id prompts the * calculated using the first grid as the current and the second as the next * generation to be added to. An odd id uses the next generation that was * previously calculated as the current and fills out the other grid with the * next generation of that grid. * @param calculate_next_gen: boolean to check whether next generation should * be calculated * @return: returns the grid containing the current cell configuration */ std::vector<std::vector<int>>& Grid::GetCurrentGrid(bool& did_gen_change_) { if (gen_id_ % 2 == 0) { CalculateNextGeneration(grids_[0], grids_[1]); } else { CalculateNextGeneration(grids_[1], grids_[0]); } did_gen_change_ = DidGridChange(); return grids_[gen_id_ % 2]; } /* * Helper method to resize the 3D vector of grids and fill in the grid's cell * configuration based on the coordinates from the json file read into seed * from cell_automaton.cc. The dimension of the 3D vector dealing with the * grids is resized to 2 to account for the current and next generation of * cells. The next two dimensions are resized to the passed in dimensions. The * cell configuration is set to 1 if a cell exists at the coordinate and is kept * as 0 if not. * @param dimension: passed in size of the grid * @param seed: vector containing coordinates of cells from json file */ void Grid::SetDimensionAndFillSeeds(int dimension, std::vector<std::vector<int>> seed) { grid_dimension_ = dimension; // first level grids_.resize(2); // second level grids_[0].resize(dimension); grids_[1].resize(dimension); // third level for (int i = 0; i < 2; i++) { for (int j = 0; j < dimension; j++) { grids_[i][j].resize(dimension); } } for (int i = 0; i < seed.size(); i++) { assert((seed[i][0]) < grid_dimension_); assert((seed[i][1]) < grid_dimension_); grids_[0][seed[i][0]][seed[i][1]] = 1; } } /* * Helper method to compare two grids for equality. Used to check when the * cell configuration has stabilized as the grids will be equal when no more * generations can be calculated. * @return: Boolean for if the grids are the same in each position */ bool Grid::DidGridChange() { for (int i = 0; i < grid_dimension_; i++) { for (int j = 0; j < grid_dimension_; j++) { if (grids_[0][i][j] != grids_[1][i][j]) { return true; } } } return false; } /* * Helper method dealing with the main logic of calculating the next generation * of cells. Method is passed in two grids- the current generation of cells to * use for cell information and the next generation to be calculated and filled * in with the cells at their calculated position. The calculations follow the * fundamental rules of the Game of life: * 1. Any live cell with fewer than two live neighbours dies. * 2. Any live cell with two or three live neighbours lives. * 3. Any live cell with more than three live neighbours dies. * 4. Any dead cell with exactly three live neighbours becomes a live cell. * At the end of the method, the gen_id_ is incremented to * allow the switch between grids by the next call. * @param curr_gen_: current generation of cell configurations * @param next_gen_: next generation of cell configurations */ void Grid::CalculateNextGeneration(std::vector<std::vector<int>>& curr_gen_, std::vector<std::vector<int>>& next_gen_) { for (int i = 0; i < curr_gen_.size(); i++) { for (int j = 0; j < curr_gen_.size(); j++) { int state = curr_gen_[i][j]; // account for edge cells if (i == 0 || i == curr_gen_.size() - 1 || j == 0 || j == curr_gen_.size() - 1) { next_gen_[i][j] = state; } else { size_t num_neighbors = CountNeighbors(curr_gen_, i, j); if (state == 1 && num_neighbors < 2) { next_gen_[i][j] = 0; } else if (state == 1 && num_neighbors > 3) { next_gen_[i][j] = 0; } else if (state == 0 && (num_neighbors == 3)) { next_gen_[i][j] = 1; } else { next_gen_[i][j] = state; } } } } gen_id_++; } /* * Helper method to count the number of surrounding cells around a particular * cell at the passed in location on the grid. Calculates neighbors by adding * the label of the cell (1 or 0). * @param grid: cell grid containing the cell configuration information * @param x: x coordinate of the cell * @param y: y coordinate of the cell * @return: method returns the numbers of neighbors of a particular cell */ size_t Grid::CountNeighbors(std::vector<std::vector<int>>& grid, int x, int y) { size_t num_neighbors = 0; for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { num_neighbors += grid[x + i][y + j]; // 0's and 1's so add for sum } } num_neighbors -= grid[x][y]; return num_neighbors; } /* * Helper method to support restarting the automaton when the user chooses. * Clears the grids, setting all positions to 0. */ void Grid::ResetGrid() { for (int i = 0; i < grid_dimension_; i++) { for (int j = 0; j < grid_dimension_; j++) { grids_[0][i][j] = 0; grids_[1][i][j] = 0; } } gen_id_ = 0; } } // namespace mylibrary
35.365269
80
0.655943
CS126SP20
07d9bcaf73944e3fb39ad3e8ff64dbd5a386d785
258
cpp
C++
Core/Event/Event.cpp
digital7-code/gaps_engine
43e2ed7c8cc43800c8815d68ab22963a773f0c5f
[ "Apache-2.0" ]
null
null
null
Core/Event/Event.cpp
digital7-code/gaps_engine
43e2ed7c8cc43800c8815d68ab22963a773f0c5f
[ "Apache-2.0" ]
null
null
null
Core/Event/Event.cpp
digital7-code/gaps_engine
43e2ed7c8cc43800c8815d68ab22963a773f0c5f
[ "Apache-2.0" ]
1
2021-10-16T14:11:00.000Z
2021-10-16T14:11:00.000Z
#include <gapspch.hpp> #include <Core/Event/Event.hpp> namespace gaps { EventId Event::GetId() const noexcept { return id; } Event::Event(const EventId id) noexcept : id{ id } { } void Event::OnCreate() { } void Event::OnRelease() { } }
10.75
40
0.631783
digital7-code
07da80fff5916e196089971a4998c90c9cc20b37
532
cpp
C++
src/systems/sources/type.cpp
hexoctal/zenith
eeef065ed62f35723da87c8e73a6716e50d34060
[ "MIT" ]
2
2021-03-18T16:25:04.000Z
2021-11-13T00:29:27.000Z
src/systems/sources/type.cpp
hexoctal/zenith
eeef065ed62f35723da87c8e73a6716e50d34060
[ "MIT" ]
null
null
null
src/systems/sources/type.cpp
hexoctal/zenith
eeef065ed62f35723da87c8e73a6716e50d34060
[ "MIT" ]
1
2021-11-13T00:29:30.000Z
2021-11-13T00:29:30.000Z
/** * @file * @author __AUTHOR_NAME__ <[email protected]> * @copyright 2021 __COMPANY_LTD__ * @license <a href="https://opensource.org/licenses/MIT">MIT License</a> */ #include "../type.hpp" #include "../../components/type.hpp" #include "../../utils/assert.hpp" namespace Zen { extern entt::registry g_registry; std::string GetType (Entity entity) { auto blendMode = g_registry.try_get<Components::Type>(entity); ZEN_ASSERT(blendMode, "The entity has no 'Type' component."); return blendMode->type; } } // namespace Zen
21.28
74
0.695489
hexoctal
07dd5260fe7a319e58385b38ffc31bad2d689dbb
29,107
hpp
C++
System.Core/include/Switch/System/Threading/Monitor.hpp
kkptm/CppLikeCSharp
b2d8d9da9973c733205aa945c9ba734de0c734bc
[ "MIT" ]
4
2021-10-14T01:43:00.000Z
2022-03-13T02:16:08.000Z
System.Core/include/Switch/System/Threading/Monitor.hpp
kkptm/CppLikeCSharp
b2d8d9da9973c733205aa945c9ba734de0c734bc
[ "MIT" ]
null
null
null
System.Core/include/Switch/System/Threading/Monitor.hpp
kkptm/CppLikeCSharp
b2d8d9da9973c733205aa945c9ba734de0c734bc
[ "MIT" ]
2
2022-03-13T02:16:06.000Z
2022-03-14T14:32:57.000Z
/// @file /// @brief Contains Switch::System::Threading::Monitor class. #pragma once #include <map> #include "../../RefPtr.hpp" #include "../../Static.hpp" #include "../IntPtr.hpp" #include "../Object.hpp" #include "../Nullable.hpp" #include "../TimeSpan.hpp" #include "AutoResetEvent.hpp" #include "Mutex.hpp" #include "Timeout.hpp" #include "../SystemException.hpp" #include "../Collections/Generic/Dictionary.hpp" /// @brief The Switch namespace contains all fundamental classes to access Hardware, Os, System, and more. namespace Switch { /// @brief The System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. namespace System { /// @brief The System::Threading namespace provides classes and interfaces that enable multithreaded programming. /// In addition to classes for synchronizing thread activities and access to data ( Mutex, Monitor, Interlocked, AutoResetEvent, and so on), this namespace includes a ThreadPool class that allows you to use a pool of system-supplied threads, and a Timer class that executes callback methods on thread pool threads. namespace Threading { /// @brief Provides a mechanism that synchronizes access to objects. class core_export_ Monitor static_ { public: /// @brief Acquires an exclusive lock on the specified obj. /// @param obj The object on which to acquire the monitor lock. /// @exception ArgumentNullException The obj parameter is null. /// @remarks Use Enter to acquire the Monitor on the object passed as the parameter. If another thread has executed an Enter on the object, but has not yet executed the corresponding Exit, the current thread will block until the other thread releases the object. It is legal for the same thread to invoke Enter more than once without it blocking; however, an equal number of Exit calls must be invoked before other threads waiting on the object will unblock. /// @remarks Usex Monitor to lock objects (that is, reference types), not value types. When you pass a value type variable to Enter, it is boxed as an object. If you pass the same variable to Enter again, the thread is block. The code that Monitor is supposedly protecting is not protected. Furthermore, when you pass the variable to Exit, still another separate object is created. Because the object passed to Exit is different from the object passed to Enter, Monitor throws SynchronizationLockException. For details, see the conceptual topic Monitors. static void Enter(const object& obj) { bool lockTaken = false; Enter(obj, lockTaken); } /// @brief Acquires an exclusive lock on the specified obj. /// @param obj The object on which to acquire the monitor lock. /// @param lockTaken The result of the attempt to acquire the lock, passed by reference. The input must be false. The output is true if the lock is acquired; otherwise, the output is false. The output is set even if an exception occurs during the attempt to acquire the lock. /// @note If no exception occurs, the output of this method is always true. /// @exception ArgumentNullException The obj parameter is null. /// @remarks Use Enter to acquire the Monitor on the object passed as the parameter. If another thread has executed an Enter on the object, but has not yet executed the corresponding Exit, the current thread will block until the other thread releases the object. It is legal for the same thread to invoke Enter more than once without it blocking; however, an equal number of Exit calls must be invoked before other threads waiting on the object will unblock. /// @remarks Use Monitor to lock objects (that is, reference types), not value types. When you pass a value type variable to Enter, it is boxed as an object. If you pass the same variable to Enter again, the thread is block. The code that Monitor is supposedly protecting is not protected. Furthermore, when you pass the variable to Exit, still another separate object is created. Because the object passed to Exit is different from the object passed to Enter, Monitor throws SynchronizationLockException. For details, see the conceptual topic Monitors. static void Enter(const object& obj, bool& lockTaken) { if (TryEnter(obj, lockTaken) == false) throw InvalidOperationException(caller_); } /// @brief Acquires an exclusive lock on the specified obj. /// @param obj The object on which to acquire the monitor lock. /// @exception ArgumentNullException The obj parameter is null. /// @remarks Use Enter to acquire the Monitor on the object passed as the parameter. If another thread has executed an Enter on the object, but has not yet executed the corresponding Exit, the current thread will block until the other thread releases the object. It is legal for the same thread to invoke Enter more than once without it blocking; however, an equal number of Exit calls must be invoked before other threads waiting on the object will unblock. /// @remarks Usex Monitor to lock objects (that is, reference types), not value types. When you pass a value type variable to Enter, it is boxed as an object. If you pass the same variable to Enter again, the thread is block. The code that Monitor is supposedly protecting is not protected. Furthermore, when you pass the variable to Exit, still another separate object is created. Because the object passed to Exit is different from the object passed to Enter, Monitor throws SynchronizationLockException. For details, see the conceptual topic Monitors. static bool IsEntered(const object& obj) { return MonitorItems().ContainsKey(ToKey(obj)); } /// @brief Notifies a thread in the waiting queue of a change in the locked object's state. /// @param obj The object a thread is waiting for. /// @exception ArgumentNullException The obj parameter is null. /// Only the current owner of the lock can signal a waiting object using Pulse. /// The thread that currently owns the lock on the specified object invokes this method to signal the next thread in line for the lock. Upon receiving the pulse, the waiting thread is moved to the ready queue. When the thread that invoked Pulse releases the lock, the next thread in the ready queue (which is not necessarily the thread that was pulsed) acquires the lock. static void Pulse(const object& obj); /// @brief Notifies all waiting threads of a change in the object's state. /// @param obj The object a thread is waiting for. /// @exception ArgumentNullException The obj parameter is null. /// @remarks The thread that currently owns the lock on the specified object invokes this method to signal all threads waiting to acquire the lock on the object. After the signal is sent, the waiting threads are moved to the ready queue. When the thread that invoked PulseAll releases the lock, the next thread in the ready queue acquires the lock. /// @remarks Note that a synchronized object holds several references, including a reference to the thread that currently holds the lock, a reference to the ready queue, which contains the threads that are ready to obtain the lock, and a reference to the waiting queue, which contains the threads that are waiting for notification of a change in the object's state. /// @remarks The Pulse, PulseAll, and Wait methods must be invoked from within a synchronized block of code. /// @remarks The remarks for the Pulse method explain what happens if Pulse is called when no threads are waiting. /// @remarks To signal a single thread, use the Pulse method. static void PulseAll(const object& obj); /// @brief Releases an exclusive lock on the specified obj. /// @param obj The object on which to release the lock. /// @exception ArgumentNullException The obj parameter is null. /// @remarks The calling thread must own the lock on the obj parameter. If the calling thread owns the lock on the specified object, and has made an equal number of Exit and Enter calls for the object, then the lock is released. If the calling thread has not invoked Exit as many times as Enter, the lock is not released. /// @remarks If the lock is released and other threads are in the ready queue for the object, one of the threads acquires the lock. If other threads are in the waiting queue waiting to acquire the lock, they are not automatically moved to the ready queue when the owner of the lock calls Exit. To move one or more waiting threads into the ready queue, call Pulse or PulseAll before invoking Exit. static void Exit(const object& obj) {Remove(obj);} /// @brief Attempts to acquire an exclusive lock on the specified object. /// @param obj The object on which to acquire the lock. /// @return bool true if the current thread acquires the lock; otherwise, false /// @exception ArgumentNullException The obj parameter is null. /// @remarks If successful, this method acquires an exclusive lock on the obj parameter. This method returns immediately, whether or not the lock is available. /// @remarks This method is similar to Enter, but it will never block. If the thread cannot enter without blocking, the method returns false, and the thread does not enter the critical section. static bool TryEnter(const object& obj) {return TryEnter(obj, Timeout::Infinite);} /// @brief Attempts to acquire an exclusive lock on the specified object. /// @param obj The object on which to acquire the lock. /// @param lockTaken The result of the attempt to acquire the lock, passed by reference. The input must be false. The output is true if the lock is acquired; otherwise, the output is false. The output is set even if an exception occurs during the attempt to acquire the lock. /// @note If no exception occurs, the output of this method is always true. /// @return bool true if the current thread acquires the lock; otherwise, false /// @exception ArgumentNullException The obj parameter is null. /// @remarks If successful, this method acquires an exclusive lock on the obj parameter. This method returns immediately, whether or not the lock is available. /// @remarks This method is similar to Enter, but it will never block. If the thread cannot enter without blocking, the method returns false, and the thread does not enter the critical section. static bool TryEnter(const object& obj, bool& lockTaken) {return TryEnter(obj, Timeout::Infinite, lockTaken);} /// @brief Attempts, for the specified number of milliseconds, to acquire an exclusive lock on the specified object. /// @param obj The object on which to acquire the lock. /// @param millisecondsTimeout The number of milliseconds to wait for the lock. /// @return bool true if the current thread acquires the lock; otherwise, false /// @exception ArgumentNullException The obj parameter is null. /// @remarks If the millisecondsTimeout parameter equals Timeout::Infinite, this method is equivalent to Enter. If millisecondsTimeout equals 0, this method is equivalent to TryEnter. static bool TryEnter(const object& obj, int32 millisecondsTimeout) { bool lockTacken = false; return TryEnter(obj, millisecondsTimeout, lockTacken); } /// @brief Attempts, for the specified number of milliseconds, to acquire an exclusive lock on the specified object. /// @param obj The object on which to acquire the lock. /// @param millisecondsTimeout The number of milliseconds to wait for the lock. /// @param lockTaken The result of the attempt to acquire the lock, passed by reference. The input must be false. The output is true if the lock is acquired; otherwise, the output is false. The output is set even if an exception occurs during the attempt to acquire the lock. /// @note If no exception occurs, the output of this method is always true. /// @return bool true if the current thread acquires the lock; otherwise, false /// @exception ArgumentNullException The obj parameter is null. /// @remarks If the millisecondsTimeout parameter equals Timeout::Infinite, this method is equivalent to Enter. If millisecondsTimeout equals 0, this method is equivalent to TryEnter. static bool TryEnter(const object& obj, int32 millisecondsTimeout, bool& lockTaken) { if (millisecondsTimeout < -1) return false; lockTaken = Add(obj, millisecondsTimeout); return true; } /// @brief Attempts, for the specified number of milliseconds, to acquire an exclusive lock on the specified object. /// @param obj The object on which to acquire the lock. /// @param millisecondsTimeout The number of milliseconds to wait for the lock. /// @return bool true if the current thread acquires the lock; otherwise, false /// @exception ArgumentNullException The obj parameter is null. /// @remarks If the millisecondsTimeout parameter equals Timeout::Infinite, this method is equivalent to Enter. If millisecondsTimeout equals 0, this method is equivalent to TryEnter. static bool TryEnter(const object& obj, int64 millisecondsTimeout) { bool lockTacken = false; return TryEnter(obj, millisecondsTimeout, lockTacken); } /// @brief Attempts, for the specified number of milliseconds, to acquire an exclusive lock on the specified object. /// @param obj The object on which to acquire the lock. /// @param millisecondsTimeout The number of milliseconds to wait for the lock. /// @param lockTaken The result of the attempt to acquire the lock, passed by reference. The input must be false. The output is true if the lock is acquired; otherwise, the output is false. The output is set even if an exception occurs during the attempt to acquire the lock. /// @note If no exception occurs, the output of this method is always true. /// @return bool true if the current thread acquires the lock; otherwise, false /// @exception ArgumentNullException The obj parameter is null. /// @remarks If the millisecondsTimeout parameter equals Timeout::Infinite, this method is equivalent to Enter. If millisecondsTimeout equals 0, this method is equivalent to TryEnter. static bool TryEnter(const object& obj, int64 millisecondsTimeout, bool& lockTaken) { if (millisecondsTimeout < -1) return false; lockTaken = Add(obj, (int32)millisecondsTimeout); return true; } /// @brief Attempts, for the specified amount of time, to acquire an exclusive lock on the specified object. /// @param obj The object on which to acquire the lock. /// @param timeout A TimeSpan representing the amount of time to wait for the lock. A value of -1 millisecond specifies an infinite wait. /// @return bool true if the current thread acquires the lock; otherwise, false /// @exception ArgumentNullException The obj timeout or parameter is null. /// @remarks If the value of the timeout parameter converted to milliseconds equals -1, this method is equivalent to Enter. If the value of timeout equals 0, this method is equivalent to TryEnter. static bool TryEnter(const object& obj, const TimeSpan& timeout) { bool lockTaken = false; return TryEnter(obj, as<int32>(timeout.TotalMilliseconds()), lockTaken); } /// @brief Attempts, for the specified amount of time, to acquire an exclusive lock on the specified object. /// @param obj The object on which to acquire the lock. /// @param timeout A TimeSpan representing the amount of time to wait for the lock. A value of -1 millisecond specifies an infinite wait. /// @param lockTaken The result of the attempt to acquire the lock, passed by reference. The input must be false. The output is true if the lock is acquired; otherwise, the output is false. The output is set even if an exception occurs during the attempt to acquire the lock. /// @note If no exception occurs, the output of this method is always true. /// @return bool true if the current thread acquires the lock; otherwise, false /// @exception ArgumentNullException The obj timeout or parameter is null. /// @remarks If the value of the timeout parameter converted to milliseconds equals -1, this method is equivalent to Enter. If the value of timeout equals 0, this method is equivalent to TryEnter. static bool TryEnter(const object& obj, const TimeSpan& timeout, bool& lockTaken) {return TryEnter(obj, as<int32>(timeout.TotalMilliseconds()), lockTaken);} /// @brief Releases the lock on an object and blocks the current thread until it reacquires the lock. /// @param obj The object on which to wait. /// @return Boolean true if the call returned because the caller reacquired the lock for the specified object. This method does not return if the lock is not reacquired. /// @exception ArgumentNullException The obj parameter is null. /// The thread that currently owns the lock on the specified object invokes this method in order to release the object so that another thread can access it. The caller is blocked while waiting to reacquire the lock. This method is called when the caller needs to wait for a state change that will occur as a result of another thread's operations. /// When a thread calls Wait, it releases the lock on the object and enters the object's waiting queue. The next thread in the object's ready queue (if there is one) acquires the lock and has exclusive use of the object. All threads that call Wait remain in the waiting queue until they receive a signal from Pulse or PulseAll, sent by the owner of the lock. If Pulse is sent, only the thread at the head of the waiting queue is affected. If PulseAll is sent, all threads that are waiting for the object are affected. When the signal is received, one or more threads leave the waiting queue and enter the ready queue. A thread in the ready queue is permitted to reacquire the lock. /// This method returns when the calling thread reacquires the lock on the object. Note that this method blocks indefinitely if the holder of the lock does not call Pulse or PulseAll. /// The caller executes Wait once, regardless of the number of times Enter has been invoked for the specified object. Conceptually, the Wait method stores the number of times the caller invoked Enter on the object and invokes Exit as many times as necessary to fully release the locked object. The caller then blocks while waiting to reacquire the object. When the caller reacquires the lock, the system calls Enter as many times as necessary to restore the saved Enter count for the caller. Calling Wait releases the lock for the specified object only; if the caller is the owner of locks on other objects, these locks are not released. /// Note that a synchronized object holds several references, including a reference to the thread that currently holds the lock, a reference to the ready queue, which contains the threads that are ready to obtain the lock, and a reference to the waiting queue, which contains the threads that are waiting for notification of a change in the object's state. /// The Pulse, PulseAll, and Wait methods must be invoked from within a synchronized block of code. /// The remarks for the Pulse method explain what happens if Pulse is called when no threads are waiting. static bool Wait(const object& obj) {return Wait(obj, Timeout::Infinite);} /// @brief Releases the lock on an object and blocks the current thread until it reacquires the lock. /// @param obj The object on which to wait. /// @param millisecondsTimeout The number of milliseconds to wait before the thread enters the ready queue. /// @return bool true if the lock was reacquired before the specified time elapsed; false if the lock was reacquired after the specified time elapsed. The method does not return until the lock is reacquired. /// @exception ArgumentNullException The obj parameter is null. /// This method does not return until it reacquires an exclusive lock on the obj parameter. /// The thread that currently owns the lock on the specified object invokes this method in order to release the object so that another thread can access it. The caller is blocked while waiting to reacquire the lock. This method is called when the caller needs to wait for a state change that will occur as a result of another thread's operations. /// The time-out ensures that the current thread does not block indefinitely if another thread releases the lock without first calling the Pulse or PulseAll method. It also moves the thread to the ready queue, bypassing other threads ahead of it in the wait queue, so that it can reacquire the lock sooner. The thread can test the return value of the Wait method to determine whether it reacquired the lock prior to the time-out. The thread can evaluate the conditions that caused it to enter the wait, and if necessary call the Wait method again. /// When a thread calls Wait, it releases the lock on the object and enters the object's waiting queue. The next thread in the object's ready queue (if there is one) acquires the lock and has exclusive use of the object. The thread that invoked Wait remains in the waiting queue until either a thread that holds the lock invokes PulseAll, or it is the next in the queue and a thread that holds the lock invokes Pulse. However, if millisecondsTimeout elapses before another thread invokes this object's Pulse or PulseAll method, the original thread is moved to the ready queue in order to regain the lock. /// If Timeout::Infinite is specified for the millisecondsTimeout parameter, this method blocks indefinitely unless the holder of the lock calls Pulse or PulseAll. If millisecondsTimeout equals 0, the thread that calls Wait releases the lock and then immediately enters the ready queue in order to regain the lock. /// The caller executes Wait once, regardless of the number of times Enter has been invoked for the specified object. Conceptually, the Wait method stores the number of times the caller invoked Enter on the object and invokes Exit as many times as necessary to fully release the locked object. The caller then blocks while waiting to reacquire the object. When the caller reacquires the lock, the system calls Enter as many times as necessary to restore the saved Enter count for the caller. Calling Wait releases the lock for the specified object only; if the caller is the owner of locks on other objects, these locks are not released. /// A synchronized object holds several references, including a reference to the thread that currently holds the lock, a reference to the ready queue, which contains the threads that are ready to obtain the lock, and a reference to the waiting queue, which contains the threads that are waiting for notification of a change in the object's state. /// The Pulse, PulseAll, and Wait methods must be invoked from within a synchronized block of code. /// The remarks for the Pulse method explain what happens if Pulse is called when no threads are waiting. static bool Wait(const object& obj, int32 millisecondsTimeout); /// @brief Releases the lock on an object and blocks the current thread until it reacquires the lock. If the specified time-out interval elapses, the thread enters the ready queue. /// @param obj The object on which to wait. /// @param timeout A TimeSpan representing the amount of time to wait before the thread enters the ready queue. /// @return bool true if the lock was reacquired before the specified time elapsed; false if the lock was reacquired after the specified time elapsed. The method does not return until the lock is reacquired. /// @exception ArgumentNullException The obj parameter is null. /// This method does not return until it reacquires an exclusive lock on the obj parameter. /// The thread that currently owns the lock on the specified object invokes this method in order to release the object so that another thread can access it. The caller is blocked while waiting to reacquire the lock. This method is called when the caller needs to wait for a state change that will occur as a result of another thread's operations. /// The time-out ensures that the current thread does not block indefinitely if another thread releases the lock without first calling the Pulse or PulseAll method. It also moves the thread to the ready queue, bypassing other threads ahead of it in the wait queue, so that it can reacquire the lock sooner. The thread can test the return value of the Wait method to determine whether it reacquired the lock prior to the time-out. The thread can evaluate the conditions that caused it to enter the wait, and if necessary call the Wait method again. /// When a thread calls Wait, it releases the lock on the object and enters the object's waiting queue. The next thread in the object's ready queue (if there is one) acquires the lock and has exclusive use of the object. The thread that invoked Wait remains in the waiting queue until either a thread that holds the lock invokes PulseAll, or it is the next in the queue and a thread that holds the lock invokes Pulse. However, if timeout elapses before another thread invokes this object's Pulse or PulseAll method, the original thread is moved to the ready queue in order to regain the lock. /// If a TimeSpan representing -1 millisecond is specified for the timeout parameter, this method blocks indefinitely unless the holder of the lock calls Pulse or PulseAll. If timeout is 0 milliseconds, the thread that calls Wait releases the lock and then immediately enters the ready queue in order to regain the lock. /// The caller executes Wait once, regardless of the number of times Enter has been invoked for the specified object. Conceptually, the Wait method stores the number of times the caller invoked Enter on the object and invokes Exit as many times as necessary to fully release the locked object. The caller then blocks while waiting to reacquire the object. When the caller reacquires the lock, the system calls Enter as many times as necessary to restore the saved Enter count for the caller. Calling Wait releases the lock for the specified object only; if the caller is the owner of locks on other objects, these locks are not released. /// A synchronized object holds several references, including a reference to the thread that currently holds the lock, a reference to the ready queue, which contains the threads that are ready to obtain the lock, and a reference to the waiting queue, which contains the threads that are waiting for notification of a change in the object's state. /// The Pulse, PulseAll, and Wait methods must be invoked from within a synchronized block of code. ///The remarks for the Pulse method explain what happens if Pulse is called when no threads are waiting. static bool Wait(const object& obj, const TimeSpan& timeout) {return Wait(obj, as<int32>(timeout.TotalMilliseconds()));} private: struct MonitorItem { MonitorItem() {} MonitorItem(const string& name) : name(name) {} bool operator==(const MonitorItem& monitorItem) const {return this->event == monitorItem.event && this->usedCounter == monitorItem.usedCounter;} bool operator!=(const MonitorItem& monitorItem) const {return !this->operator==(monitorItem);} Mutex event {false}; int32 usedCounter {0}; Nullable<string> name; }; static const object* ToKey(const object& obj) { if (is<string>(obj)) { for (const auto& item : MonitorItems()) if (item.Value().name.HasValue && item.Value().name.Value().Equals((const string&)obj)) return item.Key; } return &obj; } static System::Collections::Generic::Dictionary<const object*, MonitorItem>& MonitorItems() { static System::Collections::Generic::Dictionary<const object*, MonitorItem> monitorItems; return monitorItems; } static bool Add(const object& obj, int32 millisecondsTimeout); static void Remove(const object& obj); }; } } } using namespace Switch;
113.699219
689
0.738448
kkptm
07e204bb40e36c20f9a8052d0c265e6bee08baf0
719
cc
C++
cartographer/cloud/map_builder_server_interface.cc
laotie/cartographer
b8228ee6564f5a7ad0d6d0b9a30516521cff2ee9
[ "Apache-2.0" ]
5,196
2016-08-04T14:52:31.000Z
2020-04-02T18:30:00.000Z
cartographer/cloud/map_builder_server_interface.cc
laotie/cartographer
b8228ee6564f5a7ad0d6d0b9a30516521cff2ee9
[ "Apache-2.0" ]
1,206
2016-08-03T14:27:00.000Z
2020-03-31T21:14:18.000Z
cartographer/cloud/map_builder_server_interface.cc
laotie/cartographer
b8228ee6564f5a7ad0d6d0b9a30516521cff2ee9
[ "Apache-2.0" ]
1,810
2016-08-03T05:45:02.000Z
2020-04-02T03:44:18.000Z
#include "cartographer/cloud/map_builder_server_interface.h" #include "absl/memory/memory.h" #include "cartographer/cloud/internal/map_builder_server.h" namespace cartographer { namespace cloud { void RegisterMapBuilderServerMetrics(metrics::FamilyFactory* factory) { MapBuilderServer::RegisterMetrics(factory); } std::unique_ptr<MapBuilderServerInterface> CreateMapBuilderServer( const proto::MapBuilderServerOptions& map_builder_server_options, std::unique_ptr<mapping::MapBuilderInterface> map_builder) { return absl::make_unique<MapBuilderServer>(map_builder_server_options, std::move(map_builder)); } } // namespace cloud } // namespace cartographer
32.681818
72
0.76217
laotie
07e298c33ca879800b5608f5928da1363551daeb
11,964
cxx
C++
Packages/java/io/PrintStream.cxx
Brandon-T/Aries
4e8c4f5454e8c7c5cd0611b1b38b5be8186f86ca
[ "MIT" ]
null
null
null
Packages/java/io/PrintStream.cxx
Brandon-T/Aries
4e8c4f5454e8c7c5cd0611b1b38b5be8186f86ca
[ "MIT" ]
null
null
null
Packages/java/io/PrintStream.cxx
Brandon-T/Aries
4e8c4f5454e8c7c5cd0611b1b38b5be8186f86ca
[ "MIT" ]
null
null
null
// // PrintStream.cxx // Aries // // Created by Brandon on 2017-08-26. // Copyright © 2017 Brandon. All rights reserved. // #include "PrintStream.hxx" #include "FilterOutputStream.hxx" #include "File.hxx" #include "OutputStream.hxx" #include "CharSequence.hxx" #include "Object.hxx" #include "String.hxx" #include "Locale.hxx" using java::io::PrintStream; using java::io::File; using java::io::FilterOutputStream; using java::io::OutputStream; using java::lang::CharSequence; using java::lang::Object; using java::lang::String; using java::util::Locale; PrintStream::PrintStream(JVM* vm, jobject instance) : FilterOutputStream() { if (vm && instance) { this->vm = vm; this->cls = JVMRef<jclass>(this->vm, this->vm->FindClass("Ljava/io/PrintStream;")); this->inst = JVMRef<jobject>(this->vm, instance); } } PrintStream::PrintStream(JVM* vm, OutputStream out) : FilterOutputStream() { if (vm) { this->vm = vm; this->cls = JVMRef<jclass>(this->vm, this->vm->FindClass("Ljava/io/PrintStream;")); jmethodID constructor = this->vm->GetMethodID(this->cls.get(), "<init>", "(Ljava/io/OutputStream;)V"); this->inst = JVMRef<jobject>(this->vm, this->vm->NewObject(this->cls.get(), constructor, out.ref().get())); } } PrintStream::PrintStream(JVM* vm, OutputStream out, bool autoFlush) : FilterOutputStream() { if (vm) { this->vm = vm; this->cls = JVMRef<jclass>(this->vm, this->vm->FindClass("Ljava/io/PrintStream;")); jmethodID constructor = this->vm->GetMethodID(this->cls.get(), "<init>", "(Ljava/io/OutputStream;Z)V"); this->inst = JVMRef<jobject>(this->vm, this->vm->NewObject(this->cls.get(), constructor, out.ref().get(), autoFlush)); } } PrintStream::PrintStream(JVM* vm, OutputStream out, bool autoFlush, String encoding) : FilterOutputStream() { if (vm) { this->vm = vm; this->cls = JVMRef<jclass>(this->vm, this->vm->FindClass("Ljava/io/PrintStream;")); jmethodID constructor = this->vm->GetMethodID(this->cls.get(), "<init>", "(Ljava/io/OutputStream;ZLjava/lang/String;)V"); this->inst = JVMRef<jobject>(this->vm, this->vm->NewObject(this->cls.get(), constructor, out.ref().get(), autoFlush, encoding.ref().get())); } } PrintStream::PrintStream(JVM* vm, String fileName) : FilterOutputStream() { if (vm) { this->vm = vm; this->cls = JVMRef<jclass>(this->vm, this->vm->FindClass("Ljava/io/PrintStream;")); jmethodID constructor = this->vm->GetMethodID(this->cls.get(), "<init>", "(Ljava/lang/String;)V"); this->inst = JVMRef<jobject>(this->vm, this->vm->NewObject(this->cls.get(), constructor, fileName.ref().get())); } } PrintStream::PrintStream(JVM* vm, String fileName, String csn) : FilterOutputStream() { if (vm) { this->vm = vm; this->cls = JVMRef<jclass>(this->vm, this->vm->FindClass("Ljava/io/PrintStream;")); jmethodID constructor = this->vm->GetMethodID(this->cls.get(), "<init>", "(Ljava/lang/String;Ljava/lang/String;)V"); this->inst = JVMRef<jobject>(this->vm, this->vm->NewObject(this->cls.get(), constructor, fileName.ref().get(), csn.ref().get())); } } PrintStream::PrintStream(JVM* vm, File file) : FilterOutputStream() { if (vm) { this->vm = vm; this->cls = JVMRef<jclass>(this->vm, this->vm->FindClass("Ljava/io/PrintStream;")); jmethodID constructor = this->vm->GetMethodID(this->cls.get(), "<init>", "(Ljava/io/File;)V"); this->inst = JVMRef<jobject>(this->vm, this->vm->NewObject(this->cls.get(), constructor, file.ref().get())); } } PrintStream::PrintStream(JVM* vm, File file, String csn) : FilterOutputStream() { if (vm) { this->vm = vm; this->cls = JVMRef<jclass>(this->vm, this->vm->FindClass("Ljava/io/PrintStream;")); jmethodID constructor = this->vm->GetMethodID(this->cls.get(), "<init>", "(Ljava/io/File;Ljava/lang/String;)V"); this->inst = JVMRef<jobject>(this->vm, this->vm->NewObject(this->cls.get(), constructor, file.ref().get(), csn.ref().get())); } } PrintStream PrintStream::append(CharSequence csq) { static jmethodID appendMethod = this->vm->GetMethodID(this->cls.get(), "append", "(Ljava/lang/CharSequence;)Ljava/io/PrintStream;"); return PrintStream(this->vm, this->vm->CallObjectMethod(this->inst.get(), appendMethod, csq.ref().get())); } PrintStream PrintStream::append(CharSequence csq, std::int32_t start, std::int32_t end) { static jmethodID appendMethod = this->vm->GetMethodID(this->cls.get(), "append", "(Ljava/lang/CharSequence;II)Ljava/io/PrintStream;"); return PrintStream(this->vm, this->vm->CallObjectMethod(this->inst.get(), appendMethod, csq.ref().get(), start, end)); } PrintStream PrintStream::append(char c) { static jmethodID appendMethod = this->vm->GetMethodID(this->cls.get(), "append", "(C)Ljava/io/PrintStream;"); return PrintStream(this->vm, this->vm->CallObjectMethod(this->inst.get(), appendMethod, c)); } bool PrintStream::checkError() { static jmethodID checkErrorMethod = this->vm->GetMethodID(this->cls.get(), "checkError", "()Z"); return this->vm->CallBooleanMethod(this->inst.get(), checkErrorMethod); } void PrintStream::close() { static jmethodID closeMethod = this->vm->GetMethodID(this->cls.get(), "close", "()V"); this->vm->CallVoidMethod(this->inst.get(), closeMethod); } void PrintStream::flush() { static jmethodID flushMethod = this->vm->GetMethodID(this->cls.get(), "flush", "()V"); this->vm->CallVoidMethod(this->inst.get(), flushMethod); } PrintStream PrintStream::format(String arg0, Array<Object>& arg1) { static jmethodID formatMethod = this->vm->GetMethodID(this->cls.get(), "format", "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/io/PrintStream;"); return PrintStream(this->vm, this->vm->CallObjectMethod(this->inst.get(), formatMethod, arg0.ref().get(), arg1.ref().get())); } PrintStream PrintStream::format(Locale arg0, String arg1, Array<Object>& arg2) { static jmethodID formatMethod = this->vm->GetMethodID(this->cls.get(), "format", "(Ljava/util/Locale;Ljava/lang/String;[Ljava/lang/Object;)Ljava/io/PrintStream;"); return PrintStream(this->vm, this->vm->CallObjectMethod(this->inst.get(), formatMethod, arg0.ref().get(), arg1.ref().get(), arg2.ref().get())); } void PrintStream::print(bool b) { static jmethodID printMethod = this->vm->GetMethodID(this->cls.get(), "print", "(Z)V"); this->vm->CallVoidMethod(this->inst.get(), printMethod, b); } void PrintStream::print(char c) { static jmethodID printMethod = this->vm->GetMethodID(this->cls.get(), "print", "(C)V"); this->vm->CallVoidMethod(this->inst.get(), printMethod, c); } void PrintStream::print(std::int32_t i) { static jmethodID printMethod = this->vm->GetMethodID(this->cls.get(), "print", "(I)V"); this->vm->CallVoidMethod(this->inst.get(), printMethod, i); } void PrintStream::print(std::int64_t l) { static jmethodID printMethod = this->vm->GetMethodID(this->cls.get(), "print", "(J)V"); this->vm->CallVoidMethod(this->inst.get(), printMethod, l); } void PrintStream::print(float f) { static jmethodID printMethod = this->vm->GetMethodID(this->cls.get(), "print", "(F)V"); this->vm->CallVoidMethod(this->inst.get(), printMethod, f); } void PrintStream::print(double d) { static jmethodID printMethod = this->vm->GetMethodID(this->cls.get(), "print", "(D)V"); this->vm->CallVoidMethod(this->inst.get(), printMethod, d); } void PrintStream::print(Array<char>& s) { static jmethodID printMethod = this->vm->GetMethodID(this->cls.get(), "print", "([C)V"); this->vm->CallVoidMethod(this->inst.get(), printMethod, s.ref().get()); } void PrintStream::print(String s) { static jmethodID printMethod = this->vm->GetMethodID(this->cls.get(), "print", "(Ljava/lang/String;)V"); this->vm->CallVoidMethod(this->inst.get(), printMethod, s.ref().get()); } void PrintStream::print(Object obj) { static jmethodID printMethod = this->vm->GetMethodID(this->cls.get(), "print", "(Ljava/lang/Object;)V"); this->vm->CallVoidMethod(this->inst.get(), printMethod, obj.ref().get()); } PrintStream PrintStream::printf(String arg0, Array<Object>& arg1) { static jmethodID printfMethod = this->vm->GetMethodID(this->cls.get(), "printf", "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/io/PrintStream;"); return PrintStream(this->vm, this->vm->CallObjectMethod(this->inst.get(), printfMethod, arg0.ref().get(), arg1.ref().get())); } PrintStream PrintStream::printf(Locale arg0, String arg1, Array<Object>& arg2) { static jmethodID printfMethod = this->vm->GetMethodID(this->cls.get(), "printf", "(Ljava/util/Locale;Ljava/lang/String;[Ljava/lang/Object;)Ljava/io/PrintStream;"); return PrintStream(this->vm, this->vm->CallObjectMethod(this->inst.get(), printfMethod, arg0.ref().get(), arg1.ref().get(), arg2.ref().get())); } void PrintStream::println() { static jmethodID printlnMethod = this->vm->GetMethodID(this->cls.get(), "println", "()V"); this->vm->CallVoidMethod(this->inst.get(), printlnMethod); } void PrintStream::println(bool x) { static jmethodID printlnMethod = this->vm->GetMethodID(this->cls.get(), "println", "(Z)V"); this->vm->CallVoidMethod(this->inst.get(), printlnMethod, x); } void PrintStream::println(char x) { static jmethodID printlnMethod = this->vm->GetMethodID(this->cls.get(), "println", "(C)V"); this->vm->CallVoidMethod(this->inst.get(), printlnMethod, x); } void PrintStream::println(std::int32_t x) { static jmethodID printlnMethod = this->vm->GetMethodID(this->cls.get(), "println", "(I)V"); this->vm->CallVoidMethod(this->inst.get(), printlnMethod, x); } void PrintStream::println(std::int64_t x) { static jmethodID printlnMethod = this->vm->GetMethodID(this->cls.get(), "println", "(J)V"); this->vm->CallVoidMethod(this->inst.get(), printlnMethod, x); } void PrintStream::println(float x) { static jmethodID printlnMethod = this->vm->GetMethodID(this->cls.get(), "println", "(F)V"); this->vm->CallVoidMethod(this->inst.get(), printlnMethod, x); } void PrintStream::println(double x) { static jmethodID printlnMethod = this->vm->GetMethodID(this->cls.get(), "println", "(D)V"); this->vm->CallVoidMethod(this->inst.get(), printlnMethod, x); } void PrintStream::println(Array<char>& x) { static jmethodID printlnMethod = this->vm->GetMethodID(this->cls.get(), "println", "([C)V"); this->vm->CallVoidMethod(this->inst.get(), printlnMethod, x.ref().get()); } void PrintStream::println(String x) { static jmethodID printlnMethod = this->vm->GetMethodID(this->cls.get(), "println", "(Ljava/lang/String;)V"); this->vm->CallVoidMethod(this->inst.get(), printlnMethod, x.ref().get()); } void PrintStream::println(Object x) { static jmethodID printlnMethod = this->vm->GetMethodID(this->cls.get(), "println", "(Ljava/lang/Object;)V"); this->vm->CallVoidMethod(this->inst.get(), printlnMethod, x.ref().get()); } void PrintStream::write(std::int32_t b) { static jmethodID writeMethod = this->vm->GetMethodID(this->cls.get(), "write", "(I)V"); this->vm->CallVoidMethod(this->inst.get(), writeMethod, b); } void PrintStream::write(Array<std::uint8_t>& buf, std::int32_t off, std::int32_t len) { static jmethodID writeMethod = this->vm->GetMethodID(this->cls.get(), "write", "([BII)V"); this->vm->CallVoidMethod(this->inst.get(), writeMethod, buf.ref().get(), off, len); } void PrintStream::clearError() { static jmethodID clearErrorMethod = this->vm->GetMethodID(this->cls.get(), "clearError", "()V"); this->vm->CallVoidMethod(this->inst.get(), clearErrorMethod); } void PrintStream::setError() { static jmethodID setErrorMethod = this->vm->GetMethodID(this->cls.get(), "setError", "()V"); this->vm->CallVoidMethod(this->inst.get(), setErrorMethod); }
38.346154
167
0.666499
Brandon-T
07e3a9a55b3f4af4ca2d096594e4c06beca81467
6,729
cpp
C++
HelperFunctions/getVkPhysicalDeviceLineRasterizationFeaturesEXT.cpp
dkaip/jvulkan-natives-Linux-x86_64
ea7932f74e828953c712feea11e0b01751f9dc9b
[ "Apache-2.0" ]
null
null
null
HelperFunctions/getVkPhysicalDeviceLineRasterizationFeaturesEXT.cpp
dkaip/jvulkan-natives-Linux-x86_64
ea7932f74e828953c712feea11e0b01751f9dc9b
[ "Apache-2.0" ]
null
null
null
HelperFunctions/getVkPhysicalDeviceLineRasterizationFeaturesEXT.cpp
dkaip/jvulkan-natives-Linux-x86_64
ea7932f74e828953c712feea11e0b01751f9dc9b
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2020 Douglas Kaip * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * getVkPhysicalDeviceLineRasterizationFeaturesEXT.cpp * * Created on: Sep 9, 2020 * Author: Douglas Kaip */ #include "JVulkanHelperFunctions.hh" #include "slf4j.hh" namespace jvulkan { void getVkPhysicalDeviceLineRasterizationFeaturesEXT( JNIEnv *env, jobject jVkPhysicalDeviceLineRasterizationFeaturesEXTObject, VkPhysicalDeviceLineRasterizationFeaturesEXT *vkPhysicalDeviceLineRasterizationFeaturesEXT, std::vector<void *> *memoryToFree) { jclass theClass = env->GetObjectClass(jVkPhysicalDeviceLineRasterizationFeaturesEXTObject); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not get class for jVkPhysicalDeviceLineRasterizationFeaturesEXTObject"); return; } //////////////////////////////////////////////////////////////////////// VkStructureType sTypeValue = getSType(env, jVkPhysicalDeviceLineRasterizationFeaturesEXTObject); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Call to getSType failed."); return; } //////////////////////////////////////////////////////////////////////// jobject jpNextObject = getpNextObject(env, jVkPhysicalDeviceLineRasterizationFeaturesEXTObject); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Call to getpNext failed."); return; } void *pNext = nullptr; if (jpNextObject != nullptr) { getpNextChain( env, jpNextObject, &pNext, memoryToFree); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Call to getpNextChain failed."); return; } } //////////////////////////////////////////////////////////////////////// jmethodID methodId = env->GetMethodID(theClass, "isRectangularLines", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isRectangularLines."); return; } VkBool32 rectangularLines = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceLineRasterizationFeaturesEXTObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isBresenhamLines", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isBresenhamLines."); return; } VkBool32 bresenhamLines = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceLineRasterizationFeaturesEXTObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isSmoothLines", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isSmoothLines."); return; } VkBool32 smoothLines = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceLineRasterizationFeaturesEXTObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isStippledRectangularLines", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isStippledRectangularLines."); return; } VkBool32 stippledRectangularLines = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceLineRasterizationFeaturesEXTObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isStippledBresenhamLines", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isStippledBresenhamLines."); return; } VkBool32 stippledBresenhamLines = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceLineRasterizationFeaturesEXTObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } //////////////////////////////////////////////////////////////////////// methodId = env->GetMethodID(theClass, "isStippledSmoothLines", "()Z"); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Could not find method id for isStippledSmoothLines."); return; } VkBool32 stippledSmoothLines = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceLineRasterizationFeaturesEXTObject, methodId); if (env->ExceptionOccurred()) { LOGERROR(env, "%s", "Error calling CallBooleanMethod."); return; } vkPhysicalDeviceLineRasterizationFeaturesEXT->sType = sTypeValue; vkPhysicalDeviceLineRasterizationFeaturesEXT->pNext = (void *)pNext; vkPhysicalDeviceLineRasterizationFeaturesEXT->rectangularLines = rectangularLines; vkPhysicalDeviceLineRasterizationFeaturesEXT->bresenhamLines = bresenhamLines; vkPhysicalDeviceLineRasterizationFeaturesEXT->smoothLines = smoothLines; vkPhysicalDeviceLineRasterizationFeaturesEXT->stippledRectangularLines = stippledRectangularLines; vkPhysicalDeviceLineRasterizationFeaturesEXT->stippledBresenhamLines = stippledBresenhamLines; vkPhysicalDeviceLineRasterizationFeaturesEXT->stippledSmoothLines = stippledSmoothLines; } }
38.895954
140
0.585674
dkaip
07e3b5d7056376be055dad6e9850772b35e89d49
2,468
cpp
C++
Source/Runtime/Foundation/Filesystem/FileSystem.cpp
simeks/Sandbox
394b7ab774b172b6e8bc560eb2740620a8dee399
[ "MIT" ]
null
null
null
Source/Runtime/Foundation/Filesystem/FileSystem.cpp
simeks/Sandbox
394b7ab774b172b6e8bc560eb2740620a8dee399
[ "MIT" ]
null
null
null
Source/Runtime/Foundation/Filesystem/FileSystem.cpp
simeks/Sandbox
394b7ab774b172b6e8bc560eb2740620a8dee399
[ "MIT" ]
null
null
null
// Copyright 2008-2014 Simon Ekström #include "Common.h" #include "FileSystem.h" #include "FileSource.h" #include "File.h" #include "FileUtil.h" namespace sb { //------------------------------------------------------------------------------- FileSystem::FileSystem(const char* base_path) { _base_path = base_path; } FileSystem::~FileSystem() { // Clear any file sources that are left for (auto& source : _file_sources) { delete source; } _file_sources.clear(); } FileStreamPtr FileSystem::OpenFile(const char* file_path, const File::FileMode mode) { Assert(!_file_sources.empty()); FileStreamPtr file; for (auto& source : _file_sources) { file = source->OpenFile(file_path, mode); if (file.Get()) { return file; } } logging::Warning("FileSystem: File '%s' not found", file_path); return FileStreamPtr(); } FileSource* FileSystem::OpenFileSource(const char* path, const PathAddFlags flags) { FileSource* source = 0; // First check if the path already exists in the system for (auto& source : _file_sources) { if (source->GetPath() == path) { return source; } } source = new FileSource(this, path); if (flags == ADD_TO_TAIL) { _file_sources.push_back(source); } else { _file_sources.push_front(source); } return source; } void FileSystem::CloseFileSource(FileSource* source) { deque<FileSource*>::iterator it = std::find(_file_sources.begin(), _file_sources.end(), source); if (it != _file_sources.end()) { delete source; _file_sources.erase(it); return; } } void FileSystem::CloseFileSource(const char* path) { for (deque<FileSource*>::iterator it = _file_sources.begin(); it != _file_sources.end(); ++it) { if ((*it)->GetPath() == path) { delete (*it); _file_sources.erase(it); return; } } } void FileSystem::MakeDirectory(const char* path) { string dir_path(path); string full_path; // Is the sources file path absolute? if (dir_path.find(':') != string::npos) { full_path = dir_path; } else { file_util::BuildOSPath(full_path, _base_path, dir_path); } #ifdef SANDBOX_PLATFORM_WIN CreateDirectory(full_path.c_str(), NULL); #elif SANDBOX_PLATFORM_MACOSX mkdir(full_path.Ptr(), S_IRWXU); #endif } const string& FileSystem::GetBasePath() const { return _base_path; } //------------------------------------------------------------------------------- } // namespace sb
20.566667
98
0.623987
simeks
2e38e61fc47051fc67aa6e8ef6969c2539e90b68
952
cpp
C++
D3D12Backend/APIWrappers/CommandQueue/GraphicQueue.cpp
bestdark/BoolkaEngine
35ae68dedb42baacb19908c0aaa047fe7f71f6b2
[ "MIT" ]
27
2021-02-12T10:13:55.000Z
2022-03-24T14:44:06.000Z
D3D12Backend/APIWrappers/CommandQueue/GraphicQueue.cpp
bestdark/BoolkaEngine
35ae68dedb42baacb19908c0aaa047fe7f71f6b2
[ "MIT" ]
null
null
null
D3D12Backend/APIWrappers/CommandQueue/GraphicQueue.cpp
bestdark/BoolkaEngine
35ae68dedb42baacb19908c0aaa047fe7f71f6b2
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "GraphicQueue.h" #include "APIWrappers/CommandList/GraphicCommandListImpl.h" #include "APIWrappers/Device.h" namespace Boolka { bool GraphicQueue::Initialize(Device& device) { ID3D12CommandQueue* commandQueue = nullptr; D3D12_COMMAND_QUEUE_DESC desc = {}; desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; desc.Priority = D3D12_COMMAND_QUEUE_PRIORITY_NORMAL; desc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; desc.NodeMask = 0; HRESULT hr = device->CreateCommandQueue(&desc, IID_PPV_ARGS(&commandQueue)); if (FAILED(hr)) return false; return CommandQueue::Initialize(device, commandQueue); } void GraphicQueue::ExecuteCommandList(GraphicCommandListImpl& commandList) { ID3D12CommandList* nativeCommandList = commandList.Get(); m_Queue->ExecuteCommandLists(1, &nativeCommandList); } } // namespace Boolka
28.848485
84
0.70063
bestdark
2e3a71e3282033c5a3b41c23659a1f6082156d82
1,135
cc
C++
2020/PTA/Contest/1.cc
slowbear/TrainingCode
688872b9dab784a410069b787457f8c0871648aa
[ "CC0-1.0" ]
null
null
null
2020/PTA/Contest/1.cc
slowbear/TrainingCode
688872b9dab784a410069b787457f8c0871648aa
[ "CC0-1.0" ]
null
null
null
2020/PTA/Contest/1.cc
slowbear/TrainingCode
688872b9dab784a410069b787457f8c0871648aa
[ "CC0-1.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using LL = long long; using Pii = pair<int, int>; using Pll = pair<LL, LL>; using VI = vector<int>; using VP = vector<pair<int, int>>; #define rep(i, a, b) for (auto i = (a); i < (b); ++i) #define rev(i, a, b) for (auto i = (b - 1); i >= (a); --i) #define grep(i, u) for (auto i = gh[u]; i != -1; i = gn[i]) #define mem(x, v) memset(x, v, sizeof(x)) #define cpy(x, y) memcpy(x, y, sizeof(x)) #define SZ(V) static_cast<int>(V.size()) #define pb push_back #define mp make_pair struct factor { LL x, y; }; factor operator+(const factor &a, const factor &b) { LL new_y = a.y * b.y; LL new_x = a.x * b.y + b.x * a.y; LL d = __gcd(abs(new_x), abs(new_y)); return factor{new_x / d, new_y / d}; } int main() { int n; scanf("%d", &n); factor sum{0, 1}; rep(i, 0, n) { LL x, y; scanf("%lld/%lld", &x, &y); sum = sum + factor{x, y}; } if (!sum.x) { printf("0\n"); return 0; } LL z = sum.x / sum.y; sum.x = sum.x % sum.y; if (z) printf("%lld", z); if (sum.x) { if (z) printf(" "); printf("%lld/%lld", sum.x, sum.y); } printf("\n"); }
22.7
59
0.533921
slowbear
2e3dd45c74178ada77a28f0951aee800499e7b43
1,930
cpp
C++
engine/plugins/files/file_reader_class.cpp
dmpas/e8engine
27390fa096fa721be5f8a868a844fbb20f6ebc9c
[ "MIT" ]
1
2017-11-17T07:28:02.000Z
2017-11-17T07:28:02.000Z
engine/plugins/files/file_reader_class.cpp
dmpas/e8engine
27390fa096fa721be5f8a868a844fbb20f6ebc9c
[ "MIT" ]
null
null
null
engine/plugins/files/file_reader_class.cpp
dmpas/e8engine
27390fa096fa721be5f8a868a844fbb20f6ebc9c
[ "MIT" ]
null
null
null
#include "file_reader_class.hpp" #include <boost/filesystem.hpp> #include "e8core/env/_array.h" #include <sys/types.h> #include <sys/stat.h> namespace fs = boost::filesystem; using namespace std; void FileReaderClass::Close() { stream.close(); } void FileReaderClass::Open(E8_IN FileName, E8_IN Exclusive) { if (IsOpen()) Close(); wstring ws = FileName.to_string().to_wstring(); fs::path m_path(ws); stream.open(m_path, std::ios_base::binary); stream.seekg(0, stream.end); m_full_size = stream.tellg(); stream.seekg(0, stream.beg); m_tail_size = m_full_size; } /* .Прочитать([Размер]) -> ФиксированныйМассив */ E8::Variant FileReaderClass::Read(E8_IN Size) { if (!IsOpen()) { throw E8::EnvironmentException(); //E8_THROW_DETAIL(E8_RT_EXCEPTION_RAISED, "File not opened!"); } //std::cout << "inSize: " << Size << std::endl << std::flush; size_t size = 0; if (Size != E8::Variant::Undefined()) { size = Size.to_long(); } if (size == 0 || size > m_tail_size) size = m_tail_size; char *buf = new char[size]; int read = stream.readsome(buf, size); m_tail_size -= read; if (m_tail_size < 0) m_tail_size = 0; E8::Variant A = E8::NewObject("Array", size); int i = 0; for (i = 0; i < read; ++i) { long l_value = (unsigned char)buf[i]; E8::Variant V(l_value); A.__Call("Set", i, V); } delete buf; A = E8::NewObject("FixedArray", A); return A; } FileReaderClass *FileReaderClass::Constructor(E8_IN FileName, E8_IN Exclusive) { FileReaderClass *R = new FileReaderClass(); if (FileName != E8::Variant::Undefined()) R->Open(FileName, Exclusive); return R; } bool FileReaderClass::IsOpen() const { return stream.is_open(); } FileReaderClass::FileReaderClass() { } FileReaderClass::~FileReaderClass() { }
20.104167
79
0.615026
dmpas
2e41354ef0b892b7060c8aa8342a25d837b4f2fb
130
hpp
C++
cinemagraph_editor/opencv2.framework/Versions/A/Headers/core/base.hpp
GeonHyeongKim/cinemagraph_editor
20639c63a5a3cf55267fb5f68f56a74da5820652
[ "MIT" ]
null
null
null
cinemagraph_editor/opencv2.framework/Versions/A/Headers/core/base.hpp
GeonHyeongKim/cinemagraph_editor
20639c63a5a3cf55267fb5f68f56a74da5820652
[ "MIT" ]
null
null
null
cinemagraph_editor/opencv2.framework/Versions/A/Headers/core/base.hpp
GeonHyeongKim/cinemagraph_editor
20639c63a5a3cf55267fb5f68f56a74da5820652
[ "MIT" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:bb04bec725a144a389cb9e9109385e3d4e78b260c95a9d3196603a4ce28457ab size 26499
32.5
75
0.884615
GeonHyeongKim
2e48e9bbb8a00ab2769fdb376785d8e647aa0fc4
496
cpp
C++
code/engine/input.cpp
ugozapad/g-ray-engine
6a28c26541a6f4d50b0ca666375ab45f815c9299
[ "BSD-2-Clause" ]
1
2021-11-18T15:13:30.000Z
2021-11-18T15:13:30.000Z
code/engine/input.cpp
ugozapad/g-ray-engine
6a28c26541a6f4d50b0ca666375ab45f815c9299
[ "BSD-2-Clause" ]
null
null
null
code/engine/input.cpp
ugozapad/g-ray-engine
6a28c26541a6f4d50b0ca666375ab45f815c9299
[ "BSD-2-Clause" ]
null
null
null
#include "stdafx.h" #include "input.h" Input Input::ms_Singleton; Input* Input::Instance() { return &ms_Singleton; } void Input::KeyAction(uint32_t keyid, bool state) { if (keyid >= m_kMaxmimumKeys) return; m_Keys[keyid] = state; } void Input::MousePosAction(float x, float y) { m_MousePos.x = x; m_MousePos.y = y; } bool Input::GetKey(uint32_t keyid) { if (keyid >= m_kMaxmimumKeys) return false; return m_Keys[keyid]; } void Input::LockMouse() { } void Input::UnlockMouse() { }
13.052632
49
0.693548
ugozapad
2e491c2d707e27e7a1f347b14cbea8e2f59cb88c
3,342
cpp
C++
backends/dpdk/printUtils.cpp
st22nestrel/p4c
5285887bd4f6fcf6fd40b27e58291f647583f3b1
[ "Apache-2.0" ]
null
null
null
backends/dpdk/printUtils.cpp
st22nestrel/p4c
5285887bd4f6fcf6fd40b27e58291f647583f3b1
[ "Apache-2.0" ]
5
2022-02-11T09:23:13.000Z
2022-03-29T12:03:35.000Z
backends/dpdk/printUtils.cpp
st22nestrel/p4c
5285887bd4f6fcf6fd40b27e58291f647583f3b1
[ "Apache-2.0" ]
null
null
null
/* Copyright 2021 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "printUtils.h" namespace DPDK { bool ConvertToString::preorder(const IR::Expression *e) { BUG("%1% not implemented", e); return false; } bool ConvertToString::preorder(const IR::Type *t) { BUG("Not implemented type %1%", t->node_type_name()); return false; } bool ConvertToString::preorder(const IR::PropertyValue *p) { BUG("Not implemented property value %1%", p->node_type_name()); return false; } bool ConvertToString::preorder(const IR::Constant *e) { out << "0x" << std::hex << e->value; return false; } bool ConvertToString::preorder(const IR::BoolLiteral *e) { out << e->value; return false; } bool ConvertToString::preorder(const IR::Member *e){ out << toStr(e->expr) << "." << e->member.toString(); return false; } bool ConvertToString::preorder(const IR::PathExpression *e) { out << e->path->name; return false; } bool ConvertToString::preorder(const IR::TypeNameExpression *e) { if (auto tn = e->typeName->to<IR::Type_Name>()) { out << tn->path->name; } else { BUG("%1%: unexpected typeNameExpression", e); } return false; } bool ConvertToString::preorder(const IR::MethodCallExpression *e) { out << ""; if (auto path = e->method->to<IR::PathExpression>()) { out << path->path->name.name; } else { ::error(ErrorType::ERR_INVALID, "%1% is not a PathExpression", e->toString()); } return false; } bool ConvertToString::preorder(const IR::Cast *e) { out << toStr(e->expr); return false; } bool ConvertToString::preorder(const IR::ArrayIndex *e) { if (auto cst = e->right->to<IR::Constant>()) { out << toStr(e->left) << "_" << cst->value; } else { ::error(ErrorType::ERR_INVALID, "%1% is not a constant", e->right); } return false; } bool ConvertToString::preorder(const IR::Type_Boolean * /*type*/) { out << "bool"; return false; } bool ConvertToString::preorder(const IR::Type_Bits *type) { out << "bit_" << type->width_bits(); return false; } bool ConvertToString::preorder(const IR::Type_Name *type) { out << type->path->name; return false; } bool ConvertToString::preorder(const IR::Type_Specialized *type) { out << type->baseType->path->name.name; return false; } bool ConvertToString::preorder(const IR::ExpressionValue *property) { out << toStr(property->expression); return false; } cstring toStr(const IR::Node *const n) { auto nodeToString = new ConvertToString; n->apply(*nodeToString); if (nodeToString->out.str() != "") { return nodeToString->out.str(); } else { std::cerr << n->node_type_name() << std::endl; BUG("not implemented type"); } } } // namespace DPDK
26.736
75
0.650509
st22nestrel
2e4a2b9f781e62b5ea931bc46f0f26c60195585e
7,956
cpp
C++
RenderSystems/GLES2/src/OgreGLES2Support.cpp
MrTypename/ogre-code
b755e3884aa3b3a5fb37b2b2a75a8e44e70bcd56
[ "MIT" ]
null
null
null
RenderSystems/GLES2/src/OgreGLES2Support.cpp
MrTypename/ogre-code
b755e3884aa3b3a5fb37b2b2a75a8e44e70bcd56
[ "MIT" ]
null
null
null
RenderSystems/GLES2/src/OgreGLES2Support.cpp
MrTypename/ogre-code
b755e3884aa3b3a5fb37b2b2a75a8e44e70bcd56
[ "MIT" ]
null
null
null
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2009 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining 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. ----------------------------------------------------------------------------- */ #include "OgreGLES2Support.h" #include "OgreLogManager.h" namespace Ogre { void GLES2Support::setConfigOption(const String &name, const String &value) { ConfigOptionMap::iterator it = mOptions.find(name); if (it == mOptions.end()) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Option named " + name + " does not exist.", "GLESSupport::setConfigOption"); } else { it->second.currentValue = value; } } ConfigOptionMap& GLES2Support::getConfigOptions(void) { return mOptions; } void GLES2Support::initialiseExtensions(void) { // Set version string const GLubyte* pcVer = glGetString(GL_VERSION); assert(pcVer && "Problems getting GL version string using glGetString"); String tmpStr = (const char*)pcVer; LogManager::getSingleton().logMessage("GL_VERSION = " + tmpStr); mVersion = tmpStr.substr(0, tmpStr.find(" ")); // Get vendor const GLubyte* pcVendor = glGetString(GL_VENDOR); tmpStr = (const char*)pcVendor; LogManager::getSingleton().logMessage("GL_VENDOR = " + tmpStr); mVendor = tmpStr.substr(0, tmpStr.find(" ")); // Get renderer const GLubyte* pcRenderer = glGetString(GL_RENDERER); tmpStr = (const char*)pcRenderer; LogManager::getSingleton().logMessage("GL_RENDERER = " + tmpStr); // Set extension list std::stringstream ext; String str; const GLubyte* pcExt = glGetString(GL_EXTENSIONS); LogManager::getSingleton().logMessage("GL_EXTENSIONS = " + String((const char*)pcExt)); assert(pcExt && "Problems getting GL extension string using glGetString"); ext << pcExt; while (ext >> str) { LogManager::getSingleton().logMessage("EXT:" + str); extensionList.insert(str); } // Get function pointers on platforms that doesn't have prototypes #ifndef GL_GLEXT_PROTOTYPES // define the GL types if they are not defined # ifndef PFNGLISRENDERBUFFEROES // GL_OES_Framebuffer_object typedef GLboolean (GL_APIENTRY *PFNGLISRENDERBUFFEROES)(GLuint renderbuffer); typedef void (GL_APIENTRY *PFNGLBINDRENDERBUFFEROES)(GLenum target, GLuint renderbuffer); typedef void (GL_APIENTRY *PFNGLDELETERENDERBUFFERSOES)(GLsizei n, const GLuint *renderbuffers); typedef void (GL_APIENTRY *PFNGLGENRENDERBUFFERSOES)(GLsizei n, GLuint *renderbuffers); typedef void (GL_APIENTRY *PFNGLRENDERBUFFERSTORAGEOES)(GLenum target, GLenum internalformat,GLsizei width, GLsizei height); typedef void (GL_APIENTRY *PFNGLGETRENDERBUFFERPARAMETERIVOES)(GLenum target, GLenum pname, GLint* params); typedef GLboolean (GL_APIENTRY *PFNGLISFRAMEBUFFEROES)(GLuint framebuffer); typedef void (GL_APIENTRY *PFNGLBINDFRAMEBUFFEROES)(GLenum target, GLuint framebuffer); typedef void (GL_APIENTRY *PFNGLDELETEFRAMEBUFFERSOES)(GLsizei n, const GLuint *framebuffers); typedef void (GL_APIENTRY *PFNGLGENFRAMEBUFFERSOES)(GLsizei n, GLuint *framebuffers); typedef GLenum (GL_APIENTRY *PFNGLCHECKFRAMEBUFFERSTATUSOES)(GLenum target); typedef void (GL_APIENTRY *PFNGLFRAMEBUFFERTEXTURE2DOES)(GLenum target, GLenum attachment,GLenum textarget, GLuint texture,GLint level); typedef void (GL_APIENTRY *PFNGLFRAMEBUFFERRENDERBUFFEROES)(GLenum target, GLenum attachment,GLenum renderbuffertarget, GLuint renderbuffer); typedef void (GL_APIENTRY *PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVOES)(GLenum target, GLenum attachment,GLenum pname, GLint *params); typedef void (GL_APIENTRY *PFNGLGENERATEMIPMAPOES)(GLenum target); typedef void (GL_APIENTRY *PFNGLBLENDEQUATIONOES)(GLenum mode); typedef void (GL_APIENTRY *PFNGLBLENDFUNCSEPARATEOES)(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); typedef void (GL_APIENTRY *PFNGLBLENDEQUATIONSEPARATEOES)(GLenum modeRGB, GLenum modeAlpha); typedef void* (GL_APIENTRY *PFNGLMAPBUFFEROES)(GLenum target, GLenum access); typedef GLboolean (GL_APIENTRY *PFNGLUNMAPBUFFEROES)(GLenum target); // GL_OES_point_size_array typedef void (GL_APIENTRY *PFNGLPOINTSIZEPOINTEROES)(GLenum type, GLsizei stride, const void *ptr ); # endif glIsRenderbufferOES = (PFNGLISRENDERBUFFEROES)getProcAddress("glIsRenderbufferOES"); glBindRenderbufferOES = (PFNGLBINDRENDERBUFFEROES)getProcAddress("glBindRenderbufferOES"); glDeleteRenderbuffersOES = (PFNGLDELETERENDERBUFFERSOES)getProcAddress("glDeleteRenderbuffersOES"); glGenRenderbuffersOES = (PFNGLGENRENDERBUFFERSOES)getProcAddress("glGenRenderbuffersOES"); glRenderbufferStorageOES = (PFNGLRENDERBUFFERSTORAGEOES)getProcAddress("glRenderbufferStorageOES"); glGetRenderbufferParameterivOES = (PFNGLGETRENDERBUFFERPARAMETERIVOES)getProcAddress("glGetRenderbufferParameterivOES"); glIsFramebufferOES = (PFNGLISFRAMEBUFFEROES)getProcAddress("glIsFramebufferOES"); glBindFramebufferOES = (PFNGLBINDFRAMEBUFFEROES)getProcAddress("glBindFramebufferOES"); glDeleteFramebuffersOES = (PFNGLDELETEFRAMEBUFFERSOES)getProcAddress("glDeleteFramebuffersOES"); glGenFramebuffersOES = (PFNGLGENFRAMEBUFFERSOES)getProcAddress("glGenFramebuffersOES"); glCheckFramebufferStatusOES = (PFNGLCHECKFRAMEBUFFERSTATUSOES)getProcAddress("glCheckFramebufferStatusOES"); glFramebufferRenderbufferOES = (PFNGLFRAMEBUFFERRENDERBUFFEROES)getProcAddress("glFramebufferRenderbufferOES"); glFramebufferTexture2DOES = (PFNGLFRAMEBUFFERTEXTURE2DOES)getProcAddress("glFramebufferTexture2DOES"); glGetFramebufferAttachmentParameterivOES = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVOES)getProcAddress("glGetFramebufferAttachmentParameterivOES"); glGenerateMipmapOES = (PFNGLGENERATEMIPMAPOES)getProcAddress("glGenerateMipmapOES"); glBlendEquationOES = (PFNGLBLENDEQUATIONOES)getProcAddress("glBlendEquationOES"); glBlendFuncSeparateOES = (PFNGLBLENDFUNCSEPARATEOES)getProcAddress("glBlendFuncSeparateOES"); glBlendEquationSeparateOES = (PFNGLBLENDEQUATIONSEPARATEOES)getProcAddress("glBlendEquationSeparateOES"); glMapBufferOES = (PFNGLMAPBUFFEROES)getProcAddress("glMapBufferOES"); glUnmapBufferOES = (PFNGLUNMAPBUFFEROES)getProcAddress("glUnmapBufferOES"); #endif } bool GLES2Support::checkExtension(const String& ext) const { if(extensionList.find(ext) == extensionList.end()) return false; return true; } }
49.111111
155
0.734917
MrTypename
2e4d2e09f38fe2cc1d1902a1c02eb7b9f4ce4204
1,534
hpp
C++
assembler/inc/symtable.hpp
miledevv/GNU-assembler-linker
98b3df7f0b920e86ff8ad76981ed45a1f4639f27
[ "MIT" ]
null
null
null
assembler/inc/symtable.hpp
miledevv/GNU-assembler-linker
98b3df7f0b920e86ff8ad76981ed45a1f4639f27
[ "MIT" ]
null
null
null
assembler/inc/symtable.hpp
miledevv/GNU-assembler-linker
98b3df7f0b920e86ff8ad76981ed45a1f4639f27
[ "MIT" ]
null
null
null
#ifndef _SYMTABLE_H #define _SYMTABLE_H #include <iostream> #include <string> #include <sstream> #include <list> using namespace std; #define UND -2 #define LOCAL 0 #define GLOBAL 1 #define IS_EQU 1 #define R_VN_PC16 0 #define R_VN_16 1 typedef struct { int id; string name; int value; short bind; // 0 - local , global - 1 int mysec; int size; bool is_section; bool is_equ; } symdata; typedef struct { int offset; string type; string value; } reldata; class SymbolTable { public: SymbolTable(); void add(string name, int value, short bind, int ndx, bool is_equ); static int get_id(); void st_print(stringstream &stream); string print_mysection(symdata& el); bool is_global(string name); bool is_equ(string name); int get_symValue(string symbol_name); int get_symId(string symbol_name); int get_sectionId(string symbol_name); //Vraca mysec - tj sekciju u kojoj je simbol definisan. string get_symName(int id); void set_size(string name, int size); bool symbol_exists(string name); void set_global(string name); private: static int st_ID; list<symdata> symt_entry; }; // ----------------------------- REL TABLE ----------------------------- class RelTable { public: RelTable(string name); void push_entry(int offset, string type, string value); void print_reltable(stringstream &stream); string get_name(); private: list<reldata> relt_entry; string name; }; #endif
19.417722
106
0.651239
miledevv
2e519b4b635eae79996faec251229134c54cba03
18,250
hpp
C++
machine_learning/vector_ops.hpp
icbdubey/C-Plus-Plus
d51947a9d5a96695ea52db4394db6518d777bddf
[ "MIT" ]
20,295
2016-07-17T06:29:04.000Z
2022-03-31T23:32:16.000Z
machine_learning/vector_ops.hpp
icbdubey/C-Plus-Plus
d51947a9d5a96695ea52db4394db6518d777bddf
[ "MIT" ]
1,399
2017-06-02T05:59:45.000Z
2022-03-31T00:55:00.000Z
machine_learning/vector_ops.hpp
icbdubey/C-Plus-Plus
d51947a9d5a96695ea52db4394db6518d777bddf
[ "MIT" ]
5,775
2016-10-14T08:10:18.000Z
2022-03-31T18:26:39.000Z
/** * @file vector_ops.hpp * @author [Deep Raval](https://github.com/imdeep2905) * * @brief Various functions for vectors associated with [NeuralNetwork (aka * Multilayer Perceptron)] * (https://en.wikipedia.org/wiki/Multilayer_perceptron). * */ #ifndef VECTOR_OPS_FOR_NN #define VECTOR_OPS_FOR_NN #include <algorithm> #include <chrono> #include <iostream> #include <random> #include <valarray> #include <vector> /** * @namespace machine_learning * @brief Machine Learning algorithms */ namespace machine_learning { /** * Overloaded operator "<<" to print 2D vector * @tparam T typename of the vector * @param out std::ostream to output * @param A 2D vector to be printed */ template <typename T> std::ostream &operator<<(std::ostream &out, std::vector<std::valarray<T>> const &A) { // Setting output precision to 4 in case of floating point numbers out.precision(4); for (const auto &a : A) { // For each row in A for (const auto &x : a) { // For each element in row std::cout << x << ' '; // print element } std::cout << std::endl; } return out; } /** * Overloaded operator "<<" to print a pair * @tparam T typename of the pair * @param out std::ostream to output * @param A Pair to be printed */ template <typename T> std::ostream &operator<<(std::ostream &out, const std::pair<T, T> &A) { // Setting output precision to 4 in case of floating point numbers out.precision(4); // printing pair in the form (p, q) std::cout << "(" << A.first << ", " << A.second << ")"; return out; } /** * Overloaded operator "<<" to print a 1D vector * @tparam T typename of the vector * @param out std::ostream to output * @param A 1D vector to be printed */ template <typename T> std::ostream &operator<<(std::ostream &out, const std::valarray<T> &A) { // Setting output precision to 4 in case of floating point numbers out.precision(4); for (const auto &a : A) { // For every element in the vector. std::cout << a << ' '; // Print element } std::cout << std::endl; return out; } /** * Function to insert element into 1D vector * @tparam T typename of the 1D vector and the element * @param A 1D vector in which element will to be inserted * @param ele element to be inserted * @return new resultant vector */ template <typename T> std::valarray<T> insert_element(const std::valarray<T> &A, const T &ele) { std::valarray<T> B; // New 1D vector to store resultant vector B.resize(A.size() + 1); // Resizing it accordingly for (size_t i = 0; i < A.size(); i++) { // For every element in A B[i] = A[i]; // Copy element in B } B[B.size() - 1] = ele; // Inserting new element in last position return B; // Return resultant vector } /** * Function to remove first element from 1D vector * @tparam T typename of the vector * @param A 1D vector from which first element will be removed * @return new resultant vector */ template <typename T> std::valarray<T> pop_front(const std::valarray<T> &A) { std::valarray<T> B; // New 1D vector to store resultant vector B.resize(A.size() - 1); // Resizing it accordingly for (size_t i = 1; i < A.size(); i++) { // // For every (except first) element in A B[i - 1] = A[i]; // Copy element in B with left shifted position } return B; // Return resultant vector } /** * Function to remove last element from 1D vector * @tparam T typename of the vector * @param A 1D vector from which last element will be removed * @return new resultant vector */ template <typename T> std::valarray<T> pop_back(const std::valarray<T> &A) { std::valarray<T> B; // New 1D vector to store resultant vector B.resize(A.size() - 1); // Resizing it accordingly for (size_t i = 0; i < A.size() - 1; i++) { // For every (except last) element in A B[i] = A[i]; // Copy element in B } return B; // Return resultant vector } /** * Function to equally shuffle two 3D vectors (used for shuffling training data) * @tparam T typename of the vector * @param A First 3D vector * @param B Second 3D vector */ template <typename T> void equal_shuffle(std::vector<std::vector<std::valarray<T>>> &A, std::vector<std::vector<std::valarray<T>>> &B) { // If two vectors have different sizes if (A.size() != B.size()) { std::cerr << "ERROR (" << __func__ << ") : "; std::cerr << "Can not equally shuffle two vectors with different sizes: "; std::cerr << A.size() << " and " << B.size() << std::endl; std::exit(EXIT_FAILURE); } for (size_t i = 0; i < A.size(); i++) { // For every element in A and B // Genrating random index < size of A and B std::srand(std::chrono::system_clock::now().time_since_epoch().count()); size_t random_index = std::rand() % A.size(); // Swap elements in both A and B with same random index std::swap(A[i], A[random_index]); std::swap(B[i], B[random_index]); } return; } /** * Function to initialize given 2D vector using uniform random initialization * @tparam T typename of the vector * @param A 2D vector to be initialized * @param shape required shape * @param low lower limit on value * @param high upper limit on value */ template <typename T> void uniform_random_initialization(std::vector<std::valarray<T>> &A, const std::pair<size_t, size_t> &shape, const T &low, const T &high) { A.clear(); // Making A empty // Uniform distribution in range [low, high] std::default_random_engine generator( std::chrono::system_clock::now().time_since_epoch().count()); std::uniform_real_distribution<T> distribution(low, high); for (size_t i = 0; i < shape.first; i++) { // For every row std::valarray<T> row; // Making empty row which will be inserted in vector row.resize(shape.second); for (auto &r : row) { // For every element in row r = distribution(generator); // copy random number } A.push_back(row); // Insert new row in vector } return; } /** * Function to Intialize 2D vector as unit matrix * @tparam T typename of the vector * @param A 2D vector to be initialized * @param shape required shape */ template <typename T> void unit_matrix_initialization(std::vector<std::valarray<T>> &A, const std::pair<size_t, size_t> &shape) { A.clear(); // Making A empty for (size_t i = 0; i < shape.first; i++) { std::valarray<T> row; // Making empty row which will be inserted in vector row.resize(shape.second); row[i] = T(1); // Insert 1 at ith position A.push_back(row); // Insert new row in vector } return; } /** * Function to Intialize 2D vector as zeroes * @tparam T typename of the vector * @param A 2D vector to be initialized * @param shape required shape */ template <typename T> void zeroes_initialization(std::vector<std::valarray<T>> &A, const std::pair<size_t, size_t> &shape) { A.clear(); // Making A empty for (size_t i = 0; i < shape.first; i++) { std::valarray<T> row; // Making empty row which will be inserted in vector row.resize(shape.second); // By default all elements are zero A.push_back(row); // Insert new row in vector } return; } /** * Function to get sum of all elements in 2D vector * @tparam T typename of the vector * @param A 2D vector for which sum is required * @return returns sum of all elements of 2D vector */ template <typename T> T sum(const std::vector<std::valarray<T>> &A) { T cur_sum = 0; // Initially sum is zero for (const auto &a : A) { // For every row in A cur_sum += a.sum(); // Add sum of that row to current sum } return cur_sum; // Return sum } /** * Function to get shape of given 2D vector * @tparam T typename of the vector * @param A 2D vector for which shape is required * @return shape as pair */ template <typename T> std::pair<size_t, size_t> get_shape(const std::vector<std::valarray<T>> &A) { const size_t sub_size = (*A.begin()).size(); for (const auto &a : A) { // If supplied vector don't have same shape in all rows if (a.size() != sub_size) { std::cerr << "ERROR (" << __func__ << ") : "; std::cerr << "Supplied vector is not 2D Matrix" << std::endl; std::exit(EXIT_FAILURE); } } return std::make_pair(A.size(), sub_size); // Return shape as pair } /** * Function to scale given 3D vector using min-max scaler * @tparam T typename of the vector * @param A 3D vector which will be scaled * @param low new minimum value * @param high new maximum value * @return new scaled 3D vector */ template <typename T> std::vector<std::vector<std::valarray<T>>> minmax_scaler( const std::vector<std::vector<std::valarray<T>>> &A, const T &low, const T &high) { std::vector<std::vector<std::valarray<T>>> B = A; // Copying into new vector B const auto shape = get_shape(B[0]); // Storing shape of B's every element // As this function is used for scaling training data vector should be of // shape (1, X) if (shape.first != 1) { std::cerr << "ERROR (" << __func__ << ") : "; std::cerr << "Supplied vector is not supported for minmax scaling, shape: "; std::cerr << shape << std::endl; std::exit(EXIT_FAILURE); } for (size_t i = 0; i < shape.second; i++) { T min = B[0][0][i], max = B[0][0][i]; for (size_t j = 0; j < B.size(); j++) { // Updating minimum and maximum values min = std::min(min, B[j][0][i]); max = std::max(max, B[j][0][i]); } for (size_t j = 0; j < B.size(); j++) { // Applying min-max scaler formula B[j][0][i] = ((B[j][0][i] - min) / (max - min)) * (high - low) + low; } } return B; // Return new resultant 3D vector } /** * Function to get index of maximum element in 2D vector * @tparam T typename of the vector * @param A 2D vector for which maximum index is required * @return index of maximum element */ template <typename T> size_t argmax(const std::vector<std::valarray<T>> &A) { const auto shape = get_shape(A); // As this function is used on predicted (or target) vector, shape should be // (1, X) if (shape.first != 1) { std::cerr << "ERROR (" << __func__ << ") : "; std::cerr << "Supplied vector is ineligible for argmax" << std::endl; std::exit(EXIT_FAILURE); } // Return distance of max element from first element (i.e. index) return std::distance(std::begin(A[0]), std::max_element(std::begin(A[0]), std::end(A[0]))); } /** * Function which applys supplied function to every element of 2D vector * @tparam T typename of the vector * @param A 2D vector on which function will be applied * @param func Function to be applied * @return new resultant vector */ template <typename T> std::vector<std::valarray<T>> apply_function( const std::vector<std::valarray<T>> &A, T (*func)(const T &)) { std::vector<std::valarray<double>> B = A; // New vector to store resultant vector for (auto &b : B) { // For every row in vector b = b.apply(func); // Apply function to that row } return B; // Return new resultant 2D vector } /** * Overloaded operator "*" to multiply given 2D vector with scaler * @tparam T typename of both vector and the scaler * @param A 2D vector to which scaler will be multiplied * @param val Scaler value which will be multiplied * @return new resultant vector */ template <typename T> std::vector<std::valarray<T>> operator*(const std::vector<std::valarray<T>> &A, const T &val) { std::vector<std::valarray<double>> B = A; // New vector to store resultant vector for (auto &b : B) { // For every row in vector b = b * val; // Multiply row with scaler } return B; // Return new resultant 2D vector } /** * Overloaded operator "/" to divide given 2D vector with scaler * @tparam T typename of the vector and the scaler * @param A 2D vector to which scaler will be divided * @param val Scaler value which will be divided * @return new resultant vector */ template <typename T> std::vector<std::valarray<T>> operator/(const std::vector<std::valarray<T>> &A, const T &val) { std::vector<std::valarray<double>> B = A; // New vector to store resultant vector for (auto &b : B) { // For every row in vector b = b / val; // Divide row with scaler } return B; // Return new resultant 2D vector } /** * Function to get transpose of 2D vector * @tparam T typename of the vector * @param A 2D vector which will be transposed * @return new resultant vector */ template <typename T> std::vector<std::valarray<T>> transpose( const std::vector<std::valarray<T>> &A) { const auto shape = get_shape(A); // Current shape of vector std::vector<std::valarray<T>> B; // New vector to store result // Storing transpose values of A in B for (size_t j = 0; j < shape.second; j++) { std::valarray<T> row; row.resize(shape.first); for (size_t i = 0; i < shape.first; i++) { row[i] = A[i][j]; } B.push_back(row); } return B; // Return new resultant 2D vector } /** * Overloaded operator "+" to add two 2D vectors * @tparam T typename of the vector * @param A First 2D vector * @param B Second 2D vector * @return new resultant vector */ template <typename T> std::vector<std::valarray<T>> operator+( const std::vector<std::valarray<T>> &A, const std::vector<std::valarray<T>> &B) { const auto shape_a = get_shape(A); const auto shape_b = get_shape(B); // If vectors don't have equal shape if (shape_a.first != shape_b.first || shape_a.second != shape_b.second) { std::cerr << "ERROR (" << __func__ << ") : "; std::cerr << "Supplied vectors have different shapes "; std::cerr << shape_a << " and " << shape_b << std::endl; std::exit(EXIT_FAILURE); } std::vector<std::valarray<T>> C; for (size_t i = 0; i < A.size(); i++) { // For every row C.push_back(A[i] + B[i]); // Elementwise addition } return C; // Return new resultant 2D vector } /** * Overloaded operator "-" to add subtract 2D vectors * @tparam T typename of the vector * @param A First 2D vector * @param B Second 2D vector * @return new resultant vector */ template <typename T> std::vector<std::valarray<T>> operator-( const std::vector<std::valarray<T>> &A, const std::vector<std::valarray<T>> &B) { const auto shape_a = get_shape(A); const auto shape_b = get_shape(B); // If vectors don't have equal shape if (shape_a.first != shape_b.first || shape_a.second != shape_b.second) { std::cerr << "ERROR (" << __func__ << ") : "; std::cerr << "Supplied vectors have different shapes "; std::cerr << shape_a << " and " << shape_b << std::endl; std::exit(EXIT_FAILURE); } std::vector<std::valarray<T>> C; // Vector to store result for (size_t i = 0; i < A.size(); i++) { // For every row C.push_back(A[i] - B[i]); // Elementwise substraction } return C; // Return new resultant 2D vector } /** * Function to multiply two 2D vectors * @tparam T typename of the vector * @param A First 2D vector * @param B Second 2D vector * @return new resultant vector */ template <typename T> std::vector<std::valarray<T>> multiply(const std::vector<std::valarray<T>> &A, const std::vector<std::valarray<T>> &B) { const auto shape_a = get_shape(A); const auto shape_b = get_shape(B); // If vectors are not eligible for multiplication if (shape_a.second != shape_b.first) { std::cerr << "ERROR (" << __func__ << ") : "; std::cerr << "Vectors are not eligible for multiplication "; std::cerr << shape_a << " and " << shape_b << std::endl; std::exit(EXIT_FAILURE); } std::vector<std::valarray<T>> C; // Vector to store result // Normal matrix multiplication for (size_t i = 0; i < shape_a.first; i++) { std::valarray<T> row; row.resize(shape_b.second); for (size_t j = 0; j < shape_b.second; j++) { for (size_t k = 0; k < shape_a.second; k++) { row[j] += A[i][k] * B[k][j]; } } C.push_back(row); } return C; // Return new resultant 2D vector } /** * Function to get hadamard product of two 2D vectors * @tparam T typename of the vector * @param A First 2D vector * @param B Second 2D vector * @return new resultant vector */ template <typename T> std::vector<std::valarray<T>> hadamard_product( const std::vector<std::valarray<T>> &A, const std::vector<std::valarray<T>> &B) { const auto shape_a = get_shape(A); const auto shape_b = get_shape(B); // If vectors are not eligible for hadamard product if (shape_a.first != shape_b.first || shape_a.second != shape_b.second) { std::cerr << "ERROR (" << __func__ << ") : "; std::cerr << "Vectors have different shapes "; std::cerr << shape_a << " and " << shape_b << std::endl; std::exit(EXIT_FAILURE); } std::vector<std::valarray<T>> C; // Vector to store result for (size_t i = 0; i < A.size(); i++) { C.push_back(A[i] * B[i]); // Elementwise multiplication } return C; // Return new resultant 2D vector } } // namespace machine_learning #endif
35.436893
80
0.599068
icbdubey
2e54bdaebcea8214fdac807bd1f2f72d9d4c377a
5,705
cpp
C++
tests/cthread/test_cthread_sel_bit.cpp
rseac/systemc-compiler
ad1c68054467ed8db1c4e9b8f63eda092945d56d
[ "Apache-2.0" ]
null
null
null
tests/cthread/test_cthread_sel_bit.cpp
rseac/systemc-compiler
ad1c68054467ed8db1c4e9b8f63eda092945d56d
[ "Apache-2.0" ]
null
null
null
tests/cthread/test_cthread_sel_bit.cpp
rseac/systemc-compiler
ad1c68054467ed8db1c4e9b8f63eda092945d56d
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** * Copyright (c) 2020, Intel Corporation. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception. * *****************************************************************************/ #include "sct_assert.h" #include <systemc.h> // Bit access of SC type in LHS and RHS class top : sc_module { public: sc_in_clk clk; sc_signal<bool> arstn{"arstn", 1}; sc_signal<int> in{"in"}; sc_signal<bool> in2{"in2"}; sc_signal<int> out{"out"}; sc_uint<3> a; sc_uint<4> b; sc_uint<5> c; sc_uint<6> d; sc_uint<7> e; sc_signal<sc_uint<4>> s; sc_signal<bool> sb; SC_HAS_PROCESS(top); top(sc_module_name) { SC_CTHREAD(bit_select_use_def, clk.pos()); async_reset_signal_is(arstn, false); SC_CTHREAD(bit_select_use_def, clk.pos()); async_reset_signal_is(arstn, false); SC_CTHREAD(bit_select_lhs1, clk.pos()); async_reset_signal_is(arstn, false); SC_CTHREAD(bit_select_lhs1a, clk.pos()); async_reset_signal_is(arstn, false); SC_CTHREAD(bit_select_lhs2, clk.pos()); async_reset_signal_is(arstn, false); SC_CTHREAD(bit_select_lhs3, clk.pos()); async_reset_signal_is(arstn, false); SC_CTHREAD(bit_select_lhs4, clk.pos()); async_reset_signal_is(arstn, false); SC_CTHREAD(bit_select_lhs4a, clk.pos()); async_reset_signal_is(arstn, false); SC_CTHREAD(bit_select_logic, clk.pos()); async_reset_signal_is(arstn, false); SC_CTHREAD(bit_select_comp_logic, clk.pos()); async_reset_signal_is(arstn, false); SC_CTHREAD(bit_select_lhs_misc, clk.pos()); async_reset_signal_is(arstn, false); } // Write some bits does not lead to defined, values is unknown void bit_select_use_def() { sc_uint<5> z; wait(); while (true) { z[1] = 1; sct_assert_defined(z, false); sct_assert_unknown(z); wait(); } } // @bit() in LHS with other read/write void bit_select_lhs1() { out = 0; sc_uint<3> x = 0; a = 3; wait(); while (true) { x.bit(1) = 1; // Extra register for @x a[2] = x[1]; out.write(x[1] + a); wait(); } } // @bit() in LHS with other read/write void bit_select_lhs1a() { out = 0; sc_uint<3> x; wait(); while (true) { x[0] = 1; x[1] = 0; x[2] = x[1] != in2; out = (x[2] == in2) ? x.bit(1) + 1 : x[0]*2; wait(); } } // No write to @b except via @bit() void bit_select_lhs2() { out = 0; wait(); while (true) { b.bit(2) = 1; out = b; wait(); } } // No read from @c except via @bit() void bit_select_lhs3() { c = 0; wait(); while (true) { c = 3; c.bit(2) = 1; wait(); } } // No read/write to @d except via @bit() void bit_select_lhs4() { wait(); while (true) { d.bit(0) = 1; wait(); } } // No read/write to @d except via @bit() void bit_select_lhs4a() { out = 1; wait(); while (true) { out = e.bit(2); wait(); } } // @bit() used in logic expression void bit_select_logic() { int j = s.read(); sc_uint<7> x = 0; wait(); while (true) { int k = 0; x.bit(j) = 1; if (x[j]) k = 1; if (x.bit(j+1)) k = 2; if (x[1] || j == 1) { if (x[j] && j == 2) { k = 3; } k = 4; } bool b = x[1] || x[2] && x[3] || !x[4]; b = x[1] || true && b && !(false || x[5] || x[6]); wait(); } } // @bit() used in complex logic expression with &&/|| void bit_select_comp_logic() { int j = s.read(); sc_uint<3> x = 0; x[1] = sb.read(); wait(); while (true) { int k = 0; if (true && x[1]) k = 1; if (true || x[2]) k = 2; if (false && x[3]) k = 3; if (false || x[4]) k = 4; if (false || true && x[5] || false) k = 5; if (false || true && x[6] || true) k = 6; bool b = true && x[1]; b = true || x[2]; b = false && x[3]; b = false || x[4]; b = true && false || x[5]; wait(); } } // Various usages of bit() void bit_select_lhs_misc() { sc_uint<3> x = 0; wait(); while (true) { x = in.read(); if (x.bit(1)) { x.bit(2) = x.bit(0); } for (int i = 0; i < 3; i++) { x.bit(i) = i % 2; } wait(); } } }; int sc_main(int argc, char *argv[]) { sc_clock clk{"clk", 10, SC_NS}; top top_inst{"top_inst"}; top_inst.clk(clk); sc_start(100, SC_NS); return 0; }
23.004032
79
0.408063
rseac
2e5515112fa86ff46a1d3b8a190d567f110fbc29
3,415
cpp
C++
image/shifted_interp2_mex.cpp
ojwoodford/ojwul
fe8b45ee0c74ecdff2b6f832cde1b9c31f30e022
[ "BSD-2-Clause" ]
8
2017-03-13T01:20:50.000Z
2020-09-08T12:34:28.000Z
image/shifted_interp2_mex.cpp
ojwoodford/ojwul
fe8b45ee0c74ecdff2b6f832cde1b9c31f30e022
[ "BSD-2-Clause" ]
null
null
null
image/shifted_interp2_mex.cpp
ojwoodford/ojwul
fe8b45ee0c74ecdff2b6f832cde1b9c31f30e022
[ "BSD-2-Clause" ]
1
2017-03-13T01:20:51.000Z
2017-03-13T01:20:51.000Z
#include <mex.h> #include <math.h> #ifdef _OPENMP #include <omp.h> #endif #include <stdint.h> #include "interp2_methods.hpp" #include "../utils/private/class_handle.hpp" typedef IM_SHIFT<uint8_t, double, double> shiftIm_t; #if _MATLAB_ < 805 // R2015a extern "C" mxArray *mxCreateUninitNumericArray(mwSize ndim, const size_t *dims, mxClassID classid, mxComplexity ComplexFlag); #endif void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { // Check number of arguments if (nrhs < 1 || nrhs > 4) mexErrMsgTxt("Unexpected number of input arguments."); // Destructor if (nrhs == 1) { // Destroy the C++ object destroyObject<shiftIm_t>(prhs[0]); if (nlhs != 0) mexWarnMsgTxt("Unexpected number of output arguments."); return; } if (nlhs != 1) mexErrMsgTxt("Unexpected number of output arguments."); // Constructor if (nrhs == 2) { // Get the image matrix if (mxGetClassID(prhs[0]) != mxUINT8_CLASS) mexErrMsgTxt("im must be a uint8 array."); const uint8_t *im = (const uint8_t *)mxGetData(prhs[0]); // Get the number of channels int ndims = mxGetNumberOfDimensions(prhs[0]); const mwSize* dims = mxGetDimensions(prhs[0]); int nchannels = 1; for (int i = 2; i < ndims; ++i) nchannels *= dims[i]; // Get the value for oobv if (mxGetNumberOfElements(prhs[1]) != 1 || !mxIsDouble(prhs[1])) mexErrMsgTxt("oobv must be a scalar double."); double oobv = mxGetScalar(prhs[1]); // Create a new instance of the interpolator shiftIm_t *instance = new shiftIm_t(im, oobv, dims[0], dims[1], nchannels); // Return a handle to the class plhs[0] = convertPtr2Mat<shiftIm_t>(instance); return; } // Get the class instance pointer from the first input shiftIm_t *instance = convertMat2Ptr<shiftIm_t>(prhs[0]); // Check argument types are valid int num_points = mxGetNumberOfElements(prhs[1]); if (!mxIsDouble(prhs[1]) || !mxIsDouble(prhs[2]) || num_points != mxGetNumberOfElements(prhs[2]) || mxIsComplex(prhs[1]) || mxIsComplex(prhs[2])) mexErrMsgTxt("X and Y must be real double arrays of the same size"); // Get the value for oobv if (nrhs > 3) { if (mxGetNumberOfElements(prhs[3]) != 1 || !mxIsDouble(prhs[3])) mexErrMsgTxt("oobv must be a scalar double."); instance->SetOOBV(mxGetScalar(prhs[3])); } // Get pointers to the coordinate arrays const double *X = (const double *)mxGetData(prhs[1]); const double *Y = (const double *)mxGetData(prhs[2]); // Get output dimensions size_t out_dims[3]; out_dims[0] = mxGetM(prhs[1]); out_dims[1] = mxGetN(prhs[1]); out_dims[2] = instance->Channels(); // Create the output array plhs[0] = mxCreateUninitNumericArray(3, out_dims, mxDOUBLE_CLASS, mxREAL); double *out = (double *)mxGetData(plhs[0]); // For each of the interpolation points int i; #pragma omp parallel for if (num_points > 1000) num_threads(2) default(shared) private(i) for (i = 0; i < num_points; ++i) instance->lookup(&out[i], Y[i]-1.0, X[i]-1.0, num_points); // Do the interpolation return; }
35.947368
147
0.610835
ojwoodford
2e64db339c81803ee0fa08e3ac751b3266b9fe97
8,945
cpp
C++
OpenGLTraining/src/1.Start/CoordinateSystemDepth.cpp
NewBediver/OpenGLTraining
caf38b9601544e3145b9d2995d9bd28558bf3d11
[ "Apache-2.0" ]
null
null
null
OpenGLTraining/src/1.Start/CoordinateSystemDepth.cpp
NewBediver/OpenGLTraining
caf38b9601544e3145b9d2995d9bd28558bf3d11
[ "Apache-2.0" ]
null
null
null
OpenGLTraining/src/1.Start/CoordinateSystemDepth.cpp
NewBediver/OpenGLTraining
caf38b9601544e3145b9d2995d9bd28558bf3d11
[ "Apache-2.0" ]
null
null
null
#include <glad/glad.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <stb/stb_image.h> #include "Shader/Shader.h" #include <iostream> // Callback for resizing void framebufferSizeCallback(GLFWwindow* window, int width, int height); // Input processing void processInput(GLFWwindow* window); int main() { // Initialize OpenGL and configure it glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Create GLFWwindow and configure context GLFWwindow* window = glfwCreateWindow(800, 600, "LearnOpenGL", nullptr, nullptr); if (window == nullptr) { std::cout << "Failed to create OpenGL window!" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); // Initialize GLAD if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD!" << std::endl; return -1; } // Get the maximum number of 4 component vertex attributes int nrAttributes; glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &nrAttributes); std::cout << "Maximum nr of vertex attributes supported: " << nrAttributes << std::endl; // Configure viewport glViewport(0, 0, 800, 600); // Setup resize callback for window glfwSetFramebufferSizeCallback(window, framebufferSizeCallback); //====================================== float vertices[] = { // Position // Texture coords -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f }; // Create shader Shader ourShader("Shaders/6.1.CoordinateSystem.vs", "Shaders/6.1.CoordinateSystem.fs"); unsigned int VAO, VBO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // Set positions glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(0)); glEnableVertexAttribArray(0); // Set texture coords glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(3 * sizeof(float))); glEnableVertexAttribArray(1); // Generate texture object unsigned int texture1; glGenTextures(1, &texture1); // Bind texture glBindTexture(GL_TEXTURE_2D, texture1); // set the texture wrapping/filtering options (on currently bound texture) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Say stb to flip texture vertically stbi_set_flip_vertically_on_load(true); // Get texture image data int width, height, nrChannels; unsigned char* data = stbi_load("Textures/container.jpg", &width, &height, &nrChannels, 0); if (data) { // Generate texture and create it's bitmap glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture1" << std::endl; } // Generate texture object unsigned int texture2; glGenTextures(1, &texture2); // Bind texture glBindTexture(GL_TEXTURE_2D, texture2); // set the texture wrapping/filtering options (on currently bound texture) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Get texture image data data = stbi_load("Textures/awesomeface.png", &width, &height, &nrChannels, 0); if (data) { // Generate texture and create it's bitmap glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture2" << std::endl; } // Free image data because we have already set it to our texture stbi_image_free(data); // Set texture units to its uniforms ourShader.Use(); ourShader.SetInt("texture1", 0); ourShader.SetInt("texture2", 1); // Transformation matrices ---------------------------------------------------------------- // (Model matrix) Rotate model to -55 degrees by X axis /*glm::mat4 model = glm::rotate(glm::mat4(1.0f), glm::radians(-55.0f), glm::vec3(1.0f, 0.0f, 0.0f)); // (View matrix) Move the scene in depth of the screen glm::mat4 view = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, -3.0f)); // (Projection matrix) Define perspective projection matrix glm::mat4 projection = glm::perspective(glm::radians(45.0f), 800.0f / 600.0f, 0.1f, 100.0f);*/ // ---------------------------------------------------------------------------------------- glm::vec3 cubePositions[] = { glm::vec3( 0.0f, 0.0f, 0.0f), glm::vec3( 2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3( 2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3( 1.3f, -2.0f, -2.5f), glm::vec3( 1.5f, 2.0f, -2.5f), glm::vec3( 1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f) }; //====================================== glEnable(GL_DEPTH_TEST); // Render loop while (!glfwWindowShouldClose(window)) { // Check input processInput(window); // State-setting function setup color glClearColor(0.2f, 0.3f, 0.3f, 1.0f); // State-using function uses current state to retrieve the color glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //======================================== // Bind textures on corresponding texture units glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture1); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture2); // create transformations glm::mat4 view = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, -5.0f)); glm::mat4 projection = glm::mat4(1.0f); projection = glm::perspective(glm::radians(45.0f), 800.0f / 600.0f, 0.1f, 100.0f); // Set the matrices to transform objects glUniformMatrix4fv(glGetUniformLocation(ourShader.GetID(), "view"), 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(glGetUniformLocation(ourShader.GetID(), "projection"), 1, GL_FALSE, glm::value_ptr(projection)); // render containers glBindVertexArray(VAO); for (int i = 0; i < 10; ++i) { glm::mat4 model = glm::translate(glm::mat4(1.0f), cubePositions[i]); float angle = 20.0f * (i + 1); model = glm::rotate(model, (i % 2 == 0 ? static_cast<float>(glfwGetTime()) : 1.0f) * glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); ourShader.SetMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 36); } ourShader.Use(); glBindVertexArray(VAO); glDrawArrays(GL_TRIANGLES, 0, 36); //========================================= // Swap buffers glfwSwapBuffers(window); // Check and call events glfwPollEvents(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); // Properly cleaning / deleting all the GLFW resources glfwTerminate(); return 0; } void framebufferSizeCallback(GLFWwindow* window, int width, int height) { glViewport(0, 0, width, height); } void processInput(GLFWwindow* window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) { glfwSetWindowShouldClose(window, true); } }
30.738832
138
0.633091
NewBediver
2e66057a57e98c17598d363186ff6c09c768c0b3
3,326
cpp
C++
src/types/Categories.cpp
Mostah/parallel-pymcda
d5f5bb0de95dec90b88be9d00a3860e52eed4003
[ "MIT" ]
2
2020-12-12T22:48:57.000Z
2021-02-24T09:37:40.000Z
src/types/Categories.cpp
Mostah/parallel-pymcda
d5f5bb0de95dec90b88be9d00a3860e52eed4003
[ "MIT" ]
5
2021-01-07T19:34:24.000Z
2021-03-17T13:52:22.000Z
src/types/Categories.cpp
Mostah/parallel-pymcda
d5f5bb0de95dec90b88be9d00a3860e52eed4003
[ "MIT" ]
3
2020-12-12T22:49:56.000Z
2021-09-08T05:26:38.000Z
#include "../../include/types/Categories.h" #include "../../include/utils.h" #include <iostream> #include <ostream> #include <string.h> #include <vector> Categories::Categories(int number_of_categories, std::string prefix) { for (int i = 0; i < number_of_categories; i++) { std::string id = prefix + std::to_string(i); Category tmp_cat = Category(id, i); categories_vector_.push_back(tmp_cat); } } Categories::Categories(std::vector<std::string> vect_category_ids) { for (int i = 0; i < vect_category_ids.size(); i++) { Category tmp_cat = Category(vect_category_ids[i], i); categories_vector_.push_back(tmp_cat); } } Categories::Categories(const Categories &categories) { for (int i = 0; i < categories.categories_vector_.size(); i++) { Category tmp_cat = categories.categories_vector_[i]; categories_vector_.push_back(tmp_cat); } } Category Categories::operator[](int index) { return categories_vector_[index]; } Category Categories::operator[](int index) const { return categories_vector_[index]; } int Categories::getNumberCategories() { return categories_vector_.size(); } Categories::~Categories() { // https://stackoverflow.com/questions/993590/should-i-delete-vectorstring std::vector<Category>().swap(categories_vector_); } std::vector<int> Categories::getRankCategories() { std::vector<int> rank_categories; for (int i = 0; i < categories_vector_.size(); i++) { rank_categories.push_back(categories_vector_[i].rank_); } return rank_categories; } void Categories::setRankCategories(std::vector<int> &set_ranks) { if (set_ranks.size() != set_ranks.size()) { throw std::invalid_argument( "RankCategories setter object is not the same size as Categories."); } for (int i = 0; i < set_ranks.size(); i++) { categories_vector_[i].rank_ = set_ranks[i]; } } void Categories::setRankCategories() { for (int i = 0; i < categories_vector_.size(); i++) { categories_vector_[i].rank_ = i; } } std::vector<std::string> Categories::getIdCategories() { std::vector<std::string> categories_ids; for (int i = 0; i < categories_vector_.size(); i++) { categories_ids.push_back(categories_vector_[i].category_id_); } return categories_ids; } void Categories::setIdCategories(std::string prefix) { for (int i = 0; i < categories_vector_.size(); i++) { categories_vector_[i].category_id_ = prefix + std::to_string(i); } } void Categories::setIdCategories(std::vector<std::string> &set_category_ids) { if (set_category_ids.size() != categories_vector_.size()) { throw std::invalid_argument( "IdCategories setter object is not the same size as Categories."); } for (int i = 0; i < set_category_ids.size(); i++) { categories_vector_[i].category_id_ = set_category_ids[i]; } } Category Categories::getCategoryOfRank(int rank) { for (Category cat : categories_vector_) { if (cat.rank_ == rank) { return cat; } } throw std::invalid_argument("Category not found."); } std::ostream &operator<<(std::ostream &out, const Categories &cats) { out << "Categories("; for (int i = 0; i < cats.categories_vector_.size(); i++) { if (i == cats.categories_vector_.size() - 1) { out << cats[i]; } else { out << cats[i] << ", "; } } out << ")"; return out; }
29.696429
80
0.678894
Mostah
2e678131155f7b22525a6341caec35ed9dd8edc9
2,310
cpp
C++
Svc/TlmChan/test/perf/TelemChanImplTester.cpp
AlperenCetin0/fprime
7e20febd34019c730da1358567e7a512592de4d8
[ "Apache-2.0" ]
9,182
2017-07-06T15:51:35.000Z
2022-03-30T11:20:33.000Z
Svc/TlmChan/test/perf/TelemChanImplTester.cpp
AlperenCetin0/fprime
7e20febd34019c730da1358567e7a512592de4d8
[ "Apache-2.0" ]
719
2017-07-14T17:56:01.000Z
2022-03-31T02:41:35.000Z
Svc/TlmChan/test/perf/TelemChanImplTester.cpp
AlperenCetin0/fprime
7e20febd34019c730da1358567e7a512592de4d8
[ "Apache-2.0" ]
1,216
2017-07-12T15:41:08.000Z
2022-03-31T21:44:37.000Z
/* * PrmDbImplTester.cpp * * Created on: Mar 18, 2015 * Author: tcanham */ #include <Svc/TlmChan/test/ut/TelemChanImplTester.hpp> #include <Fw/Com/FwComBuffer.hpp> #include <Fw/Com/FwComPacket.hpp> #include <Os/IntervalTimer.hpp> #include <cstdio> namespace Svc { TelemStoreComponentBaseFriend::TelemStoreComponentBaseFriend(Svc::TelemStoreComponentBase& inst) : m_baseInst(inst) { } Fw::QueuedComponentBase::MsgDispatchStatus TelemStoreComponentBaseFriend::doDispatch() { return this->m_baseInst.doDispatch(); } void TelemChanImplTester::init(NATIVE_INT_TYPE instance) { Svc::TelemStoreComponentTesterBase::init(); } void TelemChanImplTester::pktSend_handler(NATIVE_INT_TYPE portNum, Fw::ComBuffer &data) { } TelemChanImplTester::TelemChanImplTester(Svc::TelemChanImpl& inst) : Svc::TelemStoreComponentTesterBase("testerbase"),m_impl(inst), m_baseFriend(inst) { } TelemChanImplTester::~TelemChanImplTester() { } void TelemChanImplTester::doPerfTest(U32 iterations) { Os::IntervalTimer timer; Fw::TlmBuffer buff; Fw::TlmBuffer readBack; Fw::SerializeStatus stat; Fw::Time timeTag; U32 testVal = 10; U32 retestVal = 0; // prefill telemetry to force a linear search to the end for (U32 entry = 0; entry < TelemChanImpl::NUM_TLM_ENTRIES - 1; entry++) { Fw::TlmBuffer fakeBuff; this->tlmRecv_out(0,entry,timeTag,buff); } timer.start(); for (U32 iter = 0; iter < iterations; iter++) { // create telemetry item buff.resetSer(); stat = buff.serialize(testVal); this->tlmRecv_out(0,TelemChanImpl::NUM_TLM_ENTRIES - 1,timeTag,buff); // Read back value this->tlmGet_out(0,TelemChanImpl::NUM_TLM_ENTRIES - 1,timeTag,readBack); // deserialize value retestVal = 0; buff.deserialize(retestVal); if (retestVal != testVal) { printf("Mismatch: %d %d\n",testVal,retestVal); break; } } timer.stop(); printf("Write total: %d ave: %d\n",timer.getDiffUsec(),timer.getDiffUsec()/iterations); } } /* namespace SvcTest */
28.170732
156
0.628571
AlperenCetin0
2e687517f1bae373b295ae672fba6fb05fa50aeb
398
hpp
C++
include/lol/def/LcdsSummoner.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
1
2020-07-22T11:14:55.000Z
2020-07-22T11:14:55.000Z
include/lol/def/LcdsSummoner.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
null
null
null
include/lol/def/LcdsSummoner.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
4
2018-12-01T22:48:21.000Z
2020-07-22T11:14:56.000Z
#pragma once #include "../base_def.hpp" namespace lol { struct LcdsSummoner { uint64_t sumId; std::string name; }; inline void to_json(json& j, const LcdsSummoner& v) { j["sumId"] = v.sumId; j["name"] = v.name; } inline void from_json(const json& j, LcdsSummoner& v) { v.sumId = j.at("sumId").get<uint64_t>(); v.name = j.at("name").get<std::string>(); } }
24.875
57
0.595477
Maufeat
2e6dfda112f1d2c91261561e0c813d3e05d8dfb3
52
hpp
C++
src/boost_fusion_include_iterator_facade.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_fusion_include_iterator_facade.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_fusion_include_iterator_facade.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/fusion/include/iterator_facade.hpp>
26
51
0.826923
miathedev