text
stringlengths
5
1.04M
/** Copyright (C) Nattan, Inc - All Rights Reserved ** Unauthorized copying of this file, via any medium is strictly prohibited ** Proprietary and confidential ** Written by Kam Lu <yingshulu@gmail.com>, July 2019 **/ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdarg.h> #include <unistd.h> #include <string> #include "log/Logger.h" #include "log/Log.h" #include "sync/LockGuard.h" extern "C" { #include "deps/libcask/log.h" } namespace nattan { bool DevelopLog::kSwitchOn = false; static const unsigned int LOG_BUFFER_SIZE = 4096; Logger::Logger(const int logfd): fd(logfd){} Logger::Logger(const std::string& logfile): logFile(logfile) { fd = ::open(logFile.data(), O_WRONLY | O_CREAT | O_APPEND, 0666); } void Logger::setLevel(LOGGER_LEVEL level) { this->level = level; } void Logger::printf(const char* fmt, ...) { char buffer[LOG_BUFFER_SIZE] = {0}; int n = 0; va_list args; va_start(args, fmt); n = vsnprintf(buffer, LOG_BUFFER_SIZE, fmt, args); va_end(args); if (n > 0 && n < LOG_BUFFER_SIZE) { buffer[n] = '\n'; } LockGuard guard(lock); log_printf(fd, LOG_INFO, "%s", buffer); } void Logger::debug(const char* fmt, ...) { if (level < LOGGER_DEBUG) return; char buffer[LOG_BUFFER_SIZE] = {0}; int n = 0; va_list args; va_start(args, fmt); n = vsnprintf(buffer, LOG_BUFFER_SIZE, fmt, args); va_end(args); if (n > 0 && n < LOG_BUFFER_SIZE) { buffer[n] = '\n'; } LockGuard guard(lock); log_printf(fd, LOG_DEBUG, "%s", buffer); } void Logger::info(const char* fmt, ...) { if (level < LOGGER_INFO) return; char buffer[LOG_BUFFER_SIZE] = {0}; int n = 0; va_list args; va_start(args, fmt); n = vsnprintf(buffer, LOG_BUFFER_SIZE, fmt, args); va_end(args); if (n > 0 && n < LOG_BUFFER_SIZE) { buffer[n] = '\n'; } LockGuard guard(lock); log_printf(fd, LOG_INFO, "%s", buffer); } void Logger::error(const char* fmt, ...) { if (level < LOGGER_ERROR) return; char buffer[LOG_BUFFER_SIZE] = {0}; int n = 0; va_list args; va_start(args, fmt); n = vsnprintf(buffer, LOG_BUFFER_SIZE, fmt, args); va_end(args); if (n > 0 && n < LOG_BUFFER_SIZE) { buffer[n] = '\n'; } LockGuard guard(lock); log_printf(fd, LOG_ERROR, "%s", buffer); } Logger::~Logger() { ::fdatasync(fd); ::close(fd); } } // namespace nattan
// Assignment 4 Program 1 // Shashi Kant | 2021PGCACA050 #include <iostream> #include <climits> #define MAXSIZE 6 using namespace std; class CircularQueue { private: int q[MAXSIZE]; int front; int rear; int maxSize; public: CircularQueue() { front = -1; rear = -1; maxSize = MAXSIZE; } bool isEmpty() { return (front == -1); } bool isFull() { return ((rear + 1) % maxSize == front); } // Enter data into queue void enQueue(int data) { if (isFull()) { cout << "Queue overflow. Cannot add more elements." << endl; return; } // Circular increment rear = (rear + 1) % maxSize; q[rear] = data; cout << q[rear] << " had been added." << endl; if (front == -1) front = rear; } // Delete data from queue int deQueue() { if (isEmpty()) { cout << "Queue underflow. " << endl; return INT_MIN; } int data = q[front]; if (front == rear) front = rear = -1; else front = (front + 1) % maxSize; return data; } // Display the Queue void displayQueue() { if (isEmpty()) { cout << "Queue underflow. " << endl; return; } cout << "Displaying: " << endl; int i = front; while (i != rear) { cout << q[i] << " "; i = (i + 1) % maxSize; } cout << q[rear]; cout << endl; } }; int main() { CircularQueue *cq = new CircularQueue(); int n = 1; while (n) { // Menu cout << endl; cout << "Circular QUEUE OPERATIONS-" << endl; cout << "1. Enqueue" << endl; cout << "2. Dequeue" << endl; cout << "3. Display" << endl; cout << "4. Exit" << endl << endl; cout << "Enter your choice: " << endl; int choice; cin >> choice; int element, returnValue; switch (choice) { case 1: cout << "Enter element to insert: "; cin >> element; cq->enQueue(element); break; case 2: returnValue = cq->deQueue(); if (returnValue != INT_MIN) cout << "Element dequed: " << returnValue << endl; break; case 3: cq->displayQueue(); break; case 4: n = 0; break; default: cout << "Invalid input" << endl; } } }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2018 The SocialTraders developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/socialtraders-config.h" #endif #include "net.h" #include "addrman.h" #include "chainparams.h" #include "clientversion.h" #include "miner.h" #include "obfuscation.h" #include "primitives/transaction.h" #include "ui_interface.h" #include "wallet.h" #ifdef WIN32 #include <string.h> #else #include <fcntl.h> #endif #ifdef USE_UPNP #include <miniupnpc/miniupnpc.h> #include <miniupnpc/miniwget.h> #include <miniupnpc/upnpcommands.h> #include <miniupnpc/upnperrors.h> #endif #include <boost/filesystem.hpp> #include <boost/thread.hpp> // Dump addresses to peers.dat every 15 minutes (900s) #define DUMP_ADDRESSES_INTERVAL 900 #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL) #define MSG_NOSIGNAL 0 #endif // Fix for ancient MinGW versions, that don't have defined these in ws2tcpip.h. // Todo: Can be removed when our pull-tester is upgraded to a modern MinGW version. #ifdef WIN32 #ifndef PROTECTION_LEVEL_UNRESTRICTED #define PROTECTION_LEVEL_UNRESTRICTED 10 #endif #ifndef IPV6_PROTECTION_LEVEL #define IPV6_PROTECTION_LEVEL 23 #endif #endif using namespace boost; using namespace std; namespace { const int MAX_OUTBOUND_CONNECTIONS = 16; struct ListenSocket { SOCKET socket; bool whitelisted; ListenSocket(SOCKET socket, bool whitelisted) : socket(socket), whitelisted(whitelisted) {} }; } // // Global state variables // bool fDiscover = true; bool fListen = true; uint64_t nLocalServices = NODE_NETWORK; CCriticalSection cs_mapLocalHost; map<CNetAddr, LocalServiceInfo> mapLocalHost; static bool vfReachable[NET_MAX] = {}; static bool vfLimited[NET_MAX] = {}; static CNode* pnodeLocalHost = NULL; uint64_t nLocalHostNonce = 0; static std::vector<ListenSocket> vhListenSocket; CAddrMan addrman; int nMaxConnections = 125; bool fAddressesInitialized = false; vector<CNode*> vNodes; CCriticalSection cs_vNodes; map<CInv, CDataStream> mapRelay; deque<pair<int64_t, CInv> > vRelayExpiration; CCriticalSection cs_mapRelay; limitedmap<CInv, int64_t> mapAlreadyAskedFor(MAX_INV_SZ); static deque<string> vOneShots; CCriticalSection cs_vOneShots; set<CNetAddr> setservAddNodeAddresses; CCriticalSection cs_setservAddNodeAddresses; vector<std::string> vAddedNodes; CCriticalSection cs_vAddedNodes; NodeId nLastNodeId = 0; CCriticalSection cs_nLastNodeId; static CSemaphore* semOutbound = NULL; boost::condition_variable messageHandlerCondition; // Signals for message handling static CNodeSignals g_signals; CNodeSignals& GetNodeSignals() { return g_signals; } void AddOneShot(string strDest) { LOCK(cs_vOneShots); vOneShots.push_back(strDest); } unsigned short GetListenPort() { return (unsigned short)(GetArg("-port", Params().GetDefaultPort())); } // find 'best' local address for a particular peer bool GetLocal(CService& addr, const CNetAddr* paddrPeer) { if (!fListen) return false; int nBestScore = -1; int nBestReachability = -1; { LOCK(cs_mapLocalHost); for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++) { int nScore = (*it).second.nScore; int nReachability = (*it).first.GetReachabilityFrom(paddrPeer); if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) { addr = CService((*it).first, (*it).second.nPort); nBestReachability = nReachability; nBestScore = nScore; } } } return nBestScore >= 0; } // get best local address for a particular peer as a CAddress // Otherwise, return the unroutable 0.0.0.0 but filled in with // the normal parameters, since the IP may be changed to a useful // one by discovery. CAddress GetLocalAddress(const CNetAddr* paddrPeer) { CAddress ret(CService("0.0.0.0", GetListenPort()), 0); CService addr; if (GetLocal(addr, paddrPeer)) { ret = CAddress(addr); } ret.nServices = nLocalServices; ret.nTime = GetAdjustedTime(); return ret; } bool RecvLine(SOCKET hSocket, string& strLine) { strLine = ""; while (true) { char c; int nBytes = recv(hSocket, &c, 1, 0); if (nBytes > 0) { if (c == '\n') continue; if (c == '\r') return true; strLine += c; if (strLine.size() >= 9000) return true; } else if (nBytes <= 0) { boost::this_thread::interruption_point(); if (nBytes < 0) { int nErr = WSAGetLastError(); if (nErr == WSAEMSGSIZE) continue; if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS) { MilliSleep(10); continue; } } if (!strLine.empty()) return true; if (nBytes == 0) { // socket closed LogPrint("net", "socket closed\n"); return false; } else { // socket error int nErr = WSAGetLastError(); LogPrint("net", "recv failed: %s\n", NetworkErrorString(nErr)); return false; } } } } int GetnScore(const CService& addr) { LOCK(cs_mapLocalHost); if (mapLocalHost.count(addr) == LOCAL_NONE) return 0; return mapLocalHost[addr].nScore; } // Is our peer's addrLocal potentially useful as an external IP source? bool IsPeerAddrLocalGood(CNode* pnode) { return fDiscover && pnode->addr.IsRoutable() && pnode->addrLocal.IsRoutable() && !IsLimited(pnode->addrLocal.GetNetwork()); } // pushes our own address to a peer void AdvertizeLocal(CNode* pnode) { if (fListen && pnode->fSuccessfullyConnected) { CAddress addrLocal = GetLocalAddress(&pnode->addr); // If discovery is enabled, sometimes give our peer the address it // tells us that it sees us as in case it has a better idea of our // address than we do. if (IsPeerAddrLocalGood(pnode) && (!addrLocal.IsRoutable() || GetRand((GetnScore(addrLocal) > LOCAL_MANUAL) ? 8 : 2) == 0)) { addrLocal.SetIP(pnode->addrLocal); } if (addrLocal.IsRoutable()) { pnode->PushAddress(addrLocal); } } } void SetReachable(enum Network net, bool fFlag) { LOCK(cs_mapLocalHost); vfReachable[net] = fFlag; if (net == NET_IPV6 && fFlag) vfReachable[NET_IPV4] = true; } // learn a new local address bool AddLocal(const CService& addr, int nScore) { if (!addr.IsRoutable()) return false; if (!fDiscover && nScore < LOCAL_MANUAL) return false; if (IsLimited(addr)) return false; LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore); { LOCK(cs_mapLocalHost); bool fAlready = mapLocalHost.count(addr) > 0; LocalServiceInfo& info = mapLocalHost[addr]; if (!fAlready || nScore >= info.nScore) { info.nScore = nScore + (fAlready ? 1 : 0); info.nPort = addr.GetPort(); } SetReachable(addr.GetNetwork()); } return true; } bool AddLocal(const CNetAddr& addr, int nScore) { return AddLocal(CService(addr, GetListenPort()), nScore); } /** Make a particular network entirely off-limits (no automatic connects to it) */ void SetLimited(enum Network net, bool fLimited) { if (net == NET_UNROUTABLE) return; LOCK(cs_mapLocalHost); vfLimited[net] = fLimited; } bool IsLimited(enum Network net) { LOCK(cs_mapLocalHost); return vfLimited[net]; } bool IsLimited(const CNetAddr& addr) { return IsLimited(addr.GetNetwork()); } /** vote for a local address */ bool SeenLocal(const CService& addr) { { LOCK(cs_mapLocalHost); if (mapLocalHost.count(addr) == 0) return false; mapLocalHost[addr].nScore++; } return true; } /** check whether a given address is potentially local */ bool IsLocal(const CService& addr) { LOCK(cs_mapLocalHost); return mapLocalHost.count(addr) > 0; } /** check whether a given network is one we can probably connect to */ bool IsReachable(enum Network net) { LOCK(cs_mapLocalHost); return vfReachable[net] && !vfLimited[net]; } /** check whether a given address is in a network we can probably connect to */ bool IsReachable(const CNetAddr& addr) { enum Network net = addr.GetNetwork(); return IsReachable(net); } void AddressCurrentlyConnected(const CService& addr) { addrman.Connected(addr); } uint64_t CNode::nTotalBytesRecv = 0; uint64_t CNode::nTotalBytesSent = 0; CCriticalSection CNode::cs_totalBytesRecv; CCriticalSection CNode::cs_totalBytesSent; CNode* FindNode(const CNetAddr& ip) { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) if ((CNetAddr)pnode->addr == ip) return (pnode); return NULL; } CNode* FindNode(const std::string& addrName) { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) if (pnode->addrName == addrName) return (pnode); return NULL; } CNode* FindNode(const CService& addr) { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) { if (Params().NetworkID() == CBaseChainParams::REGTEST) { //if using regtest, just check the IP if ((CNetAddr)pnode->addr == (CNetAddr)addr) return (pnode); } else { if (pnode->addr == addr) return (pnode); } } return NULL; } CNode* ConnectNode(CAddress addrConnect, const char* pszDest, bool obfuScationMaster) { if (pszDest == NULL) { // we clean masternode connections in CMasternodeMan::ProcessMasternodeConnections() // so should be safe to skip this and connect to local Hot MN on CActiveMasternode::ManageStatus() if (IsLocal(addrConnect) && !obfuScationMaster) return NULL; // Look for an existing connection CNode* pnode = FindNode((CService)addrConnect); if (pnode) { pnode->fObfuScationMaster = obfuScationMaster; pnode->AddRef(); return pnode; } } /// debug print LogPrint("net", "trying connection %s lastseen=%.1fhrs\n", pszDest ? pszDest : addrConnect.ToString(), pszDest ? 0.0 : (double)(GetAdjustedTime() - addrConnect.nTime) / 3600.0); // Connect SOCKET hSocket; bool proxyConnectionFailed = false; if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, Params().GetDefaultPort(), nConnectTimeout, &proxyConnectionFailed) : ConnectSocket(addrConnect, hSocket, nConnectTimeout, &proxyConnectionFailed)) { if (!IsSelectableSocket(hSocket)) { LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n"); CloseSocket(hSocket); return NULL; } addrman.Attempt(addrConnect); // Add node CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false); pnode->AddRef(); { LOCK(cs_vNodes); vNodes.push_back(pnode); } pnode->nTimeConnected = GetTime(); if (obfuScationMaster) pnode->fObfuScationMaster = true; return pnode; } else if (!proxyConnectionFailed) { // If connecting to the node failed, and failure is not caused by a problem connecting to // the proxy, mark this as an attempt. addrman.Attempt(addrConnect); } return NULL; } void CNode::CloseSocketDisconnect() { fDisconnect = true; if (hSocket != INVALID_SOCKET) { LogPrint("net", "disconnecting peer=%d\n", id); CloseSocket(hSocket); } // in case this fails, we'll empty the recv buffer when the CNode is deleted TRY_LOCK(cs_vRecvMsg, lockRecv); if (lockRecv) vRecvMsg.clear(); } bool CNode::DisconnectOldProtocol(int nVersionRequired, string strLastCommand) { fDisconnect = false; if (nVersion < nVersionRequired) { LogPrintf("%s : peer=%d using obsolete version %i; disconnecting\n", __func__, id, nVersion); PushMessage("reject", strLastCommand, REJECT_OBSOLETE, strprintf("Version must be %d or greater", ActiveProtocol())); fDisconnect = true; } return fDisconnect; } void CNode::PushVersion() { int nBestHeight = g_signals.GetHeight().get_value_or(0); /// when NTP implemented, change to just nTime = GetAdjustedTime() int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime()); CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0", 0))); CAddress addrMe = GetLocalAddress(&addr); GetRandBytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce)); if (fLogIPs) LogPrint("net", "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), addrYou.ToString(), id); else LogPrint("net", "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), id); PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe, nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight, true); } std::map<CNetAddr, int64_t> CNode::setBanned; CCriticalSection CNode::cs_setBanned; void CNode::ClearBanned() { setBanned.clear(); } bool CNode::IsBanned(CNetAddr ip) { bool fResult = false; { LOCK(cs_setBanned); std::map<CNetAddr, int64_t>::iterator i = setBanned.find(ip); if (i != setBanned.end()) { int64_t t = (*i).second; if (GetTime() < t) fResult = true; } } return fResult; } bool CNode::Ban(const CNetAddr& addr) { int64_t banTime = GetTime() + GetArg("-bantime", 60 * 60 * 24); // Default 24-hour ban { LOCK(cs_setBanned); if (setBanned[addr] < banTime) setBanned[addr] = banTime; } return true; } std::vector<CSubNet> CNode::vWhitelistedRange; CCriticalSection CNode::cs_vWhitelistedRange; bool CNode::IsWhitelistedRange(const CNetAddr& addr) { LOCK(cs_vWhitelistedRange); BOOST_FOREACH (const CSubNet& subnet, vWhitelistedRange) { if (subnet.Match(addr)) return true; } return false; } void CNode::AddWhitelistedRange(const CSubNet& subnet) { LOCK(cs_vWhitelistedRange); vWhitelistedRange.push_back(subnet); } #undef X #define X(name) stats.name = name void CNode::copyStats(CNodeStats& stats) { stats.nodeid = this->GetId(); X(nServices); X(nLastSend); X(nLastRecv); X(nTimeConnected); X(addrName); X(nVersion); X(cleanSubVer); X(fInbound); X(nStartingHeight); X(nSendBytes); X(nRecvBytes); X(fWhitelisted); // It is common for nodes with good ping times to suddenly become lagged, // due to a new block arriving or other large transfer. // Merely reporting pingtime might fool the caller into thinking the node was still responsive, // since pingtime does not update until the ping is complete, which might take a while. // So, if a ping is taking an unusually long time in flight, // the caller can immediately detect that this is happening. int64_t nPingUsecWait = 0; if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) { nPingUsecWait = GetTimeMicros() - nPingUsecStart; } // Raw ping time is in microseconds, but show it to user as whole seconds (socialtraders users should be well used to small numbers with many decimal places by now :) stats.dPingTime = (((double)nPingUsecTime) / 1e6); stats.dPingWait = (((double)nPingUsecWait) / 1e6); // Leave string empty if addrLocal invalid (not filled in yet) stats.addrLocal = addrLocal.IsValid() ? addrLocal.ToString() : ""; } #undef X // requires LOCK(cs_vRecvMsg) bool CNode::ReceiveMsgBytes(const char* pch, unsigned int nBytes) { while (nBytes > 0) { // get current incomplete message, or create a new one if (vRecvMsg.empty() || vRecvMsg.back().complete()) vRecvMsg.push_back(CNetMessage(SER_NETWORK, nRecvVersion)); CNetMessage& msg = vRecvMsg.back(); // absorb network data int handled; if (!msg.in_data) handled = msg.readHeader(pch, nBytes); else handled = msg.readData(pch, nBytes); if (handled < 0) return false; if (msg.in_data && msg.hdr.nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH) { LogPrint("net", "Oversized message from peer=%i, disconnecting", GetId()); return false; } pch += handled; nBytes -= handled; if (msg.complete()) { msg.nTime = GetTimeMicros(); messageHandlerCondition.notify_one(); } } return true; } int CNetMessage::readHeader(const char* pch, unsigned int nBytes) { // copy data to temporary parsing buffer unsigned int nRemaining = 24 - nHdrPos; unsigned int nCopy = std::min(nRemaining, nBytes); memcpy(&hdrbuf[nHdrPos], pch, nCopy); nHdrPos += nCopy; // if header incomplete, exit if (nHdrPos < 24) return nCopy; // deserialize to CMessageHeader try { hdrbuf >> hdr; } catch (const std::exception&) { return -1; } // reject messages larger than MAX_SIZE if (hdr.nMessageSize > MAX_SIZE) return -1; // switch state to reading message data in_data = true; return nCopy; } int CNetMessage::readData(const char* pch, unsigned int nBytes) { unsigned int nRemaining = hdr.nMessageSize - nDataPos; unsigned int nCopy = std::min(nRemaining, nBytes); if (vRecv.size() < nDataPos + nCopy) { // Allocate up to 256 KiB ahead, but never more than the total message size. vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024)); } memcpy(&vRecv[nDataPos], pch, nCopy); nDataPos += nCopy; return nCopy; } // requires LOCK(cs_vSend) void SocketSendData(CNode* pnode) { std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin(); while (it != pnode->vSendMsg.end()) { const CSerializeData& data = *it; assert(data.size() > pnode->nSendOffset); int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT); if (nBytes > 0) { pnode->nLastSend = GetTime(); pnode->nSendBytes += nBytes; pnode->nSendOffset += nBytes; pnode->RecordBytesSent(nBytes); if (pnode->nSendOffset == data.size()) { pnode->nSendOffset = 0; pnode->nSendSize -= data.size(); it++; } else { // could not send full message; stop sending more break; } } else { if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { LogPrintf("socket send error %s\n", NetworkErrorString(nErr)); pnode->CloseSocketDisconnect(); } } // couldn't send anything at all break; } } if (it == pnode->vSendMsg.end()) { assert(pnode->nSendOffset == 0); assert(pnode->nSendSize == 0); } pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it); } static list<CNode*> vNodesDisconnected; void ThreadSocketHandler() { unsigned int nPrevNodeCount = 0; while (true) { // // Disconnect nodes // { LOCK(cs_vNodes); // Disconnect unused nodes vector<CNode*> vNodesCopy = vNodes; BOOST_FOREACH (CNode* pnode, vNodesCopy) { if (pnode->fDisconnect || (pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty())) { // remove from vNodes vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end()); // release outbound grant (if any) pnode->grantOutbound.Release(); // close socket and cleanup pnode->CloseSocketDisconnect(); // hold in disconnected pool until all refs are released if (pnode->fNetworkNode || pnode->fInbound) pnode->Release(); vNodesDisconnected.push_back(pnode); } } } { // Delete disconnected nodes list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected; BOOST_FOREACH (CNode* pnode, vNodesDisconnectedCopy) { // wait until threads are done using it if (pnode->GetRefCount() <= 0) { bool fDelete = false; { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { TRY_LOCK(pnode->cs_inventory, lockInv); if (lockInv) fDelete = true; } } } if (fDelete) { vNodesDisconnected.remove(pnode); delete pnode; } } } } if (vNodes.size() != nPrevNodeCount) { nPrevNodeCount = vNodes.size(); uiInterface.NotifyNumConnectionsChanged(nPrevNodeCount); } // // Find which sockets have data to receive // struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 50000; // frequency to poll pnode->vSend fd_set fdsetRecv; fd_set fdsetSend; fd_set fdsetError; FD_ZERO(&fdsetRecv); FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); SOCKET hSocketMax = 0; bool have_fds = false; BOOST_FOREACH (const ListenSocket& hListenSocket, vhListenSocket) { FD_SET(hListenSocket.socket, &fdsetRecv); hSocketMax = max(hSocketMax, hListenSocket.socket); have_fds = true; } { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) { if (pnode->hSocket == INVALID_SOCKET) continue; FD_SET(pnode->hSocket, &fdsetError); hSocketMax = max(hSocketMax, pnode->hSocket); have_fds = true; // Implement the following logic: // * If there is data to send, select() for sending data. As this only // happens when optimistic write failed, we choose to first drain the // write buffer in this case before receiving more. This avoids // needlessly queueing received data, if the remote peer is not themselves // receiving data. This means properly utilizing TCP flow control signalling. // * Otherwise, if there is no (complete) message in the receive buffer, // or there is space left in the buffer, select() for receiving data. // * (if neither of the above applies, there is certainly one message // in the receiver buffer ready to be processed). // Together, that means that at least one of the following is always possible, // so we don't deadlock: // * We send some data. // * We wait for data to be received (and disconnect after timeout). // * We process a message in the buffer (message handler thread). { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend && !pnode->vSendMsg.empty()) { FD_SET(pnode->hSocket, &fdsetSend); continue; } } { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv && (pnode->vRecvMsg.empty() || !pnode->vRecvMsg.front().complete() || pnode->GetTotalRecvSize() <= ReceiveFloodSize())) FD_SET(pnode->hSocket, &fdsetRecv); } } } int nSelect = select(have_fds ? hSocketMax + 1 : 0, &fdsetRecv, &fdsetSend, &fdsetError, &timeout); boost::this_thread::interruption_point(); if (nSelect == SOCKET_ERROR) { if (have_fds) { int nErr = WSAGetLastError(); LogPrintf("socket select error %s\n", NetworkErrorString(nErr)); for (unsigned int i = 0; i <= hSocketMax; i++) FD_SET(i, &fdsetRecv); } FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); MilliSleep(timeout.tv_usec / 1000); } // // Accept new connections // BOOST_FOREACH (const ListenSocket& hListenSocket, vhListenSocket) { if (hListenSocket.socket != INVALID_SOCKET && FD_ISSET(hListenSocket.socket, &fdsetRecv)) { struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); SOCKET hSocket = accept(hListenSocket.socket, (struct sockaddr*)&sockaddr, &len); CAddress addr; int nInbound = 0; if (hSocket != INVALID_SOCKET) if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr)) LogPrintf("Warning: Unknown socket family\n"); bool whitelisted = hListenSocket.whitelisted || CNode::IsWhitelistedRange(addr); { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) if (pnode->fInbound) nInbound++; } if (hSocket == INVALID_SOCKET) { int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK) LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr)); } else if (!IsSelectableSocket(hSocket)) { LogPrintf("connection from %s dropped: non-selectable socket\n", addr.ToString()); CloseSocket(hSocket); } else if (nInbound >= nMaxConnections - MAX_OUTBOUND_CONNECTIONS) { LogPrint("net", "connection from %s dropped (full)\n", addr.ToString()); CloseSocket(hSocket); } else if (CNode::IsBanned(addr) && !whitelisted) { LogPrintf("connection from %s dropped (banned)\n", addr.ToString()); CloseSocket(hSocket); } else { CNode* pnode = new CNode(hSocket, addr, "", true); pnode->AddRef(); pnode->fWhitelisted = whitelisted; { LOCK(cs_vNodes); vNodes.push_back(pnode); } } } } // // Service each socket // vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; BOOST_FOREACH (CNode* pnode, vNodesCopy) pnode->AddRef(); } BOOST_FOREACH (CNode* pnode, vNodesCopy) { boost::this_thread::interruption_point(); // // Receive // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError)) { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { { // typical socket buffer is 8K-64K char pchBuf[0x10000]; int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT); if (nBytes > 0) { if (!pnode->ReceiveMsgBytes(pchBuf, nBytes)) pnode->CloseSocketDisconnect(); pnode->nLastRecv = GetTime(); pnode->nRecvBytes += nBytes; pnode->RecordBytesRecv(nBytes); } else if (nBytes == 0) { // socket closed gracefully if (!pnode->fDisconnect) LogPrint("net", "socket closed\n"); pnode->CloseSocketDisconnect(); } else if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { if (!pnode->fDisconnect) LogPrintf("socket recv error %s\n", NetworkErrorString(nErr)); pnode->CloseSocketDisconnect(); } } } } } // // Send // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetSend)) { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) SocketSendData(pnode); } // // Inactivity checking // int64_t nTime = GetTime(); if (nTime - pnode->nTimeConnected > 60) { if (pnode->nLastRecv == 0 || pnode->nLastSend == 0) { LogPrint("net", "socket no message in first 60 seconds, %d %d from %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0, pnode->id); pnode->fDisconnect = true; } else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL) { LogPrintf("socket sending timeout: %is\n", nTime - pnode->nLastSend); pnode->fDisconnect = true; } else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90 * 60)) { LogPrintf("socket receive timeout: %is\n", nTime - pnode->nLastRecv); pnode->fDisconnect = true; } else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros()) { LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart)); pnode->fDisconnect = true; } } } { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodesCopy) pnode->Release(); } } } #ifdef USE_UPNP void ThreadMapPort() { std::string port = strprintf("%u", GetListenPort()); const char* multicastif = 0; const char* minissdpdpath = 0; struct UPNPDev* devlist = 0; char lanaddr[64]; #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0); #elif MINIUPNPC_API_VERSION < 14 /* miniupnpc 1.6 */ int error = 0; devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error); #else /* miniupnpc 1.9.20150730 */ int error = 0; devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, 2, &error); #endif struct UPNPUrls urls; struct IGDdatas data; int r; r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr)); if (r == 1) { if (fDiscover) { char externalIPAddress[40]; r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress); if (r != UPNPCOMMAND_SUCCESS) LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r); else { if (externalIPAddress[0]) { LogPrintf("UPnP: ExternalIPAddress = %s\n", externalIPAddress); AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP); } else LogPrintf("UPnP: GetExternalIPAddress failed.\n"); } } string strDesc = "socialtraders " + FormatFullVersion(); try { while (true) { #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0); #else /* miniupnpc 1.6 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0"); #endif if (r != UPNPCOMMAND_SUCCESS) LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n", port, port, lanaddr, r, strupnperror(r)); else LogPrintf("UPnP Port Mapping successful.\n"); ; MilliSleep(20 * 60 * 1000); // Refresh every 20 minutes } } catch (boost::thread_interrupted) { r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0); LogPrintf("UPNP_DeletePortMapping() returned : %d\n", r); freeUPNPDevlist(devlist); devlist = 0; FreeUPNPUrls(&urls); throw; } } else { LogPrintf("No valid UPnP IGDs found\n"); freeUPNPDevlist(devlist); devlist = 0; if (r != 0) FreeUPNPUrls(&urls); } } void MapPort(bool fUseUPnP) { static boost::thread* upnp_thread = NULL; if (fUseUPnP) { if (upnp_thread) { upnp_thread->interrupt(); upnp_thread->join(); delete upnp_thread; } upnp_thread = new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort)); } else if (upnp_thread) { upnp_thread->interrupt(); upnp_thread->join(); delete upnp_thread; upnp_thread = NULL; } } #else void MapPort(bool) { // Intentionally left blank. } #endif void ThreadDNSAddressSeed() { // goal: only query DNS seeds if address need is acute if ((addrman.size() > 0) && (!GetBoolArg("-forcednsseed", false))) { MilliSleep(11 * 1000); LOCK(cs_vNodes); if (vNodes.size() >= 2) { LogPrintf("P2P peers available. Skipped DNS seeding.\n"); return; } } const vector<CDNSSeedData>& vSeeds = Params().DNSSeeds(); int found = 0; LogPrintf("Loading addresses from DNS seeds (could take a while)\n"); BOOST_FOREACH (const CDNSSeedData& seed, vSeeds) { if (HaveNameProxy()) { AddOneShot(seed.host); } else { vector<CNetAddr> vIPs; vector<CAddress> vAdd; if (LookupHost(seed.host.c_str(), vIPs)) { BOOST_FOREACH (CNetAddr& ip, vIPs) { int nOneDay = 24 * 3600; CAddress addr = CAddress(CService(ip, Params().GetDefaultPort())); addr.nTime = GetTime() - 3 * nOneDay - GetRand(4 * nOneDay); // use a random age between 3 and 7 days old vAdd.push_back(addr); found++; } } addrman.Add(vAdd, CNetAddr(seed.name, true)); } } LogPrintf("%d addresses found from DNS seeds\n", found); } void DumpAddresses() { int64_t nStart = GetTimeMillis(); CAddrDB adb; adb.Write(addrman); LogPrint("net", "Flushed %d addresses to peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart); } void static ProcessOneShot() { string strDest; { LOCK(cs_vOneShots); if (vOneShots.empty()) return; strDest = vOneShots.front(); vOneShots.pop_front(); } CAddress addr; CSemaphoreGrant grant(*semOutbound, true); if (grant) { if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true)) AddOneShot(strDest); } } void ThreadOpenConnections() { // Connect to specific addresses if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { for (int64_t nLoop = 0;; nLoop++) { ProcessOneShot(); BOOST_FOREACH (string strAddr, mapMultiArgs["-connect"]) { CAddress addr; OpenNetworkConnection(addr, NULL, strAddr.c_str()); for (int i = 0; i < 10 && i < nLoop; i++) { MilliSleep(500); } } MilliSleep(500); } } // Initiate network connections int64_t nStart = GetTime(); while (true) { ProcessOneShot(); MilliSleep(500); CSemaphoreGrant grant(*semOutbound); boost::this_thread::interruption_point(); // Add seed nodes if DNS seeds are all down (an infrastructure attack?). if (addrman.size() == 0 && (GetTime() - nStart > 60)) { static bool done = false; if (!done) { LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n"); addrman.Add(Params().FixedSeeds(), CNetAddr("127.0.0.1")); done = true; } } // // Choose an address to connect to based on most recently seen // CAddress addrConnect; // Only connect out to one peer per network group (/16 for IPv4). // Do this here so we don't have to critsect vNodes inside mapAddresses critsect. int nOutbound = 0; set<vector<unsigned char> > setConnected; { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) { if (!pnode->fInbound) { setConnected.insert(pnode->addr.GetGroup()); nOutbound++; } } } int64_t nANow = GetAdjustedTime(); int nTries = 0; while (true) { CAddress addr = addrman.Select(); // if we selected an invalid address, restart if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr)) break; // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman, // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates // already-connected network ranges, ...) before trying new addrman addresses. nTries++; if (nTries > 100) break; if (IsLimited(addr)) continue; // only consider very recently tried nodes after 30 failed attempts if (nANow - addr.nLastTry < 600 && nTries < 30) continue; // do not allow non-default ports, unless after 50 invalid addresses selected already if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50) continue; addrConnect = addr; break; } if (addrConnect.IsValid()) OpenNetworkConnection(addrConnect, &grant); } } void ThreadOpenAddedConnections() { { LOCK(cs_vAddedNodes); vAddedNodes = mapMultiArgs["-addnode"]; } if (HaveNameProxy()) { while (true) { list<string> lAddresses(0); { LOCK(cs_vAddedNodes); BOOST_FOREACH (string& strAddNode, vAddedNodes) lAddresses.push_back(strAddNode); } BOOST_FOREACH (string& strAddNode, lAddresses) { CAddress addr; CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(addr, &grant, strAddNode.c_str()); MilliSleep(500); } MilliSleep(120000); // Retry every 2 minutes } } for (unsigned int i = 0; true; i++) { list<string> lAddresses(0); { LOCK(cs_vAddedNodes); BOOST_FOREACH (string& strAddNode, vAddedNodes) lAddresses.push_back(strAddNode); } list<vector<CService> > lservAddressesToAdd(0); BOOST_FOREACH (string& strAddNode, lAddresses) { vector<CService> vservNode(0); if (Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0)) { lservAddressesToAdd.push_back(vservNode); { LOCK(cs_setservAddNodeAddresses); BOOST_FOREACH (CService& serv, vservNode) setservAddNodeAddresses.insert(serv); } } } // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry // (keeping in mind that addnode entries can have many IPs if fNameLookup) { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) for (list<vector<CService> >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++) BOOST_FOREACH (CService& addrNode, *(it)) if (pnode->addr == addrNode) { it = lservAddressesToAdd.erase(it); it--; break; } } BOOST_FOREACH (vector<CService>& vserv, lservAddressesToAdd) { CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant); MilliSleep(500); } MilliSleep(120000); // Retry every 2 minutes } } // if successful, this moves the passed grant to the constructed node bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant* grantOutbound, const char* pszDest, bool fOneShot) { // // Initiate outbound network connection // boost::this_thread::interruption_point(); if (!pszDest) { if (IsLocal(addrConnect) || FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) || FindNode(addrConnect.ToStringIPPort())) return false; } else if (FindNode(pszDest)) return false; CNode* pnode = ConnectNode(addrConnect, pszDest); boost::this_thread::interruption_point(); if (!pnode) return false; if (grantOutbound) grantOutbound->MoveTo(pnode->grantOutbound); pnode->fNetworkNode = true; if (fOneShot) pnode->fOneShot = true; return true; } void ThreadMessageHandler() { boost::mutex condition_mutex; boost::unique_lock<boost::mutex> lock(condition_mutex); SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL); while (true) { vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; BOOST_FOREACH (CNode* pnode, vNodesCopy) { pnode->AddRef(); } } // Poll the connected nodes for messages CNode* pnodeTrickle = NULL; if (!vNodesCopy.empty()) pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())]; bool fSleep = true; BOOST_FOREACH (CNode* pnode, vNodesCopy) { if (pnode->fDisconnect) continue; // Receive messages { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { if (!g_signals.ProcessMessages(pnode)) pnode->CloseSocketDisconnect(); if (pnode->nSendSize < SendBufferSize()) { if (!pnode->vRecvGetData.empty() || (!pnode->vRecvMsg.empty() && pnode->vRecvMsg[0].complete())) { fSleep = false; } } } } boost::this_thread::interruption_point(); // Send messages { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) g_signals.SendMessages(pnode, pnode == pnodeTrickle || pnode->fWhitelisted); } boost::this_thread::interruption_point(); } { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodesCopy) pnode->Release(); } if (fSleep) messageHandlerCondition.timed_wait(lock, boost::posix_time::microsec_clock::universal_time() + boost::posix_time::milliseconds(100)); } } // ppcoin: stake minter thread void static ThreadStakeMinter() { boost::this_thread::interruption_point(); LogPrintf("ThreadStakeMinter started\n"); CWallet* pwallet = pwalletMain; try { BitcoinMiner(pwallet, true); boost::this_thread::interruption_point(); } catch (std::exception& e) { LogPrintf("ThreadStakeMinter() exception \n"); } catch (...) { LogPrintf("ThreadStakeMinter() error \n"); } LogPrintf("ThreadStakeMinter exiting,\n"); } bool BindListenPort(const CService& addrBind, string& strError, bool fWhitelisted) { strError = ""; int nOne = 1; // Create socket for listening for incoming connections struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len)) { strError = strprintf("Error: Bind address family for %s not supported", addrBind.ToString()); LogPrintf("%s\n", strError); return false; } SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP); if (hListenSocket == INVALID_SOCKET) { strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError())); LogPrintf("%s\n", strError); return false; } if (!IsSelectableSocket(hListenSocket)) { strError = "Error: Couldn't create a listenable socket for incoming connections"; LogPrintf("%s\n", strError); return false; } #ifndef WIN32 #ifdef SO_NOSIGPIPE // Different way of disabling SIGPIPE on BSD setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int)); #endif // Allow binding if the port is still in TIME_WAIT state after // the program was closed and restarted. Not an issue on windows! setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int)); #endif // Set to non-blocking, incoming connections will also inherit this if (!SetSocketNonBlocking(hListenSocket, true)) { strError = strprintf("BindListenPort: Setting listening socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError())); LogPrintf("%s\n", strError); return false; } // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option // and enable it by default or not. Try to enable it, if possible. if (addrBind.IsIPv6()) { #ifdef IPV6_V6ONLY #ifdef WIN32 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int)); #else setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int)); #endif #endif #ifdef WIN32 int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED; setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int)); #endif } if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) { int nErr = WSAGetLastError(); if (nErr == WSAEADDRINUSE) strError = strprintf(_("Unable to bind to %s on this computer. socialtraders Core is probably already running."), addrBind.ToString()); else strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr)); LogPrintf("%s\n", strError); CloseSocket(hListenSocket); return false; } LogPrintf("Bound to %s\n", addrBind.ToString()); // Listen for incoming connections if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR) { strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError())); LogPrintf("%s\n", strError); CloseSocket(hListenSocket); return false; } vhListenSocket.push_back(ListenSocket(hListenSocket, fWhitelisted)); if (addrBind.IsRoutable() && fDiscover && !fWhitelisted) AddLocal(addrBind, LOCAL_BIND); return true; } void static Discover(boost::thread_group& threadGroup) { if (!fDiscover) return; #ifdef WIN32 // Get local host IP char pszHostName[256] = ""; if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) { vector<CNetAddr> vaddr; if (LookupHost(pszHostName, vaddr)) { BOOST_FOREACH (const CNetAddr& addr, vaddr) { if (AddLocal(addr, LOCAL_IF)) LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToString()); } } } #else // Get local host ip struct ifaddrs* myaddrs; if (getifaddrs(&myaddrs) == 0) { for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) continue; if ((ifa->ifa_flags & IFF_UP) == 0) continue; if (strcmp(ifa->ifa_name, "lo") == 0) continue; if (strcmp(ifa->ifa_name, "lo0") == 0) continue; if (ifa->ifa_addr->sa_family == AF_INET) { struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr); CNetAddr addr(s4->sin_addr); if (AddLocal(addr, LOCAL_IF)) LogPrintf("%s: IPv4 %s: %s\n", __func__, ifa->ifa_name, addr.ToString()); } else if (ifa->ifa_addr->sa_family == AF_INET6) { struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr); CNetAddr addr(s6->sin6_addr); if (AddLocal(addr, LOCAL_IF)) LogPrintf("%s: IPv6 %s: %s\n", __func__, ifa->ifa_name, addr.ToString()); } } freeifaddrs(myaddrs); } #endif } void StartNode(boost::thread_group& threadGroup) { uiInterface.InitMessage(_("Loading addresses...")); // Load addresses for peers.dat int64_t nStart = GetTimeMillis(); { CAddrDB adb; if (!adb.Read(addrman)) LogPrintf("Invalid or missing peers.dat; recreating\n"); } LogPrintf("Loaded %i addresses from peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart); fAddressesInitialized = true; if (semOutbound == NULL) { // initialize semaphore int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections); semOutbound = new CSemaphore(nMaxOutbound); } if (pnodeLocalHost == NULL) pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices)); Discover(threadGroup); // // Start threads // if (!GetBoolArg("-dnsseed", true)) LogPrintf("DNS seeding disabled\n"); else threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "dnsseed", &ThreadDNSAddressSeed)); // Map ports with UPnP MapPort(GetBoolArg("-upnp", DEFAULT_UPNP)); // Send and receive from sockets, accept connections threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "net", &ThreadSocketHandler)); // Initiate outbound connections from -addnode threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "addcon", &ThreadOpenAddedConnections)); // Initiate outbound connections threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "opencon", &ThreadOpenConnections)); // Process messages threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "msghand", &ThreadMessageHandler)); // Dump network addresses threadGroup.create_thread(boost::bind(&LoopForever<void (*)()>, "dumpaddr", &DumpAddresses, DUMP_ADDRESSES_INTERVAL * 1000)); // ppcoin:mint proof-of-stake blocks in the background if (GetBoolArg("-staking", true)) threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "stakemint", &ThreadStakeMinter)); } bool StopNode() { LogPrintf("StopNode()\n"); MapPort(false); if (semOutbound) for (int i = 0; i < MAX_OUTBOUND_CONNECTIONS; i++) semOutbound->post(); if (fAddressesInitialized) { DumpAddresses(); fAddressesInitialized = false; } return true; } class CNetCleanup { public: CNetCleanup() {} ~CNetCleanup() { // Close sockets BOOST_FOREACH (CNode* pnode, vNodes) if (pnode->hSocket != INVALID_SOCKET) CloseSocket(pnode->hSocket); BOOST_FOREACH (ListenSocket& hListenSocket, vhListenSocket) if (hListenSocket.socket != INVALID_SOCKET) if (!CloseSocket(hListenSocket.socket)) LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError())); // clean up some globals (to help leak detection) BOOST_FOREACH (CNode* pnode, vNodes) delete pnode; BOOST_FOREACH (CNode* pnode, vNodesDisconnected) delete pnode; vNodes.clear(); vNodesDisconnected.clear(); vhListenSocket.clear(); delete semOutbound; semOutbound = NULL; delete pnodeLocalHost; pnodeLocalHost = NULL; #ifdef WIN32 // Shutdown Windows Sockets WSACleanup(); #endif } } instance_of_cnetcleanup; void CExplicitNetCleanup::callCleanup() { // Explicit call to destructor of CNetCleanup because it's not implicitly called // when the wallet is restarted from within the wallet itself. CNetCleanup* tmp = new CNetCleanup(); delete tmp; // Stroustrup's gonna kill me for that } void RelayTransaction(const CTransaction& tx) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(10000); ss << tx; RelayTransaction(tx, ss); } void RelayTransaction(const CTransaction& tx, const CDataStream& ss) { CInv inv(MSG_TX, tx.GetHash()); { LOCK(cs_mapRelay); // Expire old relay messages while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime()) { mapRelay.erase(vRelayExpiration.front().second); vRelayExpiration.pop_front(); } // Save original serialized message so newer versions are preserved mapRelay.insert(std::make_pair(inv, ss)); vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv)); } LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) { if (!pnode->fRelayTxes) continue; LOCK(pnode->cs_filter); if (pnode->pfilter) { if (pnode->pfilter->IsRelevantAndUpdate(tx)) pnode->PushInventory(inv); } else pnode->PushInventory(inv); } } void RelayTransactionLockReq(const CTransaction& tx, bool relayToAll) { CInv inv(MSG_TXLOCK_REQUEST, tx.GetHash()); //broadcast the new lock LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) { if (!relayToAll && !pnode->fRelayTxes) continue; pnode->PushMessage("ix", tx); } } void RelayInv(CInv& inv) { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes){ if((pnode->nServices==NODE_BLOOM_WITHOUT_MN) && inv.IsMasterNodeType())continue; if (pnode->nVersion >= ActiveProtocol()) pnode->PushInventory(inv); } } void CNode::RecordBytesRecv(uint64_t bytes) { LOCK(cs_totalBytesRecv); nTotalBytesRecv += bytes; } void CNode::RecordBytesSent(uint64_t bytes) { LOCK(cs_totalBytesSent); nTotalBytesSent += bytes; } uint64_t CNode::GetTotalBytesRecv() { LOCK(cs_totalBytesRecv); return nTotalBytesRecv; } uint64_t CNode::GetTotalBytesSent() { LOCK(cs_totalBytesSent); return nTotalBytesSent; } void CNode::Fuzz(int nChance) { if (!fSuccessfullyConnected) return; // Don't fuzz initial handshake if (GetRand(nChance) != 0) return; // Fuzz 1 of every nChance messages switch (GetRand(3)) { case 0: // xor a random byte with a random value: if (!ssSend.empty()) { CDataStream::size_type pos = GetRand(ssSend.size()); ssSend[pos] ^= (unsigned char)(GetRand(256)); } break; case 1: // delete a random byte: if (!ssSend.empty()) { CDataStream::size_type pos = GetRand(ssSend.size()); ssSend.erase(ssSend.begin() + pos); } break; case 2: // insert a random byte at a random position { CDataStream::size_type pos = GetRand(ssSend.size()); char ch = (char)GetRand(256); ssSend.insert(ssSend.begin() + pos, ch); } break; } // Chance of more than one change half the time: // (more changes exponentially less likely): Fuzz(2); } // // CAddrDB // CAddrDB::CAddrDB() { pathAddr = GetDataDir() / "peers.dat"; } bool CAddrDB::Write(const CAddrMan& addr) { // Generate random temporary filename unsigned short randv = 0; GetRandBytes((unsigned char*)&randv, sizeof(randv)); std::string tmpfn = strprintf("peers.dat.%04x", randv); // serialize addresses, checksum data up to that point, then append csum CDataStream ssPeers(SER_DISK, CLIENT_VERSION); ssPeers << FLATDATA(Params().MessageStart()); ssPeers << addr; uint256 hash = Hash(ssPeers.begin(), ssPeers.end()); ssPeers << hash; // open output file, and associate with CAutoFile boost::filesystem::path pathAddr = GetDataDir() / "peers.dat"; FILE* file = fopen(pathAddr.string().c_str(), "wb"); CAutoFile fileout(file, SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error("%s : Failed to open file %s", __func__, pathAddr.string()); // Write and commit header, data try { fileout << ssPeers; } catch (std::exception& e) { return error("%s : Serialize or I/O error - %s", __func__, e.what()); } FileCommit(fileout.Get()); fileout.fclose(); return true; } bool CAddrDB::Read(CAddrMan& addr) { // open input file, and associate with CAutoFile FILE* file = fopen(pathAddr.string().c_str(), "rb"); CAutoFile filein(file, SER_DISK, CLIENT_VERSION); if (filein.IsNull()) return error("%s : Failed to open file %s", __func__, pathAddr.string()); // use file size to size memory buffer int fileSize = boost::filesystem::file_size(pathAddr); int dataSize = fileSize - sizeof(uint256); // Don't try to resize to a negative number if file is small if (dataSize < 0) dataSize = 0; vector<unsigned char> vchData; vchData.resize(dataSize); uint256 hashIn; // read data and checksum from file try { filein.read((char*)&vchData[0], dataSize); filein >> hashIn; } catch (std::exception& e) { return error("%s : Deserialize or I/O error - %s", __func__, e.what()); } filein.fclose(); CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION); // verify stored checksum matches input data uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end()); if (hashIn != hashTmp) return error("%s : Checksum mismatch, data corrupted", __func__); unsigned char pchMsgTmp[4]; try { // de-serialize file header (network specific magic number) and .. ssPeers >> FLATDATA(pchMsgTmp); // ... verify the network matches ours if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) return error("%s : Invalid network magic number", __func__); // de-serialize address data into one CAddrMan object ssPeers >> addr; } catch (std::exception& e) { return error("%s : Deserialize or I/O error - %s", __func__, e.what()); } return true; } unsigned int ReceiveFloodSize() { return 1000 * GetArg("-maxreceivebuffer", 5 * 1000); } unsigned int SendBufferSize() { return 1000 * GetArg("-maxsendbuffer", 1 * 1000); } CNode::CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn, bool fInboundIn) : ssSend(SER_NETWORK, INIT_PROTO_VERSION), setAddrKnown(5000) { nServices = 0; hSocket = hSocketIn; nRecvVersion = INIT_PROTO_VERSION; nLastSend = 0; nLastRecv = 0; nSendBytes = 0; nRecvBytes = 0; nTimeConnected = GetTime(); addr = addrIn; addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn; nVersion = 0; strSubVer = ""; fWhitelisted = false; fOneShot = false; fClient = false; // set by version message fInbound = fInboundIn; fNetworkNode = false; fSuccessfullyConnected = false; fDisconnect = false; nRefCount = 0; nSendSize = 0; nSendOffset = 0; hashContinue = 0; nStartingHeight = -1; fGetAddr = false; fRelayTxes = false; setInventoryKnown.max_size(SendBufferSize() / 1000); pfilter = new CBloomFilter(); nPingNonceSent = 0; nPingUsecStart = 0; nPingUsecTime = 0; fPingQueued = false; fObfuScationMaster = false; { LOCK(cs_nLastNodeId); id = nLastNodeId++; } if (fLogIPs) LogPrint("net", "Added connection to %s peer=%d\n", addrName, id); else LogPrint("net", "Added connection peer=%d\n", id); // Be shy and don't send version until we hear if (hSocket != INVALID_SOCKET && !fInbound) PushVersion(); GetNodeSignals().InitializeNode(GetId(), this); } CNode::~CNode() { CloseSocket(hSocket); if (pfilter) delete pfilter; GetNodeSignals().FinalizeNode(GetId()); } void CNode::AskFor(const CInv& inv) { if (mapAskFor.size() > MAPASKFOR_MAX_SZ) return; // We're using mapAskFor as a priority queue, // the key is the earliest time the request can be sent int64_t nRequestTime; limitedmap<CInv, int64_t>::const_iterator it = mapAlreadyAskedFor.find(inv); if (it != mapAlreadyAskedFor.end()) nRequestTime = it->second; else nRequestTime = 0; LogPrint("net", "askfor %s %d (%s) peer=%d\n", inv.ToString(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime / 1000000), id); // Make sure not to reuse time indexes to keep things in the same order int64_t nNow = GetTimeMicros() - 1000000; static int64_t nLastTime; ++nLastTime; nNow = std::max(nNow, nLastTime); nLastTime = nNow; // Each retry is 2 minutes after the last nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow); if (it != mapAlreadyAskedFor.end()) mapAlreadyAskedFor.update(it, nRequestTime); else mapAlreadyAskedFor.insert(std::make_pair(inv, nRequestTime)); mapAskFor.insert(std::make_pair(nRequestTime, inv)); } void CNode::BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend) { ENTER_CRITICAL_SECTION(cs_vSend); assert(ssSend.size() == 0); ssSend << CMessageHeader(pszCommand, 0); LogPrint("net", "sending: %s ", SanitizeString(pszCommand)); } void CNode::AbortMessage() UNLOCK_FUNCTION(cs_vSend) { ssSend.clear(); LEAVE_CRITICAL_SECTION(cs_vSend); LogPrint("net", "(aborted)\n"); } void CNode::EndMessage() UNLOCK_FUNCTION(cs_vSend) { // The -*messagestest options are intentionally not documented in the help message, // since they are only used during development to debug the networking code and are // not intended for end-users. if (mapArgs.count("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 2)) == 0) { LogPrint("net", "dropmessages DROPPING SEND MESSAGE\n"); AbortMessage(); return; } if (mapArgs.count("-fuzzmessagestest")) Fuzz(GetArg("-fuzzmessagestest", 10)); if (ssSend.size() == 0) return; // Set the size unsigned int nSize = ssSend.size() - CMessageHeader::HEADER_SIZE; memcpy((char*)&ssSend[CMessageHeader::MESSAGE_SIZE_OFFSET], &nSize, sizeof(nSize)); // Set the checksum uint256 hash = Hash(ssSend.begin() + CMessageHeader::HEADER_SIZE, ssSend.end()); unsigned int nChecksum = 0; memcpy(&nChecksum, &hash, sizeof(nChecksum)); assert(ssSend.size() >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum)); memcpy((char*)&ssSend[CMessageHeader::CHECKSUM_OFFSET], &nChecksum, sizeof(nChecksum)); LogPrint("net", "(%d bytes) peer=%d\n", nSize, id); std::deque<CSerializeData>::iterator it = vSendMsg.insert(vSendMsg.end(), CSerializeData()); ssSend.GetAndClear(*it); nSendSize += (*it).size(); // If write queue empty, attempt "optimistic write" if (it == vSendMsg.begin()) SocketSendData(this); LEAVE_CRITICAL_SECTION(cs_vSend); }
class Solution { public: /** * @param A: Given an integer array * @return: void */ void heapify(vector<int> &A) { // write your code here int n = A.size(); if (n == 0) { return; } for (int i = n / 2 - 1; i >= 0; --i) { heapifyHelper(A, i); } } private: void heapifyHelper(vector<int> &A, int i) { int minIndex = i; int n = A.size(); while (i * 2 + 1 < n) { int left = i * 2 + 1; if (left < n && A[left] < A[minIndex]) { minIndex = left; } int right = i * 2 + 2; if (right < n && A[right] < A[minIndex]) { minIndex = right; } if (minIndex != i) { swap(A[i], A[minIndex]); i = minIndex; } else { break; } } } };
/* * MediaStream.cpp */ #include <cstdio> #include <map> #include <algorithm> #include <string> #include <cstring> #include <vector> #include <cstdlib> #include <ctime> #include "./MediaStream.h" #include "./SdpInfo.h" #include"./WebRtcConnection.h" #include "rtp/RtpHeaders.h" #include "rtp/RtpVP8Parser.h" #include "rtp/RtcpAggregator.h" #include "rtp/RtcpForwarder.h" #include "rtp/RtpSlideShowHandler.h" #include "rtp/RtpTrackMuteHandler.h" #include "rtp/BandwidthEstimationHandler.h" #include "rtp/FecReceiverHandler.h" #include "rtp/RtcpProcessorHandler.h" #include "rtp/RtpRetransmissionHandler.h" #include "rtp/RtcpFeedbackGenerationHandler.h" #include "rtp/RtpPaddingRemovalHandler.h" #include "rtp/StatsHandler.h" #include "rtp/SRPacketHandler.h" #include "rtp/SenderBandwidthEstimationHandler.h" #include "rtp/LayerDetectorHandler.h" #include "rtp/LayerBitrateCalculationHandler.h" #include "rtp/QualityFilterHandler.h" #include "rtp/QualityManager.h" #include "rtp/PliPacerHandler.h" #include "rtp/RtpPaddingGeneratorHandler.h" #include "rtp/RtpUtils.h" #include "rtp/PacketCodecParser.h" namespace erizo { DEFINE_LOGGER(MediaStream, "MediaStream"); log4cxx::LoggerPtr MediaStream::statsLogger = log4cxx::Logger::getLogger("StreamStats"); static constexpr auto kStreamStatsPeriod = std::chrono::seconds(30); MediaStream::MediaStream(std::shared_ptr<Worker> worker, std::shared_ptr<WebRtcConnection> connection, const std::string& media_stream_id, const std::string& media_stream_label, bool is_publisher) : audio_enabled_{false}, video_enabled_{false}, connection_{std::move(connection)}, stream_id_{media_stream_id}, mslabel_ {media_stream_label}, bundle_{false}, pipeline_{Pipeline::create()}, worker_{std::move(worker)}, audio_muted_{false}, video_muted_{false}, pipeline_initialized_{false}, is_publisher_{is_publisher} { setVideoSinkSSRC(kDefaultVideoSinkSSRC); setAudioSinkSSRC(kDefaultAudioSinkSSRC); ELOG_INFO("%s message: constructor, id: %s", toLog(), media_stream_id.c_str()); source_fb_sink_ = this; sink_fb_source_ = this; stats_ = std::make_shared<Stats>(); log_stats_ = std::make_shared<Stats>(); quality_manager_ = std::make_shared<QualityManager>(); packet_buffer_ = std::make_shared<PacketBufferService>(); std::srand(std::time(nullptr)); audio_sink_ssrc_ = std::rand(); video_sink_ssrc_ = std::rand(); rtcp_processor_ = std::make_shared<RtcpForwarder>(static_cast<MediaSink*>(this), static_cast<MediaSource*>(this)); should_send_feedback_ = true; slide_show_mode_ = false; mark_ = clock::now(); rate_control_ = 0; sending_ = true; } MediaStream::~MediaStream() { ELOG_DEBUG("%s message:Destructor called", toLog()); ELOG_DEBUG("%s message: Destructor ended", toLog()); } uint32_t MediaStream::getMaxVideoBW() { uint32_t bitrate = rtcp_processor_ ? rtcp_processor_->getMaxVideoBW() : 0; return bitrate; } void MediaStream::setMaxVideoBW(uint32_t max_video_bw) { asyncTask([max_video_bw] (std::shared_ptr<MediaStream> stream) { if (stream->rtcp_processor_) { stream->rtcp_processor_->setMaxVideoBW(max_video_bw * 1000); if (stream->pipeline_) { stream->pipeline_->notifyUpdate(); } } }); } void MediaStream::syncClose() { ELOG_DEBUG("%s message:Close called", toLog()); if (!sending_) { return; } sending_ = false; video_sink_ = nullptr; audio_sink_ = nullptr; fb_sink_ = nullptr; pipeline_initialized_ = false; pipeline_->close(); pipeline_.reset(); connection_.reset(); ELOG_DEBUG("%s message: Close ended", toLog()); } void MediaStream::close() { ELOG_DEBUG("%s message: Async close called", toLog()); std::shared_ptr<MediaStream> shared_this = shared_from_this(); asyncTask([shared_this] (std::shared_ptr<MediaStream> stream) { shared_this->syncClose(); }); } bool MediaStream::init() { return true; } bool MediaStream::isSourceSSRC(uint32_t ssrc) { return isVideoSourceSSRC(ssrc) || isAudioSourceSSRC(ssrc); } bool MediaStream::isSinkSSRC(uint32_t ssrc) { return isVideoSinkSSRC(ssrc) || isAudioSinkSSRC(ssrc); } bool MediaStream::setRemoteSdp(std::shared_ptr<SdpInfo> sdp) { ELOG_DEBUG("%s message: setting remote SDP", toLog()); if (!sending_) { return true; } remote_sdp_ = sdp; if (remote_sdp_->videoBandwidth != 0) { ELOG_DEBUG("%s message: Setting remote BW, maxVideoBW: %u", toLog(), remote_sdp_->videoBandwidth); this->rtcp_processor_->setMaxVideoBW(remote_sdp_->videoBandwidth*1000); } if (pipeline_initialized_ && pipeline_) { pipeline_->notifyUpdate(); return true; } bundle_ = remote_sdp_->isBundle; auto video_ssrc_list_it = remote_sdp_->video_ssrc_map.find(getLabel()); if (video_ssrc_list_it != remote_sdp_->video_ssrc_map.end()) { setVideoSourceSSRCList(video_ssrc_list_it->second); } auto audio_ssrc_it = remote_sdp_->audio_ssrc_map.find(getLabel()); if (audio_ssrc_it != remote_sdp_->audio_ssrc_map.end()) { setAudioSourceSSRC(audio_ssrc_it->second); } if (getVideoSourceSSRCList().empty() || (getVideoSourceSSRCList().size() == 1 && getVideoSourceSSRCList()[0] == 0)) { std::vector<uint32_t> default_ssrc_list; default_ssrc_list.push_back(kDefaultVideoSinkSSRC); setVideoSourceSSRCList(default_ssrc_list); } if (getAudioSourceSSRC() == 0) { setAudioSourceSSRC(kDefaultAudioSinkSSRC); } audio_enabled_ = remote_sdp_->hasAudio; video_enabled_ = remote_sdp_->hasVideo; rtcp_processor_->addSourceSsrc(getAudioSourceSSRC()); std::for_each(video_source_ssrc_list_.begin(), video_source_ssrc_list_.end(), [this] (uint32_t new_ssrc){ rtcp_processor_->addSourceSsrc(new_ssrc); }); initializePipeline(); initializeStats(); return true; } bool MediaStream::setLocalSdp(std::shared_ptr<SdpInfo> sdp) { local_sdp_ = std::move(sdp); return true; } void MediaStream::initializeStats() { log_stats_->getNode().insertStat("streamId", StringStat{getId()}); log_stats_->getNode().insertStat("audioBitrate", CumulativeStat{0}); log_stats_->getNode().insertStat("audioFL", CumulativeStat{0}); log_stats_->getNode().insertStat("audioPL", CumulativeStat{0}); log_stats_->getNode().insertStat("audioJitter", CumulativeStat{0}); log_stats_->getNode().insertStat("audioMuted", CumulativeStat{0}); log_stats_->getNode().insertStat("audioNack", CumulativeStat{0}); log_stats_->getNode().insertStat("audioRemb", CumulativeStat{0}); log_stats_->getNode().insertStat("videoBitrate", CumulativeStat{0}); log_stats_->getNode().insertStat("videoFL", CumulativeStat{0}); log_stats_->getNode().insertStat("videoPL", CumulativeStat{0}); log_stats_->getNode().insertStat("videoJitter", CumulativeStat{0}); log_stats_->getNode().insertStat("videoMuted", CumulativeStat{0}); log_stats_->getNode().insertStat("slideshow", CumulativeStat{0}); log_stats_->getNode().insertStat("videoNack", CumulativeStat{0}); log_stats_->getNode().insertStat("videoPli", CumulativeStat{0}); log_stats_->getNode().insertStat("videoFir", CumulativeStat{0}); log_stats_->getNode().insertStat("videoRemb", CumulativeStat{0}); log_stats_->getNode().insertStat("videoErizoRemb", CumulativeStat{0}); log_stats_->getNode().insertStat("videoKeyFrames", CumulativeStat{0}); log_stats_->getNode().insertStat("SL0TL0", CumulativeStat{0}); log_stats_->getNode().insertStat("SL0TL1", CumulativeStat{0}); log_stats_->getNode().insertStat("SL0TL2", CumulativeStat{0}); log_stats_->getNode().insertStat("SL0TL3", CumulativeStat{0}); log_stats_->getNode().insertStat("SL1TL0", CumulativeStat{0}); log_stats_->getNode().insertStat("SL1TL1", CumulativeStat{0}); log_stats_->getNode().insertStat("SL1TL2", CumulativeStat{0}); log_stats_->getNode().insertStat("SL1TL3", CumulativeStat{0}); log_stats_->getNode().insertStat("SL2TL0", CumulativeStat{0}); log_stats_->getNode().insertStat("SL2TL1", CumulativeStat{0}); log_stats_->getNode().insertStat("SL2TL2", CumulativeStat{0}); log_stats_->getNode().insertStat("SL2TL3", CumulativeStat{0}); log_stats_->getNode().insertStat("SL3TL0", CumulativeStat{0}); log_stats_->getNode().insertStat("SL3TL1", CumulativeStat{0}); log_stats_->getNode().insertStat("SL3TL2", CumulativeStat{0}); log_stats_->getNode().insertStat("SL3TL3", CumulativeStat{0}); log_stats_->getNode().insertStat("maxActiveSL", CumulativeStat{0}); log_stats_->getNode().insertStat("maxActiveTL", CumulativeStat{0}); log_stats_->getNode().insertStat("selectedSL", CumulativeStat{0}); log_stats_->getNode().insertStat("selectedTL", CumulativeStat{0}); log_stats_->getNode().insertStat("isPublisher", CumulativeStat{is_publisher_}); log_stats_->getNode().insertStat("totalBitrate", CumulativeStat{0}); log_stats_->getNode().insertStat("rtxBitrate", CumulativeStat{0}); log_stats_->getNode().insertStat("paddingBitrate", CumulativeStat{0}); log_stats_->getNode().insertStat("bwe", CumulativeStat{0}); log_stats_->getNode().insertStat("maxVideoBW", CumulativeStat{0}); std::weak_ptr<MediaStream> weak_this = shared_from_this(); worker_->scheduleEvery([weak_this] () { if (auto stream = weak_this.lock()) { if (stream->sending_) { stream->printStats(); return true; } } return false; }, kStreamStatsPeriod); } void MediaStream::transferLayerStats(std::string spatial, std::string temporal) { std::string node = "SL" + spatial + "TL" + temporal; if (stats_->getNode().hasChild("qualityLayers") && stats_->getNode()["qualityLayers"].hasChild(spatial) && stats_->getNode()["qualityLayers"][spatial].hasChild(temporal)) { log_stats_->getNode() .insertStat(node, CumulativeStat{stats_->getNode()["qualityLayers"][spatial][temporal].value()}); } } void MediaStream::transferMediaStats(std::string target_node, std::string source_parent, std::string source_node) { if (stats_->getNode().hasChild(source_parent) && stats_->getNode()[source_parent].hasChild(source_node)) { log_stats_->getNode() .insertStat(target_node, CumulativeStat{stats_->getNode()[source_parent][source_node].value()}); } } void MediaStream::printStats() { std::string video_ssrc; std::string audio_ssrc; log_stats_->getNode().insertStat("audioEnabled", CumulativeStat{audio_enabled_}); log_stats_->getNode().insertStat("videoEnabled", CumulativeStat{video_enabled_}); log_stats_->getNode().insertStat("maxVideoBW", CumulativeStat{getMaxVideoBW()}); if (audio_enabled_) { audio_ssrc = std::to_string(is_publisher_ ? getAudioSourceSSRC() : getAudioSinkSSRC()); transferMediaStats("audioBitrate", audio_ssrc, "bitrateCalculated"); transferMediaStats("audioPL", audio_ssrc, "packetsLost"); transferMediaStats("audioFL", audio_ssrc, "fractionLost"); transferMediaStats("audioJitter", audio_ssrc, "jitter"); transferMediaStats("audioMuted", audio_ssrc, "erizoAudioMute"); transferMediaStats("audioNack", audio_ssrc, "NACK"); transferMediaStats("audioRemb", audio_ssrc, "bandwidth"); } if (video_enabled_) { video_ssrc = std::to_string(is_publisher_ ? getVideoSourceSSRC() : getVideoSinkSSRC()); transferMediaStats("videoBitrate", video_ssrc, "bitrateCalculated"); transferMediaStats("videoPL", video_ssrc, "packetsLost"); transferMediaStats("videoFL", video_ssrc, "fractionLost"); transferMediaStats("videoJitter", video_ssrc, "jitter"); transferMediaStats("videoMuted", audio_ssrc, "erizoVideoMute"); transferMediaStats("slideshow", video_ssrc, "erizoSlideShow"); transferMediaStats("videoNack", video_ssrc, "NACK"); transferMediaStats("videoPli", video_ssrc, "PLI"); transferMediaStats("videoFir", video_ssrc, "FIR"); transferMediaStats("videoRemb", video_ssrc, "bandwidth"); transferMediaStats("videoErizoRemb", video_ssrc, "erizoBandwidth"); transferMediaStats("videoKeyFrames", video_ssrc, "keyFrames"); } for (uint32_t spatial = 0; spatial <= 3; spatial++) { for (uint32_t temporal = 0; temporal <= 3; temporal++) { transferLayerStats(std::to_string(spatial), std::to_string(temporal)); } } transferMediaStats("maxActiveSL", "qualityLayers", "maxActiveSpatialLayer"); transferMediaStats("maxActiveTL", "qualityLayers", "maxActiveTemporalLayer"); transferMediaStats("selectedSL", "qualityLayers", "selectedSpatialLayer"); transferMediaStats("selectedTL", "qualityLayers", "selectedTemporalLayer"); transferMediaStats("totalBitrate", "total", "bitrateCalculated"); transferMediaStats("paddingBitrate", "total", "paddingBitrate"); transferMediaStats("rtxBitrate", "total", "rtxBitrate"); transferMediaStats("bwe", "total", "senderBitrateEstimation"); ELOG_INFOT(statsLogger, "%s", log_stats_->getStats()); } void MediaStream::initializePipeline() { handler_manager_ = std::make_shared<HandlerManager>(shared_from_this()); pipeline_->addService(shared_from_this()); pipeline_->addService(handler_manager_); pipeline_->addService(rtcp_processor_); pipeline_->addService(stats_); pipeline_->addService(quality_manager_); pipeline_->addService(packet_buffer_); pipeline_->addFront(std::make_shared<PacketReader>(this)); pipeline_->addFront(std::make_shared<RtcpProcessorHandler>()); pipeline_->addFront(std::make_shared<FecReceiverHandler>()); pipeline_->addFront(std::make_shared<LayerBitrateCalculationHandler>()); pipeline_->addFront(std::make_shared<QualityFilterHandler>()); pipeline_->addFront(std::make_shared<IncomingStatsHandler>()); pipeline_->addFront(std::make_shared<RtpTrackMuteHandler>()); pipeline_->addFront(std::make_shared<RtpSlideShowHandler>()); pipeline_->addFront(std::make_shared<RtpPaddingGeneratorHandler>()); pipeline_->addFront(std::make_shared<PliPacerHandler>()); pipeline_->addFront(std::make_shared<BandwidthEstimationHandler>()); pipeline_->addFront(std::make_shared<RtpPaddingRemovalHandler>()); pipeline_->addFront(std::make_shared<RtcpFeedbackGenerationHandler>()); pipeline_->addFront(std::make_shared<RtpRetransmissionHandler>()); pipeline_->addFront(std::make_shared<SRPacketHandler>()); pipeline_->addFront(std::make_shared<SenderBandwidthEstimationHandler>()); pipeline_->addFront(std::make_shared<LayerDetectorHandler>()); pipeline_->addFront(std::make_shared<OutgoingStatsHandler>()); pipeline_->addFront(std::make_shared<PacketCodecParser>()); pipeline_->addFront(std::make_shared<PacketWriter>(this)); pipeline_->finalize(); pipeline_initialized_ = true; } int MediaStream::deliverAudioData_(std::shared_ptr<DataPacket> audio_packet) { if (audio_enabled_) { sendPacketAsync(std::make_shared<DataPacket>(*audio_packet)); } return audio_packet->length; } int MediaStream::deliverVideoData_(std::shared_ptr<DataPacket> video_packet) { if (video_enabled_) { sendPacketAsync(std::make_shared<DataPacket>(*video_packet)); } return video_packet->length; } int MediaStream::deliverFeedback_(std::shared_ptr<DataPacket> fb_packet) { RtcpHeader *chead = reinterpret_cast<RtcpHeader*>(fb_packet->data); uint32_t recvSSRC = chead->getSourceSSRC(); if (chead->isREMB()) { for (uint8_t index = 0; index < chead->getREMBNumSSRC(); index++) { uint32_t ssrc = chead->getREMBFeedSSRC(index); if (isVideoSourceSSRC(ssrc)) { recvSSRC = ssrc; break; } } } if (isVideoSourceSSRC(recvSSRC)) { fb_packet->type = VIDEO_PACKET; sendPacketAsync(fb_packet); } else if (isAudioSourceSSRC(recvSSRC)) { fb_packet->type = AUDIO_PACKET; sendPacketAsync(fb_packet); } else { ELOG_DEBUG("%s deliverFeedback unknownSSRC: %u, localVideoSSRC: %u, localAudioSSRC: %u", toLog(), recvSSRC, this->getVideoSourceSSRC(), this->getAudioSourceSSRC()); } return fb_packet->length; } int MediaStream::deliverEvent_(MediaEventPtr event) { auto stream_ptr = shared_from_this(); worker_->task([stream_ptr, event]{ if (!stream_ptr->pipeline_initialized_) { return; } if (stream_ptr->pipeline_) { stream_ptr->pipeline_->notifyEvent(event); } }); return 1; } void MediaStream::onTransportData(std::shared_ptr<DataPacket> incoming_packet, Transport *transport) { if ((audio_sink_ == nullptr && video_sink_ == nullptr && fb_sink_ == nullptr)) { return; } std::shared_ptr<DataPacket> packet = std::make_shared<DataPacket>(*incoming_packet); if (transport->mediaType == AUDIO_TYPE) { packet->type = AUDIO_PACKET; } else if (transport->mediaType == VIDEO_TYPE) { packet->type = VIDEO_PACKET; } auto stream_ptr = shared_from_this(); worker_->task([stream_ptr, packet]{ if (!stream_ptr->pipeline_initialized_) { ELOG_DEBUG("%s message: Pipeline not initialized yet.", stream_ptr->toLog()); return; } char* buf = packet->data; RtpHeader *head = reinterpret_cast<RtpHeader*> (buf); RtcpHeader *chead = reinterpret_cast<RtcpHeader*> (buf); if (!chead->isRtcp()) { uint32_t recvSSRC = head->getSSRC(); if (stream_ptr->isVideoSourceSSRC(recvSSRC)) { packet->type = VIDEO_PACKET; } else if (stream_ptr->isAudioSourceSSRC(recvSSRC)) { packet->type = AUDIO_PACKET; } } if (stream_ptr->pipeline_) { stream_ptr->pipeline_->read(std::move(packet)); } }); } void MediaStream::read(std::shared_ptr<DataPacket> packet) { char* buf = packet->data; int len = packet->length; // PROCESS RTCP RtpHeader *head = reinterpret_cast<RtpHeader*> (buf); RtcpHeader *chead = reinterpret_cast<RtcpHeader*> (buf); uint32_t recvSSRC = 0; if (!chead->isRtcp()) { recvSSRC = head->getSSRC(); } else if (chead->packettype == RTCP_Sender_PT) { // Sender Report recvSSRC = chead->getSSRC(); } // DELIVER FEEDBACK (RR, FEEDBACK PACKETS) if (chead->isFeedback()) { if (fb_sink_ != nullptr && should_send_feedback_) { fb_sink_->deliverFeedback(std::move(packet)); } } else { // RTP or RTCP Sender Report if (bundle_) { // Check incoming SSRC // Deliver data if (isVideoSourceSSRC(recvSSRC) && video_sink_) { parseIncomingPayloadType(buf, len, VIDEO_PACKET); video_sink_->deliverVideoData(std::move(packet)); } else if (isAudioSourceSSRC(recvSSRC) && audio_sink_) { parseIncomingPayloadType(buf, len, AUDIO_PACKET); audio_sink_->deliverAudioData(std::move(packet)); } else { ELOG_DEBUG("%s read video unknownSSRC: %u, localVideoSSRC: %u, localAudioSSRC: %u", toLog(), recvSSRC, this->getVideoSourceSSRC(), this->getAudioSourceSSRC()); } } else { if (packet->type == AUDIO_PACKET && audio_sink_) { parseIncomingPayloadType(buf, len, AUDIO_PACKET); // Firefox does not send SSRC in SDP if (getAudioSourceSSRC() == 0) { ELOG_DEBUG("%s discoveredAudioSourceSSRC:%u", toLog(), recvSSRC); this->setAudioSourceSSRC(recvSSRC); } audio_sink_->deliverAudioData(std::move(packet)); } else if (packet->type == VIDEO_PACKET && video_sink_) { parseIncomingPayloadType(buf, len, VIDEO_PACKET); // Firefox does not send SSRC in SDP if (getVideoSourceSSRC() == 0) { ELOG_DEBUG("%s discoveredVideoSourceSSRC:%u", toLog(), recvSSRC); this->setVideoSourceSSRC(recvSSRC); } // change ssrc for RTP packets, don't touch here if RTCP video_sink_->deliverVideoData(std::move(packet)); } } // if not bundle } // if not Feedback } void MediaStream::setMediaStreamEventListener(MediaStreamEventListener* listener) { boost::mutex::scoped_lock lock(event_listener_mutex_); this->media_stream_event_listener_ = listener; } void MediaStream::notifyMediaStreamEvent(const std::string& type, const std::string& message) { boost::mutex::scoped_lock lock(event_listener_mutex_); if (this->media_stream_event_listener_ != nullptr) { media_stream_event_listener_->notifyMediaStreamEvent(type, message); } } void MediaStream::notifyToEventSink(MediaEventPtr event) { event_sink_->deliverEvent(std::move(event)); } int MediaStream::sendPLI() { RtcpHeader thePLI; thePLI.setPacketType(RTCP_PS_Feedback_PT); thePLI.setBlockCount(1); thePLI.setSSRC(this->getVideoSinkSSRC()); thePLI.setSourceSSRC(this->getVideoSourceSSRC()); thePLI.setLength(2); char *buf = reinterpret_cast<char*>(&thePLI); int len = (thePLI.getLength() + 1) * 4; sendPacketAsync(std::make_shared<DataPacket>(0, buf, len, VIDEO_PACKET)); return len; } void MediaStream::sendPLIToFeedback() { if (fb_sink_) { fb_sink_->deliverFeedback(RtpUtils::createPLI(this->getVideoSinkSSRC(), this->getVideoSourceSSRC())); } } // changes the outgoing payload type for in the given data packet void MediaStream::sendPacketAsync(std::shared_ptr<DataPacket> packet) { if (!sending_) { return; } auto stream_ptr = shared_from_this(); if (packet->comp == -1) { sending_ = false; auto p = std::make_shared<DataPacket>(); p->comp = -1; worker_->task([stream_ptr, p]{ stream_ptr->sendPacket(p); }); return; } changeDeliverPayloadType(packet.get(), packet->type); worker_->task([stream_ptr, packet]{ stream_ptr->sendPacket(packet); }); } void MediaStream::setSlideShowMode(bool state) { ELOG_DEBUG("%s slideShowMode: %u", toLog(), state); if (slide_show_mode_ == state) { return; } asyncTask([state] (std::shared_ptr<MediaStream> media_stream) { media_stream->stats_->getNode()[media_stream->getVideoSinkSSRC()].insertStat( "erizoSlideShow", CumulativeStat{state}); }); slide_show_mode_ = state; notifyUpdateToHandlers(); } void MediaStream::muteStream(bool mute_video, bool mute_audio) { asyncTask([mute_audio, mute_video] (std::shared_ptr<MediaStream> media_stream) { ELOG_DEBUG("%s message: muteStream, mute_video: %u, mute_audio: %u", media_stream->toLog(), mute_video, mute_audio); media_stream->audio_muted_ = mute_audio; media_stream->video_muted_ = mute_video; media_stream->stats_->getNode()[media_stream->getAudioSinkSSRC()].insertStat("erizoAudioMute", CumulativeStat{mute_audio}); media_stream->stats_->getNode()[media_stream->getAudioSinkSSRC()].insertStat("erizoVideoMute", CumulativeStat{mute_video}); if (media_stream && media_stream->pipeline_) { media_stream->pipeline_->notifyUpdate(); } }); } void MediaStream::setVideoConstraints(int max_video_width, int max_video_height, int max_video_frame_rate) { asyncTask([max_video_width, max_video_height, max_video_frame_rate] (std::shared_ptr<MediaStream> media_stream) { media_stream->quality_manager_->setVideoConstraints(max_video_width, max_video_height, max_video_frame_rate); }); } void MediaStream::setTransportInfo(std::string audio_info, std::string video_info) { if (video_enabled_) { uint32_t video_sink_ssrc = getVideoSinkSSRC(); uint32_t video_source_ssrc = getVideoSourceSSRC(); if (video_sink_ssrc != kDefaultVideoSinkSSRC) { stats_->getNode()[video_sink_ssrc].insertStat("clientHostType", StringStat{video_info}); } if (video_source_ssrc != 0) { stats_->getNode()[video_source_ssrc].insertStat("clientHostType", StringStat{video_info}); } } if (audio_enabled_) { uint32_t audio_sink_ssrc = getAudioSinkSSRC(); uint32_t audio_source_ssrc = getAudioSourceSSRC(); if (audio_sink_ssrc != kDefaultAudioSinkSSRC) { stats_->getNode()[audio_sink_ssrc].insertStat("clientHostType", StringStat{audio_info}); } if (audio_source_ssrc != 0) { stats_->getNode()[audio_source_ssrc].insertStat("clientHostType", StringStat{audio_info}); } } } void MediaStream::setFeedbackReports(bool will_send_fb, uint32_t target_bitrate) { if (slide_show_mode_) { target_bitrate = 0; } this->should_send_feedback_ = will_send_fb; if (target_bitrate == 1) { this->video_enabled_ = false; } this->rate_control_ = target_bitrate; } void MediaStream::setMetadata(std::map<std::string, std::string> metadata) { for (const auto &item : metadata) { log_stats_->getNode().insertStat("metadata-" + item.first, StringStat{item.second}); } setLogContext(metadata); } WebRTCEvent MediaStream::getCurrentState() { return connection_->getCurrentState(); } void MediaStream::getJSONStats(std::function<void(std::string)> callback) { asyncTask([callback] (std::shared_ptr<MediaStream> stream) { std::string requested_stats = stream->stats_->getStats(); // ELOG_DEBUG("%s message: Stats, stats: %s", stream->toLog(), requested_stats.c_str()); callback(requested_stats); }); } void MediaStream::changeDeliverPayloadType(DataPacket *dp, packetType type) { RtpHeader* h = reinterpret_cast<RtpHeader*>(dp->data); RtcpHeader *chead = reinterpret_cast<RtcpHeader*>(dp->data); if (!chead->isRtcp()) { int internalPT = h->getPayloadType(); int externalPT = internalPT; if (type == AUDIO_PACKET) { externalPT = remote_sdp_->getAudioExternalPT(internalPT); } else if (type == VIDEO_PACKET) { externalPT = remote_sdp_->getVideoExternalPT(externalPT); } if (internalPT != externalPT) { h->setPayloadType(externalPT); } } } // parses incoming payload type, replaces occurence in buf void MediaStream::parseIncomingPayloadType(char *buf, int len, packetType type) { RtcpHeader* chead = reinterpret_cast<RtcpHeader*>(buf); RtpHeader* h = reinterpret_cast<RtpHeader*>(buf); if (!chead->isRtcp()) { int externalPT = h->getPayloadType(); int internalPT = externalPT; if (type == AUDIO_PACKET) { internalPT = remote_sdp_->getAudioInternalPT(externalPT); } else if (type == VIDEO_PACKET) { internalPT = remote_sdp_->getVideoInternalPT(externalPT); } if (externalPT != internalPT) { h->setPayloadType(internalPT); } else { // ELOG_WARN("onTransportData did not find mapping for %i", externalPT); } } } void MediaStream::write(std::shared_ptr<DataPacket> packet) { if (connection_) { connection_->write(packet); } } void MediaStream::enableHandler(const std::string &name) { asyncTask([name] (std::shared_ptr<MediaStream> conn) { if (conn && conn->pipeline_) { conn->pipeline_->enable(name); } }); } void MediaStream::disableHandler(const std::string &name) { asyncTask([name] (std::shared_ptr<MediaStream> conn) { if (conn && conn->pipeline_) { conn->pipeline_->disable(name); } }); } void MediaStream::notifyUpdateToHandlers() { asyncTask([] (std::shared_ptr<MediaStream> conn) { if (conn && conn->pipeline_) { conn->pipeline_->notifyUpdate(); } }); } void MediaStream::asyncTask(std::function<void(std::shared_ptr<MediaStream>)> f) { std::weak_ptr<MediaStream> weak_this = shared_from_this(); worker_->task([weak_this, f] { if (auto this_ptr = weak_this.lock()) { f(this_ptr); } }); } void MediaStream::sendPacket(std::shared_ptr<DataPacket> p) { if (!sending_) { return; } uint32_t partial_bitrate = 0; uint64_t sentVideoBytes = 0; uint64_t lastSecondVideoBytes = 0; if (rate_control_ && !slide_show_mode_) { if (p->type == VIDEO_PACKET) { if (rate_control_ == 1) { return; } now_ = clock::now(); if ((now_ - mark_) >= kBitrateControlPeriod) { mark_ = now_; lastSecondVideoBytes = sentVideoBytes; } partial_bitrate = ((sentVideoBytes - lastSecondVideoBytes) * 8) * 10; if (partial_bitrate > this->rate_control_) { return; } sentVideoBytes += p->length; } } if (!pipeline_initialized_) { ELOG_DEBUG("%s message: Pipeline not initialized yet.", toLog()); return; } if (pipeline_) { pipeline_->write(std::move(p)); } } void MediaStream::setQualityLayer(int spatial_layer, int temporal_layer) { asyncTask([spatial_layer, temporal_layer] (std::shared_ptr<MediaStream> media_stream) { media_stream->quality_manager_->forceLayers(spatial_layer, temporal_layer); }); } void MediaStream::setMinDesiredSpatialLayer(int spatial_layer) { asyncTask([spatial_layer] (std::shared_ptr<MediaStream> media_stream) { media_stream->quality_manager_->setMinDesiredSpatialLayer(spatial_layer); }); } } // namespace erizo
#include <curses.h> #include <chrono> #include <string> #include <thread> #include <vector> #include "format.h" #include "ncurses_display.h" #include "system.h" using std::string; using std::to_string; // 50 bars uniformly displayed from 0 - 100 % // 2% is one bar(|) std::string NCursesDisplay::ProgressBar(float percent) { std::string result{"0%"}; int size{50}; float bars{percent * size}; for (int i{0}; i < size; ++i) { result += i <= bars ? '|' : ' '; } string display{to_string(percent * 100).substr(0, 4)}; if (percent < 0.1 || percent == 1.0) display = " " + to_string(percent * 100).substr(0, 3); return result + " " + display + "/100%"; } void NCursesDisplay::DisplaySystem(System& system, WINDOW* window) { int row{0}; mvwprintw(window, ++row, 2, ("OS: " + system.OperatingSystem()).c_str()); mvwprintw(window, ++row, 2, ("Kernel: " + system.Kernel()).c_str()); mvwprintw(window, ++row, 2, "CPU: "); wattron(window, COLOR_PAIR(1)); mvwprintw(window, row, 10, ""); wprintw(window, ProgressBar(system.Cpu().Utilization()).c_str()); wattroff(window, COLOR_PAIR(1)); mvwprintw(window, ++row, 2, "Memory: "); wattron(window, COLOR_PAIR(1)); mvwprintw(window, row, 10, ""); wprintw(window, ProgressBar(system.MemoryUtilization()).c_str()); wattroff(window, COLOR_PAIR(1)); mvwprintw(window, ++row, 2, ("Total Processes: " + to_string(system.TotalProcesses())).c_str()); mvwprintw( window, ++row, 2, ("Running Processes: " + to_string(system.RunningProcesses())).c_str()); mvwprintw(window, ++row, 2, ("Up Time: " + Format::ElapsedTime(system.UpTime())).c_str()); wrefresh(window); } void NCursesDisplay::DisplayProcesses(std::vector<Process>& processes, WINDOW* window, int n) { int row{0}; int const pid_column{2}; int const user_column{9}; int const cpu_column{16}; int const ram_column{26}; int const time_column{35}; int const command_column{46}; wattron(window, COLOR_PAIR(2)); mvwprintw(window, ++row, pid_column, "PID"); mvwprintw(window, row, user_column, "USER"); mvwprintw(window, row, cpu_column, "CPU[%%]"); mvwprintw(window, row, ram_column, "RAM[MB]"); mvwprintw(window, row, time_column, "TIME+"); mvwprintw(window, row, command_column, "COMMAND"); wattroff(window, COLOR_PAIR(2)); for (int i = 0; i < n; ++i) { mvwprintw(window, ++row, pid_column, to_string(processes[i].Pid()).c_str()); mvwprintw(window, row, user_column, processes[i].User().c_str()); float cpu = processes[i].CpuUtilization() * 100; mvwprintw(window, row, cpu_column, to_string(cpu).substr(0, 4).c_str()); mvwprintw(window, row, ram_column, processes[i].Ram().c_str()); mvwprintw(window, row, time_column, Format::ElapsedTime(processes[i].UpTime()).c_str()); mvwprintw(window, row, command_column, processes[i].Command().substr(0, window->_maxx - 46).c_str()); } } void NCursesDisplay::Display(System& system, int n) { initscr(); // start ncurses noecho(); // do not print input values cbreak(); // terminate ncurses on ctrl + c start_color(); // enable color int x_max{getmaxx(stdscr)}; WINDOW* system_window = newwin(9, x_max - 1, 0, 0); WINDOW* process_window = newwin(3 + n, x_max - 1, system_window->_maxy + 1, 0); while (1) { init_pair(1, COLOR_BLUE, COLOR_BLACK); init_pair(2, COLOR_GREEN, COLOR_BLACK); box(system_window, 0, 0); box(process_window, 0, 0); DisplaySystem(system, system_window); DisplayProcesses(system.Processes(), process_window, n); wrefresh(system_window); wrefresh(process_window); refresh(); std::this_thread::sleep_for(std::chrono::seconds(1)); } endwin(); }
/* Author: Manuel Bonilla This code implements a simulator for a robot UR10. However it is parameterized to be used in all mUR models */ #include "hw_mb/robot_definition.h" float curr_time; float desired_time_for_traj; hw_mb::JointPoseRef des_refs; std::vector<float> position; void cbJointStates(const sensor_msgs::JointState::ConstPtr &msg) { for (int i = 0; i < 6; ++i) { position[i] = msg->position[i]; } } void cbMovementCompleted(const std_msgs::Bool::ConstPtr &msg) { //compare time float thresh_time =0.2; if(curr_time < desired_time_for_traj - thresh_time) { ROS_INFO("Time running: %f", curr_time) ; return; } if(msg->data ) { //check for time and positions //check if successful in the desired time; if((curr_time > (desired_time_for_traj - thresh_time)) && (curr_time < (desired_time_for_traj + thresh_time))) { float err = 0.0; for (int i = 0; i < 6; ++i) { err+= position[i]-1.0; } if(err < 0.4) ROS_INFO("Test successfull :)"); return; } } ROS_INFO("Test unsuccessfull :( Time was: %f", curr_time) ; // decide if test is ok or not; } int main(int argc, char** argv) { ros::init(argc, argv, "test"); ros::NodeHandle n; int rate = 10; ros::Rate loop_rate(rate); ros::Subscriber sub_robot_on_target; ros::Publisher pub_des_joint_states; desired_time_for_traj = 5.0; //position = std::vector<float>(6,0.0); position.resize(6); des_refs.q1 = 1.0; des_refs.q2 = 1.0; des_refs.q3 = 1.0; des_refs.q4 = 1.0; des_refs.q5 = 1.0; des_refs.q6 = 1.0; des_refs.time_exec = desired_time_for_traj; pub_des_joint_states = n.advertise<hw_mb::JointPoseRef>("/moveToJointRef", 250); sub_robot_on_target = n.subscribe("/movement_completed", 250, cbMovementCompleted); ros::spinOnce(); //take ros time ros::Duration(1.0).sleep(); pub_des_joint_states.publish(des_refs); curr_time =0.0; while (ros::ok()) { ros::spinOnce(); curr_time+=1.0/rate; loop_rate.sleep(); } return 0; }
// Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * 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. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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 COPYRIGHT OWNER OR // 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. #include "src/clients/python/library/tritonclient/utils/shared_memory/shared_memory.h" #include <errno.h> #include <fcntl.h> #include <sys/mman.h> #include <unistd.h> #include <cstring> #include <iostream> #include "src/clients/python/library/tritonclient/utils/shared_memory/shared_memory_handle.h" //============================================================================== // SharedMemoryControlContext namespace { void* SharedMemoryHandleCreate( std::string triton_shm_name, void* shm_addr, std::string shm_key, int shm_fd, size_t offset, size_t byte_size) { SharedMemoryHandle* handle = new SharedMemoryHandle(); handle->triton_shm_name_ = triton_shm_name; handle->base_addr_ = shm_addr; handle->shm_key_ = shm_key; handle->shm_fd_ = shm_fd; handle->offset_ = offset; handle->byte_size_ = byte_size; return reinterpret_cast<void*>(handle); } int SharedMemoryRegionMap( int shm_fd, size_t offset, size_t byte_size, void** shm_addr) { // map shared memory to process address space *shm_addr = mmap(NULL, byte_size, PROT_WRITE, MAP_SHARED, shm_fd, offset); if (*shm_addr == MAP_FAILED) { return -1; } // close shared memory descriptor, return 0 if success else return -1 return close(shm_fd); } } // namespace int SharedMemoryRegionCreate( const char* triton_shm_name, const char* shm_key, size_t byte_size, void** shm_handle) { // get shared memory region descriptor int shm_fd = shm_open(shm_key, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); if (shm_fd == -1) { return -2; } // extend shared memory object as by default it's initialized with size 0 int res = ftruncate(shm_fd, byte_size); if (res == -1) { return -3; } // get base address of shared memory region void* shm_addr = nullptr; int err = SharedMemoryRegionMap(shm_fd, 0, byte_size, &shm_addr); if (err == -1) { return -4; } // create a handle for the shared memory region *shm_handle = SharedMemoryHandleCreate( std::string(triton_shm_name), shm_addr, std::string(shm_key), shm_fd, 0, byte_size); return 0; } int SharedMemoryRegionSet( void* shm_handle, size_t offset, size_t byte_size, const void* data) { void* shm_addr = reinterpret_cast<SharedMemoryHandle*>(shm_handle)->base_addr_; char* shm_addr_offset = reinterpret_cast<char*>(shm_addr); std::memcpy(shm_addr_offset + offset, data, byte_size); return 0; } int GetSharedMemoryHandleInfo( void* shm_handle, char** shm_addr, const char** shm_key, int* shm_fd, size_t* offset, size_t* byte_size) { SharedMemoryHandle* handle = reinterpret_cast<SharedMemoryHandle*>(shm_handle); *shm_addr = reinterpret_cast<char*>(handle->base_addr_); *shm_key = handle->shm_key_.c_str(); *shm_fd = handle->shm_fd_; *offset = handle->offset_; *byte_size = handle->byte_size_; return 0; } int SharedMemoryRegionDestroy(void* shm_handle) { std::string shm_key = reinterpret_cast<SharedMemoryHandle*>(shm_handle)->shm_key_; int shm_fd = shm_unlink(shm_key.c_str()); if (shm_fd == -1) { return -5; } return 0; } //==============================================================================
/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "rtp_sender_h264.h" #include "rtp_utility.h" namespace webrtc { RTPSenderH264::RTPSenderH264(RTPSenderInterface* rtpSender) : // H264 _rtpSender(*rtpSender), _h264Mode(H264_SINGLE_NAL_MODE), _h264SendPPS_SPS(true), _h264SVCPayloadType(-1), _h264SVCRelaySequenceNumber(0), _h264SVCRelayTimeStamp(0), _h264SVCRelayLayerComplete(false), _useHighestSendLayer(false), _highestDependencyLayerOld(MAX_NUMBER_OF_TEMPORAL_ID-1), _highestDependencyQualityIDOld(MAX_NUMBER_OF_DEPENDENCY_QUALITY_ID-1), _highestDependencyLayer(0), _highestDependencyQualityID(0), _highestTemporalLayer(0) { } RTPSenderH264::~RTPSenderH264() { } WebRtc_Word32 RTPSenderH264::Init() { _h264SendPPS_SPS = true; _h264Mode = H264_SINGLE_NAL_MODE; return 0; } /* multi-session 3 modes supported NI-T timestamps NI-TC timestamps/CS-DON NI-C CS-DON Non-interleaved timestamp based mode (NI-T) Non-interleaved cross-session decoding order number (CS-DON) based mode (NI-C) Non-interleaved combined timestamp and CS-DON mode (NI-TC) NOT supported Interleaved CS-DON (I-C) mode. NI-T and NI-TC modes both use timestamps to recover the decoding order. In order to be able to do so, it is necessary for the RTP packet stream to contain data for all sampling instances of a given RTP session in all enhancement RTP sessions that depend on the given RTP session. The NI-C and I-C modes do not have this limitation, and use the CS-DON values as a means to explicitly indicate decoding order, either directly coded in PACSI NAL units, or inferred from them using the packetization rules. It is noted that the NI-TC mode offers both alternatives and it is up to the receiver to select which one to use. */ bool RTPSenderH264::AddH264SVCNALUHeader(const H264_SVC_NALUHeader& svc, WebRtc_UWord8* databuffer, WebRtc_Word32& curByte) const { // +---------------+---------------+---------------+ // |0|1|2|3|4|5|6|7|0|1|2|3|4|5|6|7|0|1|2|3|4|5|6|7| // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // |R|I| PRID |N| DID | QID | TID |U|D|O| RR| // +---------------+---------------+---------------+ // R - Reserved for future extensions (MUST be 1). Receivers SHOULD ignore the value of R. // I - Is layer representation an IDR layer (1) or not (0). // PRID - Priority identifier for the NAL unit. // N - Specifies whether inter-layer prediction may be used for decoding the coded slice (1) or not (0). // DID - Indicates the WebRtc_Word32er-layer coding dependency level of a layer representation. // QID - Indicates the quality level of an MGS layer representation. // TID - Indicates the temporal level of a layer representation. // U - Use only reference base pictures during the WebRtc_Word32er prediction process (1) or not (0). // D - Discardable flag. // O - Output_flag. Affects the decoded picture output process as defined in Annex C of [H.264]. // RR - Reserved_three_2bits (MUST be '11'). Receivers SHOULD ignore the value of RR. // Add header data databuffer[curByte++] = (svc.r << 7) + (svc.idr << 6) + (svc.priorityID & 0x3F); databuffer[curByte++] = (svc.interLayerPred << 7) + (svc.dependencyID << 4) + (svc.qualityID & 0x0F); databuffer[curByte++] = (svc.temporalID << 5) + (svc.useRefBasePic << 4) + (svc.discardable << 3) + (svc.output << 2) + (svc.rr & 0x03); return true; } WebRtc_Word32 RTPSenderH264::AddH264PACSINALU(const bool firstPacketInNALU, const bool lastPacketInNALU, const H264_PACSI_NALU& pacsi, const H264_SVC_NALUHeader& svc, const WebRtc_UWord16 DONC, WebRtc_UWord8* databuffer, WebRtc_Word32& curByte) const { // 0 1 2 3 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // |F|NRI|Type(30) | SVC NAL unit header | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // |X|Y|T|A|P|C|S|E| TL0PICIDX (o.)| IDRPICID (o.) | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | DONC (o.) | NAL unit size 1 | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | | // | SEI NAL unit 1 | // | | // | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | | NAL unit size 2 | | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | // | | // | SEI NAL unit 2 | // | +-+-+-+-+-+-+-+-+-+-+ // | | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // If present, MUST be first NAL unit in aggregation packet + there MUST be at least // one additional unit in the same packet! The RTPHeader and payload header are set as if the 2nd NAL unit // (first non-PACSI NAL unit) is encapsulated in the same packet. // contains scalability info common for all remaining NAL units. // todo add API to configure this required for multisession const bool addDONC = false; if (svc.length == 0 || pacsi.NALlength == 0) { return 0; } WebRtc_Word32 startByte = curByte; // NAL unit header databuffer[curByte++] = 30; // NRI will be added later // Extended SVC header AddH264SVCNALUHeader(svc, databuffer, curByte); // Flags databuffer[curByte++] = (pacsi.X << 7) + (pacsi.Y << 6) + (addDONC << 5) + (pacsi.A << 4) + (pacsi.P << 3) + (pacsi.C << 2) + firstPacketInNALU?(pacsi.S << 1):0 + lastPacketInNALU?(pacsi.E):0; // Optional fields if (pacsi.Y) { databuffer[curByte++] = pacsi.TL0picIDx; databuffer[curByte++] = (WebRtc_UWord8)(pacsi.IDRpicID >> 8); databuffer[curByte++] = (WebRtc_UWord8)(pacsi.IDRpicID); } // Decoding order number if (addDONC) // pacsi.T { databuffer[curByte++] = (WebRtc_UWord8)(DONC >> 8); databuffer[curByte++] = (WebRtc_UWord8)(DONC); } // SEI NALU if(firstPacketInNALU) // IMPROVEMENT duplicate it to make sure it arrives... { // we only set this for NALU 0 to make sure we send it only once per frame for (WebRtc_UWord32 i = 0; i < pacsi.numSEINALUs; i++) { // NALU size databuffer[curByte++] = (WebRtc_UWord8)(pacsi.seiMessageLength[i] >> 8); databuffer[curByte++] = (WebRtc_UWord8)(pacsi.seiMessageLength[i]); // NALU data memcpy(databuffer + curByte, pacsi.seiMessageData[i], pacsi.seiMessageLength[i]); curByte += pacsi.seiMessageLength[i]; } } return curByte - startByte; } WebRtc_Word32 RTPSenderH264::SetH264RelaySequenceNumber(const WebRtc_UWord16 seqNum) { _h264SVCRelaySequenceNumber = seqNum; return 0; } WebRtc_Word32 RTPSenderH264::SetH264RelayCompleteLayer(const bool complete) { _h264SVCRelayLayerComplete = complete; return 0; } /* 12 Filler data The only restriction of filler data NAL units within an access unit is that they shall not precede the first VCL NAL unit with the same access unit. */ WebRtc_Word32 RTPSenderH264::SendH264FillerData(const WebRtcRTPHeader* rtpHeader, const WebRtc_UWord16 bytesToSend, const WebRtc_UWord32 ssrc) { WebRtc_UWord16 fillerLength = bytesToSend - 12 - 1; if (fillerLength > WEBRTC_IP_PACKET_SIZE - 12 - 1) { return 0; } if (fillerLength == 0) { // do not send an empty packet, will not reach JB fillerLength = 1; } // send codec valid data, H.264 has defined data which is binary 1111111 WebRtc_UWord8 dataBuffer[WEBRTC_IP_PACKET_SIZE]; dataBuffer[0] = static_cast<WebRtc_UWord8>(0x80); // version 2 dataBuffer[1] = rtpHeader->header.payloadType; ModuleRTPUtility::AssignUWord16ToBuffer(dataBuffer+2, _rtpSender.IncrementSequenceNumber()); // get the current SequenceNumber and add by 1 after returning ModuleRTPUtility::AssignUWord32ToBuffer(dataBuffer+4, rtpHeader->header.timestamp); ModuleRTPUtility::AssignUWord32ToBuffer(dataBuffer+8, rtpHeader->header.ssrc); // set filler NALU type dataBuffer[12] = 12; // NRI field = 0, type 12 // fill with 0xff memset(dataBuffer + 12 + 1, 0xff, fillerLength); return _rtpSender.SendToNetwork(dataBuffer, fillerLength, 12 + 1); } WebRtc_Word32 RTPSenderH264::SendH264FillerData(const WebRtc_UWord32 captureTimestamp, const WebRtc_UWord8 payloadType, const WebRtc_UWord32 bytes ) { const WebRtc_UWord16 rtpHeaderLength = _rtpSender.RTPHeaderLength(); WebRtc_UWord16 maxLength = _rtpSender.MaxPayloadLength() - FECPacketOverhead() - _rtpSender.RTPHeaderLength(); WebRtc_Word32 bytesToSend=bytes; WebRtc_UWord16 fillerLength=0; WebRtc_UWord8 dataBuffer[WEBRTC_IP_PACKET_SIZE]; while(bytesToSend>0) { fillerLength=maxLength; if(fillerLength<maxLength) { fillerLength = (WebRtc_UWord16) bytesToSend; } bytesToSend-=fillerLength; if (fillerLength > WEBRTC_IP_PACKET_SIZE - 12 - 1) { return 0; } if (fillerLength == 0) { // do not send an empty packet, will not reach JB fillerLength = 1; } // send paded data // correct seq num, time stamp and payloadtype _rtpSender.BuildRTPheader(dataBuffer, payloadType, false,captureTimestamp, true, true); // set filler NALU type dataBuffer[12] = 12; // NRI field = 0, type 12 // send codec valid data, H.264 has defined data which is binary 1111111 // fill with 0xff memset(dataBuffer + 12 + 1, 0xff, fillerLength-1); if( _rtpSender.SendToNetwork(dataBuffer, fillerLength, 12)<0) { return -1;; } } return 0; } WebRtc_Word32 RTPSenderH264::SendH264SVCRelayPacket(const WebRtcRTPHeader* rtpHeader, const WebRtc_UWord8* incomingRTPPacket, const WebRtc_UWord16 incomingRTPPacketSize, const WebRtc_UWord32 ssrc, const bool higestLayer) { if (rtpHeader->header.sequenceNumber != (WebRtc_UWord16)(_h264SVCRelaySequenceNumber + 1)) { // not continous, signal loss _rtpSender.IncrementSequenceNumber(); } _h264SVCRelaySequenceNumber = rtpHeader->header.sequenceNumber; if (rtpHeader->header.timestamp != _h264SVCRelayTimeStamp) { // new frame _h264SVCRelayLayerComplete = false; } if (rtpHeader->header.timestamp == _h264SVCRelayTimeStamp && _h264SVCRelayLayerComplete) { // sanity, end of layer already sent // Could happened for fragmented packet with missing PACSI info (PACSI packet reorded and received after packet it belongs to) // fragmented packet has no layer info set (default info 0) return 0; } _h264SVCRelayTimeStamp = rtpHeader->header.timestamp; // re-packetize H.264-SVC packets // we keep the timestap unchanged // make a copy and only change the SSRC and seqNum WebRtc_UWord8 dataBuffer[WEBRTC_IP_PACKET_SIZE]; memcpy(dataBuffer, incomingRTPPacket, incomingRTPPacketSize); // _sequenceNumber initiated in Init() // _ssrc initiated in constructor // re-write payload type if(_h264SVCPayloadType != -1) { dataBuffer[1] &= kRtpMarkerBitMask; dataBuffer[1] += _h264SVCPayloadType; } // _sequenceNumber will not work for re-ordering by NACK from original sender // engine responsible for this ModuleRTPUtility::AssignUWord16ToBuffer(dataBuffer+2, _rtpSender.IncrementSequenceNumber()); // get the current SequenceNumber and add by 1 after returning //ModuleRTPUtility::AssignUWord32ToBuffer(dataBuffer+8, ssrc); // how do we know it's the last relayed packet in a frame? // 1) packets arrive in order, the engine manages that // 2) highest layer that we relay // 3) the end bit is set for the highest layer if(higestLayer && rtpHeader->type.Video.codecHeader.H264.relayE) { // set marker bit dataBuffer[1] |= kRtpMarkerBitMask; // set relayed layer as complete _h264SVCRelayLayerComplete = true; } return _rtpSender.SendToNetwork(dataBuffer, incomingRTPPacketSize - rtpHeader->header.headerLength, rtpHeader->header.headerLength); } WebRtc_Word32 RTPSenderH264::SendH264_STAP_A(const FrameType frameType, const H264Info* ptrH264Info, WebRtc_UWord16 &idxNALU, const WebRtc_Word8 payloadType, const WebRtc_UWord32 captureTimeStamp, bool& switchToFUA, WebRtc_Word32 &payloadBytesToSend, const WebRtc_UWord8*& data, const WebRtc_UWord16 rtpHeaderLength) { const WebRtc_Word32 H264_NALU_LENGTH = 2; WebRtc_UWord16 h264HeaderLength = 1; // normal header length WebRtc_UWord16 maxPayloadLengthSTAP_A = _rtpSender.MaxPayloadLength() - FECPacketOverhead() - rtpHeaderLength - h264HeaderLength - H264_NALU_LENGTH; WebRtc_Word32 dataOffset = rtpHeaderLength + h264HeaderLength; WebRtc_UWord8 NRI = 0; WebRtc_UWord16 payloadBytesInPacket = 0; WebRtc_UWord8 dataBuffer[WEBRTC_IP_PACKET_SIZE]; if (ptrH264Info->payloadSize[idxNALU] > maxPayloadLengthSTAP_A) { // we need to fragment NAL switch to mode FU-A switchToFUA = true; } else { // combine as many NAL units in every IP packet do { if(!_h264SendPPS_SPS) { // don't send NALU of type 7 and 8 SPS and PPS if(ptrH264Info->type[idxNALU] == 7 || ptrH264Info->type[idxNALU] == 8) { payloadBytesToSend -= ptrH264Info->payloadSize[idxNALU] + ptrH264Info->startCodeSize[idxNALU]; data += ptrH264Info->payloadSize[idxNALU] + ptrH264Info->startCodeSize[idxNALU]; idxNALU++; continue; } } if(ptrH264Info->payloadSize[idxNALU] + payloadBytesInPacket <= maxPayloadLengthSTAP_A) { if(ptrH264Info->NRI[idxNALU] > NRI) { NRI = ptrH264Info->NRI[idxNALU]; } // put NAL size into packet dataBuffer[dataOffset] = (WebRtc_UWord8)(ptrH264Info->payloadSize[idxNALU] >> 8); dataOffset++; dataBuffer[dataOffset] = (WebRtc_UWord8)(ptrH264Info->payloadSize[idxNALU] & 0xff); dataOffset++; // Put payload in packet memcpy(&dataBuffer[dataOffset], &data[ptrH264Info->startCodeSize[idxNALU]], ptrH264Info->payloadSize[idxNALU]); dataOffset += ptrH264Info->payloadSize[idxNALU]; data += ptrH264Info->payloadSize[idxNALU] + ptrH264Info->startCodeSize[idxNALU]; payloadBytesInPacket += (WebRtc_UWord16)(ptrH264Info->payloadSize[idxNALU] + H264_NALU_LENGTH); payloadBytesToSend -= ptrH264Info->payloadSize[idxNALU] + ptrH264Info->startCodeSize[idxNALU]; } else { // we don't fitt the next NALU in this packet break; } idxNALU++; }while(payloadBytesToSend); } // sanity // don't send empty packets if (payloadBytesInPacket) { // add RTP header _rtpSender.BuildRTPheader(dataBuffer, payloadType, (payloadBytesToSend==0)?true:false, captureTimeStamp); dataBuffer[rtpHeaderLength] = 24 + NRI; // STAP-A == 24 WebRtc_UWord16 payloadLength = payloadBytesInPacket + h264HeaderLength; if(-1 == SendVideoPacket(frameType, dataBuffer, payloadLength, rtpHeaderLength)) { return -1; } } return 0; } // end STAP-A // STAP-A for H.264 SVC WebRtc_Word32 RTPSenderH264::SendH264_STAP_A_PACSI(const FrameType frameType, const H264Info* ptrH264Info, WebRtc_UWord16 &idxNALU, const WebRtc_Word8 payloadType, const WebRtc_UWord32 captureTimeStamp, bool& switchToFUA, WebRtc_Word32 &payloadBytesToSend, const WebRtc_UWord8*& data, const WebRtc_UWord16 rtpHeaderLength, WebRtc_UWord16& decodingOrderNumber) { const WebRtc_Word32 H264_NALU_LENGTH = 2; WebRtc_UWord16 h264HeaderLength = 1; // normal header length WebRtc_UWord16 maxPayloadLengthSTAP_A = _rtpSender.MaxPayloadLength() - FECPacketOverhead() - rtpHeaderLength - h264HeaderLength - H264_NALU_LENGTH; WebRtc_Word32 dataOffset = rtpHeaderLength + h264HeaderLength; WebRtc_UWord8 NRI = 0; WebRtc_UWord16 payloadBytesInPacket = 0; WebRtc_UWord8 dataBuffer[WEBRTC_IP_PACKET_SIZE]; bool firstNALUNotIDR = true; //delta // Put PACSI NAL unit into packet WebRtc_Word32 lengthPACSI = 0; WebRtc_UWord32 PACSI_NALlength = ptrH264Info->PACSI[idxNALU].NALlength; if (PACSI_NALlength > maxPayloadLengthSTAP_A) { return -1; } dataBuffer[dataOffset++] = (WebRtc_UWord8)(PACSI_NALlength >> 8); dataBuffer[dataOffset++] = (WebRtc_UWord8)(PACSI_NALlength & 0xff); // end bit will be updated later, since another NALU in this packet might be the last WebRtc_Word32 lengthPASCINALU = AddH264PACSINALU(true, false, ptrH264Info->PACSI[idxNALU], ptrH264Info->SVCheader[idxNALU], decodingOrderNumber, dataBuffer, dataOffset); if (lengthPASCINALU <= 0) { return -1; } decodingOrderNumber++; lengthPACSI = H264_NALU_LENGTH + lengthPASCINALU; maxPayloadLengthSTAP_A -= (WebRtc_UWord16)lengthPACSI; if (ptrH264Info->payloadSize[idxNALU] > maxPayloadLengthSTAP_A) { // we need to fragment NAL switch to mode FU-A switchToFUA = true; return 0; } if(!ptrH264Info->SVCheader[idxNALU].idr) { firstNALUNotIDR = true; } WebRtc_UWord32 layer = (ptrH264Info->SVCheader[idxNALU].dependencyID << 16)+ (ptrH264Info->SVCheader[idxNALU].qualityID << 8) + ptrH264Info->SVCheader[idxNALU].temporalID; { // combine as many NAL units in every IP packet, with the same priorityID // Improvement we could allow several very small MGS NALU from different layers to be sent in one packet do { if(!_h264SendPPS_SPS) { // Don't send NALU of type 7 and 8 SPS and PPS, // they could be signaled outofband if(ptrH264Info->type[idxNALU] == 7 || ptrH264Info->type[idxNALU] == 8) { payloadBytesToSend -= ptrH264Info->payloadSize[idxNALU] + ptrH264Info->startCodeSize[idxNALU]; data += ptrH264Info->payloadSize[idxNALU] + ptrH264Info->startCodeSize[idxNALU]; idxNALU++; continue; } } // don't send NALU type 6 (SEI message) not allowed when we send it in PACSI if(ptrH264Info->type[idxNALU] == 6) { // SEI NALU Don't send, not allowed when we send it in PACSI payloadBytesToSend -= ptrH264Info->payloadSize[idxNALU] + ptrH264Info->startCodeSize[idxNALU]; data += ptrH264Info->payloadSize[idxNALU] + ptrH264Info->startCodeSize[idxNALU]; idxNALU++; continue; } const WebRtc_UWord32 layerNALU = (ptrH264Info->SVCheader[idxNALU].dependencyID << 16)+ (ptrH264Info->SVCheader[idxNALU].qualityID << 8) + ptrH264Info->SVCheader[idxNALU].temporalID; // we need to break on a new layer if( ptrH264Info->payloadSize[idxNALU] + payloadBytesInPacket <= maxPayloadLengthSTAP_A && layerNALU == layer) { if(ptrH264Info->NRI[idxNALU] > NRI) { NRI = ptrH264Info->NRI[idxNALU]; } // put NAL size into packet dataBuffer[dataOffset] = (WebRtc_UWord8)(ptrH264Info->payloadSize[idxNALU] >> 8); dataOffset++; dataBuffer[dataOffset] = (WebRtc_UWord8)(ptrH264Info->payloadSize[idxNALU] & 0xff); dataOffset++; // Put payload in packet memcpy(&dataBuffer[dataOffset], &data[ptrH264Info->startCodeSize[idxNALU]], ptrH264Info->payloadSize[idxNALU]); dataOffset += ptrH264Info->payloadSize[idxNALU]; data += ptrH264Info->payloadSize[idxNALU] + ptrH264Info->startCodeSize[idxNALU]; payloadBytesInPacket += (WebRtc_UWord16)(ptrH264Info->payloadSize[idxNALU] + H264_NALU_LENGTH); payloadBytesToSend -= ptrH264Info->payloadSize[idxNALU] + ptrH264Info->startCodeSize[idxNALU]; } else { // we don't fitt the next NALU in this packet or, // it's the next layer // check if we should send this NALU // based on the layer if(_useHighestSendLayer && layerNALU != layer) { // we don't send this NALU due to it's a new layer // check if we should send the next or if this is the last const WebRtc_UWord8 dependencyQualityID = (ptrH264Info->SVCheader[idxNALU].dependencyID << 4) + ptrH264Info->SVCheader[idxNALU].qualityID; bool highestLayer; if(SendH264SVCLayer(frameType, ptrH264Info->SVCheader[idxNALU].temporalID, dependencyQualityID, highestLayer) == false) { // will trigger markerbit and stop sending this frame payloadBytesToSend = 0; } } break; } idxNALU++; }while(payloadBytesToSend); } // sanity, don't send empty packets if (payloadBytesInPacket) { // add RTP header _rtpSender.BuildRTPheader(dataBuffer, payloadType, (payloadBytesToSend==0)?true:false, captureTimeStamp); dataBuffer[rtpHeaderLength] = 24 + NRI; // STAP-A == 24 // NRI for PACSI dataBuffer[rtpHeaderLength + H264_NALU_LENGTH + 1] &= 0x1f; // zero out NRI field dataBuffer[rtpHeaderLength + H264_NALU_LENGTH + 1] |= NRI; if(ptrH264Info->PACSI[idxNALU-1].E) { // update end bit dataBuffer[rtpHeaderLength + H264_NALU_LENGTH + 5] |= 0x01; } if(firstNALUNotIDR) { // we have to check if any of the NALU in this packet is an IDR NALU bool setIBit = false; for(int i = 0; i < idxNALU; i++) { if(ptrH264Info->SVCheader[i].idr) { setIBit = true; break; } } if(setIBit) { // update I bit dataBuffer[rtpHeaderLength + H264_NALU_LENGTH + 2] |= 0x40; } } const WebRtc_UWord16 payloadLength = payloadBytesInPacket + h264HeaderLength + (WebRtc_UWord16)lengthPACSI; if(-1 == SendVideoPacket(frameType, dataBuffer, payloadLength, rtpHeaderLength, layer==0)) { return -1; } } return 0; } // end STAP-A WebRtc_Word32 RTPSenderH264::SendH264_FU_A(const FrameType frameType, const H264Info* ptrH264Info, WebRtc_UWord16 &idxNALU, const WebRtc_Word8 payloadType, const WebRtc_UWord32 captureTimeStamp, WebRtc_Word32 &payloadBytesToSend, const WebRtc_UWord8*& data, const WebRtc_UWord16 rtpHeaderLength, WebRtc_UWord16& decodingOrderNumber, const bool sendSVCPACSI) { // FUA for the rest of the frame WebRtc_UWord16 maxPayloadLength = _rtpSender.MaxPayloadLength() - FECPacketOverhead() - rtpHeaderLength; WebRtc_UWord8 dataBuffer[WEBRTC_IP_PACKET_SIZE]; WebRtc_UWord32 payloadBytesRemainingInNALU = ptrH264Info->payloadSize[idxNALU]; bool isBaseLayer=false; if(payloadBytesRemainingInNALU > maxPayloadLength) { // we need to fragment NALU const WebRtc_UWord16 H264_FUA_LENGTH = 2; // FU-a H.264 header is 2 bytes if(sendSVCPACSI) { SendH264_SinglePACSI(frameType, ptrH264Info, idxNALU, payloadType, captureTimeStamp, true, false); WebRtc_UWord32 layer = (ptrH264Info->SVCheader[idxNALU].dependencyID << 16)+ (ptrH264Info->SVCheader[idxNALU].qualityID << 8) + ptrH264Info->SVCheader[idxNALU].temporalID; isBaseLayer=(layer==0); } // First packet _rtpSender.BuildRTPheader(dataBuffer,payloadType, false, captureTimeStamp); WebRtc_UWord16 maxPayloadLengthFU_A = maxPayloadLength - H264_FUA_LENGTH ; WebRtc_UWord8 fuaIndc = 28 + ptrH264Info->NRI[idxNALU]; dataBuffer[rtpHeaderLength] = fuaIndc; // FU-A indicator dataBuffer[rtpHeaderLength+1] = (WebRtc_UWord8)(ptrH264Info->type[idxNALU] + 0x80)/*start*/; // FU-A header memcpy(&dataBuffer[rtpHeaderLength + H264_FUA_LENGTH], &data[ptrH264Info->startCodeSize[idxNALU]+1], maxPayloadLengthFU_A); WebRtc_UWord16 payloadLength = maxPayloadLengthFU_A + H264_FUA_LENGTH; if(-1 == SendVideoPacket(frameType, dataBuffer, payloadLength, rtpHeaderLength, isBaseLayer)) { return -1; } //+1 is from the type that is coded into the FU-a header data += maxPayloadLengthFU_A + 1 + ptrH264Info->startCodeSize[idxNALU]; // inc data ptr payloadBytesToSend -= maxPayloadLengthFU_A+1+ptrH264Info->startCodeSize[idxNALU]; payloadBytesRemainingInNALU -= maxPayloadLengthFU_A+1; // all non first/last packets while(payloadBytesRemainingInNALU > maxPayloadLengthFU_A) { if(sendSVCPACSI) { SendH264_SinglePACSI(frameType, ptrH264Info, idxNALU, payloadType, captureTimeStamp, false, false); } // prepare next header _rtpSender.BuildRTPheader(dataBuffer, payloadType, false, captureTimeStamp); dataBuffer[rtpHeaderLength] = (WebRtc_UWord8)fuaIndc; // FU-A indicator dataBuffer[rtpHeaderLength+1] = ptrH264Info->type[idxNALU]; // FU-A header memcpy(&dataBuffer[rtpHeaderLength+H264_FUA_LENGTH], data, maxPayloadLengthFU_A); payloadLength = maxPayloadLengthFU_A + H264_FUA_LENGTH; if(-1 == SendVideoPacket(frameType, dataBuffer, payloadLength, rtpHeaderLength,isBaseLayer)) { return -1; } data += maxPayloadLengthFU_A; // inc data ptr payloadBytesToSend -= maxPayloadLengthFU_A; payloadBytesRemainingInNALU -= maxPayloadLengthFU_A; dataBuffer[rtpHeaderLength] = fuaIndc; // FU-A indicator dataBuffer[rtpHeaderLength+1] = ptrH264Info->type[idxNALU]; // FU-A header } if(sendSVCPACSI) { SendH264_SinglePACSI(frameType, ptrH264Info, idxNALU, payloadType, captureTimeStamp, false, true); // last packet in NALU if(_useHighestSendLayer && idxNALU+1 < ptrH264Info->numNALUs) { // not last NALU in frame // check if it's the the next layer should not be sent // check if we should send the next or if this is the last const WebRtc_UWord8 dependencyQualityID = (ptrH264Info->SVCheader[idxNALU+1].dependencyID << 4) + ptrH264Info->SVCheader[idxNALU+1].qualityID; bool highestLayer; if(SendH264SVCLayer(frameType, ptrH264Info->SVCheader[idxNALU+1].temporalID, dependencyQualityID, highestLayer) == false) { // will trigger markerbit and stop sending this frame payloadBytesToSend = payloadBytesRemainingInNALU; } } } // last packet in NALU _rtpSender.BuildRTPheader(dataBuffer, payloadType,(payloadBytesToSend == (WebRtc_Word32)payloadBytesRemainingInNALU)?true:false, captureTimeStamp); dataBuffer[rtpHeaderLength+1] = ptrH264Info->type[idxNALU] + 0x40/*stop*/; // FU-A header memcpy(&dataBuffer[rtpHeaderLength+H264_FUA_LENGTH], data, payloadBytesRemainingInNALU); payloadLength = (WebRtc_UWord16)payloadBytesRemainingInNALU + H264_FUA_LENGTH; payloadBytesToSend -= payloadBytesRemainingInNALU; if(payloadBytesToSend != 0) { data += payloadBytesRemainingInNALU; // inc data ptr } idxNALU++; if(-1 == SendVideoPacket(frameType, dataBuffer, payloadLength, rtpHeaderLength,isBaseLayer)) { return -1; } } else { // send NAL unit in singel mode return SendH264_SingleMode(frameType, ptrH264Info, idxNALU, payloadType, captureTimeStamp, payloadBytesToSend, data, rtpHeaderLength, sendSVCPACSI); } // end FU-a return 0; } WebRtc_Word32 RTPSenderH264::SendH264_SingleMode(const FrameType frameType, const H264Info* ptrH264Info, WebRtc_UWord16 &idxNALU, const WebRtc_Word8 payloadType, const WebRtc_UWord32 captureTimeStamp, WebRtc_Word32 &payloadBytesToSend, const WebRtc_UWord8*& data, const WebRtc_UWord16 rtpHeaderLength, WebRtc_UWord16& decodingOrderNumber, const bool sendSVCPACSI) { // no H.264 header lenght in single mode // we use WEBRTC_IP_PACKET_SIZE instead of the configured MTU since it's better to send fragmented UDP than not to send const WebRtc_UWord16 maxPayloadLength = WEBRTC_IP_PACKET_SIZE - _rtpSender.PacketOverHead() - FECPacketOverhead() - rtpHeaderLength; WebRtc_UWord8 dataBuffer[WEBRTC_IP_PACKET_SIZE]; bool isBaseLayer=false; if(ptrH264Info->payloadSize[idxNALU] > maxPayloadLength) { return -3; } if(!_h264SendPPS_SPS) { // don't send NALU of type 7 and 8 SPS and PPS if(ptrH264Info->type[idxNALU] == 7 || ptrH264Info->type[idxNALU] == 8) { payloadBytesToSend -= ptrH264Info->payloadSize[idxNALU] + ptrH264Info->startCodeSize[idxNALU]; data += ptrH264Info->payloadSize[idxNALU] + ptrH264Info->startCodeSize[idxNALU]; idxNALU++; return 0; } } if(sendSVCPACSI) { SendH264_SinglePACSI(frameType, ptrH264Info, idxNALU, payloadType, captureTimeStamp, true, true); WebRtc_UWord32 layer = (ptrH264Info->SVCheader[idxNALU].dependencyID << 16)+ (ptrH264Info->SVCheader[idxNALU].qualityID << 8) + ptrH264Info->SVCheader[idxNALU].temporalID; isBaseLayer=(layer==0); } // Put payload in packet memcpy(&dataBuffer[rtpHeaderLength], &data[ptrH264Info->startCodeSize[idxNALU]], ptrH264Info->payloadSize[idxNALU]); WebRtc_UWord16 payloadBytesInPacket = (WebRtc_UWord16)ptrH264Info->payloadSize[idxNALU]; payloadBytesToSend -= ptrH264Info->payloadSize[idxNALU] + ptrH264Info->startCodeSize[idxNALU]; // left to send // _rtpSender.BuildRTPheader(dataBuffer,payloadType,(payloadBytesToSend ==0)?true:false, captureTimeStamp); dataBuffer[rtpHeaderLength] &= 0x1f; // zero out NRI field dataBuffer[rtpHeaderLength] |= ptrH264Info->NRI[idxNALU]; // nri if(payloadBytesToSend > 0) { data += ptrH264Info->payloadSize[idxNALU] + ptrH264Info->startCodeSize[idxNALU]; } idxNALU++; if(-1 == SendVideoPacket(frameType, dataBuffer, payloadBytesInPacket, rtpHeaderLength,isBaseLayer)) { return -1; } return 0; } WebRtc_Word32 RTPSenderH264::SendH264_SinglePACSI(const FrameType frameType, const H264Info* ptrH264Info, const WebRtc_UWord16 idxNALU, const WebRtc_Word8 payloadType, const WebRtc_UWord32 captureTimeStamp, const bool firstPacketInNALU, const bool lastPacketInNALU); { // Send PACSI in single mode WebRtc_UWord8 dataBuffer[WEBRTC_IP_PACKET_SIZE]; WebRtc_UWord16 rtpHeaderLength = (WebRtc_UWord16)_rtpSender.BuildRTPheader(dataBuffer, payloadType,false, captureTimeStamp); WebRtc_Word32 dataOffset = rtpHeaderLength; WebRtc_Word32 lengthPASCINALU = AddH264PACSINALU(firstPacketInNALU, lastPacketInNALU, ptrH264Info->PACSI[idxNALU], ptrH264Info->SVCheader[idxNALU], decodingOrderNumber, dataBuffer, dataOffset); if (lengthPASCINALU <= 0) { return -1; } decodingOrderNumber++; WebRtc_UWord16 payloadBytesInPacket = (WebRtc_UWord16)lengthPASCINALU; // Set payload header (first payload byte co-serves as the payload header) dataBuffer[rtpHeaderLength] &= 0x1f; // zero out NRI field dataBuffer[rtpHeaderLength] |= ptrH264Info->NRI[idxNALU]; // nri const WebRtc_UWord32 layer = (ptrH264Info->SVCheader[idxNALU].dependencyID << 16)+ (ptrH264Info->SVCheader[idxNALU].qualityID << 8) + ptrH264Info->SVCheader[idxNALU].temporalID; if (-1 == SendVideoPacket(frameType, dataBuffer, payloadBytesInPacket, rtpHeaderLength,layer==0)) { return -1; } return 0; } WebRtc_Word32 RTPSenderH264::SendH264SVC(const FrameType frameType, const WebRtc_Word8 payloadType, const WebRtc_UWord32 captureTimeStamp, const WebRtc_UWord8* payloadData, const WebRtc_UWord32 payloadSize, H264Information& h264Information, WebRtc_UWord16& decodingOrderNumber) { WebRtc_Word32 payloadBytesToSend = payloadSize; const WebRtc_UWord16 rtpHeaderLength = _rtpSender.RTPHeaderLength(); const H264Info* ptrH264Info = NULL; if (h264Information.GetInfo(payloadData,payloadSize, ptrH264Info) == -1) { return -1; } if(_useHighestSendLayer) { // we need to check if we should drop the frame // it could be a temporal layer (aka a temporal frame) const WebRtc_UWord8 dependencyQualityID = (ptrH264Info->SVCheader[0].dependencyID << 4) + ptrH264Info->SVCheader[0].qualityID; bool dummyHighestLayer; if(SendH264SVCLayer(frameType, ptrH264Info->SVCheader[0].temporalID, dependencyQualityID, dummyHighestLayer) == false) { // skip send this frame return 0; } } WebRtc_UWord16 idxNALU = 0; while (payloadBytesToSend > 0) { bool switchToFUA = false; if (SendH264_STAP_A_PACSI(frameType, ptrH264Info, idxNALU, payloadType, captureTimeStamp, switchToFUA, payloadBytesToSend, payloadData, rtpHeaderLength, decodingOrderNumber) != 0) { return -1; } if(switchToFUA) { // FU_A for this NALU if (SendH264_FU_A(frameType, ptrH264Info, idxNALU, payloadType, captureTimeStamp, payloadBytesToSend, payloadData, rtpHeaderLength, true) != 0) { return -1; } } } return 0; } WebRtc_Word32 RTPSenderH264::SetH264PacketizationMode(const H264PacketizationMode mode) { _h264Mode = mode; return 0; } WebRtc_Word32 RTPSenderH264::SetH264SendModeNALU_PPS_SPS(const bool dontSend) { _h264SendPPS_SPS = !dontSend; return 0; } bool RTPSenderH264::SendH264SVCLayer(const FrameType frameType, const WebRtc_UWord8 temporalID, const WebRtc_UWord8 dependencyQualityID, bool& higestLayer) { WebRtc_UWord8 dependencyID = dependencyQualityID >> 4; // keyframe required to switch between dependency layers not quality and temporal if( _highestDependencyLayer != _highestDependencyLayerOld) { // we want to switch dependency layer if(frameType == kVideoFrameKey) { // key frame we can change layer if it's correct layer if(_highestDependencyLayer > _highestDependencyLayerOld) { // we want to switch up // does this packet belong to a new layer? if( dependencyID > _highestDependencyLayerOld && dependencyID <= _highestDependencyLayer) { _highestDependencyLayerOld = dependencyID; _highestDependencyQualityIDOld = _highestDependencyQualityID; if( dependencyID == _highestDependencyLayer && dependencyQualityID == _highestDependencyQualityID) { higestLayer = true; } // relay return true; } } if(_highestDependencyLayer < _highestDependencyLayerOld) { // we want to switch down // does this packet belong to a low layer? if( dependencyID <= _highestDependencyLayer) { _highestDependencyLayerOld = dependencyID; _highestDependencyQualityIDOld = _highestDependencyQualityID; if( dependencyID == _highestDependencyLayer && dependencyQualityID == _highestDependencyQualityID) { higestLayer = true; } // relay return true; } } } else { // Delta frame and we are waiting to switch dependency layer if(_highestDependencyLayer > _highestDependencyLayerOld) { // we want to switch up to a higher dependency layer // use old setting until we get a key-frame // filter based on old dependency // we could have allowed to add a MGS layer lower than the dependency ID // but then we can't know the highest layer relayed we assume that the user // will add one layer at a time if( _highestTemporalLayer < temporalID || _highestDependencyLayerOld < dependencyID || _highestDependencyQualityIDOld < dependencyQualityID) { // drop return false; } // highest layer based on old if( dependencyID == _highestDependencyLayerOld && dependencyQualityID == _highestDependencyQualityIDOld) { higestLayer = true; } } else { // we want to switch down to a lower dependency layer, // use old setting, done bellow // drop all temporal layers while waiting for the key-frame if(temporalID > 0) { // drop return false; } // we can't drop a lower MGS layer since this might depend on it // however we can drop MGS layers larger than dependecyQualityId // with dependency from old and quality 0 if( _highestDependencyLayerOld < dependencyID || (_highestDependencyQualityIDOld & 0xf0) < dependencyQualityID) { // drop return false; } if( dependencyID == _highestDependencyLayerOld && dependencyQualityID == (_highestDependencyQualityIDOld & 0xf0)) { higestLayer = true; } } } } else { // filter based on current state if( _highestTemporalLayer < temporalID || _highestDependencyLayer < dependencyID || _highestDependencyQualityID < dependencyQualityID) { // drop return false; } if( dependencyID == _highestDependencyLayer && dependencyQualityID == _highestDependencyQualityID) { higestLayer = true; } } return true; } WebRtc_Word32 RTPSenderH264::SetHighestSendLayer(const WebRtc_UWord8 dependencyQualityLayer, const WebRtc_UWord8 temporalLayer) { const WebRtc_UWord8 dependencyLayer = (dependencyQualityLayer >> 4); if(_highestDependencyLayerOld != _highestDependencyLayer) { // we have not switched to the new dependency yet } else { if(_highestDependencyLayer == dependencyLayer) { // no change of dependency // switch now _highestDependencyQualityIDOld _highestDependencyQualityIDOld = dependencyQualityLayer; }else { // change of dependency, update _highestDependencyQualityIDOld store as old _highestDependencyQualityIDOld = _highestDependencyQualityID; } } _useHighestSendLayer = true; _highestDependencyLayer = dependencyLayer; _highestDependencyQualityID = dependencyQualityLayer; _highestTemporalLayer = temporalLayer; return 0; } WebRtc_Word32 RTPSenderH264::HighestSendLayer(WebRtc_UWord8& dependencyQualityLayer, WebRtc_UWord8& temporalLayer) { if (!_useHighestSendLayer) { // No information set return -1; } dependencyQualityLayer = _highestDependencyQualityID; temporalLayer = _highestTemporalLayer; return 0; } /* * H.264 */ WebRtc_Word32 RTPSenderH264::SendH264(const FrameType frameType, const WebRtc_Word8 payloadType, const WebRtc_UWord32 captureTimeStamp, const WebRtc_UWord8* payloadData, const WebRtc_UWord32 payloadSize, H264Information& h264Information) { WebRtc_Word32 payloadBytesToSend = payloadSize; const WebRtc_UWord8* data = payloadData; bool switchToFUA = false; const WebRtc_UWord16 rtpHeaderLength = _rtpSender.RTPHeaderLength(); const H264Info* ptrH264Info = NULL; if (h264Information.GetInfo(payloadData,payloadSize, ptrH264Info) == -1) { return -1; } WebRtc_UWord16 idxNALU = 0; WebRtc_UWord16 DONCdummy = 0; while (payloadBytesToSend > 0) { switch(_h264Mode) { case H264_NON_INTERLEAVED_MODE: if(!switchToFUA) { if(SendH264_STAP_A(frameType, ptrH264Info, idxNALU, payloadType, captureTimeStamp, switchToFUA, payloadBytesToSend, data, rtpHeaderLength) != 0) { return -1; } } else { // FUA for the rest of the frame if(SendH264_FU_A(frameType, ptrH264Info, idxNALU, payloadType, captureTimeStamp, payloadBytesToSend, data, rtpHeaderLength, DONCdummy) != 0) { return -1; } // try to go back to STAP_A switchToFUA = false; } break; case H264_SINGLE_NAL_MODE: { // modeSingleU if(SendH264_SingleMode(frameType, ptrH264Info, idxNALU, payloadType, captureTimeStamp, payloadBytesToSend, data, rtpHeaderLength, DONCdummy) != 0) { return -1; } break; } case H264_INTERLEAVED_MODE: // not supported assert(false); return -1; } } return 0; } } // namespace webrtc
/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm/gm.h" #include "include/core/SkBitmap.h" #include "include/core/SkCanvas.h" #include "include/core/SkColor.h" #include "include/core/SkImage.h" #include "include/core/SkImageFilter.h" #include "include/core/SkMatrix.h" #include "include/core/SkPaint.h" #include "include/core/SkRect.h" #include "include/core/SkRefCnt.h" #include "include/core/SkScalar.h" #include "include/core/SkSize.h" #include "include/core/SkString.h" #include "include/effects/SkImageFilters.h" #include "src/core/SkImageFilter_Base.h" #include "tools/ToolUtils.h" #include <utility> #define WIDTH 600 #define HEIGHT 100 #define MARGIN 12 class OffsetImageFilterGM : public skiagm::GM { public: OffsetImageFilterGM() { this->setBGColor(0xFF000000); } protected: SkString onShortName() override { return SkString("offsetimagefilter"); } SkISize onISize() override { return SkISize::Make(WIDTH, HEIGHT); } void onOnceBeforeDraw() override { fBitmap = SkImage::MakeFromBitmap( ToolUtils::create_string_bitmap(80, 80, 0xD000D000, 15, 65, 96, "e")); fCheckerboard = SkImage::MakeFromBitmap( ToolUtils::create_checkerboard_bitmap(80, 80, 0xFFA0A0A0, 0xFF404040, 8)); } void onDraw(SkCanvas* canvas) override { canvas->clear(SK_ColorBLACK); SkPaint paint; for (int i = 0; i < 4; i++) { sk_sp<SkImage> image = (i & 0x01) ? fCheckerboard : fBitmap; SkIRect cropRect = SkIRect::MakeXYWH(i * 12, i * 8, image->width() - i * 8, image->height() - i * 12); sk_sp<SkImageFilter> tileInput(SkImageFilters::Image(image)); SkScalar dx = SkIntToScalar(i*5); SkScalar dy = SkIntToScalar(i*10); paint.setImageFilter(SkImageFilters::Offset(dx, dy, std::move(tileInput), &cropRect)); DrawClippedImage(canvas, image.get(), paint, 1, cropRect); canvas->translate(SkIntToScalar(image->width() + MARGIN), 0); } SkIRect cropRect = SkIRect::MakeXYWH(0, 0, 100, 100); paint.setImageFilter(SkImageFilters::Offset(-5, -10, nullptr, &cropRect)); DrawClippedImage(canvas, fBitmap.get(), paint, 2, cropRect); } private: static void DrawClippedImage(SkCanvas* canvas, const SkImage* image, const SkPaint& paint, SkScalar scale, const SkIRect& cropRect) { SkRect clipRect = SkRect::MakeIWH(image->width(), image->height()); canvas->save(); canvas->clipRect(clipRect); canvas->scale(scale, scale); canvas->drawImage(image, 0, 0, &paint); canvas->restore(); // Draw a boundary rect around the intersection of the clip rect and crop rect. SkRect cropRectFloat; SkMatrix::Scale(scale, scale).mapRect(&cropRectFloat, SkRect::Make(cropRect)); if (clipRect.intersect(cropRectFloat)) { SkPaint strokePaint; strokePaint.setStyle(SkPaint::kStroke_Style); strokePaint.setStrokeWidth(2); strokePaint.setColor(SK_ColorRED); canvas->drawRect(clipRect, strokePaint); } } sk_sp<SkImage> fBitmap, fCheckerboard; using INHERITED = skiagm::GM; }; DEF_GM( return new OffsetImageFilterGM; ) ////////////////////////////////////////////////////////////////////////////// class SimpleOffsetImageFilterGM : public skiagm::GM { public: SimpleOffsetImageFilterGM() {} protected: SkString onShortName() override { return SkString("simple-offsetimagefilter"); } SkISize onISize() override { return SkISize::Make(640, 200); } void doDraw(SkCanvas* canvas, const SkRect& r, sk_sp<SkImageFilter> imgf, const SkRect* clipR = nullptr) { SkPaint p; if (clipR) { p.setColor(0xFF00FF00); p.setStyle(SkPaint::kStroke_Style); canvas->drawRect(clipR->makeInset(SK_ScalarHalf, SK_ScalarHalf), p); p.setStyle(SkPaint::kFill_Style); } // Visualize the crop rect for debugging if (imgf && as_IFB(imgf)->cropRectIsSet()) { SkImageFilter::CropRect cr = as_IFB(imgf)->getCropRect(); p.setColor(0x66FF00FF); p.setStyle(SkPaint::kStroke_Style); canvas->drawRect(cr.rect().makeInset(SK_ScalarHalf, SK_ScalarHalf), p); p.setStyle(SkPaint::kFill_Style); } p.setColor(0x660000FF); canvas->drawRect(r, p); if (clipR) { canvas->save(); canvas->clipRect(*clipR); } if (imgf) { p.setImageFilter(std::move(imgf)); } p.setColor(0x66FF0000); canvas->drawRect(r, p); if (clipR) { canvas->restore(); } } void onDraw(SkCanvas* canvas) override { SkIRect cr0 = SkIRect::MakeWH(40, 40); SkIRect cr1 = SkIRect::MakeWH(20, 20); SkIRect cr2 = SkIRect::MakeXYWH(40, 0, 40, 40); const SkRect r = SkRect::Make(cr0); const SkRect r2 = SkRect::Make(cr2); canvas->translate(40, 40); canvas->save(); this->doDraw(canvas, r, nullptr); canvas->translate(100, 0); this->doDraw(canvas, r, SkImageFilters::Offset(20, 20, nullptr)); canvas->translate(100, 0); this->doDraw(canvas, r, SkImageFilters::Offset(20, 20, nullptr, &cr0)); canvas->translate(100, 0); this->doDraw(canvas, r, SkImageFilters::Offset(20, 20, nullptr), &r); canvas->translate(100, 0); this->doDraw(canvas, r, SkImageFilters::Offset(20, 20, nullptr, &cr1)); SkRect clipR = SkRect::MakeXYWH(40, 40, 40, 40); canvas->translate(100, 0); this->doDraw(canvas, r, SkImageFilters::Offset(20, 20, nullptr, nullptr), &clipR); canvas->restore(); // 2nd row canvas->translate(0, 80); /* * combos of clip and crop rects that align with src and dst */ // crop==clip==src this->doDraw(canvas, r, SkImageFilters::Offset(40, 0, nullptr, &cr0), &r); // crop==src, clip==dst canvas->translate(100, 0); this->doDraw(canvas, r, SkImageFilters::Offset(40, 0, nullptr, &cr0), &r2); // crop==dst, clip==src canvas->translate(100, 0); this->doDraw(canvas, r, SkImageFilters::Offset(40, 0, nullptr, &cr2), &r); // crop==clip==dst canvas->translate(100, 0); this->doDraw(canvas, r, SkImageFilters::Offset(40, 0, nullptr, &cr2), &r2); } private: using INHERITED = skiagm::GM; }; DEF_GM( return new SimpleOffsetImageFilterGM; )
#include "ukf.h" #include "Eigen/Dense" #include <iostream> #include "fstream" using namespace std; using Eigen::MatrixXd; using Eigen::VectorXd; using std::vector; /** * Initializes Unscented Kalman filter * This is scaffolding, do not modify */ UKF::UKF() { // if this is false, laser measurements will be ignored (except during init) use_laser_ = true; // if this is false, radar measurements will be ignored (except during init) use_radar_ = true; // initial state vector x_ = VectorXd::Zero(5); // initial covariance matrix P_ = MatrixXd::Zero(5, 5); // Process noise standard deviation longitudinal acceleration in m/s^2 std_a_ = 3; // Process noise standard deviation yaw acceleration in rad/s^2 std_yawdd_ = 3; //DO NOT MODIFY measurement noise values below these are provided by the sensor manufacturer. // Laser measurement noise standard deviation position1 in m std_laspx_ = 0.15; // Laser measurement noise standard deviation position2 in m std_laspy_ = 0.15; // Radar measurement noise standard deviation radius in m std_radr_ = 0.3; // Radar measurement noise standard deviation angle in rad std_radphi_ = 0.03; // Radar measurement noise standard deviation radius change in m/s std_radrd_ = 0.3; //DO NOT MODIFY measurement noise values above these are provided by the sensor manufacturer. /** TODO: Complete the initialization. See ukf.h for other member properties. Hint: one or more values initialized above might be wildly off... */ eps = 1e-5; n_x_ = x_.size(); n_aug_ = n_x_ + 2; lambda_ = 3 - n_aug_; Xsig_aug = MatrixXd::Zero(n_aug_, 2*n_aug_+1); Xsig_pred_ = MatrixXd::Zero(n_x_, 2*n_aug_+1); previous_t = 0; x_aug = VectorXd::Zero(n_aug_); P_aug = MatrixXd::Zero(n_aug_, n_aug_); weights_ = VectorXd::Zero(2*n_aug_+1); is_initialized_ = false; weights_(0) = lambda_ / (lambda_ + n_aug_); for(int i=1;i<2*n_aug_+1;i++){ weights_(i) = 0.5/(lambda_ + n_aug_); } R_radar = MatrixXd::Zero(3,3); R_radar(0,0) = std_radr_*std_radr_; R_radar(1,1) = std_radphi_*std_radphi_; R_radar(2,2) = std_radrd_*std_radrd_; R_lidar = MatrixXd::Zero(2,2); R_lidar(0,0) = std_laspx_ * std_laspx_; R_lidar(1,1) = std_laspy_ * std_laspy_; Q = MatrixXd::Zero(2,2); Q<<std_a_*std_a_,0,0,std_yawdd_*std_yawdd_; // H matrix for lidar H_lidar = MatrixXd::Zero(2,5); H_lidar(0,0) = 1; H_lidar(1,1) = 1; // clear the data file ofstream data_file; data_file.open("data.txt", ofstream::out | ofstream::trunc); data_file.close(); } UKF::~UKF() {} /** * @param {MeasurementPackage} meas_package The latest measurement data of * either radar or laser. */ void UKF::ProcessMeasurement(MeasurementPackage meas_package) { /** TODO: Complete this function! Make sure you switch between lidar and radar measurements. modify parameter which in ukf.h */ if (!is_initialized_){ P_ = MatrixXd::Identity(n_x_, n_x_); if (meas_package.sensor_type_ == MeasurementPackage::LASER){ x_(0) = meas_package.raw_measurements_(0); x_(1) = meas_package.raw_measurements_(1); }else{ x_(1) = meas_package.raw_measurements_(0) * cos(meas_package.raw_measurements_(1)); x_(0) = meas_package.raw_measurements_(0) * sin(meas_package.raw_measurements_(1)); } previous_t = meas_package.timestamp_; is_initialized_ = true; return; } double delta_t = (meas_package.timestamp_ - previous_t) / 1e6; previous_t = meas_package.timestamp_; Prediction(delta_t); if(meas_package.sensor_type_ == MeasurementPackage::LASER){ UpdateLidar(meas_package); }else{ UpdateRadar(meas_package); } cout<<"nis: "<<nis<<endl; // write to file ofstream outfile; outfile.open("data.txt", ios_base::app); outfile << to_string(nis)<<' '; } /** * Predicts sigma points, the state, and the state covariance matrix. * @param {double} delta_t the change in time (in seconds) between the last * measurement and this one. */ void UKF::Prediction(double delta_t) { /** TODO: Complete this function! Estimate the object's location. Modify the state vector, x_. Predict sigma points, the state, and the state covariance matrix. */ gen_sigma_point(); predict_sigma_point(delta_t); cal_mean_cov(); } /** * Updates the state and the state covariance matrix using a laser measurement. * @param {MeasurementPackage} meas_package */ void UKF::UpdateLidar(MeasurementPackage meas_package) { /** TODO: Complete this function! Use lidar data to update the belief about the object's position. Modify the state vector, x_, and covariance, P_. You'll also need to calculate the lidar NIS. */ predict_lidar_measurement(); cout<<"predict_lidar_measurement_succ"<<endl; VectorXd y = meas_package.raw_measurements_ - z_pred; MatrixXd K = P_ * H_lidar.transpose()*S.inverse(); x_ += K * y; P_ -= K * H_lidar * P_; // K.transpose(); nis = cal_nis(meas_package); } /** * Updates the state and the state covariance matrix using a radar measurement. * @param {MeasurementPackage} meas_package */ void UKF::UpdateRadar(MeasurementPackage meas_package) { /** TODO: Complete this function! Use radar data to update the belief about the object's position. Modify the state vector, x_, and covariance, P_. You'll also need to calculate the radar NIS. */ predict_radar_measurement(); cout<<"predict_radar_measurement_succ"<<endl; Tc = MatrixXd::Zero(n_x_, 3); VectorXd sub_x; VectorXd sub_z; for(int i=0;i<2*n_aug_+1;i++){ sub_x = Xsig_pred_.col(i) - x_; sub_x(1) = atan2(sin(sub_x(1)), cos(sub_x(1))); sub_z = Zsig.col(i) - z_pred; sub_z(1) = atan2(sin(sub_z(1)), cos(sub_z(1))); Tc += weights_(i) * sub_x*sub_z.transpose(); } //calculate Kalman gain K; MatrixXd K = Tc*S.inverse(); //update state mean and covariance matrix x_ += K * (meas_package.raw_measurements_ - z_pred); P_ -= K * S * K.transpose(); nis = cal_nis(meas_package); } void UKF::gen_sigma_point() { // augmentation x_aug.head(n_x_) = x_; x_aug(n_x_) = 0; x_aug(n_x_ + 1) = 0; P_aug.topLeftCorner(n_x_, n_x_) = P_; P_aug.bottomRightCorner(2,2) = Q; MatrixXd A = P_aug.llt().matrixL(); Xsig_aug.col(0) = x_aug; for(int i = 0; i < n_aug_;i++){ Xsig_aug.col(i+1) = x_aug.array() + sqrt(lambda_ + n_aug_)*A.array().col(i); Xsig_aug.col(n_aug_ + i + 1) = x_aug.array() - sqrt(lambda_ + n_aug_)*A.array().col(i); } } void UKF::predict_sigma_point(double delta_t) { for(int i=0;i<Xsig_aug.cols();i++){ double px = Xsig_aug.col(i)(0); double py = Xsig_aug.col(i)(1); double v = Xsig_aug.col(i)(2); double yaw = Xsig_aug.col(i)(3); double yaw_dot = Xsig_aug.col(i)(4); double v_dot = Xsig_aug.col(i)(5); double yaw_dot_dot = Xsig_aug.col(i)(6); // noise vector VectorXd noise(n_x_); noise<<pow(delta_t,2)*cos(yaw)*v_dot/2, pow(delta_t,2)*sin(yaw)*v_dot/2, delta_t*v_dot, pow(delta_t, 2)*yaw_dot_dot/2, delta_t*yaw_dot_dot; if(Xsig_aug.col(i)(4)==0){ px += v*cos(yaw)*delta_t ; py += v*sin(yaw)*delta_t ; v += 0; yaw += 0; yaw_dot += 0; }else{ px += v*(sin(yaw + yaw_dot*delta_t) - sin(yaw))/yaw_dot; py += v*(-cos(yaw + yaw_dot*delta_t) + cos(yaw))/yaw_dot; v += 0; yaw += yaw_dot*delta_t; yaw_dot += 0; } Xsig_pred_.col(i) << px, py, v, yaw, yaw_dot; Xsig_pred_.col(i) += noise; } } void UKF::cal_mean_cov(){ P_ = MatrixXd::Zero(n_x_, n_x_); x_ = Xsig_pred_ * weights_; for(int i=0;i<2*n_aug_+1;i++){ VectorXd subtract = Xsig_pred_.col(i) - x_; subtract(3) = atan2(sin(subtract(3)),cos(subtract(3))); P_ += weights_(i) * subtract*subtract.transpose(); } } void UKF::predict_radar_measurement() { // UKF // initialization Zsig = MatrixXd::Zero(3, 2 * n_aug_ + 1); z_pred = VectorXd::Zero(3); //measurement covariance matrix S S = MatrixXd::Zero(3,3); for (int i = 0; i < 2 * n_aug_ + 1; i++) { //2n+1 simga points // extract values for better readibility double p_x = Xsig_pred_(0,i); double p_y = Xsig_pred_(1,i); double v = Xsig_pred_(2,i); double yaw = Xsig_pred_(3,i); double v1 = cos(yaw)*v; double v2 = sin(yaw)*v; // measurement model Zsig(0,i) = sqrt(p_x*p_x + p_y*p_y); //r Zsig(1,i) = atan2(p_y,p_x); //phi Zsig(2,i) = (p_x*v1 + p_y*v2 ) / max(sqrt(p_x*p_x + p_y*p_y), eps); //r_dot } //calculate mean predicted measurement for(int i=0;i<2*n_aug_ + 1;i++){ z_pred += weights_(i)*Zsig.col(i); } //calculate innovation covariance matrix S for(int i=0;i<2*n_aug_ + 1;i++){ VectorXd sub = Zsig.col(i) - z_pred; // norm sub(1) = atan2(sin(sub(1)),cos(sub(1))); S+= weights_(i)*sub*sub.transpose(); } S+=R_radar; } void UKF::predict_lidar_measurement() { // EKF S = MatrixXd::Zero(2,2); z_pred = H_lidar * x_; S = H_lidar * P_ * H_lidar.transpose() + R_lidar; } double UKF::cal_nis(MeasurementPackage mp) { VectorXd sub = mp.raw_measurements_ - z_pred; double nis_ = sub.transpose() * S.inverse() * sub; return nis_; }
/* * 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/ecm/v20190719/model/BatchDeregisterTargetsResponse.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Ecm::V20190719::Model; using namespace std; BatchDeregisterTargetsResponse::BatchDeregisterTargetsResponse() : m_failListenerIdSetHasBeenSet(false) { } CoreInternalOutcome BatchDeregisterTargetsResponse::Deserialize(const string &payload) { rapidjson::Document d; d.Parse(payload.c_str()); if (d.HasParseError() || !d.IsObject()) { return CoreInternalOutcome(Core::Error("response not json format")); } if (!d.HasMember("Response") || !d["Response"].IsObject()) { return CoreInternalOutcome(Core::Error("response `Response` is null or not object")); } rapidjson::Value &rsp = d["Response"]; if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString()) { return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string")); } string requestId(rsp["RequestId"].GetString()); SetRequestId(requestId); if (rsp.HasMember("Error")) { if (!rsp["Error"].IsObject() || !rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() || !rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString()) { return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId)); } string errorCode(rsp["Error"]["Code"].GetString()); string errorMsg(rsp["Error"]["Message"].GetString()); return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId)); } if (rsp.HasMember("FailListenerIdSet") && !rsp["FailListenerIdSet"].IsNull()) { if (!rsp["FailListenerIdSet"].IsArray()) return CoreInternalOutcome(Core::Error("response `FailListenerIdSet` is not array type")); const rapidjson::Value &tmpValue = rsp["FailListenerIdSet"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { m_failListenerIdSet.push_back((*itr).GetString()); } m_failListenerIdSetHasBeenSet = true; } return CoreInternalOutcome(true); } string BatchDeregisterTargetsResponse::ToJsonString() const { rapidjson::Document value; value.SetObject(); rapidjson::Document::AllocatorType& allocator = value.GetAllocator(); if (m_failListenerIdSetHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "FailListenerIdSet"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); for (auto itr = m_failListenerIdSet.begin(); itr != m_failListenerIdSet.end(); ++itr) { value[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator); } } rapidjson::Value iKey(rapidjson::kStringType); string key = "RequestId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); value.Accept(writer); return buffer.GetString(); } vector<string> BatchDeregisterTargetsResponse::GetFailListenerIdSet() const { return m_failListenerIdSet; } bool BatchDeregisterTargetsResponse::FailListenerIdSetHasBeenSet() const { return m_failListenerIdSetHasBeenSet; }
/* * Copyright (c) 2017-2018, The Alloy Developers. * * This file is part of Alloy. * * This file is subject to the terms and conditions defined in the * file 'LICENSE', which is part of this source code package. */ #include "TransactionUtils.h" #include <unordered_set> #include "crypto/crypto.h" #include "CryptoNoteCore/Account.h" #include "CryptoNoteFormatUtils.h" #include "TransactionExtra.h" using namespace Crypto; namespace CryptoNote { bool checkInputsKeyimagesDiff(const CryptoNote::TransactionPrefix& tx) { std::unordered_set<Crypto::KeyImage> ki; for (const auto& in : tx.inputs) { if (in.type() == typeid(KeyInput)) { if (!ki.insert(boost::get<KeyInput>(in).keyImage).second) return false; } } return true; } // TransactionInput helper functions size_t getRequiredSignaturesCount(const TransactionInput& in) { if (in.type() == typeid(KeyInput)) { return boost::get<KeyInput>(in).outputIndexes.size(); } return 0; } uint64_t getTransactionInputAmount(const TransactionInput& in) { if (in.type() == typeid(KeyInput)) { return boost::get<KeyInput>(in).amount; } return 0; } TransactionTypes::InputType getTransactionInputType(const TransactionInput& in) { if (in.type() == typeid(KeyInput)) { return TransactionTypes::InputType::Key; } if (in.type() == typeid(BaseInput)) { return TransactionTypes::InputType::Generating; } return TransactionTypes::InputType::Invalid; } const TransactionInput& getInputChecked(const CryptoNote::TransactionPrefix& transaction, size_t index) { if (transaction.inputs.size() <= index) { throw std::runtime_error("Transaction input index out of range"); } return transaction.inputs[index]; } const TransactionInput& getInputChecked(const CryptoNote::TransactionPrefix& transaction, size_t index, TransactionTypes::InputType type) { const auto& input = getInputChecked(transaction, index); if (getTransactionInputType(input) != type) { throw std::runtime_error("Unexpected transaction input type"); } return input; } // TransactionOutput helper functions TransactionTypes::OutputType getTransactionOutputType(const TransactionOutputTarget& out) { if (out.type() == typeid(KeyOutput)) { return TransactionTypes::OutputType::Key; } return TransactionTypes::OutputType::Invalid; } const TransactionOutput& getOutputChecked(const CryptoNote::TransactionPrefix& transaction, size_t index) { if (transaction.outputs.size() <= index) { throw std::runtime_error("Transaction output index out of range"); } return transaction.outputs[index]; } const TransactionOutput& getOutputChecked(const CryptoNote::TransactionPrefix& transaction, size_t index, TransactionTypes::OutputType type) { const auto& output = getOutputChecked(transaction, index); if (getTransactionOutputType(output.target) != type) { throw std::runtime_error("Unexpected transaction output target type"); } return output; } bool isOutToKey(const Crypto::PublicKey& spendPublicKey, const Crypto::PublicKey& outKey, const Crypto::KeyDerivation& derivation, size_t keyIndex) { Crypto::PublicKey pk; derive_public_key(derivation, keyIndex, spendPublicKey, pk); return pk == outKey; } bool findOutputsToAccount(const CryptoNote::TransactionPrefix& transaction, const AccountPublicAddress& addr, const SecretKey& viewSecretKey, std::vector<uint32_t>& out, uint64_t& amount) { AccountKeys keys; keys.address = addr; // only view secret key is used, spend key is not needed keys.viewSecretKey = viewSecretKey; Crypto::PublicKey txPubKey = getTransactionPublicKeyFromExtra(transaction.extra); amount = 0; size_t keyIndex = 0; uint32_t outputIndex = 0; Crypto::KeyDerivation derivation; generate_key_derivation(txPubKey, keys.viewSecretKey, derivation); for (const TransactionOutput& o : transaction.outputs) { assert(o.target.type() == typeid(KeyOutput)); if (o.target.type() == typeid(KeyOutput)) { if (is_out_to_acc(keys, boost::get<KeyOutput>(o.target), derivation, keyIndex)) { out.push_back(outputIndex); amount += o.amount; } ++keyIndex; } ++outputIndex; } return true; } }
/* ------------------------------------------------------------------------- This source file is a part of OGRE-Next (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 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 "WorkspaceEventArgs.h" WorkspaceEventArgs::WorkspaceEventArgs() : mWorkspace(0), mProject(0) { } WorkspaceEventArgs::WorkspaceEventArgs(Workspace* workspace, Project* project) : mWorkspace(workspace), mProject(project) { } WorkspaceEventArgs::~WorkspaceEventArgs() { } Workspace* WorkspaceEventArgs::getWorkspace() { return mWorkspace; } Project* WorkspaceEventArgs::getProject() { return mProject; }
/* * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. */ #include <boost/statechart/custom_reaction.hpp> #include <boost/statechart/event.hpp> #include <boost/statechart/simple_state.hpp> #include <boost/statechart/state.hpp> #include <boost/statechart/state_machine.hpp> #include <cmn/agent_cmn.h> #include <route/route.h> #include <oper/route_common.h> #include <oper/vrf.h> #include <oper/mirror_table.h> #include <oper/path_preference.h> namespace sc = boost::statechart; namespace mpl = boost::mpl; SandeshTraceBufferPtr PathPreferenceTraceBuf( SandeshTraceBufferCreate("PathPreference", 5000)); struct EvStart : sc::event<EvStart> { EvStart() { } static const char *Name() { return "Start"; } }; struct EvTrafficSeen : sc::event<EvTrafficSeen> { EvTrafficSeen() { } static const char *Name() { return "TrafficSeen"; } }; struct EvWaitForTraffic : sc::event<EvWaitForTraffic> { EvWaitForTraffic() { } static const char *Name() { return "WaitForTraffic"; } }; struct EvSeqChange : sc::event<EvSeqChange> { EvSeqChange(uint32_t sequence) : sequence_(sequence) { } static const char *Name() { return "SeqChange"; } uint32_t sequence_; }; //Path transition to ECMP struct EvActiveActiveMode : sc::event<EvActiveActiveMode> { EvActiveActiveMode() { } static const char *Name() { return "EcmpRoute"; } }; struct EvControlNodeInSync : sc::event<EvControlNodeInSync> { EvControlNodeInSync() { } static const char *Name() { return "Control node route in sync"; } }; struct Init : public sc::state<Init, PathPreferenceSM> { typedef mpl::list< sc::custom_reaction<EvStart> > reactions; Init(my_context ctx) : my_base(ctx) { PathPreferenceSM *state_machine = &context<PathPreferenceSM>(); state_machine->Log("INIT"); } sc::result react(const EvStart &event) { return transit<WaitForTraffic>(); } }; struct WaitForTraffic : sc::state<WaitForTraffic, PathPreferenceSM> { typedef mpl::list< sc::custom_reaction<EvTrafficSeen>, sc::custom_reaction<EvSeqChange>, sc::custom_reaction<EvWaitForTraffic>, sc::custom_reaction<EvActiveActiveMode>, sc::custom_reaction<EvControlNodeInSync> > reactions; WaitForTraffic(my_context ctx) : my_base(ctx) { PathPreferenceSM *state_machine = &context<PathPreferenceSM>(); if (state_machine->wait_for_traffic() == false) { state_machine->set_wait_for_traffic(true); state_machine->set_preference(PathPreference::LOW); state_machine->EnqueuePathChange(); state_machine->UpdateDependentRoute(); state_machine->Log("Wait For Traffic"); } } sc::result react(const EvTrafficSeen &event) { return transit<TrafficSeen>(); } sc::result react(const EvSeqChange &event) { PathPreferenceSM *state_machine = &context<PathPreferenceSM>(); state_machine->set_max_sequence(event.sequence_); return discard_event(); } sc::result react(const EvWaitForTraffic &event) { return discard_event(); } sc::result react(const EvActiveActiveMode &event) { return transit<ActiveActiveState>(); } sc::result react(const EvControlNodeInSync &event) { return discard_event(); } }; struct TrafficSeen : sc::state<TrafficSeen, PathPreferenceSM> { typedef mpl::list< sc::custom_reaction<EvTrafficSeen>, sc::custom_reaction<EvSeqChange>, sc::custom_reaction<EvWaitForTraffic>, sc::custom_reaction<EvActiveActiveMode>, sc::custom_reaction<EvControlNodeInSync> > reactions; TrafficSeen(my_context ctx) : my_base(ctx) { PathPreferenceSM *state_machine = &context<PathPreferenceSM>(); //Enqueue a route change if (state_machine->wait_for_traffic() == true) { state_machine->UpdateFlapTime(); if (state_machine->flap_count() == 0) { state_machine->DecreaseRetryTimeout(); } uint32_t seq = state_machine->max_sequence(); state_machine->set_wait_for_traffic(false); seq++; state_machine->set_max_sequence(seq); if (state_machine->is_dependent_rt() == false) { state_machine->set_sequence(seq); } state_machine->set_preference(PathPreference::HIGH); state_machine->EnqueuePathChange(); state_machine->UpdateDependentRoute(); state_machine->Log("Traffic seen"); } } sc::result react(const EvTrafficSeen &event) { return discard_event(); } sc::result react(const EvWaitForTraffic &event) { return transit<WaitForTraffic>(); } sc::result react(const EvSeqChange &event) { PathPreferenceSM *state_machine = &context<PathPreferenceSM>(); if (event.sequence_ > state_machine->sequence()) { state_machine->set_max_sequence(event.sequence_); if (state_machine->IsPathFlapping()) { //If path is continuosly flapping //delay wihtdrawing of route if (state_machine->RetryTimerRunning() == false) { state_machine->IncreaseRetryTimeout(); state_machine->StartRetryTimer(); state_machine->Log("Back off and retry update"); } return discard_event(); } } return transit<WaitForTraffic>(); } sc::result react(const EvActiveActiveMode &event) { return transit<ActiveActiveState>(); } sc::result react(const EvControlNodeInSync &event) { PathPreferenceSM *state_machine = &context<PathPreferenceSM>(); state_machine->Log("in sync with control-node"); return discard_event(); } }; struct ActiveActiveState : sc::state<ActiveActiveState, PathPreferenceSM> { typedef mpl::list< sc::custom_reaction<EvTrafficSeen>, sc::custom_reaction<EvSeqChange>, sc::custom_reaction<EvWaitForTraffic>, sc::custom_reaction<EvActiveActiveMode>, sc::custom_reaction<EvControlNodeInSync> > reactions; ActiveActiveState(my_context ctx) : my_base(ctx) { PathPreferenceSM *state_machine = &context<PathPreferenceSM>(); //Enqueue a route change if (state_machine->preference() == PathPreference::LOW) { state_machine->set_wait_for_traffic(false); uint32_t seq = 0; state_machine->set_max_sequence(seq); state_machine->set_sequence(seq); state_machine->set_preference(PathPreference::HIGH); state_machine->EnqueuePathChange(); state_machine->UpdateDependentRoute(); state_machine->Log("Ecmp path"); } } sc::result react(const EvTrafficSeen &event) { return discard_event(); } sc::result react(const EvWaitForTraffic &event) { return transit<WaitForTraffic>(); } sc::result react(const EvSeqChange &event) { PathPreferenceSM *state_machine = &context<PathPreferenceSM>(); state_machine->set_max_sequence(event.sequence_); return transit<WaitForTraffic>(); } sc::result react(const EvActiveActiveMode &event) { return discard_event(); } sc::result react(const EvControlNodeInSync &event) { return discard_event(); } }; PathPreferenceSM::PathPreferenceSM(Agent *agent, const Peer *peer, AgentRoute *rt, bool is_dependent_route, const PathPreference &pref): agent_(agent), peer_(peer), rt_(rt), path_preference_(0, PathPreference::LOW, false, false), max_sequence_(0), timer_(NULL), timeout_(kMinInterval), flap_count_(0), is_dependent_rt_(is_dependent_route), dependent_rt_(this) { path_preference_ = pref; initiate(); process_event(EvStart()); } PathPreferenceSM::~PathPreferenceSM() { if (timer_ != NULL) { timer_->Cancel(); TimerManager::DeleteTimer(timer_); } timer_ = NULL; } bool PathPreferenceSM::Retry() { flap_count_ = 0; process_event(EvWaitForTraffic()); return false; } void PathPreferenceSM::StartRetryTimer() { if (timer_ == NULL) { timer_ = TimerManager::CreateTimer( *(agent_->event_manager())->io_service(), "Stale cleanup timer", TaskScheduler::GetInstance()->GetTaskId("db::DBTable"), 0, false); } timer_->Start(timeout_, boost::bind(&PathPreferenceSM::Retry, this)); } void PathPreferenceSM::CancelRetryTimer() { if (timer_ == NULL) { return; } timer_->Cancel(); } bool PathPreferenceSM::RetryTimerRunning() { if (timer_ == NULL) { return false; } return timer_->running(); } void PathPreferenceSM::IncreaseRetryTimeout() { timeout_ = timeout_ * 2; if (timeout_ > kMaxInterval) { timeout_ = kMaxInterval; } } void PathPreferenceSM::DecreaseRetryTimeout() { timeout_ = timeout_ / 2; if (timeout_ < kMinInterval) { timeout_ = kMinInterval; } } void PathPreferenceSM::UpdateFlapTime() { uint64_t time_sec = (UTCTimestampUsec() - last_high_priority_change_at_)/1000; //Update last flap time last_high_priority_change_at_ = UTCTimestampUsec(); if (time_sec < timeout_ + kMinInterval) { flap_count_++; } else { flap_count_ = 0; } } bool PathPreferenceSM::IsPathFlapping() const { if (flap_count_ >= kMaxFlapCount) { return true; } return false; } void PathPreferenceSM::UpdateDependentRoute() { if (is_dependent_rt_ == true) { return; } PathDependencyList::iterator iter = dependent_routes_.begin(); for (;iter != dependent_routes_.end(); iter++) { PathPreferenceSM *path_sm = iter.operator->(); if (path_preference_.preference() == PathPreference::HIGH) { path_sm->process_event(EvTrafficSeen()); } else { path_sm->process_event(EvWaitForTraffic()); } } } void PathPreferenceSM::Process() { uint32_t max_sequence = 0; const AgentPath *best_path = NULL; //Dont act on notification of derived routes if (is_dependent_rt_) { if (dependent_rt_.get()) { if (dependent_rt_->path_preference_.preference() == PathPreference::HIGH) { process_event(EvTrafficSeen()); } else { process_event(EvWaitForTraffic()); } } return; } const AgentPath *local_path = rt_->FindPath(peer_); if (local_path->path_preference().ecmp() == true) { path_preference_.set_ecmp(true); //If a path is ecmp, just set the priority to HIGH process_event(EvActiveActiveMode()); return; } //Check if BGP path is present for (Route::PathList::iterator it = rt_->GetPathList().begin(); it != rt_->GetPathList().end(); ++it) { const AgentPath *path = static_cast<const AgentPath *>(it.operator->()); if (path == local_path) { if (path->path_preference().sequence() < sequence()) { EnqueuePathChange(); } continue; } //Get best preference and sequence no from all BGP peer if (max_sequence < path->sequence()) { max_sequence = path->sequence(); best_path = path; } } if (!best_path) { return; } if (ecmp() == true) { path_preference_.set_ecmp(local_path->path_preference().ecmp()); //Route transition from ECMP to non ECMP, //move to wait for traffic state process_event(EvWaitForTraffic()); return; } if (max_sequence > sequence()) { process_event(EvSeqChange(max_sequence)); } else if (sequence() == max_sequence && best_path->ComputeNextHop(agent_) == local_path->ComputeNextHop(agent_)) { //Control node chosen path and local path are same process_event(EvControlNodeInSync()); } else if (sequence() == max_sequence && best_path->ComputeNextHop(agent_) != local_path->ComputeNextHop(agent_)) { process_event(EvWaitForTraffic()); } UpdateDependentRoute(); } void PathPreferenceSM::Log(std::string state) { std::string dependent_ip_str = ""; if (is_dependent_rt()) { dependent_ip_str = dependent_ip().to_string(); } PATH_PREFERENCE_TRACE(rt_->vrf()->GetName(), rt_->GetAddressString(), preference(), sequence(), state, timeout(), dependent_ip_str); } void PathPreferenceSM::EnqueuePathChange() { DBRequest req(DBRequest::DB_ENTRY_ADD_CHANGE); req.key = rt_->GetDBRequestKey(); AgentRouteKey *key = static_cast<AgentRouteKey *>(req.key.get()); key->sub_op_ = AgentKey::RESYNC; key->set_peer(peer_); req.data.reset(new PathPreferenceData(path_preference_)); if (rt_->vrf() == NULL) { return; } AgentRouteTable *table = NULL; if (rt_->GetTableType() == Agent::EVPN) { table = agent_->fabric_evpn_table(); } else if (rt_->GetTableType() == Agent::INET4_UNICAST) { table = agent_->fabric_inet4_unicast_table(); } else if (rt_->GetTableType() == Agent::INET6_UNICAST) { table = agent_->fabric_inet4_unicast_table(); } if (table) { table->Enqueue(&req); } } PathPreferenceIntfState::RouteAddrList::RouteAddrList() : family_(Address::INET), ip_(), plen_(0), vrf_name_(), seen_(false) { } PathPreferenceIntfState::RouteAddrList::RouteAddrList (const Address::Family &family, const IpAddress &ip, uint32_t plen, const std::string &vrf) : family_(family), ip_(ip), plen_(plen), vrf_name_(vrf), seen_(false) { } bool PathPreferenceIntfState::RouteAddrList::operator<( const RouteAddrList &rhs) const { if (family_ != rhs.family_) { return family_ < rhs.family_; } if (ip_ != rhs.ip_) { return ip_ < rhs.ip_; } if (plen_ != rhs.plen_) { return plen_ < rhs.plen_; } return vrf_name_ < rhs.vrf_name_; } bool PathPreferenceIntfState::RouteAddrList::operator==( const RouteAddrList &rhs) const { if ((family_ == rhs.family_) && (ip_ == rhs.ip_) && (plen_ == rhs.plen_) && (vrf_name_ == rhs.vrf_name_)) { return true; } return false; } PathPreferenceIntfState::PathPreferenceIntfState(const VmInterface *intf): intf_(intf) { } void PathPreferenceIntfState::Insert(RouteAddrList &rt, bool traffic_seen) { std::set<RouteAddrList>::const_iterator it = dependent_rt_.find(rt); if (it != dependent_rt_.end()) { it->seen_ = true; return; } rt.seen_ = true; dependent_rt_.insert(rt); } void PathPreferenceIntfState::DeleteOldEntries() { std::set<RouteAddrList>::const_iterator it = dependent_rt_.begin(); while (it != dependent_rt_.end()) { std::set<RouteAddrList>::const_iterator prev_it = it++; if (prev_it->seen_ == false) { dependent_rt_.erase(prev_it); continue; } prev_it->seen_ = false; } } /* Updates the preference of routes dependent on given IP/prefix */ void PathPreferenceIntfState::UpdateDependentRoute(std::string vrf_name, Ip4Address ip, uint32_t plen, bool traffic_seen, PathPreferenceModule *path_preference_module) { if (instance_ip_.vrf_name_ != vrf_name || instance_ip_.plen_ != plen || instance_ip_.ip_ != ip) { return; } Agent *agent = path_preference_module->agent(); std::set<RouteAddrList>::const_iterator it = dependent_rt_.begin(); for(;it != dependent_rt_.end();it++) { const VrfEntry *vrf = agent->vrf_table()->FindVrfFromName(it->vrf_name_); if (vrf == NULL) { continue; } const PathPreferenceVrfState *state = static_cast<const PathPreferenceVrfState *>( vrf->GetState(agent->vrf_table(), path_preference_module->vrf_id())); if (!state) { continue; } InetUnicastRouteKey rt_key(NULL, it->vrf_name_, it->ip_.to_v4(), it->plen_); const InetUnicastRouteEntry *rt = static_cast<const InetUnicastRouteEntry *>( vrf->GetInet4UnicastRouteTable()->FindActiveEntry(&rt_key)); if (!rt) { continue; } const PathPreferenceState *cpath_preference = static_cast<const PathPreferenceState *>( rt->GetState(vrf->GetInet4UnicastRouteTable(), state->uc_rt_id_)); if (!cpath_preference) { continue; } PathPreferenceState *path_preference = const_cast<PathPreferenceState *>(cpath_preference); PathPreferenceSM *path_preference_sm = path_preference->GetSM(intf_->peer()); if (path_preference_sm && traffic_seen) { EvTrafficSeen ev; path_preference_sm->process_event(ev); } } } void PathPreferenceIntfState::Notify() { //Copy over instance IP if (intf_->vrf()) { instance_ip_.vrf_name_ = intf_->vrf()->GetName(); } instance_ip_.ip_ = intf_->primary_ip_addr(); instance_ip_.plen_ = 32; //Check if the native IP is active bool traffic_seen = true; if (intf_->WaitForTraffic() == true) { traffic_seen = false; } //Go thru floating ip const VmInterface::FloatingIpSet &fip_list = intf_->floating_ip_list().list_; VmInterface::FloatingIpSet::const_iterator it = fip_list.begin(); for (;it != fip_list.end(); ++it) { if (it->floating_ip_.is_v4()) { RouteAddrList rt(Address::INET, it->floating_ip_.to_v4(), 32, it->vrf_name_); Insert(rt, traffic_seen); } } //Go thru interface static routes const VmInterface::ServiceVlanSet &service_vlan_set = intf_->service_vlan_list().list_; VmInterface::ServiceVlanSet::const_iterator service_vlan_it = service_vlan_set.begin(); for (;service_vlan_it != service_vlan_set.end(); ++service_vlan_it) { if (!service_vlan_it->addr_.is_unspecified()) { RouteAddrList rt(Address::INET, service_vlan_it->addr_, 32, service_vlan_it->vrf_name_); Insert(rt, traffic_seen); } } //Go thru interface static routes const VmInterface::StaticRouteSet &static_rt_list = intf_->static_route_list().list_; VmInterface::StaticRouteSet::const_iterator static_rt_it = static_rt_list.begin(); for (;static_rt_it != static_rt_list.end(); ++static_rt_it) { if (static_rt_it->addr_.is_v4()) { if (static_rt_it->vrf_ == "") { continue; } RouteAddrList rt(Address::INET, static_rt_it->addr_, static_rt_it->plen_, static_rt_it->vrf_); Insert(rt, traffic_seen); } } //Delete all old entries not present in new list DeleteOldEntries(); } PathPreferenceState::PathPreferenceState(Agent *agent, AgentRoute *rt): agent_(agent), rt_(rt) { } PathPreferenceState::~PathPreferenceState() { PeerPathPreferenceMap::iterator path_preference_it = path_preference_peer_map_.begin(); while (path_preference_it != path_preference_peer_map_.end()) { PeerPathPreferenceMap::iterator prev_it = path_preference_it++; PathPreferenceSM *path_preference_sm = prev_it->second; delete path_preference_sm; path_preference_peer_map_.erase(prev_it); } PathPreferenceModule *path_module = agent_->oper_db()->route_preference_module(); path_module->DeleteUnresolvedPath(this); } //Given a VRF table the table listener id for given route bool PathPreferenceState::GetRouteListenerId(const VrfEntry* vrf, DBTableBase::ListenerId &rt_id) const { if (vrf == NULL) { return false; } DBTableBase::ListenerId vrf_id = agent_->oper_db()->route_preference_module()->vrf_id(); const PathPreferenceVrfState *vrf_state = static_cast<const PathPreferenceVrfState *>( vrf->GetState(agent_->vrf_table(), vrf_id)); if (!vrf_state) { return false; } rt_id = DBTableBase::kInvalidId; if (rt_->GetTableType() == Agent::EVPN) { rt_id = vrf_state->evpn_rt_id_; } else if (rt_->GetTableType() == Agent::INET4_UNICAST) { rt_id = vrf_state->uc_rt_id_; } else if (rt_->GetTableType() == Agent::INET6_UNICAST) { rt_id = vrf_state->uc6_rt_id_; } else { return false; } return true; } PathPreferenceSM* PathPreferenceState::GetDependentPath(const AgentPath *path) const { if (path->path_preference().IsDependentRt() == false) { return NULL; } uint32_t plen = 32; if (path->path_preference().dependent_ip().is_v6()) { plen = 128; } InetUnicastRouteKey key(path->peer(), path->path_preference().vrf(), path->path_preference().dependent_ip(), plen); const VrfEntry *vrf = agent_->vrf_table()->FindVrfFromName(path->path_preference().vrf()); if (!vrf) { return NULL; } AgentRouteTable *table = NULL; if (path->path_preference().dependent_ip().is_v4()) { table = static_cast<AgentRouteTable *>( vrf->GetInet4UnicastRouteTable()); } else if (path->path_preference().dependent_ip().is_v6()) { table = static_cast<AgentRouteTable *>( vrf->GetInet6UnicastRouteTable()); } AgentRoute *rt = static_cast<AgentRoute *>(table->Find(&key)); if (rt == NULL) { return NULL; } DBTableBase::ListenerId rt_id = DBTableBase::kInvalidId; GetRouteListenerId(vrf, rt_id); PathPreferenceState *state = static_cast<PathPreferenceState *>( rt->GetState(table, rt_id)); if (state == NULL) { return NULL; } return state->GetSM(path->peer()); } void PathPreferenceState::Process() { PathPreferenceModule *path_module = agent_->oper_db()->route_preference_module(); //Set all the path as not seen, eventually when path is seen //flag would be set appropriatly PeerPathPreferenceMap::iterator path_preference_it = path_preference_peer_map_.begin(); while (path_preference_it != path_preference_peer_map_.end()) { PathPreferenceSM *path_preference_sm = path_preference_it->second; path_preference_sm->set_seen(false); path_preference_it++; } for (Route::PathList::iterator it = rt_->GetPathList().begin(); it != rt_->GetPathList().end(); ++it) { const AgentPath *path = static_cast<const AgentPath *>(it.operator->()); if (path->peer() == NULL) { continue; } if (path->peer()->GetType() != Peer::LOCAL_VM_PORT_PEER) { continue; } PathPreferenceSM *path_preference_sm; if (path_preference_peer_map_.find(path->peer()) == path_preference_peer_map_.end()) { //Add new path path_preference_sm = new PathPreferenceSM(agent_, path->peer(), rt_, false, path->path_preference()); path_preference_peer_map_.insert( std::pair<const Peer *, PathPreferenceSM *> (path->peer(), path_preference_sm)); } else { path_preference_sm = path_preference_peer_map_.find(path->peer())->second; } bool dependent_rt = path->path_preference().IsDependentRt(); if (dependent_rt) { PathPreferenceSM *sm = GetDependentPath(path); if (sm == NULL) { //Path is unresolved, //add it to unresolved list path_module->AddUnresolvedPath(this); } else { path_module->DeleteUnresolvedPath(this); } path_preference_sm->set_dependent_rt(sm); } else { path_preference_sm->set_dependent_rt(NULL); } path_preference_sm->set_is_dependent_rt(dependent_rt); path_preference_sm->set_dependent_ip( path->path_preference().dependent_ip()); path_preference_sm->set_seen(true); path_preference_sm->Process(); if (dependent_rt == false) { //Resolve path which may not be resolved yet path_module->Resolve(); } } //Delete all path not seen, in latest path list path_preference_it = path_preference_peer_map_.begin(); while (path_preference_it != path_preference_peer_map_.end()) { PeerPathPreferenceMap::iterator prev_it = path_preference_it++; PathPreferenceSM *path_preference_sm = prev_it->second; if (path_preference_sm->seen() == false) { delete path_preference_sm; path_preference_peer_map_.erase(prev_it); } } } PathPreferenceSM* PathPreferenceState::GetSM(const Peer *peer) { if (path_preference_peer_map_.find(peer) == path_preference_peer_map_.end()) { return NULL; } return path_preference_peer_map_.find(peer)->second; } PathPreferenceRouteListener::PathPreferenceRouteListener(Agent *agent, AgentRouteTable *table): agent_(agent), rt_table_(table), id_(DBTableBase::kInvalidId), table_delete_ref_(this, table->deleter()), deleted_(false) { } void PathPreferenceRouteListener::Init() { id_ = rt_table_->Register(boost::bind(&PathPreferenceRouteListener::Notify, this, _1, _2)); } void PathPreferenceRouteListener::Delete() { set_deleted(); DBTableWalker *walker = agent_->db()->GetWalker(); walker->WalkTable(rt_table_, NULL, boost::bind(&PathPreferenceRouteListener::DeleteState, this, _1, _2), boost::bind(&PathPreferenceRouteListener::Walkdone, this, _1, this)); } void PathPreferenceRouteListener::ManagedDelete() { Delete(); } void PathPreferenceRouteListener::Walkdone(DBTableBase *partition, PathPreferenceRouteListener *state) { rt_table_->Unregister(id_); table_delete_ref_.Reset(NULL); delete state; } bool PathPreferenceRouteListener::DeleteState(DBTablePartBase *partition, DBEntryBase *e) { PathPreferenceState *state = static_cast<PathPreferenceState *>(e->GetState(rt_table_, id_)); if (state) { e->ClearState(rt_table_, id_); delete state; } return true; } void PathPreferenceRouteListener::Notify(DBTablePartBase *partition, DBEntryBase *e) { PathPreferenceState *state = static_cast<PathPreferenceState *>(e->GetState(rt_table_, id_)); if (e->IsDeleted()) { if (state) { e->ClearState(rt_table_, id_); delete state; } return; } if (deleted_) return; AgentRoute *rt = static_cast<AgentRoute *>(e); for (Route::PathList::iterator it = rt->GetPathList().begin(); it != rt->GetPathList().end(); ++it) { const AgentPath *path = static_cast<const AgentPath *>(it.operator->()); if (path->peer() == NULL) { continue; } if (path->peer()->GetType() != Peer::LOCAL_VM_PORT_PEER) { continue; } if (path->path_preference().static_preference() == true) { return; } } if (!state) { state = new PathPreferenceState(agent_, rt); } state->Process(); e->SetState(rt_table_, id_, state); } PathPreferenceModule::PathPreferenceModule(Agent *agent): agent_(agent), vrf_id_(DBTableBase::kInvalidId), work_queue_(TaskScheduler::GetInstance()->GetTaskId("db::DBTable"), 0, boost::bind(&PathPreferenceModule::DequeueEvent, this, _1)) { work_queue_.set_name("Path Preference"); } bool PathPreferenceModule::DequeueEvent(PathPreferenceEventContainer event) { const Interface *intf = agent_->interface_table()->FindInterface(event.interface_index_); if (intf == NULL || (intf->type() != Interface::VM_INTERFACE)) { return true; } const VmInterface *vm_intf = static_cast<const VmInterface *>(intf); const VrfEntry *vrf = agent_->vrf_table()->FindVrfFromId(event.vrf_index_); if (vrf == NULL) { return true; } const PathPreferenceVrfState *state = static_cast<const PathPreferenceVrfState *>( vrf->GetState(agent_->vrf_table(), vrf_id_)); if (!state) { return true; } PathPreferenceState *path_preference = NULL; PathPreferenceSM *path_preference_sm = NULL; const PathPreferenceState *cpath_preference = NULL; EvpnRouteKey evpn_key(NULL, vrf->GetName(), event.mac_, event.ip_, event.vxlan_id_); const EvpnRouteEntry *evpn_rt = static_cast<const EvpnRouteEntry *>( vrf->GetEvpnRouteTable()->FindActiveEntry(&evpn_key)); if (evpn_rt) { cpath_preference = static_cast<const PathPreferenceState *>( evpn_rt->GetState(vrf->GetEvpnRouteTable(), state->evpn_rt_id_)); if (cpath_preference) { path_preference = const_cast<PathPreferenceState *>(cpath_preference); path_preference_sm = path_preference->GetSM(vm_intf->peer()); if (path_preference_sm) { EvTrafficSeen ev; path_preference_sm->process_event(ev); } } } EvpnRouteKey evpn_null_ip_key(NULL, vrf->GetName(), event.mac_, Ip4Address(0), event.vxlan_id_); evpn_rt = static_cast<const EvpnRouteEntry *>( vrf->GetEvpnRouteTable()->FindActiveEntry(&evpn_null_ip_key)); if (evpn_rt) { cpath_preference = static_cast<const PathPreferenceState *>( evpn_rt->GetState(vrf->GetEvpnRouteTable(), state->evpn_rt_id_)); if (cpath_preference) { path_preference = const_cast<PathPreferenceState *>(cpath_preference); path_preference_sm = path_preference->GetSM(vm_intf->peer()); if (path_preference_sm) { EvTrafficSeen ev; path_preference_sm->process_event(ev); } } } InetUnicastRouteKey rt_key(NULL, vrf->GetName(), event.ip_, event.plen_); const InetUnicastRouteEntry *rt = NULL; if (event.ip_.is_v4()) { rt = static_cast<const InetUnicastRouteEntry *>( vrf->GetInet4UnicastRouteTable()->FindActiveEntry(&rt_key)); } else if(event.ip_.is_v6()) { rt = static_cast<const InetUnicastRouteEntry *>( vrf->GetInet6UnicastRouteTable()->FindActiveEntry(&rt_key)); } if (!rt) { return true; } if (event.ip_.is_v4()) { cpath_preference = static_cast<const PathPreferenceState *>( rt->GetState(vrf->GetInet4UnicastRouteTable(), state->uc_rt_id_)); } else if(event.ip_.is_v6()) { cpath_preference = static_cast<const PathPreferenceState *>( rt->GetState(vrf->GetInet6UnicastRouteTable(), state->uc6_rt_id_)); } if (!cpath_preference) { return true; } path_preference = const_cast<PathPreferenceState *>(cpath_preference); path_preference_sm = path_preference->GetSM(vm_intf->peer()); if (path_preference_sm) { EvTrafficSeen ev; path_preference_sm->process_event(ev); } #if 0 //Enqueue event for same on all dependent routes of interface const PathPreferenceIntfState *cintf_state = static_cast<const PathPreferenceIntfState *>( vm_intf->GetState(agent_->interface_table(), intf_id_)); PathPreferenceIntfState *intf_state = const_cast<PathPreferenceIntfState *>(cintf_state); /* Only events with IPv4 IP is enqueued now */ intf_state->UpdateDependentRoute(vrf->GetName(), event.ip_.to_v4(), event.plen_, true, this); #endif return true; } void PathPreferenceModule::EnqueueTrafficSeen(IpAddress ip, uint32_t plen, uint32_t interface_index, uint32_t vrf_index, const MacAddress &mac) { const Interface *intf = agent_->interface_table()->FindInterface(interface_index); if (intf == NULL || (intf->type() != Interface::VM_INTERFACE)) { return; } const VmInterface *vm_intf = static_cast<const VmInterface *>(intf); //If the local preference is set by config, we dont identify Active //node dynamically if (vm_intf->local_preference() != VmInterface::INVALID) { return; } const VrfEntry *vrf = agent_->vrf_table()->FindVrfFromId(vrf_index); if (vrf == NULL) { return; } InetUnicastRouteEntry *rt = vrf->GetUcRoute(ip); EvpnRouteKey key(vm_intf->peer(), vrf->GetName(), mac, ip, vm_intf->ethernet_tag()); EvpnRouteEntry *evpn_rt = static_cast<EvpnRouteEntry *>( vrf->GetEvpnRouteTable()->FindActiveEntry(&key)); if (!rt && !evpn_rt) { return; } const AgentPath *path = NULL; const AgentPath *evpn_path = NULL; if (rt) { path = rt->FindPath(vm_intf->peer()); } if (evpn_rt) { evpn_path = evpn_rt->FindPath(vm_intf->peer()); } if (!path && !evpn_path) { return; } PathPreferenceEventContainer event; if (rt) { event.ip_ = rt->addr(); event.plen_ = rt->plen(); } else { // (0 IP + Mac) event required for EVPN event.ip_ = IpAddress(); event.plen_ = 32; } event.interface_index_ = interface_index; event.vrf_index_ = vrf_index; event.mac_ = mac; event.vxlan_id_ = vm_intf->ethernet_tag(); work_queue_.Enqueue(event); } void PathPreferenceModule::VrfNotify(DBTablePartBase *partition, DBEntryBase *e) { const VrfEntry *vrf = static_cast<const VrfEntry *>(e); PathPreferenceVrfState *vrf_state = static_cast<PathPreferenceVrfState *>(e->GetState(partition->parent(), vrf_id_)); if (vrf->IsDeleted()) { if (vrf_state) { e->ClearState(partition->parent(), vrf_id_); delete vrf_state; } return; } if (vrf_state) { return; } PathPreferenceRouteListener *uc_rt_listener = new PathPreferenceRouteListener(agent_, vrf->GetInet4UnicastRouteTable()); uc_rt_listener->Init(); PathPreferenceRouteListener *evpn_rt_listener = new PathPreferenceRouteListener(agent_, vrf->GetEvpnRouteTable()); evpn_rt_listener->Init(); PathPreferenceRouteListener *uc6_rt_listener = new PathPreferenceRouteListener(agent_, vrf->GetInet6UnicastRouteTable()); uc6_rt_listener->Init(); vrf_state = new PathPreferenceVrfState(uc_rt_listener->id(), evpn_rt_listener->id(), uc6_rt_listener->id()); e->SetState(partition->parent(), vrf_id_, vrf_state); return; } void PathPreferenceModule::IntfNotify(DBTablePartBase *partition, DBEntryBase *e) { const Interface *intf = static_cast<const Interface *>(e); if (intf->type() != Interface::VM_INTERFACE) { return; } PathPreferenceIntfState *intf_state = static_cast<PathPreferenceIntfState *>(e->GetState(partition->parent(), intf_id_)); if (intf->IsDeleted()) { if (intf_state) { e->ClearState(partition->parent(), intf_id_); delete intf_state; } return; } const VmInterface *vm_intf = static_cast<const VmInterface *>(intf); if (!intf_state) { intf_state = new PathPreferenceIntfState(vm_intf); } intf_state->Notify(); e->SetState(partition->parent(), intf_id_, intf_state); } void PathPreferenceModule::AddUnresolvedPath(PathPreferenceState *sm) { unresolved_paths_.insert(sm); } void PathPreferenceModule::DeleteUnresolvedPath(PathPreferenceState *sm) { std::set<PathPreferenceState *>::iterator it = unresolved_paths_.find(sm); if (it != unresolved_paths_.end()) { unresolved_paths_.erase(it); } } void PathPreferenceModule::Resolve() { std::set<PathPreferenceState *> tmp = unresolved_paths_; unresolved_paths_.clear(); //Process all the elements std::set<PathPreferenceState *>::iterator it = tmp.begin(); for(; it != tmp.end(); it++) { (*it)->Process(); } } void PathPreferenceModule::Init() { vrf_id_ = agent_->vrf_table()->Register( boost::bind(&PathPreferenceModule::VrfNotify, this, _1, _2)); #if 0 intf_id_ = agent_->interface_table()->Register( boost::bind(&PathPreferenceModule::IntfNotify, this, _1, _2)); #endif } void PathPreferenceModule::Shutdown() { agent_->vrf_table()->Unregister(vrf_id_); #if 0 agent_->interface_table()->Unregister(intf_id_); #endif }
// Copyright (C) 2018-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <memory> #include <vector> #include <algorithm> #include <transformations_visibility.hpp> #include "ngraph/coordinate_diff.hpp" #include "ngraph/op/op.hpp" namespace ngraph { namespace op { class TRANSFORMATIONS_API ConvolutionIE : public Op { public: static constexpr NodeTypeInfo type_info{"ConvolutionIE", 1}; const NodeTypeInfo& get_type_info() const override { return type_info; } /// \brief Constructs a batched convolution operation. ConvolutionIE() = default; /// \brief Constructs a batched convolution operation. /// /// \param data_batch The node producing the input data batch tensor.<br> /// `[N, C_IN, D1, ... Df]` /// \param filters The node producing the filters tensor.<br> /// `[C_OUT, C_IN, F1, ... Ff]` /// \param strides The strides.<br> /// `[f]` /// \param dilations The dilations.<br> /// `[f]` /// \param pads_begin The beginning of padding shape.<br> /// `[f]` /// \param pads_end The end of padding shape.<br> /// `[f]` /// \param auto_pad The pad type for automatically computing padding sizes.<br> /// `[f]` /// /// Output `[N, C_OUT, R1, ... Rf]` /// ConvolutionIE(const Output<Node>& data_batch, const Output<Node>& filters, const Strides& strides, const Strides& dilations, const CoordinateDiff& pads_begin, const CoordinateDiff& pads_end, const size_t& group = 1, const PadType& auto_pad = PadType::EXPLICIT); ConvolutionIE(const Output<Node>& data_batch, const Output<Node>& filters, const Output<Node>& bias, const Strides& strides, const Strides& dilations, const CoordinateDiff& pads_begin, const CoordinateDiff& pads_end, const size_t& group = 1, const PadType& auto_pad = PadType::EXPLICIT); void validate_and_infer_types() override; std::shared_ptr<Node> clone_with_new_inputs(const OutputVector & new_args) const override; /// \return The strides. const Strides& get_strides() const { return m_strides; } void set_strides(const Strides& strides) { m_strides = strides; } /// \return The dilations. const Strides& get_dilations() const { return m_dilations; } void set_dilations(const Strides& dilations) { m_dilations = dilations; } /// \return The padding-below sizes (possibly negative). const CoordinateDiff& get_pads_begin() const { return m_pads_begin; } void set_pads_begin(const CoordinateDiff& pads_begin) { m_pads_begin = pads_begin; } /// \return The padding-above sizes (possibly negative). const CoordinateDiff& get_pads_end() const { return m_pads_end; } void set_adding_above(const CoordinateDiff& pads_end) { m_pads_end = pads_end; } /// \return The pad type for convolution. const PadType& get_auto_pad() const { return m_auto_pad; } void set_auto_pad(const PadType& auto_pad) { m_auto_pad = auto_pad; } /// \return The groups for convolution. const size_t& get_group() const { return m_group; } void set_group(const size_t & group) { m_group = group; } protected: Strides m_strides; Strides m_dilations; CoordinateDiff m_pads_begin; CoordinateDiff m_pads_end; PadType m_auto_pad; size_t m_group; }; } // namespace op } // namespace ngraph
#include <Chart.hpp> #include <Event.hpp> Chart::Chart() : packages(), keysounds() { } void Chart::AddPackage(Package pkg) { packages.push_back(pkg); } void Chart::AddKeysound(std::string name) { keysounds[name] = keysounds.size() + 1; } std::vector<Package> Chart::GetPackages() { return packages; } int Chart::GetKeysound(std::string name) { return keysounds[name]; }
// // MSLocalSocket.hpp // MSSocket // // Created by Mihail Shevchuk on 15.01.18. // Copyright © 2018 Mihail Shevchuk. All rights reserved. // #ifndef MSLocalSocket_hpp #define MSLocalSocket_hpp #include "MSSocket.hpp" class MSLocalSocket: public MSSocket { public: MSLocalSocket(pChar serverPath, uint32_t sizeBuffer); virtual ~MSLocalSocket() {}; bool Connect(); inline void GenerateEvent(MSEvent event) { // mErrorManager->ThrowLocalEvent(event); } private: sockaddr_un mServerAdress; void CreateSocket(); void ReceiveMessage(pVoid message, size_t size); }; #endif /* MSLocalSocket_hpp */
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the name of Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 * COPYRIGHT OWNER OR 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. *********************************************************************/ /* Author: Ioan Sucan, Mario Prats, Dave Coleman */ #include <moveit/benchmarks/benchmark_execution.h> #include <moveit/benchmarks/benchmarks_utils.h> #include <moveit/kinematic_constraints/utils.h> #include <moveit/planning_scene/planning_scene.h> #include <moveit/robot_state/conversions.h> #include <boost/regex.hpp> #include <boost/tokenizer.hpp> #include <boost/lexical_cast.hpp> #include <boost/program_options/parsers.hpp> #include <boost/program_options/variables_map.hpp> #include <boost/algorithm/string/case_conv.hpp> #include <boost/algorithm/string.hpp> #include <boost/math/constants/constants.hpp> #include <boost/progress.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <eigen_conversions/eigen_msg.h> #include <Eigen/Core> #include <Eigen/Geometry> #include <fstream> #include <memory> namespace moveit_benchmarks { namespace { // update the constrained link for Position and Orientation constraints, if that link is empty void checkConstrainedLink(moveit_msgs::Constraints &c, const std::string &link_name) { for (std::size_t i = 0; i < c.position_constraints.size(); ++i) if (c.position_constraints[i].link_name.empty()) c.position_constraints[i].link_name = link_name; for (std::size_t i = 0; i < c.orientation_constraints.size(); ++i) if (c.orientation_constraints[i].link_name.empty()) c.orientation_constraints[i].link_name = link_name; } void checkHeader(moveit_msgs::Constraints &c, const std::string &header_frame) { for (std::size_t i = 0; i < c.position_constraints.size(); ++i) if (c.position_constraints[i].header.frame_id.empty()) { c.position_constraints[i].header.frame_id = header_frame; c.position_constraints[i].header.stamp = ros::Time::now(); } for (std::size_t i = 0; i < c.orientation_constraints.size(); ++i) if (c.orientation_constraints[i].header.frame_id.empty()) { c.orientation_constraints[i].header.frame_id = header_frame; c.orientation_constraints[i].header.stamp = ros::Time::now(); } } } } moveit_benchmarks::BenchmarkExecution::BenchmarkExecution(const planning_scene::PlanningScenePtr &scene, warehouse_ros::DatabaseConnection::Ptr conn) : planning_scene_(scene), pss_(conn), psws_(conn), cs_(conn), tcs_(conn), rs_(conn) { // load the pluginlib class loader try { planner_plugin_loader_.reset(new pluginlib::ClassLoader<planning_interface::PlannerManager>( "moveit_core", "planning_interface::PlannerManager")); } catch (pluginlib::PluginlibException &ex) { ROS_FATAL_STREAM("Exception while creating planning plugin loader " << ex.what()); } // load the planning plugins const std::vector<std::string> &classes = planner_plugin_loader_->getDeclaredClasses(); for (std::size_t i = 0; i < classes.size(); ++i) { ROS_INFO("Attempting to load and configure %s", classes[i].c_str()); try { planning_interface::PlannerManagerPtr p = planner_plugin_loader_->createUniqueInstance(classes[i]); p->initialize(planning_scene_->getRobotModel(), ""); planner_interfaces_[classes[i]] = p; } catch (pluginlib::PluginlibException &ex) { ROS_ERROR_STREAM("Exception while loading planner '" << classes[i] << "': " << ex.what()); } } // error check if (planner_interfaces_.empty()) ROS_ERROR("No planning plugins have been loaded. Nothing to do for the benchmarking service."); else { std::stringstream ss; for (std::map<std::string, planning_interface::PlannerManagerPtr>::const_iterator it = planner_interfaces_.begin(); it != planner_interfaces_.end(); ++it) ss << it->first << " "; ROS_INFO("Available planner instances: %s", ss.str().c_str()); } } void moveit_benchmarks::BenchmarkExecution::runAllBenchmarks(BenchmarkType type) { moveit_warehouse::PlanningSceneWithMetadata pswm; moveit_warehouse::PlanningSceneWorldWithMetadata pswwm; bool world_only = false; // read the environment geometry if (!pss_.hasPlanningScene(options_.scene)) { if (psws_.hasPlanningSceneWorld(options_.scene)) { bool ok = false; try { ok = psws_.getPlanningSceneWorld(pswwm, options_.scene); } catch (std::runtime_error &ex) { ROS_ERROR("%s", ex.what()); } if (!ok) return; world_only = true; } else { std::stringstream ss; std::vector<std::string> names; pss_.getPlanningSceneNames(names); for (std::size_t i = 0; i < names.size(); ++i) ss << names[i] << " "; ROS_ERROR("Scene '%s' not found in warehouse. Available names: %s", options_.scene.c_str(), ss.str().c_str()); return; } } else { bool ok = false; try { ok = pss_.getPlanningScene(pswm, options_.scene); } catch (std::runtime_error &ex) { ROS_ERROR("%s", ex.what()); } if (!ok) { ROS_ERROR("Scene '%s' not found in warehouse", options_.scene.c_str()); return; } } // fill in the environment geometry in the benchmark request BenchmarkRequest req; req.benchmark_type = type; if (world_only) { req.scene.world = static_cast<const moveit_msgs::PlanningSceneWorld &>(*pswwm); req.scene.robot_model_name = "NO ROBOT INFORMATION. ONLY WORLD GEOMETRY"; // so that run_benchmark sees a different robot name } else req.scene = static_cast<const moveit_msgs::PlanningScene &>(*pswm); // check if this scene has associated queries req.scene.name = options_.scene; std::vector<std::string> planning_queries_names; try { pss_.getPlanningQueriesNames(options_.query_regex, planning_queries_names, options_.scene); } catch (std::runtime_error &ex) { ROS_ERROR("%s", ex.what()); } if (planning_queries_names.empty()) ROS_DEBUG("Scene '%s' has no associated queries", options_.scene.c_str()); // fill in the plugins option req.plugins = options_.plugins; // see if we have any start states specified; if we do, we run the benchmark for // each start state; if not, we run it for one start state only: the current one saved in the loaded scene std::vector<std::string> start_states; if (!options_.start_regex.empty()) { boost::regex start_regex(options_.start_regex); std::vector<std::string> state_names; rs_.getKnownRobotStates(state_names); for (std::size_t i = 0; i < state_names.size(); ++i) { boost::cmatch match; if (boost::regex_match(state_names[i].c_str(), match, start_regex)) start_states.push_back(state_names[i]); } if (start_states.empty()) { ROS_WARN("No stored states matched the provided regex: '%s'", options_.start_regex.c_str()); return; } else ROS_INFO("Running benchmark using %u start states.", (unsigned int)start_states.size()); } else ROS_INFO("No specified start state. Running benchmark once with the default start state."); unsigned int n_call = 0; bool have_more_start_states = true; std::unique_ptr<moveit_msgs::RobotState> start_state_to_use; while (have_more_start_states) { start_state_to_use.reset(); // if no set of start states provided, run once for the current one if (options_.start_regex.empty()) have_more_start_states = false; else { // otherwise, extract the start states one by one std::string state_name = start_states.back(); start_states.pop_back(); have_more_start_states = !start_states.empty(); moveit_warehouse::RobotStateWithMetadata robot_state; bool got_robot_state = false; try { got_robot_state = rs_.getRobotState(robot_state, state_name); } catch (std::runtime_error &ex) { ROS_ERROR("%s", ex.what()); } if (got_robot_state) { start_state_to_use.reset(new moveit_msgs::RobotState(*robot_state)); ROS_INFO("Loaded start state '%s'", state_name.c_str()); } else continue; } // run benchmarks for specified queries // ************************************ if (!options_.query_regex.empty()) { for (std::size_t i = 0; i < planning_queries_names.size(); ++i) { moveit_warehouse::MotionPlanRequestWithMetadata planning_query; pss_.getPlanningQuery(planning_query, options_.scene, planning_queries_names[i]); // Save name of goal - only used for later analysis req.goal_name = planning_queries_names[i]; // read request from db req.motion_plan_request = static_cast<const moveit_msgs::MotionPlanRequest &>(*planning_query); // set the workspace bounds req.motion_plan_request.workspace_parameters = options_.workspace_parameters; // update request given .cfg options if (start_state_to_use) req.motion_plan_request.start_state = *start_state_to_use; req.filename = options_.output + "." + boost::lexical_cast<std::string>(++n_call) + ".log"; if (!options_.group_override.empty()) req.motion_plan_request.group_name = options_.group_override; if (options_.timeout > 0.0) req.motion_plan_request.allowed_planning_time = options_.timeout; if (!options_.default_constrained_link.empty()) { checkConstrainedLink(req.motion_plan_request.path_constraints, options_.default_constrained_link); for (std::size_t j = 0; j < req.motion_plan_request.goal_constraints.size(); ++j) checkConstrainedLink(req.motion_plan_request.goal_constraints[j], options_.default_constrained_link); } if (!options_.planning_frame.empty()) { checkHeader(req.motion_plan_request.path_constraints, options_.planning_frame); for (std::size_t j = 0; j < req.motion_plan_request.goal_constraints.size(); ++j) checkHeader(req.motion_plan_request.goal_constraints[j], options_.planning_frame); } ROS_INFO("Benckmarking query '%s' (%d of %d)", planning_queries_names[i].c_str(), (int)i + 1, (int)planning_queries_names.size()); runBenchmark(req); } } // if we have any goals specified as constraints, run benchmarks for those as well // ******************************************************************************* if (!options_.goal_regex.empty()) { std::vector<std::string> cnames; cs_.getKnownConstraints(options_.goal_regex, cnames); for (std::size_t i = 0; i < cnames.size(); ++i) { moveit_warehouse::ConstraintsWithMetadata constr; bool got_constraints = false; try { got_constraints = cs_.getConstraints(constr, cnames[i]); } catch (std::runtime_error &ex) { ROS_ERROR("%s", ex.what()); } if (got_constraints) { // Save name of goal - only used for later analysis req.goal_name = cnames[i]; // construct a planning request from the constraints message req.motion_plan_request = moveit_msgs::MotionPlanRequest(); req.motion_plan_request.goal_constraints.resize(1); if (start_state_to_use) req.motion_plan_request.start_state = *start_state_to_use; req.motion_plan_request.goal_constraints[0] = *constr; // set the workspace bounds req.motion_plan_request.workspace_parameters = options_.workspace_parameters; // Apply the goal offset for constraints that appear to specify IK poses if (constr->position_constraints.size() == 1 && constr->orientation_constraints.size() == 1 && kinematic_constraints::countIndividualConstraints(*constr) == 2 && constr->position_constraints[0].constraint_region.primitive_poses.size() == 1 && constr->position_constraints[0].constraint_region.mesh_poses.empty()) { geometry_msgs::Pose wMc_msg; wMc_msg.position = constr->position_constraints[0].constraint_region.primitive_poses[0].position; wMc_msg.orientation = constr->orientation_constraints[0].orientation; Eigen::Affine3d wMc; tf::poseMsgToEigen(wMc_msg, wMc); Eigen::Affine3d offset_tf(Eigen::AngleAxis<double>(options_.offsets[3], Eigen::Vector3d::UnitX()) * Eigen::AngleAxis<double>(options_.offsets[4], Eigen::Vector3d::UnitY()) * Eigen::AngleAxis<double>(options_.offsets[5], Eigen::Vector3d::UnitZ())); offset_tf.translation() = Eigen::Vector3d(options_.offsets[0], options_.offsets[1], options_.offsets[2]); Eigen::Affine3d wMnc = wMc * offset_tf; geometry_msgs::Pose wMnc_msg; tf::poseEigenToMsg(wMnc, wMnc_msg); req.motion_plan_request.goal_constraints[0] .position_constraints[0] .constraint_region.primitive_poses[0] .position = wMnc_msg.position; req.motion_plan_request.goal_constraints[0].orientation_constraints[0].orientation = wMnc_msg.orientation; } if (!options_.group_override.empty()) req.motion_plan_request.group_name = options_.group_override; if (options_.timeout > 0.0) req.motion_plan_request.allowed_planning_time = options_.timeout; if (!options_.default_constrained_link.empty()) checkConstrainedLink(req.motion_plan_request.goal_constraints[0], options_.default_constrained_link); if (!options_.planning_frame.empty()) checkHeader(req.motion_plan_request.goal_constraints[0], options_.planning_frame); req.filename = options_.output + "." + boost::lexical_cast<std::string>(++n_call) + ".log"; ROS_INFO("Benckmarking goal '%s' (%d of %d)", cnames[i].c_str(), (int)i + 1, (int)cnames.size()); runBenchmark(req); } } } // if we have any goals specified as trajectory constraints, run benchmarks for those as well // ****************************************************************************************** if (!options_.trajectory_regex.empty()) { std::vector<std::string> cnames; tcs_.getKnownTrajectoryConstraints(options_.trajectory_regex, cnames); for (std::size_t i = 0; i < cnames.size(); ++i) { moveit_warehouse::TrajectoryConstraintsWithMetadata constr; bool got_constraints = false; try { got_constraints = tcs_.getTrajectoryConstraints(constr, cnames[i]); } catch (std::runtime_error &ex) { ROS_ERROR("%s", ex.what()); } // Save name of goal - only used for later analysis req.goal_name = cnames[i]; if (got_constraints) { // construct a planning request from the trajectory constraints message req.motion_plan_request = moveit_msgs::MotionPlanRequest(); if (start_state_to_use) req.motion_plan_request.start_state = *start_state_to_use; req.motion_plan_request.trajectory_constraints = *constr; // set the workspace bounds req.motion_plan_request.workspace_parameters = options_.workspace_parameters; Eigen::Affine3d offset_tf(Eigen::AngleAxis<double>(options_.offsets[3], Eigen::Vector3d::UnitX()) * Eigen::AngleAxis<double>(options_.offsets[4], Eigen::Vector3d::UnitY()) * Eigen::AngleAxis<double>(options_.offsets[5], Eigen::Vector3d::UnitZ())); offset_tf.translation() = Eigen::Vector3d(options_.offsets[0], options_.offsets[1], options_.offsets[2]); // Apply waypoint offsets, check fields for (std::size_t tc = 0; tc < constr->constraints.size(); ++tc) { // Apply the goal offset for constraints that appear to specify IK poses if (constr->constraints[tc].position_constraints.size() == 1 && constr->constraints[tc].orientation_constraints.size() == 1 && kinematic_constraints::countIndividualConstraints(constr->constraints[tc]) == 2 && constr->constraints[tc].position_constraints[0].constraint_region.primitive_poses.size() == 1 && constr->constraints[tc].position_constraints[0].constraint_region.mesh_poses.empty()) { geometry_msgs::Pose wMc_msg; wMc_msg.position = req.motion_plan_request.trajectory_constraints.constraints[tc] .position_constraints[0] .constraint_region.primitive_poses[0] .position; wMc_msg.orientation = req.motion_plan_request.trajectory_constraints.constraints[tc].orientation_constraints[0].orientation; Eigen::Affine3d wMc; tf::poseMsgToEigen(wMc_msg, wMc); Eigen::Affine3d wMnc = wMc * offset_tf; geometry_msgs::Pose wMnc_msg; tf::poseEigenToMsg(wMnc, wMnc_msg); req.motion_plan_request.trajectory_constraints.constraints[tc] .position_constraints[0] .constraint_region.primitive_poses[0] .position = wMnc_msg.position; req.motion_plan_request.trajectory_constraints.constraints[tc].orientation_constraints[0].orientation = wMnc_msg.orientation; } if (!options_.default_constrained_link.empty()) checkConstrainedLink(req.motion_plan_request.trajectory_constraints.constraints[tc], options_.default_constrained_link); if (!options_.planning_frame.empty()) checkHeader(req.motion_plan_request.trajectory_constraints.constraints[tc], options_.planning_frame); } if (!options_.group_override.empty()) req.motion_plan_request.group_name = options_.group_override; if (options_.timeout > 0.0) req.motion_plan_request.allowed_planning_time = options_.timeout; req.filename = options_.output + ".trajectory." + boost::lexical_cast<std::string>(i + 1) + ".log"; ROS_INFO("Benckmarking trajectory '%s' (%d of %d)", cnames[i].c_str(), (int)i + 1, (int)cnames.size()); runBenchmark(req); } } } } } bool moveit_benchmarks::BenchmarkExecution::readOptions(const std::string &filename) { ROS_INFO("Loading '%s'...", filename.c_str()); std::ifstream cfg(filename.c_str()); if (!cfg.good()) { ROS_ERROR_STREAM("Unable to open file '" << filename << "'"); return false; } // "scene" options try { boost::program_options::options_description desc; desc.add_options()("scene.name", boost::program_options::value<std::string>(), "Scene name")( "scene.runs", boost::program_options::value<std::string>()->default_value("1"), "Number of runs")( "scene.timeout", boost::program_options::value<std::string>()->default_value(""), "Timeout for planning (s)")("scene.start", boost::program_options::value<std::string>()->default_value(""), "Regex for the start states to use")( "scene.query", boost::program_options::value<std::string>()->default_value(".*"), "Regex for the queries to execute")("scene.goal", boost::program_options::value<std::string>()->default_value(""), "Regex for the names of constraints to use as goals")( "scene.trajectory", boost::program_options::value<std::string>()->default_value(""), "Regex for the names of constraints to use as trajectories")( "scene.group", boost::program_options::value<std::string>()->default_value(""), "Override the group to plan for")("scene.planning_frame", boost::program_options::value<std::string>()->default_value(""), "Override the planning frame to use")( "scene.default_constrained_link", boost::program_options::value<std::string>()->default_value(""), "Specify the default link to consider as constrained when one is not specified in a moveit_msgs::Constraints " "message")("scene.goal_offset_x", boost::program_options::value<std::string>()->default_value("0.0"), "Goal offset in x")( "scene.goal_offset_y", boost::program_options::value<std::string>()->default_value("0.0"), "Goal offset in y")( "scene.goal_offset_z", boost::program_options::value<std::string>()->default_value("0.0"), "Goal offset in z")("scene.goal_offset_roll", boost::program_options::value<std::string>()->default_value("0.0"), "Goal offset in roll")( "scene.goal_offset_pitch", boost::program_options::value<std::string>()->default_value("0.0"), "Goal offset in pitch")("scene.goal_offset_yaw", boost::program_options::value<std::string>()->default_value("0.0"), "Goal offset in yaw")("scene.output", boost::program_options::value<std::string>(), "Location of benchmark log file")( "scene.workspace", boost::program_options::value<std::string>(), "Bounding box of workspace to plan in - " "min_x, min_y, min_z, max_x, max_y, max_z")( "scene.workspace_frame", boost::program_options::value<std::string>(), "Frame id of bounding box of workspace " "to plan in"); boost::program_options::variables_map vm; boost::program_options::parsed_options po = boost::program_options::parse_config_file(cfg, desc, true); cfg.close(); boost::program_options::store(po, vm); std::map<std::string, std::string> declared_options; for (boost::program_options::variables_map::iterator it = vm.begin(); it != vm.end(); ++it) declared_options[it->first] = boost::any_cast<std::string>(vm[it->first].value()); options_.scene = declared_options["scene.name"]; options_.start_regex = declared_options["scene.start"]; options_.query_regex = declared_options["scene.query"]; options_.goal_regex = declared_options["scene.goal"]; options_.trajectory_regex = declared_options["scene.trajectory"]; options_.group_override = declared_options["scene.group"]; options_.default_constrained_link = declared_options["scene.default_constrained_link"]; options_.planning_frame = declared_options["scene.planning_frame"]; try { memset(options_.offsets, 0, 6 * sizeof(double)); if (!declared_options["scene.goal_offset_x"].empty()) options_.offsets[0] = boost::lexical_cast<double>(declared_options["scene.goal_offset_x"]); if (!declared_options["scene.goal_offset_y"].empty()) options_.offsets[1] = boost::lexical_cast<double>(declared_options["scene.goal_offset_y"]); if (!declared_options["scene.goal_offset_z"].empty()) options_.offsets[2] = boost::lexical_cast<double>(declared_options["scene.goal_offset_z"]); if (!declared_options["scene.goal_offset_roll"].empty()) options_.offsets[3] = boost::lexical_cast<double>(declared_options["scene.goal_offset_roll"]); if (!declared_options["scene.goal_offset_pitch"].empty()) options_.offsets[4] = boost::lexical_cast<double>(declared_options["scene.goal_offset_pitch"]); if (!declared_options["scene.goal_offset_yaw"].empty()) options_.offsets[5] = boost::lexical_cast<double>(declared_options["scene.goal_offset_yaw"]); } catch (boost::bad_lexical_cast &ex) { ROS_WARN("%s", ex.what()); } // Workspace bounds if (!declared_options["scene.workspace"].empty()) { std::vector<std::string> strings; boost::split(strings, declared_options["scene.workspace"], boost::is_any_of(",")); if (strings.size() != 6) { ROS_WARN_STREAM("Invalid number of workspace parameters. Expected 6, recieved " << strings.size()); } else if (declared_options["scene.workspace_frame"].empty()) { ROS_WARN_STREAM("No workspace_frame parameter provided, required with the workspace frame"); } else { try { // add workspace bounds if specified in the .cfg file options_.workspace_parameters.header.frame_id = declared_options["scene.workspace_frame"]; options_.workspace_parameters.header.stamp = ros::Time::now(); options_.workspace_parameters.min_corner.x = boost::lexical_cast<double>(strings[0]); options_.workspace_parameters.min_corner.y = boost::lexical_cast<double>(strings[1]); options_.workspace_parameters.min_corner.z = boost::lexical_cast<double>(strings[2]); options_.workspace_parameters.max_corner.x = boost::lexical_cast<double>(strings[3]); options_.workspace_parameters.max_corner.y = boost::lexical_cast<double>(strings[4]); options_.workspace_parameters.max_corner.z = boost::lexical_cast<double>(strings[5]); } catch (boost::bad_lexical_cast &ex) { ROS_WARN("%s", ex.what()); } } } // Filename options_.output = declared_options["scene.output"]; if (options_.output.empty()) options_.output = filename; options_.plugins.clear(); // Runs std::size_t default_run_count = 1; if (!declared_options["scene.runs"].empty()) { try { default_run_count = boost::lexical_cast<std::size_t>(declared_options["scene.runs"]); } catch (boost::bad_lexical_cast &ex) { ROS_WARN("%s", ex.what()); } } options_.default_run_count = default_run_count; // Timeout options_.timeout = 0.0; if (!declared_options["scene.timeout"].empty()) { try { options_.timeout = boost::lexical_cast<double>(declared_options["scene.timeout"]); } catch (boost::bad_lexical_cast &ex) { ROS_WARN("%s", ex.what()); } } // Process non-scene options std::vector<std::string> unr = boost::program_options::collect_unrecognized(po.options, boost::program_options::exclude_positional); std::unique_ptr<PlanningPluginOptions> bpo; for (std::size_t i = 0; i < unr.size() / 2; ++i) { std::string key = boost::to_lower_copy(unr[i * 2]); std::string val = unr[i * 2 + 1]; // "plugin" options if (key.substr(0, 7) == "plugin.") { std::string k = key.substr(7); if (k == "name") { if (bpo) options_.plugins.push_back(*bpo); bpo.reset(new PlanningPluginOptions()); bpo->name = val; bpo->runs = default_run_count; } else if (k == "runs") { if (bpo) { try { bpo->runs = boost::lexical_cast<std::size_t>(val); } catch (boost::bad_lexical_cast &ex) { ROS_WARN("%s", ex.what()); } } else ROS_WARN("Ignoring option '%s' = '%s'. Please include plugin name first.", key.c_str(), val.c_str()); } else if (k == "planners") { if (bpo) { boost::char_separator<char> sep(" "); boost::tokenizer<boost::char_separator<char>> tok(val, sep); for (boost::tokenizer<boost::char_separator<char>>::iterator beg = tok.begin(); beg != tok.end(); ++beg) bpo->planners.push_back(*beg); } else ROS_WARN("Ignoring option '%s' = '%s'. Please include plugin name first.", key.c_str(), val.c_str()); } } // parameter sweeping option else if (key.substr(0, 6) == "sweep.") { std::string sweep_var = key.substr(6); // Convert the string of a:b:c numbers into parsed doubles std::vector<std::string> strings; boost::split(strings, val, boost::is_any_of(":")); if (strings.size() != 3) { ROS_WARN_STREAM("Invalid sweep parameter for key " << sweep_var << ". Expected 3 values (start, iterator, end) but only recieved " << strings.size()); continue; } ParameterOptions new_sweep; new_sweep.is_sweep = true; // not a fractional factorial analaysis try { new_sweep.start = boost::lexical_cast<double>(strings[0]); new_sweep.step_size = boost::lexical_cast<double>(strings[1]); new_sweep.end = boost::lexical_cast<double>(strings[2]); new_sweep.key = sweep_var; // for logging to file: std::ostringstream ss; ss << "param_" << sweep_var << " REAL"; new_sweep.log_key = ss.str(); } catch (boost::bad_lexical_cast &ex) { ROS_WARN("%s", ex.what()); } // Error check if (new_sweep.start > new_sweep.end) { ROS_ERROR_STREAM("Invalid sweep parameter for key " << sweep_var << ". Start is greater than end"); continue; } // Insert into array of all sweeps param_options_.push_back(new_sweep); } else { ROS_WARN("Unknown option: '%s' = '%s'", key.c_str(), val.c_str()); continue; } } if (bpo) options_.plugins.push_back(*bpo); } catch (...) { ROS_ERROR_STREAM("Unable to parse '" << filename << "'"); return false; } return true; } void moveit_benchmarks::BenchmarkExecution::printOptions(std::ostream &out) { out << "Benchmark for scene '" << options_.scene << "' to be saved at location '" << options_.output << "'" << std::endl; if (!options_.query_regex.empty()) out << "Planning requests associated to the scene that match '" << options_.query_regex << "' will be evaluated" << std::endl; if (!options_.goal_regex.empty()) out << "Planning requests constructed from goal constraints that match '" << options_.goal_regex << "' will be evaluated" << std::endl; if (!options_.trajectory_regex.empty()) out << "Planning requests constructed from trajectory constraints that match '" << options_.trajectory_regex << "' will be evaluated" << std::endl; out << "Plugins:" << std::endl; for (std::size_t i = 0; i < options_.plugins.size(); ++i) { out << " * name: " << options_.plugins[i].name << " (to be run " << options_.plugins[i].runs << " times for each planner)" << std::endl; out << " * planners:"; for (std::size_t j = 0; j < options_.plugins[i].planners.size(); ++j) out << ' ' << options_.plugins[i].planners[j]; out << std::endl; } } void moveit_benchmarks::BenchmarkExecution::runBenchmark(BenchmarkRequest &req) { if (req.benchmark_type & BENCHMARK_PLANNERS) runPlanningBenchmark(req); if (req.benchmark_type & BENCHMARK_GOAL_EXISTANCE) runGoalExistenceBenchmark(req); } void moveit_benchmarks::BenchmarkExecution::collectMetrics(RunData &rundata, const planning_interface::MotionPlanDetailedResponse &mp_res, bool solved, double total_time) { rundata["total_time REAL"] = boost::lexical_cast<std::string>(total_time); rundata["solved BOOLEAN"] = boost::lexical_cast<std::string>(solved); double L = 0.0; double clearance = 0.0; double smoothness = 0.0; bool correct = true; if (solved) { double process_time = total_time; for (std::size_t j = 0; j < mp_res.trajectory_.size(); ++j) { correct = true; L = 0.0; clearance = 0.0; smoothness = 0.0; const robot_trajectory::RobotTrajectory &p = *mp_res.trajectory_[j]; // compute path length for (std::size_t k = 1; k < p.getWayPointCount(); ++k) L += p.getWayPoint(k - 1).distance(p.getWayPoint(k)); // compute correctness and clearance collision_detection::CollisionRequest req; for (std::size_t k = 0; k < p.getWayPointCount(); ++k) { collision_detection::CollisionResult res; planning_scene_->checkCollisionUnpadded(req, res, p.getWayPoint(k)); if (res.collision) correct = false; if (!p.getWayPoint(k).satisfiesBounds()) correct = false; double d = planning_scene_->distanceToCollisionUnpadded(p.getWayPoint(k)); if (d > 0.0) // in case of collision, distance is negative clearance += d; } clearance /= (double)p.getWayPointCount(); // compute smoothness if (p.getWayPointCount() > 2) { double a = p.getWayPoint(0).distance(p.getWayPoint(1)); for (std::size_t k = 2; k < p.getWayPointCount(); ++k) { // view the path as a sequence of segments, and look at the triangles it forms: // s1 // /\ s4 // a / \ b | // / \ | // /......\_______| // s0 c s2 s3 // // use Pythagoras generalized theorem to find the cos of the angle between segments a and b double b = p.getWayPoint(k - 1).distance(p.getWayPoint(k)); double cdist = p.getWayPoint(k - 2).distance(p.getWayPoint(k)); double acosValue = (a * a + b * b - cdist * cdist) / (2.0 * a * b); if (acosValue > -1.0 && acosValue < 1.0) { // the smoothness is actually the outside angle of the one we compute double angle = (boost::math::constants::pi<double>() - acos(acosValue)); // and we normalize by the length of the segments double u = 2.0 * angle; /// (a + b); smoothness += u * u; } a = b; } smoothness /= (double)p.getWayPointCount(); } rundata["path_" + mp_res.description_[j] + "_correct BOOLEAN"] = boost::lexical_cast<std::string>(correct); rundata["path_" + mp_res.description_[j] + "_length REAL"] = boost::lexical_cast<std::string>(L); rundata["path_" + mp_res.description_[j] + "_clearance REAL"] = boost::lexical_cast<std::string>(clearance); rundata["path_" + mp_res.description_[j] + "_smoothness REAL"] = boost::lexical_cast<std::string>(smoothness); rundata["path_" + mp_res.description_[j] + "_time REAL"] = boost::lexical_cast<std::string>(mp_res.processing_time_[j]); process_time -= mp_res.processing_time_[j]; } if (process_time <= 0.0) process_time = 0.0; rundata["process_time REAL"] = boost::lexical_cast<std::string>(process_time); } } namespace { bool isIKSolutionCollisionFree(const planning_scene::PlanningScene *scene, robot_state::RobotState *state, const robot_model::JointModelGroup *group, const double *ik_solution, bool *reachable) { state->setJointGroupPositions(group, ik_solution); state->update(); *reachable = true; if (scene->isStateColliding(*state, group->getName(), false)) return false; else return true; } } void moveit_benchmarks::BenchmarkExecution::runPlanningBenchmark(BenchmarkRequest &req) { /* Dev Notes: * planner_interface => planning plugin * planner => planning algorithm within a planning plugin * planner_ids => id of a planner */ // check that all requested plugins exist if (!req.plugins.empty()) for (std::size_t i = 0; i < req.plugins.size(); ++i) if (planner_interfaces_.find(req.plugins[i].name) == planner_interfaces_.end()) ROS_ERROR("Planning interface '%s' was not found", req.plugins[i].name.c_str()); // pointer list of planning plugins std::vector<planning_interface::PlannerManager *> planner_interfaces_to_benchmark; // each planning plugin has a vector of its sub algorithms (planners) that it can run std::vector<std::vector<std::string>> planner_ids_to_benchmark_per_planner_interface; // number of runs to execute every *algorithm* per *plugin* std::vector<std::size_t> runs_per_planner_interface; // average_count_per_planner_interface planning_interface::MotionPlanRequest motion_plan_req = req.motion_plan_request; // loop through each planning interface for (std::map<std::string, planning_interface::PlannerManagerPtr>::const_iterator it = planner_interfaces_.begin(); it != planner_interfaces_.end(); ++it) { // find the plugin that the planning interface belongs to int found = -1; if (!req.plugins.empty()) { for (std::size_t i = 0; i < req.plugins.size(); ++i) { if (req.plugins[i].name == it->first) // this benchmark request includes this planning plugin { found = i; break; } } if (found < 0) continue; } // Determine whether this plugin instance is able to represent this planning request if (it->second->canServiceRequest(motion_plan_req)) { // copy the pointer of the planner_interface planner_interfaces_to_benchmark.push_back(it->second.get()); // add new rows to the "mapper" for the new planner_interface planner_ids_to_benchmark_per_planner_interface.resize(planner_ids_to_benchmark_per_planner_interface.size() + 1); runs_per_planner_interface.resize(runs_per_planner_interface.size() + 1, 1); // TODO: a vector does not need to // be resized, it does so // automatically right?? // get a list of all the algorithms that the planner can use std::vector<std::string> known; it->second->getPlanningAlgorithms(known); if (found < 0 || req.plugins[found].planners.empty()) { // no algorithms found OR this benchmark request does not use this algorithm planner_ids_to_benchmark_per_planner_interface.back() = known; } else { runs_per_planner_interface.back() = std::max<std::size_t>(1, req.plugins[found].runs); // TODO: change it here too // loop through every planner(algorithm) in this plugin that the benchmark request desires for (std::size_t k = 0; k < req.plugins[found].planners.size(); ++k) { bool planner_found = false; for (std::size_t q = 0; q < known.size(); ++q) { // Check if the requested planner is actually in the plugin if (known[q] == req.plugins[found].planners[k] || motion_plan_req.group_name + "[" + req.plugins[found].planners[k] + "]" == known[q]) { planner_found = true; break; } } if (planner_found) planner_ids_to_benchmark_per_planner_interface.back().push_back(req.plugins[found].planners[k]); else { ROS_ERROR("The planner id '%s' is not known to the planning interface '%s'", req.plugins[found].planners[k].c_str(), it->first.c_str()); // To help user debug, list all available planners: ROS_ERROR_STREAM("Known algorithms in " << it->first.c_str() << ":"); for (std::size_t i = 0; i < known.size(); ++i) { ROS_ERROR_STREAM(" - " << known[i]); } } } } if (planner_ids_to_benchmark_per_planner_interface.back().empty()) ROS_ERROR("Planning interface '%s' has no planners defined", it->first.c_str()); } else ROS_WARN_STREAM("Planning interface '" << it->second->getDescription() << "' is not able to solve the specified " "benchmark problem."); } // error check if (planner_interfaces_to_benchmark.empty()) { ROS_ERROR("There are no planning interfaces to benchmark"); return; } // output information about planners to be tested std::stringstream sst; for (std::size_t i = 0; i < planner_interfaces_to_benchmark.size(); ++i) { if (planner_ids_to_benchmark_per_planner_interface[i].empty()) continue; sst << " * " << planner_interfaces_to_benchmark[i]->getDescription() << " - Will execute interface " << runs_per_planner_interface[i] << " times:" << std::endl; for (std::size_t k = 0; k < planner_ids_to_benchmark_per_planner_interface[i].size(); ++k) sst << " - " << planner_ids_to_benchmark_per_planner_interface[i][k] << std::endl; sst << std::endl; } ROS_INFO("Benchmarking Planning Interfaces:\n%s", sst.str().c_str()); // configure planning context if (req.scene.robot_model_name != planning_scene_->getRobotModel()->getName()) { // if we have a different robot, use the world geometry only // clear all geometry from the scene planning_scene_->getWorldNonConst()->clearObjects(); planning_scene_->getCurrentStateNonConst().clearAttachedBodies(); planning_scene_->getCurrentStateNonConst().setToDefaultValues(); planning_scene_->processPlanningSceneWorldMsg(req.scene.world); } else planning_scene_->usePlanningSceneMsg(req.scene); // parameter sweeping functionality std::size_t n_parameter_sets = generateParamCombinations(); // this is for parameter sweeping // get stats on how many planners and total runs will be executed std::size_t total_n_planners = 0; std::size_t total_n_runs = 0; for (std::size_t i = 0; i < planner_ids_to_benchmark_per_planner_interface.size(); ++i) { total_n_planners += planner_ids_to_benchmark_per_planner_interface[i].size(); // n = algorithms * runs * parameters total_n_runs += planner_ids_to_benchmark_per_planner_interface[i].size() * runs_per_planner_interface[i] * n_parameter_sets; } // benchmark all the planners ros::WallTime startTime = ros::WallTime::now(); boost::progress_display progress(total_n_runs, std::cout); std::vector<AlgorithmRunsData> data; // holds all of the results std::vector<bool> first_solution_flag(planner_interfaces_to_benchmark.size(), true); // loop through the planning plugins for (std::size_t i = 0; i < planner_interfaces_to_benchmark.size(); ++i) { // loop through the algorithms in each plugin for (std::size_t j = 0; j < planner_ids_to_benchmark_per_planner_interface[i].size(); ++j) { motion_plan_req.planner_id = planner_ids_to_benchmark_per_planner_interface[i][j]; AlgorithmRunsData runs(runs_per_planner_interface[i] * n_parameter_sets); // param tracking std::size_t param_combinations_id_ = 0; // loop through the desired parameters for (std::size_t param_count = 0; param_count < n_parameter_sets; ++param_count) { // Check if ROS is still alive if (!ros::ok()) return; // Create new instance of the chosen parameters RunData parameter_data; // apply the current parameter, if we are using those if (n_parameter_sets > 1) { modifyPlannerConfiguration(*planner_interfaces_to_benchmark[i], motion_plan_req.planner_id, param_combinations_id_, parameter_data); ++param_combinations_id_; } planning_interface::PlanningContextPtr pcontext = planner_interfaces_to_benchmark[i]->getPlanningContext(planning_scene_, motion_plan_req); // loop through the desired number of runs for (unsigned int run_count = 0; run_count < runs_per_planner_interface[i]; ++run_count) { // Combine two for loops into one id std::size_t run_id = run_count * n_parameter_sets + param_count; ++progress; // this outputs asterisks // run a single benchmark ROS_DEBUG("Calling %s:%s", planner_interfaces_to_benchmark[i]->getDescription().c_str(), motion_plan_req.planner_id.c_str()); planning_interface::MotionPlanDetailedResponse mp_res; ros::WallTime start = ros::WallTime::now(); bool solved = pcontext->solve(mp_res); double total_time = (ros::WallTime::now() - start).toSec(); // collect data start = ros::WallTime::now(); runs[run_id].insert(parameter_data.begin(), parameter_data.end()); // initalize this run's data with the // chosen parameters, if we have any collectMetrics(runs[run_id], mp_res, solved, total_time); double metrics_time = (ros::WallTime::now() - start).toSec(); ROS_DEBUG("Spent %lf seconds collecting metrics", metrics_time); // record the first solution in the response if (solved && first_solution_flag[i]) { first_solution_flag[i] = false; } } } // this vector of runs represents all the runs*parameters data.push_back(runs); } // end j - planning algoritms } // end i - planning plugins double duration = (ros::WallTime::now() - startTime).toSec(); std::string host = moveit_benchmarks::getHostname(); std::string filename = req.filename.empty() ? ("moveit_benchmarks_" + host + "_" + boost::posix_time::to_iso_extended_string(startTime.toBoost()) + ".log") : req.filename; std::ofstream out(filename.c_str()); out << "Experiment " << (planning_scene_->getName().empty() ? "NO_NAME" : planning_scene_->getName()) << std::endl; out << "Running on " << (host.empty() ? "UNKNOWN" : host) << std::endl; out << "Starting at " << boost::posix_time::to_iso_extended_string(startTime.toBoost()) << std::endl; out << "Goal name " << (req.goal_name.empty() ? "UNKNOWN" : req.goal_name) << std::endl; // out << "<<<|" << std::endl << "ROS" << std::endl << req.motion_plan_request << std::endl << "|>>>" << std::endl; out << req.motion_plan_request.allowed_planning_time << " seconds per run" << std::endl; out << duration << " seconds spent to collect the data" << std::endl; out << total_n_planners << " planners" << std::endl; // tracks iteration location in data[] vector std::size_t run_id = 0; // loop through the planning *plugins* for (std::size_t q = 0; q < planner_interfaces_to_benchmark.size(); ++q) { // loop through the planning *algorithms* times the # parameter combinations for (std::size_t p = 0; p < planner_ids_to_benchmark_per_planner_interface[q].size(); ++p) { // Output name of planning algorithm out << planner_interfaces_to_benchmark[q]->getDescription() + "_" + planner_ids_to_benchmark_per_planner_interface[q][p] << std::endl; // in general, we could have properties specific for a planner; // right now, we do not include such properties out << "0 common properties" << std::endl; // construct the list of all possible properties for all runs std::set<std::string> properties_set; for (std::size_t j = 0; j < std::size_t(data[run_id].size()); ++j) { for (RunData::const_iterator mit = data[run_id][j].begin(); mit != data[run_id][j].end(); ++mit) { properties_set.insert(mit->first); } } // copy that set to a vector of properties std::vector<std::string> properties; for (std::set<std::string>::iterator it = properties_set.begin(); it != properties_set.end(); ++it) properties.push_back(*it); out << properties.size() << " properties for each run" << std::endl; // output the vector of properties to the log file for (unsigned int j = 0; j < properties.size(); ++j) out << properties[j] << std::endl; out << data[run_id].size() << " runs" << std::endl; // output all the data to the log file for (std::size_t j = 0; j < data[run_id].size(); ++j) { for (unsigned int k = 0; k < properties.size(); ++k) { // check if this current row contains each property RunData::const_iterator it = data[run_id][j].find(properties[k]); if (it != data[run_id][j].end()) out << it->second; out << "; "; } // end the line out << std::endl; } out << '.' << std::endl; ++run_id; } } out.close(); ROS_INFO("Results saved to '%s'", filename.c_str()); } void moveit_benchmarks::BenchmarkExecution::runGoalExistenceBenchmark(BenchmarkRequest &req) { // configure planning context if (req.scene.robot_model_name != planning_scene_->getRobotModel()->getName()) { // if we have a different robot, use the world geometry only // clear all geometry from the scene planning_scene_->getWorldNonConst()->clearObjects(); planning_scene_->getCurrentStateNonConst().clearAttachedBodies(); planning_scene_->getCurrentStateNonConst().setToDefaultValues(); planning_scene_->processPlanningSceneWorldMsg(req.scene.world); planning_scene_->setName(req.scene.name); } else planning_scene_->usePlanningSceneMsg(req.scene); // \todo the code below needs to be replaced with using constraint samplers; if (req.motion_plan_request.goal_constraints.size() == 0 && req.motion_plan_request.goal_constraints[0].position_constraints.size() == 0 && req.motion_plan_request.goal_constraints[0].position_constraints[0].constraint_region.primitive_poses.size() == 0 && req.motion_plan_request.goal_constraints[0].orientation_constraints.size() == 0 && req.motion_plan_request.trajectory_constraints.constraints.size() == 0) { ROS_ERROR("Invalid goal constraints"); return; } bool success = false; bool reachable = false; if (req.motion_plan_request.goal_constraints.size() > 0 && req.motion_plan_request.goal_constraints[0].position_constraints.size() > 0 && req.motion_plan_request.goal_constraints[0].position_constraints[0].constraint_region.primitive_poses.size() > 0 && req.motion_plan_request.goal_constraints[0].orientation_constraints.size() > 0) { // Compute IK on goal constraints geometry_msgs::Pose ik_pose; ik_pose.position.x = req.motion_plan_request.goal_constraints[0] .position_constraints[0] .constraint_region.primitive_poses[0] .position.x; ik_pose.position.y = req.motion_plan_request.goal_constraints[0] .position_constraints[0] .constraint_region.primitive_poses[0] .position.y; ik_pose.position.z = req.motion_plan_request.goal_constraints[0] .position_constraints[0] .constraint_region.primitive_poses[0] .position.z; ik_pose.orientation.x = req.motion_plan_request.goal_constraints[0].orientation_constraints[0].orientation.x; ik_pose.orientation.y = req.motion_plan_request.goal_constraints[0].orientation_constraints[0].orientation.y; ik_pose.orientation.z = req.motion_plan_request.goal_constraints[0].orientation_constraints[0].orientation.z; ik_pose.orientation.w = req.motion_plan_request.goal_constraints[0].orientation_constraints[0].orientation.w; robot_state::RobotState robot_state(planning_scene_->getCurrentState()); robot_state::robotStateMsgToRobotState(req.motion_plan_request.start_state, robot_state); // Compute IK ROS_INFO_STREAM("Processing goal " << req.motion_plan_request.goal_constraints[0].name << " ..."); ros::WallTime startTime = ros::WallTime::now(); success = robot_state.setFromIK( robot_state.getJointModelGroup(req.motion_plan_request.group_name), ik_pose, req.motion_plan_request.num_planning_attempts, req.motion_plan_request.allowed_planning_time, boost::bind(&isIKSolutionCollisionFree, planning_scene_.get(), _1, _2, _3, &reachable)); if (success) { ROS_INFO(" Success!"); } else if (reachable) { ROS_INFO(" Reachable, but in collision"); } else { ROS_INFO(" Not reachable"); } // Log double duration = (ros::WallTime::now() - startTime).toSec(); std::string host = moveit_benchmarks::getHostname(); std::string filename = req.filename.empty() ? ("moveit_benchmarks_" + host + "_" + boost::posix_time::to_iso_extended_string(startTime.toBoost()) + ".log") : req.filename; std::ofstream out(filename.c_str()); out << "Experiment " << (planning_scene_->getName().empty() ? "NO_NAME" : planning_scene_->getName()) << std::endl; out << "Running on " << (host.empty() ? "UNKNOWN" : host) << std::endl; out << "Starting at " << boost::posix_time::to_iso_extended_string(startTime.toBoost()) << std::endl; out << "<<<|" << std::endl << "ROS" << std::endl << req.motion_plan_request << std::endl << "|>>>" << std::endl; out << req.motion_plan_request.allowed_planning_time << " seconds per run" << std::endl; out << duration << " seconds spent to collect the data" << std::endl; out << "reachable BOOLEAN" << std::endl; out << "collision_free BOOLEAN" << std::endl; out << "total_time REAL" << std::endl; out << reachable << "; " << success << "; " << duration << std::endl; out.close(); ROS_INFO("Results saved to '%s'", filename.c_str()); } if (req.motion_plan_request.trajectory_constraints.constraints.size() > 0) { // Compute IK on trajectory constraints // Start Log ros::WallTime startTime = ros::WallTime::now(); std::string host = moveit_benchmarks::getHostname(); std::string filename = req.filename.empty() ? ("moveit_benchmarks_" + host + "_" + boost::posix_time::to_iso_extended_string(startTime.toBoost()) + ".log") : req.filename; std::ofstream out(filename.c_str()); out << "Experiment " << (planning_scene_->getName().empty() ? "NO_NAME" : planning_scene_->getName()) << std::endl; out << "Running on " << (host.empty() ? "UNKNOWN" : host) << std::endl; out << "Starting at " << boost::posix_time::to_iso_extended_string(startTime.toBoost()) << std::endl; out << "<<<|" << std::endl << "ROS" << std::endl << req.motion_plan_request << std::endl << "|>>>" << std::endl; out << req.motion_plan_request.allowed_planning_time << " seconds per run" << std::endl; out << "reachable BOOLEAN" << std::endl; out << "collision_free BOOLEAN" << std::endl; out << "total_time REAL" << std::endl; for (std::size_t tc = 0; tc < req.motion_plan_request.trajectory_constraints.constraints.size(); ++tc) { geometry_msgs::Pose ik_pose; ik_pose.position.x = req.motion_plan_request.trajectory_constraints.constraints[tc] .position_constraints[0] .constraint_region.primitive_poses[0] .position.x; ik_pose.position.y = req.motion_plan_request.trajectory_constraints.constraints[tc] .position_constraints[0] .constraint_region.primitive_poses[0] .position.y; ik_pose.position.z = req.motion_plan_request.trajectory_constraints.constraints[tc] .position_constraints[0] .constraint_region.primitive_poses[0] .position.z; ik_pose.orientation.x = req.motion_plan_request.trajectory_constraints.constraints[tc].orientation_constraints[0].orientation.x; ik_pose.orientation.y = req.motion_plan_request.trajectory_constraints.constraints[tc].orientation_constraints[0].orientation.y; ik_pose.orientation.z = req.motion_plan_request.trajectory_constraints.constraints[tc].orientation_constraints[0].orientation.z; ik_pose.orientation.w = req.motion_plan_request.trajectory_constraints.constraints[tc].orientation_constraints[0].orientation.w; robot_state::RobotState robot_state(planning_scene_->getCurrentState()); robot_state::robotStateMsgToRobotState(req.motion_plan_request.start_state, robot_state); // Compute IK ROS_INFO_STREAM("Processing trajectory waypoint " << req.motion_plan_request.trajectory_constraints.constraints[tc].name << " ..."); startTime = ros::WallTime::now(); success = robot_state.setFromIK( robot_state.getJointModelGroup(req.motion_plan_request.group_name), ik_pose, req.motion_plan_request.num_planning_attempts, req.motion_plan_request.allowed_planning_time, boost::bind(&isIKSolutionCollisionFree, planning_scene_.get(), _1, _2, _3, &reachable)); double duration = (ros::WallTime::now() - startTime).toSec(); if (success) { ROS_INFO(" Success!"); } else if (reachable) { ROS_INFO(" Reachable, but in collision"); } else { ROS_INFO(" Not reachable"); } out << reachable << "; " << success << "; " << duration << std::endl; } out.close(); ROS_INFO("Results saved to '%s'", filename.c_str()); } } void moveit_benchmarks::BenchmarkExecution::modifyPlannerConfiguration(planning_interface::PlannerManager &planner, const std::string &planner_id, std::size_t param_combinations_id_, RunData &parameter_data) { // Get the planner's current settings planning_interface::PlannerConfigurationMap settings = planner.getPlannerConfigurations(); // Check if this planner_id already has settings (it should) planning_interface::PlannerConfigurationMap::iterator settings_it = settings.find(planner_id); if (settings_it != settings.end()) { // key exists, loop through all values in this param instance std::string str_parameter_value; for (std::size_t i = 0; i < param_options_.size(); ++i) { // convert from double to string try { double value = param_combinations_[param_combinations_id_][param_options_[i].key]; str_parameter_value = boost::lexical_cast<std::string>(value); } catch (boost::bad_lexical_cast &ex) { ROS_WARN("%s", ex.what()); } // record parameter values for logging parameter_data[param_options_[i].log_key] = str_parameter_value; // record parameter to planner config settings_it->second.config[param_options_[i].key] = str_parameter_value; } } else // settings for this planner_id does not exist { ROS_ERROR_STREAM("Settings for " << planner_id << " do not exist. This should not happen."); } // Apply the new settings planner.setPlannerConfigurations(settings); } std::size_t moveit_benchmarks::BenchmarkExecution::generateParamCombinations() { if (!param_options_.size()) return 1; // by default there are no parameters, so the param loop runs once // Create initial param instance of all min values for the parameters ParameterInstance param_instance; for (std::size_t i = 0; i < param_options_.size(); ++i) { // start = min value param_instance[param_options_[i].key] = param_options_[i].start; } // call recusive function for every param option available int initial_options_id = 0; recursiveParamCombinations(initial_options_id, param_instance); // DEBUG /* for (std::size_t i = 0; i < param_combinations_.size(); ++i) { // Debug map for(std::map<std::string,double>::const_iterator it = param_combinations_[i].begin(); it != param_combinations_[i].end(); ++it) std::cout << " - " << it->first << " => " << it->second << std::endl; } */ // Total number of parameters return param_combinations_.size(); } void moveit_benchmarks::BenchmarkExecution::recursiveParamCombinations(int options_id, ParameterInstance param_instance) { // Get a pointer to current parameter const ParameterOptions &param_option = param_options_[options_id]; do { // Call the next parameter if one exists if (param_options_.size() > options_id + 1) { recursiveParamCombinations(options_id + 1, param_instance); } else // we are the end of the recursive call, so we can add this param_instance to the vector { param_combinations_.push_back(param_instance); } // Increment this value param_instance[param_option.key] += param_option.step_size; // Continue adding iteration amount until value equals end } while (param_instance[param_option.key] <= param_option.end + 0.00001); // rounding issues fudge parameter return; } /// Output to console the settings void moveit_benchmarks::BenchmarkExecution::printConfigurationSettings( const planning_interface::PlannerConfigurationMap &settings, std::ostream &out) { // Debug map for (planning_interface::PlannerConfigurationMap::const_iterator it = settings.begin(); it != settings.end(); ++it) { out << " - " << it->first << " => " << it->second.name << "/" << it->second.group << std::endl; // Debug map for (std::map<std::string, std::string>::const_iterator config_it = it->second.config.begin(); config_it != it->second.config.end(); ++config_it) out << " - " << config_it->first << " => " << config_it->second << std::endl; } }
/* Copyright (c) 2018 PaddlePaddle Authors. 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. */ #ifdef PAD2D_OP #include "operators/kernel/pad2d_kernel.h" #include "operators/math/pad.h" namespace paddle_mobile { namespace operators { template <> bool Pad2DKernel<CPU, float>::Init(Pad2DParam<CPU> *param) { return true; } template <> void Pad2DKernel<CPU, float>::Compute(const Pad2DParam<CPU> &param) { const auto *input = param.InputX(); auto *output = param.Out(); const auto &paddings = param.paddings_; // if (param.mode_ == "constant" && param.pad_value_ == 0) { math::PadFunctor<CPU, float> pad; pad(*input, paddings[0], paddings[1], paddings[2], paddings[3], output); // } else { // PADDLE_MOBILE_THROW_EXCEPTION("Pad2D has not been implemented."); // } output->set_lod(input->lod()); } } // namespace operators } // namespace paddle_mobile #endif // PAD2D_OP
#include "LevelManipulator.h" #include "../Random.h" const LevelTiles &LevelManipulator::getLevelTiles() const { return levelTiles; } void LevelManipulator::setMinimumWallHeight() { for (int y = 0; y < levelTiles.height() - 1; y++) { for (int x = 1; x < levelTiles.width() - 1; x++) { setVertWall(y, x); } } } void LevelManipulator::setVertWall(int y, int x) { if (levelTiles.getTileOn(x, y) == TileType::wall && levelTiles.getTileOn(x, y + 1) != TileType::wall) { //it is last wall vertically in this group if (!levelTiles.isWalkable(x, y - 1)) { //thick wall, swapping last wall tile vertically to vertical wall levelTiles.setTileType(x, y, TileType::verticalWall); } else if (levelTiles.isWalkable(x, y + 1) && levelTiles.isWalkable(x, y + 1)) { //passage is thick so we can make change floor tile to a wall tile levelTiles.setTileType(x, y + 1, TileType::wall); //we just created a thicker wall, vertical wall will be added in one of the next iterations } else { //no way to make vertical wall, so we delete it instead levelTiles.setWalkable(x, y); } } } void LevelManipulator::generateBorder() { auto levelCpy = this->levelTiles; levelTiles = LevelTiles(levelCpy.width() + 2, levelCpy.height() + 2); for (int y = 0; y < levelCpy.height(); y++) { for (int x = 0; x < levelCpy.width(); x++) { levelTiles.setTileType(x + 1, y + 1, levelCpy.getTileOn(x, y)); } } }
#include <OmegaWTK.h> using namespace OmegaWTK; static OmegaWTK::Core::SharedPtr<Composition::Brush> brush; static SharedHandle<Composition::Font> font; class RectWidget : public Widget { public: RectWidget(const Core::Rect &rect,Widget *parent):Widget(rect,parent){ }; void render() override { auto & surface = rootView->getLayerTreeLimb()->getRootLayer()->getSurface(); surface->drawRect(rect(),brush); rootView->commitRender(); }; }; int omegaWTKMain(OmegaWTK::AppInst *app){ Composition::FontDescriptor desc ("Arial",20); std::cout << "Hello World" << std::endl; brush = Composition::ColorBrush(Composition::Color::Green); font = Composition::FontEngine::instance->CreateFont(desc); AppWindow window (Core::Rect {Core::Position {0,0},500,500}); app->windowManager->setRootWindow(&window); app->windowManager->displayRootWindow(); return AppInst::start(); };
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // 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 "hardsigmoid_arm.h" #if __ARM_NEON #include <arm_neon.h> #endif // __ARM_NEON namespace ncnn { HardSigmoid_arm::HardSigmoid_arm() { #if __ARM_NEON support_packing = true; #if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC support_fp16_storage = true; #endif #endif // __ARM_NEON #if NCNN_BF16 support_bf16_storage = true; #endif } int HardSigmoid_arm::forward_inplace(Mat& bottom_top_blob, const Option& opt) const { int elembits = bottom_top_blob.elembits(); #if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC if (opt.use_fp16_storage && elembits == 16) { if (opt.use_fp16_arithmetic) return forward_inplace_fp16sa(bottom_top_blob, opt); else return forward_inplace_fp16s(bottom_top_blob, opt); } #endif #if NCNN_BF16 if (opt.use_bf16_storage && elembits == 16) return forward_inplace_bf16s(bottom_top_blob, opt); #endif int w = bottom_top_blob.w; int h = bottom_top_blob.h; int channels = bottom_top_blob.c; int size = w * h; int elempack = bottom_top_blob.elempack; #if __ARM_NEON if (elempack == 4) { #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { float* ptr = bottom_top_blob.channel(q); float32x4_t _zero = vdupq_n_f32(0.f); float32x4_t _one = vdupq_n_f32(1.f); for (int i = 0; i < size; i++) { float32x4_t _p = vld1q_f32(ptr); float32x4_t _ans = vdupq_n_f32(beta); _ans = vmlaq_n_f32(_ans, _p, alpha); _ans = vmaxq_f32(_ans, _zero); _ans = vminq_f32(_ans, _one); vst1q_f32(ptr, _ans); ptr += 4; } } return 0; } #endif // __ARM_NEON #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { float* ptr = bottom_top_blob.channel(q); #if __ARM_NEON int nn = size >> 2; int remain = size - (nn << 2); #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _zero = vdupq_n_f32(0.f); float32x4_t _one = vdupq_n_f32(1.f); while (nn--) { float32x4_t _p = vld1q_f32(ptr); float32x4_t _ans = vdupq_n_f32(beta); _ans = vmlaq_n_f32(_ans, _p, alpha); _ans = vmaxq_f32(_ans, _zero); _ans = vminq_f32(_ans, _one); vst1q_f32(ptr, _ans); ptr += 4; } #endif // __ARM_NEON for (; remain > 0; remain--) { if (*ptr < lower) *ptr = 0.f; else if (*ptr > upper) *ptr = 1.f; else *ptr = *ptr * alpha + beta; ++ptr; } } return 0; } #if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC int HardSigmoid_arm::forward_inplace_fp16s(Mat& bottom_top_blob, const Option& opt) const { int w = bottom_top_blob.w; int h = bottom_top_blob.h; int channels = bottom_top_blob.c; int size = w * h; int elempack = bottom_top_blob.elempack; if (elempack == 4) { #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { __fp16* ptr = bottom_top_blob.channel(q); float32x4_t _zero = vdupq_n_f32(0.f); float32x4_t _one = vdupq_n_f32(1.f); for (int i = 0; i < size; i++) { float32x4_t _p = vcvt_f32_f16(vld1_f16(ptr)); float32x4_t _ans = vdupq_n_f32(beta); _ans = vfmaq_n_f32(_ans, _p, alpha); _ans = vmaxq_f32(_ans, _zero); _ans = vminq_f32(_ans, _one); vst1_f16(ptr, vcvt_f16_f32(_ans)); ptr += 4; } } return 0; } #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { __fp16* ptr = bottom_top_blob.channel(q); float32x4_t _zero = vdupq_n_f32(0.f); float32x4_t _one = vdupq_n_f32(1.f); int i = 0; for (; i + 3 < size; i += 4) { float32x4_t _p = vcvt_f32_f16(vld1_f16(ptr)); float32x4_t _ans = vdupq_n_f32(beta); _ans = vfmaq_n_f32(_ans, _p, alpha); _ans = vmaxq_f32(_ans, _zero); _ans = vminq_f32(_ans, _one); vst1_f16(ptr, vcvt_f16_f32(_ans)); ptr += 4; } for (; i < size; i++) { float v = (float)*ptr; if (v < lower) v = 0.f; else if (v > upper) v = 1.f; else v = v * alpha + beta; *ptr = (__fp16)v; ++ptr; } } return 0; } int HardSigmoid_arm::forward_inplace_fp16sa(Mat& bottom_top_blob, const Option& opt) const { int w = bottom_top_blob.w; int h = bottom_top_blob.h; int channels = bottom_top_blob.c; int size = w * h; int elempack = bottom_top_blob.elempack; if (elempack == 8) { #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { __fp16* ptr = bottom_top_blob.channel(q); __fp16 alpha_fp16 = (__fp16)alpha; __fp16 beta_fp16 = (__fp16)beta; float16x8_t _zero = vdupq_n_f16((__fp16)0.f); float16x8_t _one = vdupq_n_f16((__fp16)1.f); for (int i = 0; i < size; i++) { float16x8_t _p = vld1q_f16(ptr); float16x8_t _ans = vdupq_n_f16(beta_fp16); _ans = vfmaq_n_f16(_ans, _p, alpha_fp16); _ans = vmaxq_f16(_ans, _zero); _ans = vminq_f16(_ans, _one); vst1q_f16(ptr, _ans); ptr += 8; } } return 0; } if (elempack == 4) { #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { __fp16* ptr = bottom_top_blob.channel(q); __fp16 alpha_fp16 = (__fp16)alpha; __fp16 beta_fp16 = (__fp16)beta; float16x8_t _zero = vdupq_n_f16((__fp16)0.f); float16x8_t _one = vdupq_n_f16((__fp16)1.f); int i = 0; for (; i + 1 < size; i += 2) { float16x8_t _p = vld1q_f16(ptr); float16x8_t _ans = vdupq_n_f16(beta_fp16); _ans = vfmaq_n_f16(_ans, _p, alpha_fp16); _ans = vmaxq_f16(_ans, _zero); _ans = vminq_f16(_ans, _one); vst1q_f16(ptr, _ans); ptr += 8; } for (; i < size; i++) { float16x4_t _p = vld1_f16(ptr); float16x4_t _ans = vdup_n_f16(beta_fp16); _ans = vfma_n_f16(_ans, _p, alpha_fp16); _ans = vmax_f16(_ans, vget_low_f16(_zero)); _ans = vmin_f16(_ans, vget_low_f16(_one)); vst1_f16(ptr, _ans); ptr += 4; } } return 0; } #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { __fp16* ptr = bottom_top_blob.channel(q); __fp16 alpha_fp16 = (__fp16)alpha; __fp16 beta_fp16 = (__fp16)beta; float16x8_t _zero = vdupq_n_f16((__fp16)0.f); float16x8_t _one = vdupq_n_f16((__fp16)1.f); int i = 0; for (; i + 7 < size; i += 8) { float16x8_t _p = vld1q_f16(ptr); float16x8_t _ans = vdupq_n_f16(beta_fp16); _ans = vfmaq_n_f16(_ans, _p, alpha_fp16); _ans = vmaxq_f16(_ans, _zero); _ans = vminq_f16(_ans, _one); vst1q_f16(ptr, _ans); ptr += 8; } for (; i + 3 < size; i += 4) { float16x4_t _p = vld1_f16(ptr); float16x4_t _ans = vdup_n_f16(beta_fp16); _ans = vfma_n_f16(_ans, _p, alpha_fp16); _ans = vmax_f16(_ans, vget_low_f16(_zero)); _ans = vmin_f16(_ans, vget_low_f16(_one)); vst1_f16(ptr, _ans); ptr += 4; } for (; i < size; i++) { __fp16 v = *ptr; if (v < (__fp16)lower) v = (__fp16)0.f; else if (v > (__fp16)upper) v = (__fp16)1.f; else v = v * alpha_fp16 + beta_fp16; *ptr = v; ++ptr; } } return 0; } #endif // __ARM_FEATURE_FP16_VECTOR_ARITHMETIC #if NCNN_BF16 int HardSigmoid_arm::forward_inplace_bf16s(Mat& bottom_top_blob, const Option& opt) const { int w = bottom_top_blob.w; int h = bottom_top_blob.h; int channels = bottom_top_blob.c; int size = w * h; int elempack = bottom_top_blob.elempack; #if __ARM_NEON if (elempack == 4) { #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { unsigned short* ptr = bottom_top_blob.channel(q); float32x4_t _zero = vdupq_n_f32(0.f); float32x4_t _one = vdupq_n_f32(1.f); for (int i = 0; i < size; i++) { float32x4_t _p = vcvt_f32_bf16(vld1_u16(ptr)); float32x4_t _ans = vdupq_n_f32(beta); _ans = vmlaq_n_f32(_ans, _p, alpha); _ans = vmaxq_f32(_ans, _zero); _ans = vminq_f32(_ans, _one); vst1_u16(ptr, vcvt_bf16_f32(_ans)); ptr += 4; } } return 0; } #endif // __ARM_NEON #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { unsigned short* ptr = bottom_top_blob.channel(q); #if __ARM_NEON int nn = size >> 2; int remain = size - (nn << 2); #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _zero = vdupq_n_f32(0.f); float32x4_t _one = vdupq_n_f32(1.f); while (nn--) { float32x4_t _p = vcvt_f32_bf16(vld1_u16(ptr)); float32x4_t _ans = vdupq_n_f32(beta); _ans = vmlaq_n_f32(_ans, _p, alpha); _ans = vmaxq_f32(_ans, _zero); _ans = vminq_f32(_ans, _one); vst1_u16(ptr, vcvt_bf16_f32(_ans)); ptr += 4; } #endif // __ARM_NEON for (; remain > 0; remain--) { float v = bfloat16_to_float32(*ptr); if (v < lower) v = 0.f; else if (v > upper) v = 1.f; else v = v * alpha + beta; *ptr = float32_to_bfloat16(v); ++ptr; } } return 0; } #endif // NCNN_BF16 } // namespace ncnn
/** * Copyright (c) 2013, Ford Motor Company * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 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. * * Neither the name of the Ford Motor Company nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR 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. */ #include "rpc/gmock_class_container.h" GMockClassContainer::GMockClassContainer() { } GMockClassContainer::~GMockClassContainer() { } GMockClassContainer* GMockClassContainer::instance() { static GMockClassContainer container; return &container; } void GMockClassContainer::AddTest(ITestArgument* in_check) { mas_.push_back(in_check); testing::internal::MakeAndRegisterTestInfo( in_check->GetUnitTestName().data(), in_check->GetTestName().data(), 0, 0, testing::internal::GetTestTypeId(), testing::Test::SetUpTestCase, testing::Test::TearDownTestCase, new testing::internal::TestFactoryImpl<GTestFord>); } ITestArgument* GMockClassContainer::GetTest(int i) { ITestArgument* returnValues = NULL; if (i <= mas_.size()) { returnValues = mas_[i]; } return returnValues; }
#include <iostream> #include <vector> #include <algorithm> #include "Utility.h" using namespace std; vector<string> n_gram::getArray() const { return words_; } ostream& operator<<(ostream& out, const n_gram& ng){ out << "("; for (int i=0; i<ng.n_-1; i++) out << ng.words_[i] << ","; out << ng.words_[ng.n_-1]<< ")"; return out; } bool n_gram::operator== (const n_gram& ng) const { /*bool check_words_ = true; for (int i=0; i<words_.size(); i++) { if (words_[i]!=ng.words_[i]) { check_words_ = false; break; } } return ((n_==ng.n_) && check_words_);*/ return ((n_==ng.n_) && (words_==ng.words_)); } n_gram& n_gram::operator= (const n_gram& ng) { n_=ng.n_; words_=ng.words_; return *this; } void Tokenize(string line, vector<string> & tokens, string delimiters){ string token = ""; string OneCharString = " "; for (int i=0; i<line.size(); i++) if (find(delimiters.begin(), delimiters.end(), line[i])!=delimiters.end()) // line[i] is one of the delimiter characters { if (token != "") tokens.push_back(token); token = ""; } else { OneCharString[0] = line[i]; token +=OneCharString; } if (token != "") tokens.push_back(token); } size_t n_gram_hash::operator () (const n_gram& ng) const{ int s=0; for (int i=0; i< ng.words_.size(); i++) { string a = ng.words_[i]; for (int j=0; j<a.size(); j++) s+=(int)a[j]; } return s; }
/* Copyright 2001, 2019 IBM Corporation * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR 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. */ #ifndef __TORUSXYZ_HPP__ #define __TORUSXYZ_HPP__ #include <pk/XYZ.hpp> typedef cXYZ TorusXYZ; enum { X_PLUS = 0, X_MINUS = 1, Y_PLUS = 2, Y_MINUS = 3, Z_PLUS = 4, Z_MINUS = 5 }; // Return the link directioin from a Loc toward the Root. static TorusXYZ GetRootBoundTreeLink( TorusXYZ aPeriod, TorusXYZ aRoot, TorusXYZ aLoc ) { TorusXYZ rc; rc.Set( 0, 0, 0 ); if( aRoot != aLoc ) { //////TorusXYZ mvec = aRoot - aLoc; // Need a minimum image manhattan vector ... from vector from aLoc to aRoot TorusXYZ mvec = aLoc.ManhattanVectorImaged( aPeriod, aRoot ); // Figure out which is thee greates distance to go -- and send in that dir. // NOTE: there is bias in this that will effect link load balance! if( ( abs( mvec.mX ) > abs( mvec.mY ) ) && ( abs( mvec.mX ) > abs( mvec.mZ ) ) ) { if( mvec.mX > 0 ) rc.mX = 1; else rc.mX = -1; } else if( abs( mvec.mY ) > abs( mvec.mZ ) ) { if( mvec.mY > 0 ) rc.mY = 1; else rc.mY = -1; } else { if( mvec.mZ > 0 ) rc.mZ = 1; else rc.mZ = -1; } } return( rc ); } #define ASSERT_VALID_LINK(txyz) (assert( (abs(txyz.mX)+abs(txyz.mY)+abs(txyz.mZ)) == 1 ) ) static int GetLinkNumber( TorusXYZ aTXYZ ) { ASSERT_VALID_LINK( aTXYZ ); if( aTXYZ.mX == 1 ) return( X_PLUS ); if( aTXYZ.mX == -1 ) return( X_MINUS ); if( aTXYZ.mY == 1 ) return( Y_PLUS ); if( aTXYZ.mY == -1 ) return( Y_MINUS ); if( aTXYZ.mZ == 1 ) return( Z_PLUS ); if( aTXYZ.mZ == -1 ) return( Z_MINUS ); assert(!"Shouldn't get here"); return(-1); } static TorusXYZ GetLinkFromNumber( int aLinkNumber ) { assert( aLinkNumber >= 0 && aLinkNumber < 6 ); // 0..5 inclusive TorusXYZ rc; rc.Zero(); switch( aLinkNumber ) { case X_PLUS : rc.mX = 1; break; case X_MINUS : rc.mX = -1; break; case Y_PLUS : rc.mY = 1; break; case Y_MINUS : rc.mY = -1; break; case Z_PLUS : rc.mZ = 1; break; case Z_MINUS : rc.mZ = -1; break; default: assert( 0 ); }; return( rc ); } static char * GetLinkName( TorusXYZ aTXYZ ) { if( aTXYZ == TorusXYZ::ZERO_VALUE() ) return( "--" ); ASSERT_VALID_LINK( aTXYZ ); if( aTXYZ.mX == 1 ) return( "X+" ); if( aTXYZ.mX == -1 ) return( "X-" ); if( aTXYZ.mY == 1 ) return( "Y+" ); if( aTXYZ.mY == -1 ) return( "Y-" ); if( aTXYZ.mZ == 1 ) return( "Z+" ); if( aTXYZ.mZ == -1 ) return( "Z-" ); assert(!"Shouldn't get here"); return("Shouln't get here"); } #endif
#include <chrono> #include "utils.h" //#define __ANDROID__ #ifdef __ANDROID__ #include "net.h" #if NCNN_BENCHMARK #include "benchmark.h" #endif // NCNN_BENCHMARK #if NCNN_VULKAN #include "command.h" #endif // NCNN_VULKAN #include "datareader.h" #endif #ifdef WIN32 #include <io.h> #endif std::string get_timestamp() { const auto now = std::chrono::system_clock::now(); auto sec_utc = std::chrono::system_clock::to_time_t(now); struct tm* ptm = localtime(&sec_utc); auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000; char tmp[30] = { 0 }; sprintf(tmp, "%4d-%02d-%02d %02d:%02d:%02d:%03d", (int)ptm->tm_year + 1900, (int)ptm->tm_mon + 1, (int)ptm->tm_mday, (int)ptm->tm_hour, (int)ptm->tm_min, (int)ptm->tm_sec, ms); std::string filename = tmp; return filename; } void read_filelist(const std::string& listfilename, std::vector<std::string>& vec_list_filename) { std::ifstream listfile; int filenum = 0; listfile.open(listfilename.c_str()); listfile >> filenum; listfile.ignore(65536, '\n'); std::string stringbuf; for (int i = 0; i < filenum; i++) { listfile >> stringbuf; vec_list_filename.push_back(stringbuf); stringbuf.clear(); } listfile.close(); }
#include <szen/System/SceneManager.hpp> #include <szen/System/AssetManager.hpp> #include <szen/System/Window.hpp> using namespace sz; namespace { ScenePtr m_currentScene; Core* p_core; ScenePtr m_overlayScene; bool m_toggle = false; } //////////////////////////////////////////////////// void SceneManager::init(Core* corePtr) { p_core = corePtr; } //////////////////////////////////////////////////// void SceneManager::setScene(Scene* scene) { assert(scene != NULL && "Scene can't be null"); // Unload previous scene before changing to the next if(m_currentScene) { Asset::freeSceneAssets(); m_currentScene->unload(); } // Replace the current pointer m_currentScene.reset(scene); // Set screen size sf::Vector2u size = Window::getSize(); scene->Screen.width = size.x; scene->Screen.height = size.y; scene->Screen.size = static_cast<sf::Vector2f>(size); scene->Screen.center = scene->Screen.size / 2.f; // Load the new scene's content scene->load(); } //////////////////////////////////////////////////// void SceneManager::setOverlayScene(Scene* scene) { assert(scene != NULL && "Scene can't be null"); // Unload previous scene before changing to the next if(m_overlayScene) { m_overlayScene->unload(); } // Replace the current pointer m_overlayScene.reset(scene); // Set screen size sf::Vector2u size = Window::getSize(); scene->Screen.width = size.x; scene->Screen.height = size.y; scene->Screen.size = static_cast<sf::Vector2f>(size); scene->Screen.center = scene->Screen.size / 2.f; // Load the new scene's content scene->load(); } //////////////////////////////////////////////////// void SceneManager::handleEvents(const sf::Event &event) { assert(m_currentScene && "Scene must be initialized"); m_currentScene->events(event); if(m_overlayScene && m_toggle) { m_overlayScene->events(event); } } //////////////////////////////////////////////////// void SceneManager::update() { assert(m_currentScene && "Scene must be initialized"); m_currentScene->updateClocks(); m_currentScene->update(); if(m_overlayScene && m_toggle) { m_overlayScene->updateClocks(); m_overlayScene->update(); } } //////////////////////////////////////////////////// void SceneManager::render() { assert(m_currentScene && "Scene must be initialized"); m_currentScene->render(); if(m_overlayScene && m_toggle) { m_overlayScene->render(); } } //////////////////////////////////////////////////// bool SceneManager::isOverlayEnabled() { return m_toggle; } //////////////////////////////////////////////////// void SceneManager::toggleOverlay(bool enabled) { m_toggle = enabled; }
// This file has been generated by Py++. #ifndef _ref_ptr_less__osgAnimation_scope_Channel__greater___value_traits_pypp_hpp_hpp__pyplusplus_wrapper #define _ref_ptr_less__osgAnimation_scope_Channel__greater___value_traits_pypp_hpp_hpp__pyplusplus_wrapper namespace boost { namespace python { namespace indexing { template<> struct value_traits< osg::ref_ptr< osgAnimation::Channel > >{ static bool const equality_comparable = false; static bool const less_than_comparable = false; template<typename PythonClass, typename Policy> static void visit_container_class(PythonClass &, Policy const &){ } }; }/*indexing*/ } /*python*/ } /*boost*/ #endif//_ref_ptr_less__osgAnimation_scope_Channel__greater___value_traits_pypp_hpp_hpp__pyplusplus_wrapper
// // Copyright 2019 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 // // 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 "zetasql/compliance/runtime_expected_errors.h" #include <memory> #include <utility> #include <vector> #include "zetasql/compliance/matchers.h" #include "absl/memory/memory.h" #include "absl/status/status.h" namespace zetasql { std::unique_ptr<MatcherCollection<absl::Status>> RuntimeExpectedErrorMatcher( std::string matcher_name) { // This is a list of runtime errors that will be ignored if they occur during // randomized testing. // // The test framework generates random data and random queries and, in so // doing, it is inevitable that such runtime errors will occur. A simple // example is // SELECT t.a/t.b FROM myTable AS T; // Such a query will fail with a division by 0 error if there is a row for // which b=0. // // Preventing such errors in the randomized test framework is possible in // principle but a complex challenge. Ingoring these runtime errors means we // could miss genuine bugs whereby runtime errors incorrectly occur. // However, that is not a common bug pattern compared to e.g. ZETASQL_RET_CHECKS and // incorrect results, and this is the balance we have currently struck. std::vector<std::unique_ptr<MatcherBase<absl::Status>>> error_matchers; // Runtime errors // error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Bitwise binary operator for BYTES requires equal length of the inputs")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Output of REPEAT exceeds max allowed output size of 1MB")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Output of LPAD/RPAD exceeds max allowed output size of 1MB")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Output of TO_JSON_STRING exceeds max allowed output size of 1MB")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Output of TRANSLATE exceeds max allowed output size of 1MB")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "Array index (-?[\\d]+) is out of bounds")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Corrupted protocol buffer")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "Cannot encode a null value(.*) in (required|repeated) protocol message " "field")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Elements in input array to RANGE_BUCKET must be in ascending order")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Elements in input array to RANGE_BUCKET")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Invalid return_position_after_match")); // Out of range errors // error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "division by zero")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "(uint64_t|int64|int32_t|uint32|float|numeric|BIGNUMERIC) out of range: ")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Illegal conversion of non-finite floating point number to an integer")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Sequence step cannot be 0")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "Truncating date (.+) to WEEK resulted in " "an out of range date value: (.+)")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Negative NUMERIC value cannot be raised to " "a fractional power")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Negative BIGNUMERIC value cannot be raised to " "a fractional power")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "Input calculates to invalid (date|time)")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "Invalid Proto3 (Timestamp|TimeOfDay) input")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Input is outside of Proto3 (TimeOfDay|Date) range")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "ErrorFunction_RQG")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "Second argument in (LEFT|RIGHT)\\(\\) cannot be negative")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Occurrence must be positive")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Position must be non-zero")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "Duplicate character (.*) in TRANSLATE source characters")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "Duplicate byte 0x(.{2}) in TRANSLATE source bytes")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "Invalid encoded timestamp: (.*) with format: TIMESTAMP_(.*)")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Invalid non-int32_t date:")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Invalid DATE_DECIMAL:")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Cannot set field of NULL")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Cannot store a NULL element in repeated proto field (.+)")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Position must be positive")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Invalid return_position_after_match")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Cannot write NULL to key or value of map field")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Key not found in map")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "MODIFY_MAP: All key arguments must be non-NULL")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "MODIFY_MAP: Only one instance of each key is allowed")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Invalid input to PARSE_NUMERIC")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Invalid input to PARSE_BIGNUMERIC")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Invalid input to PARSE_JSON")); // REPLACE_FIELDS() specific error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "REPLACE_FIELDS(.*) cannot be used to modify the fields of " "(a NULL valued|an unset) proto")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Cannot set field of NULL")); // Overflow errors // error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "(uint32_t|int32|uint64_t|int64|integer|double|float|numeric|BIGNUMERIC) " "overflow")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "Floating point overflow in function: (ACOS|ACOSH|ASIN|COSH|SINH)")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "Floating point error in function: " "(ACOS|ACOSH|ASIN|ATANH|EXP|LN|ZETASQL_LOG|LOG10|POW)")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "Argument to SQRT cannot be negative")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "(Adding|Subtracting) (-?\\d+) (\\w+) (to|from) " "(date|timestamp|datetime|time) (.+) causes overflow")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "LN is undefined for zero or negative value")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "LOG10 is undefined for zero or negative value")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "LOG is undefined for zero or negative value, or when base equals 1")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "SQRT is undefined for negative value")); // CASTing errors for un-castable values. // error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "Bad (uint32_t|int32|uint64_t|int64|float|double) value")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "Invalid NUMERIC value")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "Invalid BIGNUMERIC value")); // Regex/Like Errors // error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Cannot parse regular expression:")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Invalid REGEXP_REPLACE pattern")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "pattern too large")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Regular expressions passed into extraction functions must not have more " "than 1 capturing group")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "LIKE pattern ends with a backslash")); // TODO: known issue error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "PARSE_TIMESTAMP mismatch between format character '(.+)' and " "timestamp string character '(.+)'")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Regular expression passed to REGEXP_EXTRACT_ALL must not have " "more than 1 capturing group")); // Net function errors // error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "NET\\.(FORMAT_IP|PARSE_IP|PARSE_PACKED_IP|FORMAT_PACKED_IP|IP_IN_NET|" "MAKE_NET|IP_FROM_STRING|IP_TO_STRING|IPV4_FROM_INT64|IPV4_TO_INT64)\\(" "\\) encountered a(n?) (.+)")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "NET.MAKE_NET() is trying to expand a subnet")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "The (first|second) argument of NET\\.(IP_NET_MASK|IP_TRUNC)\\(\\) must " "(have|be) (.+)")); // Date/Time Value Errors // error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "Invalid (time zone|timestamp|date|datetime|time)")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Invalid empty time zone")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "Cannot truncate a TIMESTAMP_(.+) value to (.+)")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "DATE_FROM_UNIX_DATE range is -719162 to 2932896 but saw")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "TIMESTAMP_DIFF at (\\w+) precision between " "values of (-?\\d+) and (-?\\d+) causes overflow")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "TIMESTAMP_(ADD|SUB) interval value (-?\\d+) at (\\w+) precision " "causes overflow")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "Converting timestamp interval (-?\\d+) at TIMESTAMP_(\\w+) scale to " "TIMESTAMP_(\\w+) scale causes overflow")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "Invalid format: %(.*) is not allowed for " "the (DATE|DATETIME|TIME) type")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "Timezone is not allowed in (.+)")); // Interval Errors // error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "Interval field .* is out of range")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Invalid interval")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "TIMESTAMP +/- INTERVAL is not supported for intervals with non-zero")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Interval overflow during multiplication")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Illegal non-space trailing data")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Failed to parse input string")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Format string cannot end with a single '%'")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Mismatch between format character")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Invalid ASCII value")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Invalid codepoint")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Argument to ASCII is not a structurally valid ASCII string")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Failed to decode invalid hexadecimal string")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "Input value (-?\\d+) cannot be converted into a TIMESTAMP, " "because it would be out of the allowed range between " "(-\\d+) to (\\d+) \\(microseconds\\)")); // PercentileDisc function. // TODO: Support array args in percentile_disc error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kUnimplemented, "Unsupported argument type for percentile_disc.")); // Parsing and analysis errors. // error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kInvalidArgument, "Stack overflow while trying to parse")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kInvalidArgument, "Could not cast (.+) to type (UINT32|INT32|UINT64|INT64|FLOAT|DOUBLE|" "TIMESTAMP|DATE|DATETIME|TIME|STRING|BOOL|NUMERIC|BIGNUMERIC|JSON|" "INTERVAL)")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Bad bool value:")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kInvalidArgument, "Invalid cast of bytes to UTF8 string")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Invalid cast of bytes to UTF8 string")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Third argument (pad pattern) for LPAD/RPAD cannot be empty")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kInvalidArgument, "Update item (.+) overlaps with (.+)")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kInvalidArgument, "(.+) does not support (.+) date part (.+)")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kInvalidArgument, "A valid date part name is required(.+)")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kInvalidArgument, "Found invalid date part argument syntax (.+)")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kInvalidArgument, "Found invalid date part argument function call syntax for (.+)")); // TODO: array<proto> literals don't round trip in the SQL Builder error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kInvalidArgument, "Argument 3 to (LAG|LEAD) must be a literal or query parameter")); // TODO: Remove the following two once the bug is resolved. error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kInvalidArgument, "ARRAY_IS_DISTINCT cannot be used on argument of type .* because the " "array's element type does not support grouping")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kInvalidArgument, "ARRAY_INCLUDES(_ANY)? cannot be used on argument of type .* because the " "array's element type does not support equality")); // TODO: Remove after randomized compat test is happy. error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kInvalidArgument, "Argument 2 to ARRAY_INCLUDES must support equality")); // TODO: Remove after the bug is fixed. // Due to the above expected errors, rqg could generate invalid expressions. // An invalid lambda body manifests as "No matching signature". error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kInvalidArgument, "No matching signature for function " "(ARRAY_FILTER|ARRAY_TRANSFORM|ARRAY_INCLUDES) .*")); // HLL sketch format errors // error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "Invalid or incompatible sketch in HLL_COUNT\\.(.+)")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "Invalid sketch in HLL_COUNT\\.(.+)")); // GEOGRAPHY related errors // // GEOGRAPHY constructors errors (not converted from S2Error). error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Input geographies for ")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "cannot include an empty geography")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "Failed to find geography format for the input.")); // All GEOGRAPHY STLIB errors converted from S2Error. error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "[stlib]")); // Unimplemented functions // TODO: implement error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kUnimplemented, "Precision argument of ST_AsGeoJSON ")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kUnimplemented, "(ST_BUFFER|ST_BUFFERWITHTOLERANCE) does not yet implement " "use_spheroid=true")); // REPLACE_FIELDS() specific error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kInvalidArgument, "REPLACE_FIELDS(.+) field path (.+) overlaps with field path (.+)")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kInvalidArgument, "Modifying multiple fields from the same OneOf is unsupported by " "REPLACE_FIELDS()")); // COLLATION related errors error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kUnimplemented, "(ResolvedFunctionCallBase::collation_list not accessed and has " "non-default value)")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kInvalidArgument, "The second argument of COLLATE\\(\\) must be a string literal")); // TODO PARSE_JSON sometimes is generated with invalid string // inputs. error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kInvalidArgument, "parse error at line")); // JSON related errors // TO_JSON will return OUT_OF_RANGE error if the input type is // numeric/bignumeric and FEATURE_JSON_STRICT_NUMBER_PARSING is enabled when // there is precision loss. error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "Failed to convert type (NUMERIC|BIGNUMERIC) to JSON")); error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "The provided JSON input is not (a string|a boolean|an integer|a " "number)")); return absl::make_unique<MatcherCollection<absl::Status>>( matcher_name, std::move(error_matchers)); } std::unique_ptr<MatcherCollection<absl::Status>> RuntimeDMLExpectedErrorMatcher( std::string matcher_name) { // Legitimate errors that are difficult to prevent when generating queries. std::vector<std::unique_ptr<MatcherBase<absl::Status>>> error_matchers; // OR X errors when there is no primary key. // We want the RQG to generate these statements to ensure engines // return the same errors as reference impl. error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "INSERT OR IGNORE is not allowed because the table does not have a " "primary key")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "INSERT OR UPDATE is not allowed because the table does not have a " "primary key")); error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kOutOfRange, "INSERT OR REPLACE is not allowed because the table does not have a " "primary key")); // This error can happen if multiple of the same key is added // to the same insert. Even though we attempt to avoid duplicates as best // we can, there is still a chance different AST trees can resolve // to the same value. error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kInvalidArgument, "was already created in this transaction.")); // ALREADY_EXISTS can happen if our duplicate checking during DML insert // fails or if a row already exists in the table for an inserted row. We do // our best to avoid duplicates, but since the insert is random, errors will // happen. Note that the message only contains the name of the table which // is not deterministic. error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kAlreadyExists, "^(\\w+)\\(.+\\)")); // Error when ASSERT ROWS MODIFIED failed count error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "ASSERT_ROWS_MODIFIED expected (.*) rows modified, but found (.*)")); // This error can happen on inserts on random schemas where the insert // is performed on a child table with a key that does not exist in the // parent table. // TODO: b/109660988 DML RQG: account for constraints error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kNotFound, "Parent row is missing")); // Aggregate values can overflow in large queries. error_matchers.emplace_back(absl::make_unique<StatusRegexMatcher>( absl::StatusCode::kOutOfRange, "Aggregate values are limited to .*")); // TODO: Not yet implemented/supported. error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kUnimplemented, "does not yet implement use_spheroid=true")); // TODO PARSE_JSON sometimes is generated with invalid string // inputs. error_matchers.emplace_back(absl::make_unique<StatusSubstringMatcher>( absl::StatusCode::kInvalidArgument, "parse error at line")); error_matchers.emplace_back(RuntimeExpectedErrorMatcher("RuntimeErrors")); return absl::make_unique<MatcherCollection<absl::Status>>( matcher_name, std::move(error_matchers)); } } // namespace zetasql
/****************************************************************************** * Copyright (c) 2018(-2021) STMicroelectronics. * All rights reserved. * * This file is part of the TouchGFX 4.17.0 distribution. * * 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. * *******************************************************************************/ /** * @file touchgfx/widgets/canvas/PainterXRGB8888.hpp * * Declares the touchgfx::PainterXRGB8888 class. */ #ifndef TOUCHGFX_PAINTERXRGB8888_HPP #define TOUCHGFX_PAINTERXRGB8888_HPP #include <touchgfx/hal/Types.hpp> #include <touchgfx/Color.hpp> #include <touchgfx/widgets/canvas/AbstractPainterARGB8888.hpp> namespace touchgfx { /** * The PainterXRGB8888 class allows a shape to be filled with a given color * value. This allows anti-aliased elements to be drawn. * * @see AbstractPainter */ class PainterXRGB8888 : public AbstractPainterARGB8888 { public: /** * Initializes a new instance of the PainterXRGB8888 class. * * @param color (Optional) the color, default is black. */ PainterXRGB8888(colortype color = 0) : AbstractPainterARGB8888(), painterRed(0), painterGreen(0), painterBlue(0) { setColor(color); } /** * Sets color to use when drawing the CanvasWidget. * * @param color The color. */ void setColor(colortype color) { painterColor = color; painterRed = Color::getRed(color); painterGreen = Color::getGreen(color); painterBlue = Color::getBlue(color); } /** * Gets the current color. * * @return The color. */ colortype getColor() const { return painterColor; } virtual void render(uint8_t* ptr, int x, int xAdjust, int y, unsigned count, const uint8_t* covers); protected: virtual bool renderNext(uint8_t& red, uint8_t& green, uint8_t& blue, uint8_t& alpha); colortype painterColor; ///< The painter color uint8_t painterRed; ///< The red part of the color uint8_t painterGreen; ///< The green part of the color uint8_t painterBlue; ///< The blue part of the color }; } // namespace touchgfx #endif // TOUCHGFX_PAINTERXRGB8888_HPP
#pragma once #include <pykebc/object.hpp> namespace pykebc::types { class Int : public Object { public: explicit Int(long value) noexcept; long get_value() const noexcept; void set_value(long value) noexcept; static Object* get_type_object(); // Holy shit! I've never even thought Python had so many methods Object* add(Object* rhs) const; // __add__ Object* bit_and(Object* rhs) const; // __and__ Object* bit_invert() const; // __invert__ Object* bit_or(Object* rhs) const; // __or__ Object* bit_xor(Object* rhs) const; // __xor__ Object* ceil() const; // __ceil__ Object* floor() const; // __floor__ Object* floor_div(Object* rhs) const; // __floordiv__ Object* format(Object* format_string) const; // __format__ Object* greater_or_equal(Object* rhs) const; // __ge__ Object* greater_than(Object* rhs) const; // __gt__ Object* hash() const; // __hash__ Object* index() const; // __index__ Object* init(Object* value); // __init__ Object* less_or_equal(Object* rhs) const; // __le__ Object* less_than(Object* rhs) const; // __lt__ Object* lshift(Object* rhs) const; // __lshift__ Object* mod(Object* rhs) const; // __mod__ Object* mult(Object* rhs) const; // __mul__ Object* negate() const; // __neg__ Object* not_equal(Object* rhs) const; // __ne__ Object* power(Object* rhs) const; // __pow__ Object* repr() const; // __repr__ Object* round() const; // __round__ Object* str() const; // __str__ Object* sub(Object* rhs) const; // __sub__ Object* to_bool() const; // __bool__ Object* to_float() const; // __float__ Object* to_int() const; // __int__ Object* true_div(Object* rhs) const; // __truediv__ Object* trunc() const; // __trunc__ private: long value; }; }
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2015 Pivotal Inc. // // @filename: // CXformGbAggWithMDQA2Join.cpp // // @doc: // Transform a GbAgg with multiple distinct qualified aggregates (MDQAs) // to a join tree with single DQA leaves //--------------------------------------------------------------------------- #include "gpos/base.h" #include "gpos/memory/CAutoMemoryPool.h" #include "gpopt/base/CUtils.h" #include "gpopt/base/CKeyCollection.h" #include "gpopt/operators/ops.h" #include "gpopt/operators/COperator.h" #include "gpopt/xforms/CXformUtils.h" #include "gpopt/xforms/CXformGbAggWithMDQA2Join.h" using namespace gpmd; using namespace gpopt; //--------------------------------------------------------------------------- // @function: // CXformGbAggWithMDQA2Join::CXformGbAggWithMDQA2Join // // @doc: // Ctor // //--------------------------------------------------------------------------- CXformGbAggWithMDQA2Join::CXformGbAggWithMDQA2Join(CMemoryPool *mp) : CXformExploration( // pattern GPOS_NEW(mp) CExpression( mp, GPOS_NEW(mp) CLogicalGbAgg(mp), GPOS_NEW(mp) CExpression( mp, GPOS_NEW(mp) CPatternTree(mp)), // relational child GPOS_NEW(mp) CExpression( mp, GPOS_NEW(mp) CPatternTree(mp)) // scalar project list )) { } //--------------------------------------------------------------------------- // @function: // CXformGbAggWithMDQA2Join::Exfp // // @doc: // Compute xform promise for a given expression handle; // //--------------------------------------------------------------------------- CXform::EXformPromise CXformGbAggWithMDQA2Join::Exfp(CExpressionHandle &exprhdl) const { CAutoMemoryPool amp; CLogicalGbAgg *popAgg = CLogicalGbAgg::PopConvert(exprhdl.Pop()); if (COperator::EgbaggtypeGlobal == popAgg->Egbaggtype() && exprhdl.DeriveHasMultipleDistinctAggs(1)) { return CXform::ExfpHigh; } return CXform::ExfpNone; } //--------------------------------------------------------------------------- // @function: // CXformGbAggWithMDQA2Join::PexprMDQAs2Join // // @doc: // Converts GbAgg with multiple distinct aggregates into a join of single // distinct aggregates, // // distinct aggregates that share the same argument are grouped together // in one leaf of the generated join expression, // // non-distinct aggregates are also grouped together in one leaf of the // generated join expression // //--------------------------------------------------------------------------- CExpression * CXformGbAggWithMDQA2Join::PexprMDQAs2Join(CMemoryPool *mp, CExpression *pexpr) { GPOS_ASSERT(NULL != pexpr); GPOS_ASSERT(COperator::EopLogicalGbAgg == pexpr->Pop()->Eopid()); GPOS_ASSERT((*pexpr)[1]->DeriveHasMultipleDistinctAggs()); // extract components CExpression *pexprChild = (*pexpr)[0]; CColRefSet *pcrsChildOutput = pexprChild->DeriveOutputColumns(); CColRefArray *pdrgpcrChildOutput = pcrsChildOutput->Pdrgpcr(mp); // create a CTE producer based on child expression CCTEInfo *pcteinfo = COptCtxt::PoctxtFromTLS()->Pcteinfo(); const ULONG ulCTEId = pcteinfo->next_id(); (void) CXformUtils::PexprAddCTEProducer(mp, ulCTEId, pdrgpcrChildOutput, pexprChild); // create a CTE consumer with child output columns CExpression *pexprConsumer = GPOS_NEW(mp) CExpression( mp, GPOS_NEW(mp) CLogicalCTEConsumer(mp, ulCTEId, pdrgpcrChildOutput)); pcteinfo->IncrementConsumers(ulCTEId); // finalize GbAgg expression by replacing its child with CTE consumer pexpr->Pop()->AddRef(); (*pexpr)[1]->AddRef(); CExpression *pexprGbAggWithConsumer = GPOS_NEW(mp) CExpression(mp, pexpr->Pop(), pexprConsumer, (*pexpr)[1]); CExpression *pexprJoinDQAs = CXformUtils::PexprGbAggOnCTEConsumer2Join(mp, pexprGbAggWithConsumer); GPOS_ASSERT(NULL != pexprJoinDQAs); pexprGbAggWithConsumer->Release(); return GPOS_NEW(mp) CExpression( mp, GPOS_NEW(mp) CLogicalCTEAnchor(mp, ulCTEId), pexprJoinDQAs); } //--------------------------------------------------------------------------- // @function: // CXformGbAggWithMDQA2Join::PexprExpandMDQAs // // @doc: // Expand GbAgg with multiple distinct aggregates into a join of single // distinct aggregates, // return NULL if expansion is not done // //--------------------------------------------------------------------------- CExpression * CXformGbAggWithMDQA2Join::PexprExpandMDQAs(CMemoryPool *mp, CExpression *pexpr) { GPOS_ASSERT(NULL != pexpr); GPOS_ASSERT(COperator::EopLogicalGbAgg == pexpr->Pop()->Eopid()); COperator *pop = pexpr->Pop(); if (CLogicalGbAgg::PopConvert(pop)->FGlobal()) { BOOL fHasMultipleDistinctAggs = (*pexpr)[1]->DeriveHasMultipleDistinctAggs(); if (fHasMultipleDistinctAggs) { CExpression *pexprExpanded = PexprMDQAs2Join(mp, pexpr); // recursively process the resulting expression CExpression *pexprResult = PexprTransform(mp, pexprExpanded); pexprExpanded->Release(); return pexprResult; } } return NULL; } //--------------------------------------------------------------------------- // @function: // CXformGbAggWithMDQA2Join::PexprTransform // // @doc: // Main transformation driver // //--------------------------------------------------------------------------- CExpression * CXformGbAggWithMDQA2Join::PexprTransform(CMemoryPool *mp, CExpression *pexpr) { // protect against stack overflow during recursion GPOS_CHECK_STACK_SIZE; GPOS_ASSERT(NULL != mp); GPOS_ASSERT(NULL != pexpr); COperator *pop = pexpr->Pop(); if (COperator::EopLogicalGbAgg == pop->Eopid()) { CExpression *pexprResult = PexprExpandMDQAs(mp, pexpr); if (NULL != pexprResult) { return pexprResult; } } // recursively process child expressions const ULONG arity = pexpr->Arity(); CExpressionArray *pdrgpexprChildren = GPOS_NEW(mp) CExpressionArray(mp); for (ULONG ul = 0; ul < arity; ul++) { CExpression *pexprChild = PexprTransform(mp, (*pexpr)[ul]); pdrgpexprChildren->Append(pexprChild); } pop->AddRef(); return GPOS_NEW(mp) CExpression(mp, pop, pdrgpexprChildren); } //--------------------------------------------------------------------------- // @function: // CXformGbAggWithMDQA2Join::Transform // // @doc: // Actual transformation to expand multiple distinct qualified aggregates // (MDQAs) to a join tree with single DQA leaves // //--------------------------------------------------------------------------- void CXformGbAggWithMDQA2Join::Transform(CXformContext *pxfctxt, CXformResult *pxfres, CExpression *pexpr) const { GPOS_ASSERT(NULL != pxfctxt); GPOS_ASSERT(NULL != pxfres); GPOS_ASSERT(FPromising(pxfctxt->Pmp(), this, pexpr)); GPOS_ASSERT(FCheckPattern(pexpr)); CMemoryPool *mp = pxfctxt->Pmp(); CExpression *pexprResult = PexprTransform(mp, pexpr); if (NULL != pexprResult) { pxfres->Add(pexprResult); } } BOOL CXformGbAggWithMDQA2Join::IsApplyOnce() { return true; } // EOF
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // <set> // class multiset // template <class InputIterator> // multiset(InputIterator first, InputIterator last); #include <set> #include <cassert> #include "test_macros.h" #include "test_iterators.h" #include "min_allocator.h" int main(int, char**) { { typedef int V; V ar[] = { 1, 1, 1, 2, 2, 2, 3, 3, 3 }; std::multiset<V> m(input_iterator<const int*>(ar), input_iterator<const int*>(ar+sizeof(ar)/sizeof(ar[0]))); assert(m.size() == 9); assert(distance(m.begin(), m.end()) == 9); assert(*next(m.begin(), 0) == 1); assert(*next(m.begin(), 1) == 1); assert(*next(m.begin(), 2) == 1); assert(*next(m.begin(), 3) == 2); assert(*next(m.begin(), 4) == 2); assert(*next(m.begin(), 5) == 2); assert(*next(m.begin(), 6) == 3); assert(*next(m.begin(), 7) == 3); assert(*next(m.begin(), 8) == 3); } #if TEST_STD_VER >= 11 { typedef int V; V ar[] = { 1, 1, 1, 2, 2, 2, 3, 3, 3 }; std::multiset<V, std::less<V>, min_allocator<V>> m(input_iterator<const int*>(ar), input_iterator<const int*>(ar+sizeof(ar)/sizeof(ar[0]))); assert(m.size() == 9); assert(distance(m.begin(), m.end()) == 9); assert(*next(m.begin(), 0) == 1); assert(*next(m.begin(), 1) == 1); assert(*next(m.begin(), 2) == 1); assert(*next(m.begin(), 3) == 2); assert(*next(m.begin(), 4) == 2); assert(*next(m.begin(), 5) == 2); assert(*next(m.begin(), 6) == 3); assert(*next(m.begin(), 7) == 3); assert(*next(m.begin(), 8) == 3); } #endif return 0; }
//------------------------------------------------------------------------------ // // Copyright 2018-2020 Fetch.AI Limited // // 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 "test_types.hpp" #include "core/serializers/main_serializer.hpp" #include "math/base_types.hpp" #include "math/standard_functions/abs.hpp" #include "ml/ops/activations/randomised_relu.hpp" #include "ml/serializers/ml_types.hpp" #include "gtest/gtest.h" namespace fetch { namespace ml { namespace test { template <typename T> class RandomisedReluTest : public ::testing::Test { }; TYPED_TEST_SUITE(RandomisedReluTest, math::test::TensorFloatingTypes, ); /** * @tparam DataType * @param a * @param b * @param lower_bound * @param upper_bound * @return bool if abs(a)>=abs(b*lower) and abs(a)<=abs(b*upper) */ template <typename DataType> bool IsAbsWithinRange(DataType a, DataType b, DataType lower_bound, DataType upper_bound) { return (fetch::math::Abs(a) >= fetch::math::Abs(b * lower_bound)) && (fetch::math::Abs(a) <= fetch::math::Abs(b * upper_bound)); } /** * Function for forward pass tests * Checks if RandomRelu is applied for negative values only * @tparam TypeParam * @param data * @param prediction * @param lower_bound * @param upper_bound */ template <typename TypeParam> void CheckForwardValues(TypeParam &data, TypeParam &prediction, typename TypeParam::Type lower_bound, typename TypeParam::Type upper_bound) { auto data_it = data.begin(); auto pred_it = prediction.begin(); while (data_it.is_valid()) { if (*data_it < typename TypeParam::Type{0}) { EXPECT_TRUE(IsAbsWithinRange(*pred_it, *data_it, lower_bound, upper_bound)); } else { EXPECT_TRUE(*pred_it == *data_it); } ++data_it; ++pred_it; } } TYPED_TEST(RandomisedReluTest, forward_test) { using DataType = typename TypeParam::Type; using TensorType = TypeParam; TensorType data = TensorType::FromString("1, -2, 3, -4, 5, -6, 7, -8"); DataType lower_bound = fetch::math::Type<DataType>("0.03"); DataType upper_bound = fetch::math::Type<DataType>("0.08"); fetch::ml::ops::RandomisedRelu<TensorType> op(fetch::math::Type<DataType>("0.03"), fetch::math::Type<DataType>("0.08"), 12345); TensorType prediction(op.ComputeOutputShape({std::make_shared<const TensorType>(data)})); op.Forward({std::make_shared<const TensorType>(data)}, prediction); // test if values are within ranges CheckForwardValues(data, prediction, lower_bound, upper_bound); // Test after generating new random alpha value TensorType prediction_2 = TensorType(op.ComputeOutputShape({std::make_shared<const TensorType>(data)})); op.Forward({std::make_shared<const TensorType>(data)}, prediction_2); // test if values changed EXPECT_FALSE(prediction_2.AllClose(prediction, math::function_tolerance<DataType>(), math::function_tolerance<DataType>())); // test if values are within ranges CheckForwardValues(data, prediction_2, lower_bound, upper_bound); // Test with is_training set to false op.SetTraining(false); TensorType gt = TensorType::FromString("1, -0.11, 3, -0.22, 5, -0.33, 7, -0.44"); TensorType prediction_3 = TensorType(op.ComputeOutputShape({std::make_shared<const TensorType>(data)})); op.Forward({std::make_shared<const TensorType>(data)}, prediction); // test correct values EXPECT_TRUE(prediction.AllClose(gt, math::function_tolerance<DataType>(), math::function_tolerance<DataType>())); } TYPED_TEST(RandomisedReluTest, forward_3d_tensor_test) { using DataType = typename TypeParam::Type; using TensorType = TypeParam; DataType lower_bound = fetch::math::Type<DataType>("0.03"); DataType upper_bound = fetch::math::Type<DataType>("0.08"); TensorType data = TensorType::FromString("1, 3, 5, 7; -2, -4, -6, -8;"); data.Reshape({2, 2, 2}); fetch::ml::ops::RandomisedRelu<TensorType> op(lower_bound, upper_bound, 12345); TensorType prediction(op.ComputeOutputShape({std::make_shared<const TensorType>(data)})); op.Forward({std::make_shared<const TensorType>(data)}, prediction); // test if values are within ranges CheckForwardValues(data, prediction, lower_bound, upper_bound); } TYPED_TEST(RandomisedReluTest, backward_test) { using DataType = typename TypeParam::Type; using TensorType = TypeParam; DataType lower_bound = fetch::math::Type<DataType>("0.03"); DataType upper_bound = fetch::math::Type<DataType>("0.08"); TensorType data = TensorType::FromString("1, -2, 3, -4, 5, -6, 7, -8"); TensorType error = TensorType::FromString("0, 0, 0, 0, 1, 1, 0, 0"); fetch::ml::ops::RandomisedRelu<TensorType> op(lower_bound, upper_bound, 12345); std::vector<TensorType> prediction = op.Backward({std::make_shared<const TensorType>(data)}, error); // test if values are within ranges EXPECT_TRUE(prediction[0].At(0, 0) == DataType{0}); EXPECT_TRUE(prediction[0].At(0, 1) == DataType{0}); EXPECT_TRUE(prediction[0].At(0, 2) == DataType{0}); EXPECT_TRUE(prediction[0].At(0, 3) == DataType{0}); EXPECT_TRUE(prediction[0].At(0, 4) == DataType{1}); EXPECT_TRUE(prediction[0].At(0, 5) >= lower_bound && prediction[0].At(0, 5) <= upper_bound); EXPECT_TRUE(prediction[0].At(0, 6) == DataType{0}); EXPECT_TRUE(prediction[0].At(0, 7) == DataType{0}); // Test after generating new random alpha value // Forward pass will update random value TensorType output(op.ComputeOutputShape({std::make_shared<const TensorType>(data)})); op.Forward({std::make_shared<const TensorType>(data)}, output); std::vector<TensorType> prediction_2 = op.Backward({std::make_shared<const TensorType>(data)}, error); // test if values changed EXPECT_FALSE(prediction_2[0].AllClose(prediction[0], math::function_tolerance<DataType>(), math::function_tolerance<DataType>())); // test if values are within ranges EXPECT_TRUE(prediction_2[0].At(0, 0) == DataType{0}); EXPECT_TRUE(prediction_2[0].At(0, 1) == DataType{0}); EXPECT_TRUE(prediction_2[0].At(0, 2) == DataType{0}); EXPECT_TRUE(prediction_2[0].At(0, 3) == DataType{0}); EXPECT_TRUE(prediction_2[0].At(0, 4) == DataType{1}); EXPECT_TRUE(prediction_2[0].At(0, 5) >= lower_bound && prediction_2[0].At(0, 5) <= upper_bound); EXPECT_TRUE(prediction_2[0].At(0, 6) == DataType{0}); EXPECT_TRUE(prediction_2[0].At(0, 7) == DataType{0}); // Test with is_training set to false op.SetTraining(false); TensorType gt = TensorType::FromString("0, 0, 0, 0, 1, 0.055, 0, 0"); prediction = op.Backward({std::make_shared<const TensorType>(data)}, error); // test correct values EXPECT_TRUE(prediction[0].AllClose(gt, math::function_tolerance<DataType>(), math::function_tolerance<DataType>())); } TYPED_TEST(RandomisedReluTest, backward_3d_tensor_test) { using DataType = typename TypeParam::Type; using TensorType = TypeParam; DataType lower_bound = fetch::math::Type<DataType>("0.03"); DataType upper_bound = fetch::math::Type<DataType>("0.08"); TensorType data = TensorType::FromString("1, 3, 5, 7;-2, -4, -6, -8;"); data.Reshape({2, 2, 2}); TensorType error = TensorType::FromString("0, 0, 1, 0;0, 0, 1, 0;"); error.Reshape({2, 2, 2}); fetch::ml::ops::RandomisedRelu<TensorType> op(lower_bound, upper_bound, 12345); std::vector<TensorType> prediction = op.Backward({std::make_shared<const TensorType>(data)}, error); // test if values are within ranges EXPECT_TRUE(prediction[0].At(0, 0, 0) == DataType{0}); EXPECT_TRUE(prediction[0].At(0, 0, 1) == DataType{1}); EXPECT_TRUE(prediction[0].At(0, 1, 0) == DataType{0}); EXPECT_TRUE(prediction[0].At(0, 1, 1) == DataType{0}); EXPECT_TRUE(prediction[0].At(1, 0, 0) == DataType{0}); EXPECT_TRUE(prediction[0].At(1, 0, 1) >= lower_bound && prediction[0].At(1, 0, 1) <= upper_bound); EXPECT_TRUE(prediction[0].At(1, 1, 0) == DataType{0}); EXPECT_TRUE(prediction[0].At(1, 1, 1) == DataType{0}); } TYPED_TEST(RandomisedReluTest, saveparams_test) { using DataType = typename TypeParam::Type; using TensorType = TypeParam; using VecTensorType = typename fetch::ml::ops::Ops<TensorType>::VecTensorType; using SPType = typename fetch::ml::ops::RandomisedRelu<TensorType>::SPType; using OpType = typename fetch::ml::ops::RandomisedRelu<TensorType>; DataType lower_bound = fetch::math::Type<DataType>("0.03"); DataType upper_bound = fetch::math::Type<DataType>("0.08"); TensorType data = TensorType::FromString("1, -2, 3, -4, 5, -6, 7, -8"); fetch::ml::ops::RandomisedRelu<TensorType> op(lower_bound, upper_bound, 12345); TensorType prediction(op.ComputeOutputShape({std::make_shared<const TensorType>(data)})); VecTensorType vec_data({std::make_shared<const TensorType>(data)}); op.Forward(vec_data, prediction); // extract saveparams std::shared_ptr<fetch::ml::OpsSaveableParams> sp = op.GetOpSaveableParams(); // downcast to correct type auto dsp = std::static_pointer_cast<SPType>(sp); // serialize fetch::serializers::MsgPackSerializer b; b << *dsp; // make another prediction with the original graph op.Forward(vec_data, prediction); // deserialize b.seek(0); auto dsp2 = std::make_shared<SPType>(); b >> *dsp2; // rebuild node OpType new_op(*dsp2); // check that new predictions match the old TensorType new_prediction(op.ComputeOutputShape({std::make_shared<const TensorType>(data)})); new_op.Forward(vec_data, new_prediction); // test correct values EXPECT_TRUE(new_prediction.AllClose(prediction, DataType{0}, DataType{0})); } TYPED_TEST(RandomisedReluTest, saveparams_backward_3d_tensor_test) { using DataType = typename TypeParam::Type; using TensorType = TypeParam; using OpType = typename fetch::ml::ops::RandomisedRelu<TensorType>; using SPType = typename OpType::SPType; DataType lower_bound = fetch::math::Type<DataType>("0.03"); DataType upper_bound = fetch::math::Type<DataType>("0.08"); TensorType data = TensorType::FromString("1, 3, 5, 7;-2, -4, -6, -8;"); data.Reshape({2, 2, 2}); TensorType error = TensorType::FromString("0, 0, 1, 0;0, 0, 1, 0;"); error.Reshape({2, 2, 2}); fetch::ml::ops::RandomisedRelu<TensorType> op(lower_bound, upper_bound, 12345); // run op once to make sure caches etc. have been filled. Otherwise the test might be trivial! std::vector<TensorType> prediction = op.Backward({std::make_shared<const TensorType>(data)}, error); // extract saveparams std::shared_ptr<fetch::ml::OpsSaveableParams> sp = op.GetOpSaveableParams(); // downcast to correct type auto dsp = std::dynamic_pointer_cast<SPType>(sp); // serialize fetch::serializers::MsgPackSerializer b; b << *dsp; // make another prediction with the original op prediction = op.Backward({std::make_shared<const TensorType>(data)}, error); // deserialize b.seek(0); auto dsp2 = std::make_shared<SPType>(); b >> *dsp2; // rebuild node OpType new_op(*dsp2); // check that new predictions match the old std::vector<TensorType> new_prediction = new_op.Backward({std::make_shared<const TensorType>(data)}, error); // test correct values EXPECT_TRUE(prediction.at(0).AllClose( new_prediction.at(0), fetch::math::function_tolerance<typename TypeParam::Type>(), fetch::math::function_tolerance<typename TypeParam::Type>())); } } // namespace test } // namespace ml } // namespace fetch
#include "celero/Celero.h" #include <iostream> constexpr int number_of_samples = 10; constexpr int number_of_operations = 1; #ifdef __APPLE__ const std::string find_cmd = "gfind "; #else const std::string find_cmd = "find "; #endif const std::string fast_find("../commands/fast-find "); const std::string tmp_file = "/tmp/output.log"; const std::string test_path(std::getenv("TEST_DIR")); int test(const std::string &command, const std::string &path) { std::string buffer = command + path + " &> " + tmp_file; return system(buffer.data()); } int test_find_regex(const std::string &command, const std::string &regex, const std::string &path) { std::string buffer = command + " " + path + " |& grep -E " + regex + " > " + tmp_file; return system(buffer.data()); } int test_fast_find_regex(const std::string &command, const std::string &regex, const std::string &path) { std::string buffer = command + " -e " + regex + " " + path + " &> " + tmp_file; return system(buffer.data()); } int test_fd_regex(const std::string &command, const std::string &regex, const std::string &path) { std::string buffer = command + " " + regex + " " + path + " &> " + tmp_file; return system(buffer.data()); } // const std::string pattern1{"\'/\\w+options.c(p)*$\'"}; const std::string pattern1{" zstd/.*doc/README[.]md$ "}; CELERO_MAIN // Find all files in mid size folder. BASELINE(all, find, number_of_samples, number_of_operations) { test(find_cmd, test_path); } BENCHMARK(all, fd_noignore, number_of_samples, number_of_operations) { test("fd -H --no-ignore . ", test_path); } BENCHMARK(all, fast_find, number_of_samples, number_of_operations) { test(fast_find + " --donot-ignore-git ", test_path); } BENCHMARK(all, fast_find_bfs, number_of_samples, number_of_operations) { test(fast_find + " --bfs --donot-ignore-git ", test_path); } // Find all files and ignore .git folder BASELINE(ignore_git, find, number_of_samples, number_of_operations) { test(find_cmd, test_path); } BENCHMARK(ignore_git, fd, number_of_samples, number_of_operations) { test("fd . ", test_path); } BENCHMARK(ignore_git, fast_find_default, number_of_samples, number_of_operations) { test(fast_find, test_path); } BENCHMARK(ignore_git, fast_find_bfs, number_of_samples, number_of_operations) { test(fast_find + " --bfs ", test_path); } // Find all files using a regex that does not match any results BASELINE(regex, find, number_of_samples, number_of_operations) { test_find_regex(find_cmd, pattern1, test_path); } BENCHMARK(regex, fd, number_of_samples, number_of_operations) { test_fd_regex("fd --full-path ", pattern1, test_path); } BENCHMARK(regex, fast_find, number_of_samples, number_of_operations) { test_fast_find_regex(fast_find, pattern1, test_path); } BENCHMARK(regex, fast_find_bfs, number_of_samples, number_of_operations) { test_fast_find_regex(fast_find + " --bfs", pattern1, test_path); }
#include "CGBL_dmesh.h" #include "Cmdline.h" #include "janelia.h" #include "File.h" #include "CAffineLens.h" #include "Debug.h" /* --------------------------------------------------------------- */ /* Constants ----------------------------------------------------- */ /* --------------------------------------------------------------- */ /* --------------------------------------------------------------- */ /* Macros -------------------------------------------------------- */ /* --------------------------------------------------------------- */ #define ID_UNSET -999 /* --------------------------------------------------------------- */ /* Types --------------------------------------------------------- */ /* --------------------------------------------------------------- */ /* --------------------------------------------------------------- */ /* Globals ------------------------------------------------------- */ /* --------------------------------------------------------------- */ CGBL_dmesh GBL; /* --------------------------------------------------------------- */ /* Statics ------------------------------------------------------- */ /* --------------------------------------------------------------- */ /* --------------------------------------------------------------- */ /* PrintUsage --------------------------------------------------- */ /* --------------------------------------------------------------- */ static void PrintUsage() { fprintf( stderr, "\n" "Usage: ptest za.ia^zb.ib [ options ], where,\n" "\n" " za >= 0 (overridden by -jtilea option),\n" " ia >= 0 (overridden by -jtilea option; sets to -1),\n" " zb >= 0 (overridden by -jtileb option),\n" " ib >= 0 (overridden by -jtileb option; sets to -1).\n" "\n" " Options:\n" " -jtilea=<URL to tile-A JSON>\n" " -jtileb=<URL to tile-B JSON>\n" " -prm=<path to matchparams.txt>\n" " -Tdfm=<six comma-separated values>\n" " -Tab=<six comma-separated values>\n" " -Ta=<six comma-separated values>\n" " -Tb=<six comma-separated values>\n" " -SCALE=<value>\n" " -XSCALE=<value>\n" " -YSCALE=<value>\n" " -SKEW=<value>\n" " -ima=<path to image a>\n" " -imb=<path to image b>\n" " -fma=<path to foldmask a>\n" " -fmb=<path to foldmask b>\n" " -FLD=<Y=use, N=none, X=XL only>\n" " -MODE=<value, see matchparams.txt>\n" " -CTR=<value>\n" " -tr\n" " -ws\n" " -nf\n" " -sf\n" " -Tmsh=<six comma-separated values>\n" " -XYexp=<two comma-separated values>\n" " -json\n" " -v\n" " -comp_png=<path to comp.png>\n" " -registered_png=<path to registered.png>\n" " -heatmap\n" " -dbgcor\n" "\n" ); } /* --------------------------------------------------------------- */ /* Object management --------------------------------------------- */ /* --------------------------------------------------------------- */ CGBL_dmesh::CGBL_dmesh() { _arg.SCALE = 999.0; _arg.XSCALE = 999.0; _arg.YSCALE = 999.0; _arg.SKEW = 999.0; _arg.matchparams = NULL; _arg.ima = NULL; _arg.imb = NULL; _arg.FLD = 0; _arg.MODE = 0; arg.CTR = 999.0; arg.fma = NULL; arg.fmb = NULL; arg.comp_png = NULL; arg.registered_png = NULL; arg.Transpose = false; arg.WithinSection = false; arg.SingleFold = false; arg.JSON = false; arg.Verbose = false; arg.Heatmap = false; A.z = 0; A.id = ID_UNSET; B.z = 0; B.id = ID_UNSET; } /* --------------------------------------------------------------- */ /* SetCmdLine ---------------------------------------------------- */ /* --------------------------------------------------------------- */ bool CGBL_dmesh::SetCmdLine( int argc, char* argv[] ) { // Parse args const char *key = NULL; vector<double> vD; for( int i = 1; i < argc; ++i ) { if( argv[i][0] != '-' ) key = argv[i]; else if( GetArgList( vD, "-Tdfm=", argv[i] ) ) { if( 6 == vD.size() ) _arg.Tdfm.push_back( TAffine( &vD[0] ) ); else { fprintf( stderr, "main: WARNING: Bad format in -Tdfm [%s].\n", argv[i] ); } } else if( GetArgList( vD, "-Tab=", argv[i] ) ) { if( 6 == vD.size() ) _arg.Tab.push_back( TAffine( &vD[0] ) ); else { fprintf( stderr, "main: WARNING: Bad format in -Tab [%s].\n", argv[i] ); } } else if( GetArgList( vD, "-Ta=", argv[i] ) ) { if( 6 == vD.size() ) _arg.Ta.push_back( TAffine( &vD[0] ) ); else { fprintf( stderr, "main: WARNING: Bad format in -Ta [%s].\n", argv[i] ); } } else if( GetArgList( vD, "-Tb=", argv[i] ) ) { if( 6 == vD.size() ) _arg.Tb.push_back( TAffine( &vD[0] ) ); else { fprintf( stderr, "main: WARNING: Bad format in -Tb [%s].\n", argv[i] ); } } else if( GetArg( &_arg.SCALE, "-SCALE=%lf", argv[i] ) ) ; else if( GetArg( &_arg.XSCALE, "-XSCALE=%lf", argv[i] ) ) ; else if( GetArg( &_arg.YSCALE, "-YSCALE=%lf", argv[i] ) ) ; else if( GetArg( &_arg.SKEW, "-SKEW=%lf", argv[i] ) ) ; else if( GetArgStr( _arg.matchparams, "-prm=", argv[i] ) ) ; else if( GetArgStr( _arg.ima, "-ima=", argv[i] ) ) ; else if( GetArgStr( _arg.imb, "-imb=", argv[i] ) ) ; else if( GetArg( &_arg.FLD, "-FLD=%c", argv[i] ) ) ; else if( GetArg( &_arg.MODE, "-MODE=%c", argv[i] ) ) ; else if( GetArg( &arg.CTR, "-CTR=%lf", argv[i] ) ) ; else if( GetArgStr( arg.fma, "-fma=", argv[i] ) ) ; else if( GetArgStr( arg.fmb, "-fmb=", argv[i] ) ) ; else if( GetArgStr( arg.comp_png, "-comp_png=", argv[i] ) ) ; else if( GetArgStr( arg.registered_png, "-registered_png=", argv[i] ) ) ; else if( IsArg( "-tr", argv[i] ) ) arg.Transpose = true; else if( IsArg( "-ws", argv[i] ) ) arg.WithinSection = true; else if( IsArg( "-nf", argv[i] ) ) _arg.FLD = 'N'; else if( IsArg( "-sf", argv[i] ) ) arg.SingleFold = true; else if( IsArg( "-json", argv[i] ) ) arg.JSON = true; else if( IsArg( "-v", argv[i] ) ) arg.Verbose = true; else if( IsArg( "-heatmap", argv[i] ) ) arg.Heatmap = true; else if( IsArg( "-dbgcor", argv[i] ) ) dbgCor = true; else if( GetArgList( vD, "-Tmsh=", argv[i] ) ) { if( 6 == vD.size() ) Tmsh.push_back( TAffine( &vD[0] ) ); else { fprintf( stderr, "main: WARNING: Bad format in -Tmsh [%s].\n", argv[i] ); } } else if( GetArgList( vD, "-XYexp=", argv[i] ) ) { if( 2 == vD.size() ) XYexp.push_back( Point( vD[0], vD[1] ) ); else { fprintf( stderr, "main: WARNING: Bad format in -XYexp [%s].\n", argv[i] ); } } else if( GetTileSpecFromURL( A, "-jtilea=", argv[i] ) ) ; else if( GetTileSpecFromURL( B, "-jtileb=", argv[i] ) ) ; else { fprintf( stderr, "Did not understand option '%s'.\n", argv[i] ); return false; } } // Decode labels in key { int az, aid, bz, bid; if( !key || (4 != sscanf( key, "%d.%d^%d.%d", &az, &aid, &bz, &bid )) ) { PrintUsage(); return false; } else { if( A.id == ID_UNSET ) { A.z = az; A.id = aid; } if( B.id == ID_UNSET ) { B.z = bz; B.id = bid; } } } // Start logging fprintf( stderr, "\n---- dmesh start ----\n" ); // Record start time time_t t0 = time( NULL ); fprintf( stderr, "main: Start: %s\n", ctime(&t0) ); // Get default parameters if( !ReadMatchParams( mch, A.z, B.z, _arg.matchparams, stderr ) ) return false; // Which file params to use according to (same,cross) layer double cSCALE=1, cXSCALE=1, cYSCALE=1, cSKEW=0; int cDfmFromTab; ctx.FLD = mch.FLD; if( A.z == B.z ) { cDfmFromTab = mch.TAB2DFM_SL; //ctx.Tdfm = identity (default) ctx.XYCONF = mch.XYCONF_SL; ctx.NBMXHT = mch.NBMXHT_SL; ctx.HFANGDN = mch.HFANGDN_SL; ctx.HFANGPR = mch.HFANGPR_SL; ctx.RTRSH = mch.RTRSH_SL; ctx.RIT = mch.RIT_SL; ctx.RFA = mch.RFA_SL; ctx.RFT = mch.RFT_SL; ctx.OLAP2D = mch.OLAP2D_SL; ctx.MODE = mch.MODE_SL; ctx.THMDEC = mch.THMDEC_SL; ctx.OLAP1D = mch.OLAP1D_SL; ctx.LIMXY = mch.LIMXY_SL; ctx.OPT = mch.OPT_SL; } else { cSCALE = mch.SCALE; cXSCALE = mch.XSCALE; cYSCALE = mch.YSCALE; cSKEW = mch.SKEW; ctx.Tdfm.ComposeDfm( cSCALE, cXSCALE, cYSCALE, 0, cSKEW ); cDfmFromTab = mch.TAB2DFM_XL; ctx.XYCONF = mch.XYCONF_XL; ctx.NBMXHT = mch.NBMXHT_XL; ctx.HFANGDN = mch.HFANGDN_XL; ctx.HFANGPR = mch.HFANGPR_XL; ctx.RTRSH = mch.RTRSH_XL; ctx.RIT = mch.RIT_XL; ctx.RFA = mch.RFA_XL; ctx.RFT = mch.RFT_XL; ctx.OLAP2D = mch.OLAP2D_XL; ctx.MODE = mch.MODE_XL; ctx.THMDEC = mch.THMDEC_XL; ctx.OLAP1D = mch.OLAP1D_XL; ctx.LIMXY = mch.LIMXY_XL; ctx.OPT = true; } // Fetch Til2Img entries (using image overrides) fprintf( stderr, "\n---- Input images ----\n" ); if( A.id >= 0 || B.id >= 0 ) IDBFromTemp( idb, "../../", stderr ); if( A.id >= 0 ) { if( !IDBT2IGet1( A.t2i, idb, A.z, A.id, _arg.ima, stderr ) ) return false; } else if( _arg.ima ) A.t2i.path = _arg.ima; if( B.id >= 0 ) { if( !IDBT2IGet1( B.t2i, idb, B.z, B.id, _arg.imb, stderr ) ) return false; } else if( _arg.imb ) B.t2i.path = _arg.imb; PrintTil2Img( stderr, 'A', A.t2i ); PrintTil2Img( stderr, 'B', B.t2i ); fprintf( stderr, "\n" ); // Commandline parameter overrides fprintf( stderr, "\n---- Command-line overrides ----\n" ); if( _arg.Tab.size() ) { Tab = _arg.Tab[0]; // remove lens parts of Tab coming from cross_thisblock if( mch.PXLENS && A.z != B.z ) { CAffineLens LN; if( !LN.ReadIDB( idb, stderr ) ) return false; LN.UpdateTFormRHS( Tab, A.t2i.cam, true ); LN.UpdateTFormLHS( Tab, B.t2i.cam, false ); } Tab.TPrint( stderr, "Tab= " ); } else if( _arg.Ta.size() || _arg.Tb.size() ) { TAffine Ta, Tb; if( _arg.Ta.size() ) Ta = _arg.Ta[0]; if( _arg.Tb.size() ) Tb = _arg.Tb[0]; Tab.FromAToB( Ta, Tb ); Ta.TPrint( stderr, "Ta= " ); Tb.TPrint( stderr, "Tb= " ); Tab.TPrint( stderr, "Tab= " ); } else Tab.FromAToB( A.t2i.T, B.t2i.T ); int altTdfm = false; if( _arg.Tdfm.size() ) { ctx.Tdfm = _arg.Tdfm[0]; altTdfm = true; } else { if( _arg.SCALE != 999.0 ) { cSCALE = _arg.SCALE; altTdfm = true; fprintf( stderr, "SCALE=%g\n", _arg.SCALE ); } if( _arg.XSCALE != 999.0 ) { cXSCALE = _arg.XSCALE; altTdfm = true; fprintf( stderr, "XSCALE=%g\n", _arg.XSCALE ); } if( _arg.YSCALE != 999.0 ) { cYSCALE = _arg.YSCALE; altTdfm = true; fprintf( stderr, "YSCALE=%g\n", _arg.YSCALE ); } if( _arg.SKEW != 999.0 ) { cSKEW = _arg.SKEW; altTdfm = true; fprintf( stderr, "SKEW=%g\n", _arg.SKEW ); } if( altTdfm ) ctx.Tdfm.ComposeDfm( cSCALE, cXSCALE, cYSCALE, 0, cSKEW ); } if( !altTdfm && cDfmFromTab ) { TAffine R; R.NUSetRot( -Tab.GetRadians() ); ctx.Tdfm = Tab; ctx.Tdfm.SetXY( 0, 0 ); ctx.Tdfm = R * ctx.Tdfm; } ctx.Tdfm.TPrint( stderr, "Tdfm=" ); if( _arg.FLD ) { ctx.FLD = _arg.FLD; fprintf( stderr, "FLD=%c\n", _arg.FLD ); } if( ctx.FLD == 'X' ) { ctx.FLD = (GBL.A.z == GBL.B.z ? 'N' : 'Y'); fprintf( stderr, "FLD=%c (was X)\n", ctx.FLD ); } if( _arg.MODE ) { ctx.MODE = _arg.MODE; fprintf( stderr, "MODE=%c\n", _arg.MODE ); } if( ctx.MODE == 'Z' ) { ctx.MODE = 'C'; arg.CTR = 0.0; fprintf( stderr, "MODE=C (was Z)\n" ); } else if( ctx.MODE == 'M' ) { ctx.MODE = 'N'; arg.CTR = 0.0; fprintf( stderr, "MODE=N (was M)\n" ); } if( arg.CTR != 999.0 ) fprintf( stderr, "CTR=%g\n", arg.CTR ); fprintf( stderr, "\n" ); return true; }
#include "../map_editor_controller.h" #include <range/v3/to_container.hpp> #include <range/v3/view/concat.hpp> namespace lmeditor { map_editor_controller::command delete_selected_command{ [](map_editor_controller::command_args const &args) { if (args.controller.have_selection()) { auto selected_box = args.controller.get_selection(); lmng::orphan_children(args.map, selected_box); args.map.destroy(selected_box); args.controller.clear_selection(); return true; } return false; }, "Delete selected", }; map_editor_controller::command add_command{ [](map_editor_controller::command_args const &args) { Eigen::Vector3f add_pos = Eigen::Vector3f::Zero(); if (args.controller.have_selection()) { args.controller .template enter_state<map_editor_controller::add_adjacent_state>( std::get<map_editor_controller::select_state>( args.controller.state)); return true; } entt::entity new_box = args.controller.add_cube(args.map, add_pos, 1.f); args.controller.clear_selection(); return true; }, "Add entity", }; map_editor_controller::command deselect_command{ [](map_editor_controller::command_args const &args) { if (args.controller.have_selection()) { args.controller.clear_selection(); return true; } return false; }, "Clear selection", }; map_editor_controller::command translate_command{ [](map_editor_controller::command_args const &args) { if (args.controller.have_selection()) { args.controller .template enter_state<map_editor_controller::translate_state>( std::get<map_editor_controller::select_state>( args.controller.state)); return true; } else return false; }, "Translate entity", }; map_editor_controller::command copy_entity_command{ [](map_editor_controller::command_args const &args) { Eigen::Vector3f add_pos = Eigen::Vector3f::Zero(); if (args.controller.have_selection()) { args.controller .template enter_state<map_editor_controller::copy_entity_state>( std::get<map_editor_controller::select_state>( args.controller.state)); return true; } return false; }, "Copy entity", }; map_editor_controller::command reparent_command{ [](map_editor_controller::command_args const &args) { if (args.controller.have_selection()) { args.controller .template enter_state<map_editor_controller::reparent_state>( std::get<map_editor_controller::select_state>( args.controller.state)); return true; } return false; }, "Reparent entity", }; map_editor_controller::command scale_command{ [](map_editor_controller::command_args const &args) { auto selected_box = args.controller.get_selection(); if ( args.controller.have_selection() && (args.map.has<lmng::box_render>(selected_box) || args.map.has<lmng::box_collider>(selected_box))) { args.controller .template enter_state<map_editor_controller::scale_state>( std::get<map_editor_controller::select_state>( args.controller.state)); return true; } return false; }, "Scale entity", }; map_editor_controller::command rotate_command{ [](map_editor_controller::command_args const &args) { if (args.controller.have_selection()) { args.controller .template enter_state<map_editor_controller::rotate_state>( std::get<map_editor_controller::select_state>( args.controller.state)); return true; } return false; }, "Rotate entity", }; map_editor_controller::command_list select_commands{ {{lmpl::key_code::X}, delete_selected_command}, {{lmpl::key_code::A}, add_command}, {{lmpl::key_code::N}, deselect_command}, {{lmpl::key_code::M}, translate_command}, {{lmpl::key_code::C}, copy_entity_command}, {{lmpl::key_code::Y}, reparent_command}, {{lmpl::key_code::LeftShift, lmpl::key_code::S}, scale_command}, {{lmpl::key_code::LeftShift, lmpl::key_code::R}, rotate_command}, }; map_editor_controller::select_state::select_state( map_editor_controller &map_editor) : commands{ranges::views::concat(map_editor_controller::move_selection_commands, map_editor_controller::viewport_commands, select_commands) | ranges::to<command_list>()}, key_command_map{ranges::views::all(commands) | ranges::to<command_map>()} { } } // namespace lmeditor
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" #include "extern/beatsaber-hook/shared/utils/typedefs-array.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: Org::BouncyCastle::Asn1 namespace Org::BouncyCastle::Asn1 { // Forward declaring type: Asn1Set class Asn1Set; // Forward declaring type: Asn1InputStream class Asn1InputStream; } // Forward declaring namespace: System::IO namespace System::IO { // Forward declaring type: Stream class Stream; } // Forward declaring namespace: Org::BouncyCastle::X509 namespace Org::BouncyCastle::X509 { // Forward declaring type: PemParser class PemParser; // Forward declaring type: X509Certificate class X509Certificate; } // Forward declaring namespace: Org::BouncyCastle::Asn1::X509 namespace Org::BouncyCastle::Asn1::X509 { // Forward declaring type: X509CertificateStructure class X509CertificateStructure; } // Forward declaring namespace: System::Collections namespace System::Collections { // Forward declaring type: ICollection class ICollection; } // Completed forward declares // Type namespace: Org.BouncyCastle.X509 namespace Org::BouncyCastle::X509 { // Forward declaring type: X509CertificateParser class X509CertificateParser; } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(Org::BouncyCastle::X509::X509CertificateParser); DEFINE_IL2CPP_ARG_TYPE(Org::BouncyCastle::X509::X509CertificateParser*, "Org.BouncyCastle.X509", "X509CertificateParser"); // Type namespace: Org.BouncyCastle.X509 namespace Org::BouncyCastle::X509 { // Size: 0x28 #pragma pack(push, 1) // Autogenerated type: Org.BouncyCastle.X509.X509CertificateParser // [TokenAttribute] Offset: FFFFFFFF class X509CertificateParser : public ::Il2CppObject { public: #ifdef USE_CODEGEN_FIELDS public: #else protected: #endif // private Org.BouncyCastle.Asn1.Asn1Set sData // Size: 0x8 // Offset: 0x10 Org::BouncyCastle::Asn1::Asn1Set* sData; // Field size check static_assert(sizeof(Org::BouncyCastle::Asn1::Asn1Set*) == 0x8); // private System.Int32 sDataObjectCount // Size: 0x4 // Offset: 0x18 int sDataObjectCount; // Field size check static_assert(sizeof(int) == 0x4); // Padding between fields: sDataObjectCount and: currentStream char __padding1[0x4] = {}; // private System.IO.Stream currentStream // Size: 0x8 // Offset: 0x20 System::IO::Stream* currentStream; // Field size check static_assert(sizeof(System::IO::Stream*) == 0x8); public: // Get static field: static private readonly Org.BouncyCastle.X509.PemParser PemCertParser static Org::BouncyCastle::X509::PemParser* _get_PemCertParser(); // Set static field: static private readonly Org.BouncyCastle.X509.PemParser PemCertParser static void _set_PemCertParser(Org::BouncyCastle::X509::PemParser* value); // Get instance field reference: private Org.BouncyCastle.Asn1.Asn1Set sData Org::BouncyCastle::Asn1::Asn1Set*& dyn_sData(); // Get instance field reference: private System.Int32 sDataObjectCount int& dyn_sDataObjectCount(); // Get instance field reference: private System.IO.Stream currentStream System::IO::Stream*& dyn_currentStream(); // static private System.Void .cctor() // Offset: 0x216FE14 static void _cctor(); // private Org.BouncyCastle.X509.X509Certificate ReadDerCertificate(Org.BouncyCastle.Asn1.Asn1InputStream dIn) // Offset: 0x216F558 Org::BouncyCastle::X509::X509Certificate* ReadDerCertificate(Org::BouncyCastle::Asn1::Asn1InputStream* dIn); // private Org.BouncyCastle.X509.X509Certificate GetCertificate() // Offset: 0x216F75C Org::BouncyCastle::X509::X509Certificate* GetCertificate(); // private Org.BouncyCastle.X509.X509Certificate ReadPemCertificate(System.IO.Stream inStream) // Offset: 0x216F854 Org::BouncyCastle::X509::X509Certificate* ReadPemCertificate(System::IO::Stream* inStream); // protected Org.BouncyCastle.X509.X509Certificate CreateX509Certificate(Org.BouncyCastle.Asn1.X509.X509CertificateStructure c) // Offset: 0x216F908 Org::BouncyCastle::X509::X509Certificate* CreateX509Certificate(Org::BouncyCastle::Asn1::X509::X509CertificateStructure* c); // public Org.BouncyCastle.X509.X509Certificate ReadCertificate(System.Byte[] input) // Offset: 0x216F968 Org::BouncyCastle::X509::X509Certificate* ReadCertificate(::ArrayW<uint8_t> input); // public System.Collections.ICollection ReadCertificates(System.Byte[] input) // Offset: 0x216FC7C System::Collections::ICollection* ReadCertificates(::ArrayW<uint8_t> input); // public Org.BouncyCastle.X509.X509Certificate ReadCertificate(System.IO.Stream inStream) // Offset: 0x216F9E0 Org::BouncyCastle::X509::X509Certificate* ReadCertificate(System::IO::Stream* inStream); // public System.Collections.ICollection ReadCertificates(System.IO.Stream inStream) // Offset: 0x216FCF4 System::Collections::ICollection* ReadCertificates(System::IO::Stream* inStream); // public System.Void .ctor() // Offset: 0x216FE88 // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static X509CertificateParser* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("Org::BouncyCastle::X509::X509CertificateParser::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<X509CertificateParser*, creationType>())); } }; // Org.BouncyCastle.X509.X509CertificateParser #pragma pack(pop) static check_size<sizeof(X509CertificateParser), 32 + sizeof(System::IO::Stream*)> __Org_BouncyCastle_X509_X509CertificateParserSizeCheck; static_assert(sizeof(X509CertificateParser) == 0x28); } #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: Org::BouncyCastle::X509::X509CertificateParser::_cctor // Il2CppName: .cctor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&Org::BouncyCastle::X509::X509CertificateParser::_cctor)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::X509::X509CertificateParser*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: Org::BouncyCastle::X509::X509CertificateParser::ReadDerCertificate // Il2CppName: ReadDerCertificate template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<Org::BouncyCastle::X509::X509Certificate* (Org::BouncyCastle::X509::X509CertificateParser::*)(Org::BouncyCastle::Asn1::Asn1InputStream*)>(&Org::BouncyCastle::X509::X509CertificateParser::ReadDerCertificate)> { static const MethodInfo* get() { static auto* dIn = &::il2cpp_utils::GetClassFromName("Org.BouncyCastle.Asn1", "Asn1InputStream")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::X509::X509CertificateParser*), "ReadDerCertificate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{dIn}); } }; // Writing MetadataGetter for method: Org::BouncyCastle::X509::X509CertificateParser::GetCertificate // Il2CppName: GetCertificate template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<Org::BouncyCastle::X509::X509Certificate* (Org::BouncyCastle::X509::X509CertificateParser::*)()>(&Org::BouncyCastle::X509::X509CertificateParser::GetCertificate)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::X509::X509CertificateParser*), "GetCertificate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: Org::BouncyCastle::X509::X509CertificateParser::ReadPemCertificate // Il2CppName: ReadPemCertificate template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<Org::BouncyCastle::X509::X509Certificate* (Org::BouncyCastle::X509::X509CertificateParser::*)(System::IO::Stream*)>(&Org::BouncyCastle::X509::X509CertificateParser::ReadPemCertificate)> { static const MethodInfo* get() { static auto* inStream = &::il2cpp_utils::GetClassFromName("System.IO", "Stream")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::X509::X509CertificateParser*), "ReadPemCertificate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{inStream}); } }; // Writing MetadataGetter for method: Org::BouncyCastle::X509::X509CertificateParser::CreateX509Certificate // Il2CppName: CreateX509Certificate template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<Org::BouncyCastle::X509::X509Certificate* (Org::BouncyCastle::X509::X509CertificateParser::*)(Org::BouncyCastle::Asn1::X509::X509CertificateStructure*)>(&Org::BouncyCastle::X509::X509CertificateParser::CreateX509Certificate)> { static const MethodInfo* get() { static auto* c = &::il2cpp_utils::GetClassFromName("Org.BouncyCastle.Asn1.X509", "X509CertificateStructure")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::X509::X509CertificateParser*), "CreateX509Certificate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{c}); } }; // Writing MetadataGetter for method: Org::BouncyCastle::X509::X509CertificateParser::ReadCertificate // Il2CppName: ReadCertificate template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<Org::BouncyCastle::X509::X509Certificate* (Org::BouncyCastle::X509::X509CertificateParser::*)(::ArrayW<uint8_t>)>(&Org::BouncyCastle::X509::X509CertificateParser::ReadCertificate)> { static const MethodInfo* get() { static auto* input = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg; return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::X509::X509CertificateParser*), "ReadCertificate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{input}); } }; // Writing MetadataGetter for method: Org::BouncyCastle::X509::X509CertificateParser::ReadCertificates // Il2CppName: ReadCertificates template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Collections::ICollection* (Org::BouncyCastle::X509::X509CertificateParser::*)(::ArrayW<uint8_t>)>(&Org::BouncyCastle::X509::X509CertificateParser::ReadCertificates)> { static const MethodInfo* get() { static auto* input = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg; return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::X509::X509CertificateParser*), "ReadCertificates", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{input}); } }; // Writing MetadataGetter for method: Org::BouncyCastle::X509::X509CertificateParser::ReadCertificate // Il2CppName: ReadCertificate template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<Org::BouncyCastle::X509::X509Certificate* (Org::BouncyCastle::X509::X509CertificateParser::*)(System::IO::Stream*)>(&Org::BouncyCastle::X509::X509CertificateParser::ReadCertificate)> { static const MethodInfo* get() { static auto* inStream = &::il2cpp_utils::GetClassFromName("System.IO", "Stream")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::X509::X509CertificateParser*), "ReadCertificate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{inStream}); } }; // Writing MetadataGetter for method: Org::BouncyCastle::X509::X509CertificateParser::ReadCertificates // Il2CppName: ReadCertificates template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Collections::ICollection* (Org::BouncyCastle::X509::X509CertificateParser::*)(System::IO::Stream*)>(&Org::BouncyCastle::X509::X509CertificateParser::ReadCertificates)> { static const MethodInfo* get() { static auto* inStream = &::il2cpp_utils::GetClassFromName("System.IO", "Stream")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::X509::X509CertificateParser*), "ReadCertificates", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{inStream}); } }; // Writing MetadataGetter for method: Org::BouncyCastle::X509::X509CertificateParser::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
#include <cstdio> #include <cuda_runtime.h> int main() { int deviceCount, device; int gpuDeviceCount = 0; struct cudaDeviceProp properties; cudaError_t cudaResultCode = cudaGetDeviceCount(&deviceCount); if (cudaResultCode != cudaSuccess) deviceCount = 0; /* machines with no GPUs can still report one emulation device */ for (device = 0; device < deviceCount; ++device) { cudaGetDeviceProperties(&properties, device); if (properties.major != 9999) /* 9999 means emulation only */ ++gpuDeviceCount; } printf("%d GPU CUDA device(s) found\n", gpuDeviceCount); /* don't just return the number of gpus, because other runtime cuda errors can also yield non-zero return values */ if (gpuDeviceCount > 0) return 0; /* success */ else return 1; /* failure */ }
/* file: kmeans_dense_lloyd_batch_fpt_dispatcher_v1.cpp */ /******************************************************************************* * Copyright 2014-2020 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. *******************************************************************************/ /* //++ // Implementation of K-means algorithm container -- a class that contains // Lloyd K-means kernels for supported architectures. //-- */ #include "src/algorithms/kmeans/inner/kmeans_container_v1.h" namespace daal { namespace algorithms { __DAAL_INSTANTIATE_DISPATCH_CONTAINER_SYCL(kmeans::interface1::BatchContainer, batch, DAAL_FPTYPE, kmeans::lloydDense); } // namespace algorithms } // namespace daal
class Solution { public: bool hasGroupsSizeX(vector<int> &deck) { if (deck.size() < 2) { return false; } sort(deck.begin(), deck.end()); int x = -1, cnt = 1; for (int i = 0; i < deck.size() - 1; i++) { if (deck[i] == deck[i + 1]) { cnt++; // last if (i == deck.size() - 2) { x = gcd(x, cnt); } } else if (x == -1) { x = cnt; cnt = 1; } else { x = gcd(x, cnt); cnt = 1; } // cout << i << " " << x << endl; if (x >= 0 && x < 2) { return false; } } return true; } int gcd(int x, int y) { int r; // 引数チェック if (x == 0 || y == 0) { return 0; } // ユーグリッドの互除法 // yで割り切れるまでループ while ((r = x % y) != 0) { x = y; y = r; } return y; } };
// Distributed under the MIT License. // See LICENSE.txt for details. #pragma once #include <pup.h> #include "Domain/BoundaryConditions/BoundaryCondition.hpp" namespace RelativisticEuler::Valencia { /// \brief Boundary conditions for the relativistic Euler system namespace BoundaryConditions { /// \brief The base class off of which all boundary conditions must inherit template <size_t Dim> class BoundaryCondition : public domain::BoundaryConditions::BoundaryCondition { public: BoundaryCondition() = default; BoundaryCondition(BoundaryCondition&&) = default; BoundaryCondition& operator=(BoundaryCondition&&) = default; BoundaryCondition(const BoundaryCondition&) = default; BoundaryCondition& operator=(const BoundaryCondition&) = default; ~BoundaryCondition() override = default; explicit BoundaryCondition(CkMigrateMessage* msg); void pup(PUP::er& p) override; }; } // namespace BoundaryConditions } // namespace RelativisticEuler::Valencia
/* * Copyright (C) 2014 The Android Open Source Project * * 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. */ //#define LOG_NDEBUG 0 #define LOG_TAG "ClearKeyCryptoPlugin" #include <utils/Log.h> #include <openssl/aes.h> #include "AesCtrDecryptor.h" namespace clearkeydrm { static const size_t kBlockBitCount = kBlockSize * 8; android::status_t AesCtrDecryptor::decrypt(const android::Vector<uint8_t>& key, const Iv iv, const uint8_t* source, uint8_t* destination, const SubSample* subSamples, size_t numSubSamples, size_t* bytesDecryptedOut) { uint32_t blockOffset = 0; uint8_t previousEncryptedCounter[kBlockSize]; memset(previousEncryptedCounter, 0, kBlockSize); if (key.size() != kBlockSize || (sizeof(Iv) / sizeof(uint8_t)) != kBlockSize) { android_errorWriteLog(0x534e4554, "63982768"); return android::ERROR_DRM_DECRYPT; } size_t offset = 0; AES_KEY opensslKey; AES_set_encrypt_key(key.array(), kBlockBitCount, &opensslKey); Iv opensslIv; memcpy(opensslIv, iv, sizeof(opensslIv)); for (size_t i = 0; i < numSubSamples; ++i) { const SubSample& subSample = subSamples[i]; if (subSample.mNumBytesOfClearData > 0) { memcpy(destination + offset, source + offset, subSample.mNumBytesOfClearData); offset += subSample.mNumBytesOfClearData; } if (subSample.mNumBytesOfEncryptedData > 0) { AES_ctr128_encrypt(source + offset, destination + offset, subSample.mNumBytesOfEncryptedData, &opensslKey, opensslIv, previousEncryptedCounter, &blockOffset); offset += subSample.mNumBytesOfEncryptedData; } } *bytesDecryptedOut = offset; return android::OK; } } // namespace clearkeydrm
#include <limits.h> /* PATH_MAX */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> int main(void) { char buf[PATH_MAX]; /* PATH_MAX incudes the \0 so +1 is not required */ char *res = realpath("text.txt", buf); if (res) { // or: if (res != NULL)123 printf("This source is at %s\n", buf); } else { char* errStr = strerror(errno); printf("error string: %s\n", errStr); perror("realpath"); exit(EXIT_FAILURE); } return 0; }
#include "obfuscation.h" #include "masternodeman.h" #include "masternode.h" #include "activemasternode.h" /* Global */ int RequestedMasterNodeList = 0; void ThreadBitPool() { if(fMNLiteMode) return; //disable all Darksend/Masternode related functionality // Make this thread recognisable as the wallet flushing thread RenameThread("vitae-bitpool"); unsigned int c = 0; std::string errorMessage; while (true) { c++; MilliSleep(1000); //LogPrintf("ThreadCheckDarkSendPool::check timeout\n"); //darkSendPool.CheckTimeout(); //darkSendPool.CheckForCompleteQueue(); if(c % 60 == 0) { LOCK(cs_main); /* cs_main is required for doing CMasternode.Check because something is modifying the coins view without a mempool lock. It causes segfaults from this code without the cs_main lock. */ m_nodeman.CheckAndRemove(); m_nodeman.ProcessMasternodeConnections(); masternodePayments.CleanPaymentList(); //CleanTransactionLocksList(); } if(c % MASTERNODE_PING_SECONDS == 0) activeMasternode.ManageStatus(); if(c % MASTERNODES_DUMP_SECONDS == 0) DumpMasternodes(); //try to sync the Masternode list and payment list every 5 seconds from at least 3 nodes if(c % 5 == 0 && RequestedMasterNodeList < 3){ bool fIsInitialDownload = IsInitialBlockDownload(); if(!fIsInitialDownload) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (true/* pnode->nVersion >= MIN_POOL_PEER_PROTO_VERSION */) { //keep track of who we've asked for the list if(!pnode->HasFulfilledRequest("mnsync")){ pnode->FulfilledRequest("mnsync"); LogPrintf("Successfully synced, asking for Masternode list and payment list\n"); //request full mn list only if Masternodes.dat was updated quite a long time ago m_nodeman.DsegUpdate(pnode); pnode->PushMessage("mnget"); //sync payees pnode->PushMessage("getmn_sporks"); //get current network sporks //g_connman->PushMessage(pnode, CNetMsgMaker(PROTOCOL_VERSION).Make(SERIALIZE_TRANSACTION_NO_WITNESS, "mnget")); //g_connman->PushMessage(pnode, CNetMsgMaker(PROTOCOL_VERSION).Make(SERIALIZE_TRANSACTION_NO_WITNESS, "getsporks")); RequestedMasterNodeList++; } } } } } } }
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: java.sql.ParameterMetaData ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_SQL_PARAMETERMETADATA_HPP_DECL #define J2CPP_JAVA_SQL_PARAMETERMETADATA_HPP_DECL namespace j2cpp { namespace java { namespace lang { class Object; } } } namespace j2cpp { namespace java { namespace lang { class String; } } } #include <java/lang/Object.hpp> #include <java/lang/String.hpp> namespace j2cpp { namespace java { namespace sql { class ParameterMetaData; class ParameterMetaData : public object<ParameterMetaData> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) J2CPP_DECLARE_METHOD(4) J2CPP_DECLARE_METHOD(5) J2CPP_DECLARE_METHOD(6) J2CPP_DECLARE_METHOD(7) J2CPP_DECLARE_METHOD(8) J2CPP_DECLARE_FIELD(0) J2CPP_DECLARE_FIELD(1) J2CPP_DECLARE_FIELD(2) J2CPP_DECLARE_FIELD(3) J2CPP_DECLARE_FIELD(4) J2CPP_DECLARE_FIELD(5) J2CPP_DECLARE_FIELD(6) explicit ParameterMetaData(jobject jobj) : object<ParameterMetaData>(jobj) { } operator local_ref<java::lang::Object>() const; local_ref< java::lang::String > getParameterClassName(jint); jint getParameterCount(); jint getParameterMode(jint); jint getParameterType(jint); local_ref< java::lang::String > getParameterTypeName(jint); jint getPrecision(jint); jint getScale(jint); jint isNullable(jint); jboolean isSigned(jint); static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), jint > parameterModeIn; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(1), J2CPP_FIELD_SIGNATURE(1), jint > parameterModeInOut; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(2), J2CPP_FIELD_SIGNATURE(2), jint > parameterModeOut; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(3), J2CPP_FIELD_SIGNATURE(3), jint > parameterModeUnknown; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(4), J2CPP_FIELD_SIGNATURE(4), jint > parameterNoNulls; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(5), J2CPP_FIELD_SIGNATURE(5), jint > parameterNullable; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(6), J2CPP_FIELD_SIGNATURE(6), jint > parameterNullableUnknown; }; //class ParameterMetaData } //namespace sql } //namespace java } //namespace j2cpp #endif //J2CPP_JAVA_SQL_PARAMETERMETADATA_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_SQL_PARAMETERMETADATA_HPP_IMPL #define J2CPP_JAVA_SQL_PARAMETERMETADATA_HPP_IMPL namespace j2cpp { java::sql::ParameterMetaData::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } local_ref< java::lang::String > java::sql::ParameterMetaData::getParameterClassName(jint a0) { return call_method< java::sql::ParameterMetaData::J2CPP_CLASS_NAME, java::sql::ParameterMetaData::J2CPP_METHOD_NAME(0), java::sql::ParameterMetaData::J2CPP_METHOD_SIGNATURE(0), local_ref< java::lang::String > >(get_jobject(), a0); } jint java::sql::ParameterMetaData::getParameterCount() { return call_method< java::sql::ParameterMetaData::J2CPP_CLASS_NAME, java::sql::ParameterMetaData::J2CPP_METHOD_NAME(1), java::sql::ParameterMetaData::J2CPP_METHOD_SIGNATURE(1), jint >(get_jobject()); } jint java::sql::ParameterMetaData::getParameterMode(jint a0) { return call_method< java::sql::ParameterMetaData::J2CPP_CLASS_NAME, java::sql::ParameterMetaData::J2CPP_METHOD_NAME(2), java::sql::ParameterMetaData::J2CPP_METHOD_SIGNATURE(2), jint >(get_jobject(), a0); } jint java::sql::ParameterMetaData::getParameterType(jint a0) { return call_method< java::sql::ParameterMetaData::J2CPP_CLASS_NAME, java::sql::ParameterMetaData::J2CPP_METHOD_NAME(3), java::sql::ParameterMetaData::J2CPP_METHOD_SIGNATURE(3), jint >(get_jobject(), a0); } local_ref< java::lang::String > java::sql::ParameterMetaData::getParameterTypeName(jint a0) { return call_method< java::sql::ParameterMetaData::J2CPP_CLASS_NAME, java::sql::ParameterMetaData::J2CPP_METHOD_NAME(4), java::sql::ParameterMetaData::J2CPP_METHOD_SIGNATURE(4), local_ref< java::lang::String > >(get_jobject(), a0); } jint java::sql::ParameterMetaData::getPrecision(jint a0) { return call_method< java::sql::ParameterMetaData::J2CPP_CLASS_NAME, java::sql::ParameterMetaData::J2CPP_METHOD_NAME(5), java::sql::ParameterMetaData::J2CPP_METHOD_SIGNATURE(5), jint >(get_jobject(), a0); } jint java::sql::ParameterMetaData::getScale(jint a0) { return call_method< java::sql::ParameterMetaData::J2CPP_CLASS_NAME, java::sql::ParameterMetaData::J2CPP_METHOD_NAME(6), java::sql::ParameterMetaData::J2CPP_METHOD_SIGNATURE(6), jint >(get_jobject(), a0); } jint java::sql::ParameterMetaData::isNullable(jint a0) { return call_method< java::sql::ParameterMetaData::J2CPP_CLASS_NAME, java::sql::ParameterMetaData::J2CPP_METHOD_NAME(7), java::sql::ParameterMetaData::J2CPP_METHOD_SIGNATURE(7), jint >(get_jobject(), a0); } jboolean java::sql::ParameterMetaData::isSigned(jint a0) { return call_method< java::sql::ParameterMetaData::J2CPP_CLASS_NAME, java::sql::ParameterMetaData::J2CPP_METHOD_NAME(8), java::sql::ParameterMetaData::J2CPP_METHOD_SIGNATURE(8), jboolean >(get_jobject(), a0); } static_field< java::sql::ParameterMetaData::J2CPP_CLASS_NAME, java::sql::ParameterMetaData::J2CPP_FIELD_NAME(0), java::sql::ParameterMetaData::J2CPP_FIELD_SIGNATURE(0), jint > java::sql::ParameterMetaData::parameterModeIn; static_field< java::sql::ParameterMetaData::J2CPP_CLASS_NAME, java::sql::ParameterMetaData::J2CPP_FIELD_NAME(1), java::sql::ParameterMetaData::J2CPP_FIELD_SIGNATURE(1), jint > java::sql::ParameterMetaData::parameterModeInOut; static_field< java::sql::ParameterMetaData::J2CPP_CLASS_NAME, java::sql::ParameterMetaData::J2CPP_FIELD_NAME(2), java::sql::ParameterMetaData::J2CPP_FIELD_SIGNATURE(2), jint > java::sql::ParameterMetaData::parameterModeOut; static_field< java::sql::ParameterMetaData::J2CPP_CLASS_NAME, java::sql::ParameterMetaData::J2CPP_FIELD_NAME(3), java::sql::ParameterMetaData::J2CPP_FIELD_SIGNATURE(3), jint > java::sql::ParameterMetaData::parameterModeUnknown; static_field< java::sql::ParameterMetaData::J2CPP_CLASS_NAME, java::sql::ParameterMetaData::J2CPP_FIELD_NAME(4), java::sql::ParameterMetaData::J2CPP_FIELD_SIGNATURE(4), jint > java::sql::ParameterMetaData::parameterNoNulls; static_field< java::sql::ParameterMetaData::J2CPP_CLASS_NAME, java::sql::ParameterMetaData::J2CPP_FIELD_NAME(5), java::sql::ParameterMetaData::J2CPP_FIELD_SIGNATURE(5), jint > java::sql::ParameterMetaData::parameterNullable; static_field< java::sql::ParameterMetaData::J2CPP_CLASS_NAME, java::sql::ParameterMetaData::J2CPP_FIELD_NAME(6), java::sql::ParameterMetaData::J2CPP_FIELD_SIGNATURE(6), jint > java::sql::ParameterMetaData::parameterNullableUnknown; J2CPP_DEFINE_CLASS(java::sql::ParameterMetaData,"java/sql/ParameterMetaData") J2CPP_DEFINE_METHOD(java::sql::ParameterMetaData,0,"getParameterClassName","(I)Ljava/lang/String;") J2CPP_DEFINE_METHOD(java::sql::ParameterMetaData,1,"getParameterCount","()I") J2CPP_DEFINE_METHOD(java::sql::ParameterMetaData,2,"getParameterMode","(I)I") J2CPP_DEFINE_METHOD(java::sql::ParameterMetaData,3,"getParameterType","(I)I") J2CPP_DEFINE_METHOD(java::sql::ParameterMetaData,4,"getParameterTypeName","(I)Ljava/lang/String;") J2CPP_DEFINE_METHOD(java::sql::ParameterMetaData,5,"getPrecision","(I)I") J2CPP_DEFINE_METHOD(java::sql::ParameterMetaData,6,"getScale","(I)I") J2CPP_DEFINE_METHOD(java::sql::ParameterMetaData,7,"isNullable","(I)I") J2CPP_DEFINE_METHOD(java::sql::ParameterMetaData,8,"isSigned","(I)Z") J2CPP_DEFINE_FIELD(java::sql::ParameterMetaData,0,"parameterModeIn","I") J2CPP_DEFINE_FIELD(java::sql::ParameterMetaData,1,"parameterModeInOut","I") J2CPP_DEFINE_FIELD(java::sql::ParameterMetaData,2,"parameterModeOut","I") J2CPP_DEFINE_FIELD(java::sql::ParameterMetaData,3,"parameterModeUnknown","I") J2CPP_DEFINE_FIELD(java::sql::ParameterMetaData,4,"parameterNoNulls","I") J2CPP_DEFINE_FIELD(java::sql::ParameterMetaData,5,"parameterNullable","I") J2CPP_DEFINE_FIELD(java::sql::ParameterMetaData,6,"parameterNullableUnknown","I") } //namespace j2cpp #endif //J2CPP_JAVA_SQL_PARAMETERMETADATA_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
/******************************************************************************* * Copyright 2020-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 <daal/src/algorithms/k_nearest_neighbors/kdtree_knn_classification_train_kernel.h> #include <src/algorithms/k_nearest_neighbors/kdtree_knn_classification_model_impl.h> #include "oneapi/dal/algo/knn/backend/model_conversion.hpp" #include "oneapi/dal/algo/knn/backend/cpu/train_kernel.hpp" #include "oneapi/dal/algo/knn/backend/model_impl.hpp" #include "oneapi/dal/backend/interop/common.hpp" #include "oneapi/dal/backend/interop/error_converter.hpp" #include "oneapi/dal/backend/interop/table_conversion.hpp" #include "oneapi/dal/table/row_accessor.hpp" #include "oneapi/dal/exceptions.hpp" namespace oneapi::dal::knn::backend { using daal::services::Status; using dal::backend::context_cpu; namespace daal_knn = daal::algorithms::kdtree_knn_classification; namespace interop = dal::backend::interop; template <typename Float, daal::CpuType Cpu> using daal_knn_kd_tree_kernel_t = daal_knn::training::internal:: KNNClassificationTrainBatchKernel<Float, daal_knn::training::defaultDense, Cpu>; template <typename Float, typename Task> static train_result<Task> call_daal_kernel(const context_cpu& ctx, const detail::descriptor_base<Task>& desc, const table& data, const table& responses) { if constexpr (std::is_same_v<Task, task::regression>) { throw unimplemented( dal::detail::error_messages::knn_regression_task_is_not_implemented_for_cpu()); } using model_t = model<Task>; using daal_model_interop_t = model_interop; const std::int64_t column_count = data.get_column_count(); const auto daal_data = interop::convert_to_daal_table<Float>(data); const std::int64_t dummy_seed = 777; const auto data_use_in_model = daal_knn::doNotUse; daal_knn::Parameter daal_parameter( dal::detail::integral_cast<std::size_t>(desc.get_class_count()), dal::detail::integral_cast<std::size_t>(desc.get_neighbor_count()), dal::detail::integral_cast<int>(dummy_seed), data_use_in_model); Status status; const auto model_ptr = daal_knn::Model::create(column_count, &status); interop::status_to_exception(status); auto knn_model = static_cast<daal_knn::Model*>(model_ptr.get()); // Data or responses should not be copied, copy will be happened when // the tables are passed to old ifaces const bool copy_data_responses = data_use_in_model == daal_knn::doNotUse; knn_model->impl()->setData<Float>(daal_data, copy_data_responses); auto daal_responses = daal::data_management::NumericTablePtr(); if (desc.get_result_options().test(result_options::responses)) { daal_responses = interop::convert_to_daal_table<Float>(responses); knn_model->impl()->setLabels<Float>(daal_responses, copy_data_responses); } interop::status_to_exception(interop::call_daal_kernel<Float, daal_knn_kd_tree_kernel_t>( ctx, knn_model->impl()->getData().get(), knn_model->impl()->getLabels().get(), knn_model, *daal_parameter.engine.get())); auto interop = new daal_model_interop_t(model_ptr); const auto model_impl = std::make_shared<kd_tree_model_impl<Task>>(interop); return train_result<Task>().set_model(dal::detail::make_private<model_t>(model_impl)); } template <typename Float, typename Task> static train_result<Task> train(const context_cpu& ctx, const detail::descriptor_base<Task>& desc, const train_input<Task>& input) { return call_daal_kernel<Float, Task>(ctx, desc, input.get_data(), input.get_responses()); } template <typename Float, typename Task> struct train_kernel_cpu<Float, method::kd_tree, Task> { train_result<Task> operator()(const context_cpu& ctx, const detail::descriptor_base<Task>& desc, const train_input<Task>& input) const { return train<Float, Task>(ctx, desc, input); } }; template struct train_kernel_cpu<float, method::kd_tree, task::classification>; template struct train_kernel_cpu<double, method::kd_tree, task::classification>; template struct train_kernel_cpu<float, method::kd_tree, task::regression>; template struct train_kernel_cpu<double, method::kd_tree, task::regression>; template struct train_kernel_cpu<float, method::kd_tree, task::search>; template struct train_kernel_cpu<double, method::kd_tree, task::search>; } // namespace oneapi::dal::knn::backend
// $Id: Codecs.cpp 91813 2010-09-17 07:52:52Z johnnyw $ #include "ace/Codecs.h" #include "ace/Log_Msg.h" #include "ace/OS_Memory.h" #include "ace/OS_NS_ctype.h" namespace { // Just in case ... #undef alphabet #undef pad #undef max_columns // Symbols which form the Base64 alphabet (Defined as per RFC 2045) ACE_Byte const alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // The padding character used in the encoding ACE_Byte const pad = '='; // Number of columns per line of encoded output (Can have a maximum // value of 76). int const max_columns = 72; } ACE_BEGIN_VERSIONED_NAMESPACE_DECL bool ACE_Base64::init_ = false; ACE_Byte ACE_Base64::decoder_[256]; ACE_Byte ACE_Base64::member_[256]; ACE_Byte* ACE_Base64::encode (const ACE_Byte* input, const size_t input_len, size_t* output_len, bool is_chunked) { if (!ACE_Base64::init_) ACE_Base64::init(); if (!input) return 0; ACE_Byte* result = 0; size_t length = ((input_len + 2) / 3) * 4; size_t num_lines = length / max_columns + 1; length += num_lines + 1; ACE_NEW_RETURN (result, ACE_Byte[length], 0); int char_count = 0; int bits = 0; size_t pos = 0; int cols = 0; for (size_t i = 0; i < input_len; ++i) { bits += input[i]; ++char_count; if (char_count == 3) { result[pos++] = alphabet[bits >> 18]; result[pos++] = alphabet[(bits >> 12) & 0x3f]; result[pos++] = alphabet[(bits >> 6) & 0x3f]; result[pos++] = alphabet[bits & 0x3f]; cols += 4; if (cols == max_columns) { if (is_chunked) result[pos++] = '\n'; cols = 0; } bits = 0; char_count = 0; } else { bits <<= 8; } } if (char_count != 0) { bits <<= (16 - (8 * char_count)); result[pos++] = alphabet[bits >> 18]; result[pos++] = alphabet[(bits >> 12) & 0x3f]; cols += 2; if (char_count == 1) { result[pos++] = pad; result[pos++] = pad; cols += 2; } else { result[pos++] = alphabet[(bits >> 6) & 0x3f]; result[pos++] = pad; cols += 2; } } if (cols > 0 && is_chunked) result[pos++] = '\n'; result[pos] = 0; *output_len = pos; return result; } size_t ACE_Base64::length (const ACE_Byte* input) { if (!ACE_Base64::init_) ACE_Base64::init(); ACE_Byte* ptr = const_cast<ACE_Byte*> (input); while (*ptr != 0 && (member_[*(ptr)] == 1 || *ptr == pad || ACE_OS::ace_isspace (*ptr))) ++ptr; size_t len = ptr - input; len = ((len + 3) / 4) * 3 + 1 ; return len; } ACE_Byte* ACE_Base64::decode (const ACE_Byte* input, size_t* output_len) { if (!ACE_Base64::init_) ACE_Base64::init(); if (!input) return 0; size_t result_len = ACE_Base64::length (input); ACE_Byte* result = 0; ACE_NEW_RETURN (result, ACE_Byte[result_len], 0); ACE_Byte* ptr = const_cast<ACE_Byte*> (input); while (*ptr != 0 && (member_[*(ptr)] == 1 || *ptr == pad || ACE_OS::ace_isspace (*ptr))) ++ptr; size_t input_len = ptr - input; int char_count = 0; int bits = 0; size_t pos = 0; size_t i = 0; for (; i < input_len; ++i) { if (input[i] == pad) break; if (!ACE_Base64::member_[input[i]]) continue; bits += decoder_[input[i]]; ++char_count; if (char_count == 4) { result[pos++] = static_cast<ACE_Byte> (bits >> 16); result[pos++] = static_cast<ACE_Byte> ((bits >> 8) & 0xff); result[pos++] = static_cast<ACE_Byte> (bits & 0xff); bits = 0; char_count = 0; } else { bits <<= 6; } } int errors = 0; if ( i == input_len) { if (char_count) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("Decoding incomplete: atleast %d bits truncated\n"), (4 - char_count) * 6)); ++errors; } } else { switch (char_count) { case 1: ACE_ERROR ((LM_ERROR, ACE_TEXT ("Decoding incomplete: atleast 2 bits missing\n"))); ++errors; break; case 2: result[pos++] = static_cast<ACE_Byte> (bits >> 10); break; case 3: result[pos++] = static_cast<ACE_Byte> (bits >> 16); result[pos++] = static_cast<ACE_Byte> ((bits >> 8) & 0xff); break; } } if (errors) { delete[] result; return 0; } result[pos] = 0; *output_len = pos; return result; } void ACE_Base64::init () { if (!ACE_Base64::init_) { for (ACE_Byte i = 0; i < sizeof (alphabet); ++i) { ACE_Base64::decoder_[alphabet[i]] = i; ACE_Base64::member_ [alphabet[i]] = 1; } ACE_Base64::init_ = true; } return; } ACE_END_VERSIONED_NAMESPACE_DECL
/** BSD-3-Clause Copyright 2019 Alliance for Sustainable Energy, LLC 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 copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER, CONTRIBUTORS, UNITED STATES GOVERNMENT OR UNITED STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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. */ #include <algorithm> #include <cmath> #include <memory> #include "lib_battery_lifetime.h" #include "lib_battery_lifetime_nmc.h" #include "lib_battery_lifetime_calendar_cycle.h" extern double tolerance; extern double low_tolerance; void lifetime_cycle_t::initialize() { state->n_cycles = 0; state->cycle_range = 0; state->cycle_DOD = 0; state->average_range = 0; state->cycle->q_relative_cycle = bilinear(0., 0); state->cycle->rainflow_jlt = 0; state->cycle->rainflow_Xlt = 0; state->cycle->rainflow_Ylt = 0; state->cycle->rainflow_peaks.clear(); } lifetime_cycle_t::lifetime_cycle_t(const util::matrix_t<double> &batt_lifetime_matrix) { params = std::make_shared<lifetime_params>(); params->cal_cyc->cycling_matrix = batt_lifetime_matrix; state = std::make_shared<lifetime_state>(); initialize(); } lifetime_cycle_t::lifetime_cycle_t(std::shared_ptr<lifetime_params> params_ptr) : params(std::move(params_ptr)) { state = std::make_shared<lifetime_state>(); initialize(); } lifetime_cycle_t::lifetime_cycle_t(std::shared_ptr<lifetime_params> params_ptr, std::shared_ptr<lifetime_state> state_ptr) : params(std::move(params_ptr)), state(std::move(state_ptr)){ } lifetime_cycle_t::lifetime_cycle_t(const lifetime_cycle_t &rhs) { state = std::make_shared<lifetime_state>(*rhs.state); operator=(rhs); } lifetime_cycle_t &lifetime_cycle_t::operator=(const lifetime_cycle_t &rhs) { if (this != &rhs) { *state = *rhs.state; *params = *rhs.params; } return *this; } lifetime_cycle_t *lifetime_cycle_t::clone() { return new lifetime_cycle_t(*this); } double lifetime_cycle_t::estimateCycleDamage() { // Initialize assuming 50% DOD double DOD = 50; if (state->average_range > 0) { DOD = state->average_range; } return (bilinear(DOD, state->n_cycles + 1) - bilinear(DOD, state->n_cycles + 2)); } double lifetime_cycle_t::runCycleLifetime(double DOD) { rainflow(DOD); // return the effective capacity (Q_neg) return state->cycle->q_relative_cycle; } void lifetime_cycle_t::rainflow(double DOD) { // initialize return code int retCode = cycle_state::LT_GET_DATA; // Begin algorithm state->cycle->rainflow_peaks.push_back(DOD); bool atStepTwo = true; // Loop until break while (atStepTwo) { // Rainflow: Step 2: Form ranges X,Y if (state->cycle->rainflow_jlt >= 2) rainflow_ranges(); else { // Get more data (Step 1) retCode = cycle_state::LT_GET_DATA; break; } // Rainflow: Step 3: Compare ranges retCode = rainflow_compareRanges(); // We break to get more data, or if we are done with step 5 if (retCode == cycle_state::LT_GET_DATA) break; } if (retCode == cycle_state::LT_GET_DATA) state->cycle->rainflow_jlt++; } void lifetime_cycle_t::rainflow_ranges() { state->cycle->rainflow_Ylt = fabs(state->cycle->rainflow_peaks[state->cycle->rainflow_jlt - (size_t) 1] - state->cycle->rainflow_peaks[state->cycle->rainflow_jlt - (size_t) 2]); state->cycle->rainflow_Xlt = fabs(state->cycle->rainflow_peaks[state->cycle->rainflow_jlt] - state->cycle->rainflow_peaks[state->cycle->rainflow_jlt - (size_t) 1]); } void lifetime_cycle_t::rainflow_ranges_circular(int index) { size_t end = state->cycle->rainflow_peaks.size() - 1; if (index == 0) { state->cycle->rainflow_Xlt = fabs(state->cycle->rainflow_peaks[0] - state->cycle->rainflow_peaks[end]); state->cycle->rainflow_Ylt = fabs(state->cycle->rainflow_peaks[end] - state->cycle->rainflow_peaks[end - 1]); } else if (index == 1) { state->cycle->rainflow_Xlt = fabs(state->cycle->rainflow_peaks[1] - state->cycle->rainflow_peaks[0]); state->cycle->rainflow_Ylt = fabs(state->cycle->rainflow_peaks[0] - state->cycle->rainflow_peaks[end]); } else rainflow_ranges(); } int lifetime_cycle_t::rainflow_compareRanges() { int retCode = cycle_state::LT_SUCCESS; bool contained = true; // modified to disregard some of algorithm which doesn't work well if (state->cycle->rainflow_Xlt + tolerance < state->cycle->rainflow_Ylt) retCode = cycle_state::LT_GET_DATA; else contained = false; // Step 5: Count range Y, discard peak & valley of Y, go to Step 2 if (!contained) { state->cycle_range = state->cycle->rainflow_Ylt; state->cycle_DOD = *std::max_element(state->cycle->rainflow_peaks.begin(), state->cycle->rainflow_peaks.end()); state->average_range = (state->average_range * state->n_cycles + state->cycle_range) / (double)(state->n_cycles + (size_t) 1); state->n_cycles++; // the capacity percent cannot increase double dq = bilinear(state->average_range, state->n_cycles) - bilinear(state->average_range, state->n_cycles + 1); if (dq > 0) state->cycle->q_relative_cycle -= dq; if (state->cycle->q_relative_cycle < 0) state->cycle->q_relative_cycle = 0.; // discard peak & valley of Y double save = state->cycle->rainflow_peaks[state->cycle->rainflow_jlt]; state->cycle->rainflow_peaks.pop_back(); state->cycle->rainflow_peaks.pop_back(); state->cycle->rainflow_peaks.pop_back(); state->cycle->rainflow_peaks.push_back(save); state->cycle->rainflow_jlt -= 2; // stay in while loop retCode = cycle_state::LT_RERANGE; } return retCode; } void lifetime_cycle_t::replaceBattery(double replacement_percent) { state->cycle->q_relative_cycle += replacement_percent; state->cycle->q_relative_cycle = fmin(bilinear(0., 0), state->cycle->q_relative_cycle); // More work to figure out degradation of multiple-aged battery units if (replacement_percent == 100) { state->n_cycles = 0; state->cycle_range = 0; state->cycle_DOD = 0; state->average_range = 0; } state->cycle->rainflow_jlt = 0; state->cycle->rainflow_Xlt = 0; state->cycle->rainflow_Ylt = 0; state->cycle->rainflow_peaks.clear(); } int lifetime_cycle_t::cycles_elapsed() { return state->n_cycles; } double lifetime_cycle_t::cycle_range() { return state->cycle_range; } double lifetime_cycle_t::cycle_depth() { return state->cycle_DOD; } double lifetime_cycle_t::average_range() { return state->average_range; } double lifetime_cycle_t::capacity_percent() { return state->cycle->q_relative_cycle; } lifetime_state lifetime_cycle_t::get_state() { return *state; } double lifetime_cycle_t::bilinear(double DOD, int cycle_number) { /* Work could be done to make this simpler Current idea is to interpolate first along the C = f(n) curves for each DOD to get C_DOD_, C_DOD_+ Then interpolate C_, C+ to get C at the DOD of interest */ std::vector<double> D_unique_vect; std::vector<double> C_n_low_vect; std::vector<double> D_high_vect; std::vector<double> C_n_high_vect; std::vector<size_t> low_indices; std::vector<size_t> high_indices; double D = 0.; size_t n = 0; double C = 100; size_t n_rows = params->cal_cyc->cycling_matrix.nrows(); // get unique values of D D_unique_vect.push_back(params->cal_cyc->cycling_matrix.at(0, calendar_cycle_params::DOD)); for (size_t i = 0; i < n_rows; i++) { bool contained = false; for (double j : D_unique_vect) { if (params->cal_cyc->cycling_matrix.at(i, calendar_cycle_params::DOD) == j) { contained = true; break; } } if (!contained) { D_unique_vect.push_back(params->cal_cyc->cycling_matrix.at(i, calendar_cycle_params::DOD)); } } n = D_unique_vect.size(); if (n > 1) { // get where DOD is bracketed [D_lo, DOD, D_hi] double D_lo = 0; double D_hi = 100; for (size_t i = 0; i < n_rows; i++) { D = params->cal_cyc->cycling_matrix.at(i, calendar_cycle_params::DOD); if (D < DOD && D > D_lo) D_lo = D; else if (D >= DOD && D < D_hi) D_hi = D; } // Separate table into bins double D_min = 100.; double D_max = 0.; for (size_t i = 0; i < n_rows; i++) { D = params->cal_cyc->cycling_matrix.at(i, calendar_cycle_params::DOD); if (D == D_lo) low_indices.push_back(i); else if (D == D_hi) high_indices.push_back(i); if (D < D_min) { D_min = D; } else if (D > D_max) { D_max = D; } } // if we're out of the bounds, just make the upper bound equal to the highest input if (high_indices.empty()) { for (size_t i = 0; i != n_rows; i++) { if (params->cal_cyc->cycling_matrix.at(i, calendar_cycle_params::DOD) == D_max) high_indices.push_back(i); } } size_t n_rows_lo = low_indices.size(); size_t n_rows_hi = high_indices.size(); size_t n_cols = 2; // If we aren't bounded, fill in values if (n_rows_lo == 0) { // Assumes 0% DOD for (int i = 0; i < n_rows_hi; i++) { C_n_low_vect.push_back(0. + (double)i * 500); // cycles C_n_low_vect.push_back(100.); // 100 % capacity } } if (n_rows_lo != 0) { for (int i = 0; i < (int) n_rows_lo; i++) { C_n_low_vect.push_back(params->cal_cyc->cycling_matrix.at(low_indices[i], calendar_cycle_params::CYCLE)); C_n_low_vect.push_back(params->cal_cyc->cycling_matrix.at(low_indices[i], calendar_cycle_params::CAPACITY_CYCLE)); } } if (n_rows_hi != 0) { for (int i = 0; i < (int) n_rows_hi; i++) { C_n_high_vect.push_back(params->cal_cyc->cycling_matrix.at(high_indices[i], calendar_cycle_params::CYCLE)); C_n_high_vect.push_back(params->cal_cyc->cycling_matrix.at(high_indices[i], calendar_cycle_params::CAPACITY_CYCLE)); } } n_rows_lo = C_n_low_vect.size() / n_cols; n_rows_hi = C_n_high_vect.size() / n_cols; if (n_rows_lo == 0 || n_rows_hi == 0) { // need a safeguard here } util::matrix_t<double> C_n_low(n_rows_lo, n_cols, &C_n_low_vect); util::matrix_t<double> C_n_high(n_rows_lo, n_cols, &C_n_high_vect); // Compute C(D_lo, n), C(D_hi, n) double C_Dlo = util::linterp_col(C_n_low, 0, cycle_number, 1); double C_Dhi = util::linterp_col(C_n_high, 0, cycle_number, 1); if (C_Dlo < 0.) C_Dlo = 0.; if (C_Dhi > 100.) C_Dhi = 100.; // Interpolate to get C(D, n) C = util::interpolate(D_lo, C_Dlo, D_hi, C_Dhi, DOD); } // just have one row, single level interpolation else { C = util::linterp_col(params->cal_cyc->cycling_matrix, 1, cycle_number, 2); } return C; } /* Lifetime Calendar Model */ bool calendar_state::operator==(const calendar_state &p) const { bool equal = (q_relative_calendar == p.q_relative_calendar); // equal &= (day_age_of_battery == p.day_age_of_battery); equal &= (dq_relative_calendar_old == p.dq_relative_calendar_old); return equal; } void lifetime_calendar_t::initialize() { state->day_age_of_battery = 0; state->calendar->q_relative_calendar = 100; state->calendar->dq_relative_calendar_old = 0; if (params->cal_cyc->calendar_choice == calendar_cycle_params::CALENDAR_CHOICE::MODEL) { dt_day = params->dt_hr / util::hours_per_day; state->calendar->q_relative_calendar = params->cal_cyc->calendar_q0 * 100; } else if (params->cal_cyc->calendar_choice == calendar_cycle_params::CALENDAR_CHOICE::TABLE) { if (params->cal_cyc->calendar_matrix.nrows() < 2 || params->cal_cyc->calendar_matrix.ncols() != 2) throw std::runtime_error("lifetime_calendar_t error: Battery calendar lifetime matrix must have 2 columns and at least 2 rows"); } } lifetime_calendar_t::lifetime_calendar_t(double dt_hour, const util::matrix_t<double>& calendar_matrix) { params = std::make_shared<lifetime_params>(); params->dt_hr = dt_hour; params->cal_cyc->calendar_choice = calendar_cycle_params::CALENDAR_CHOICE::TABLE; params->cal_cyc->calendar_matrix = calendar_matrix; state = std::make_shared<lifetime_state>(); initialize(); } lifetime_calendar_t::lifetime_calendar_t(double dt_hour, double q0, double a, double b, double c) { params = std::make_shared<lifetime_params>(); params->dt_hr = dt_hour; params->cal_cyc->calendar_choice = calendar_cycle_params::CALENDAR_CHOICE::MODEL; params->cal_cyc->calendar_q0 = q0; params->cal_cyc->calendar_a = a; params->cal_cyc->calendar_b = b; params->cal_cyc->calendar_c = c; state = std::make_shared<lifetime_state>(); initialize(); } lifetime_calendar_t::lifetime_calendar_t(std::shared_ptr<lifetime_params> params_ptr, std::shared_ptr<lifetime_state> state_ptr) : params(std::move(params_ptr)), state(std::move(state_ptr)) { } lifetime_calendar_t::lifetime_calendar_t(const lifetime_calendar_t &rhs) { state = std::make_shared<lifetime_state>(*rhs.state); params = std::make_shared<lifetime_params>(*rhs.params); dt_day = rhs.dt_day; } lifetime_calendar_t &lifetime_calendar_t::operator=(const lifetime_calendar_t &rhs) { if (this != &rhs) { *params = *rhs.params; *state = *rhs.state; dt_day = rhs.dt_day; } return *this; } lifetime_calendar_t *lifetime_calendar_t::clone() { return new lifetime_calendar_t(*this); } double lifetime_calendar_t::capacity_percent() { return state->calendar->q_relative_calendar; } lifetime_state lifetime_calendar_t::get_state() { return *state; } double lifetime_calendar_t::runLifetimeCalendarModel(size_t lifetimeIndex, double T, double SOC) { state->day_age_of_battery = lifetimeIndex / (util::hours_per_day / params->dt_hr); if (params->cal_cyc->calendar_choice == calendar_cycle_params::CALENDAR_CHOICE::MODEL) runLithiumIonModel(T, SOC); else if (params->cal_cyc->calendar_choice == calendar_cycle_params::CALENDAR_CHOICE::TABLE) runTableModel(); else state->calendar->q_relative_calendar = 100; return state->calendar->q_relative_calendar; } void lifetime_calendar_t::runLithiumIonModel(double temp, double SOC) { temp += 273.15; SOC *= 0.01; double k_cal = params->cal_cyc->calendar_a * exp(params->cal_cyc->calendar_b * (1. / temp - 1. / 296)) * exp(params->cal_cyc->calendar_c * (SOC / temp - 1. / 296)); double dq_new; if (state->calendar->dq_relative_calendar_old == 0) dq_new = k_cal * sqrt(dt_day); else dq_new = (0.5 * pow(k_cal, 2) / state->calendar->dq_relative_calendar_old) * dt_day + state->calendar->dq_relative_calendar_old; state->calendar->dq_relative_calendar_old = dq_new; state->calendar->q_relative_calendar = (params->cal_cyc->calendar_q0 - (dq_new)) * 100; } void lifetime_calendar_t::runTableModel() { size_t n_rows = params->cal_cyc->calendar_matrix.nrows(); size_t n = n_rows - 1; size_t day_lo = 0; auto day_hi = (size_t) params->cal_cyc->calendar_matrix.at(n, calendar_cycle_params::DAYS); double capacity_lo = 100; double capacity_hi = 0; // interpolation mode for (size_t i = 0; i != n_rows; i++) { int day = (int)params->cal_cyc->calendar_matrix.at(i, calendar_cycle_params::DAYS); double capacity = (int) params->cal_cyc->calendar_matrix.at(i, calendar_cycle_params::CAPACITY_CAL); if (day <= (int)state->day_age_of_battery) { day_lo = day; capacity_lo = capacity; } if (day > (int)state->day_age_of_battery) { day_hi = day; capacity_hi = capacity; break; } } if (day_lo == day_hi) { day_lo = (int) params->cal_cyc->calendar_matrix.at(n - 1, calendar_cycle_params::DAYS); day_hi = (int) params->cal_cyc->calendar_matrix.at(n, calendar_cycle_params::DAYS); capacity_lo = (int) params->cal_cyc->calendar_matrix.at(n - 1, calendar_cycle_params::CAPACITY_CAL); capacity_hi = (int) params->cal_cyc->calendar_matrix.at(n, calendar_cycle_params::CAPACITY_CAL); } state->calendar->q_relative_calendar = util::interpolate((double) day_lo, capacity_lo, (double) day_hi, capacity_hi, state->day_age_of_battery); } void lifetime_calendar_t::replaceBattery(double replacement_percent) { state->day_age_of_battery = 0; state->calendar->dq_relative_calendar_old = 0; state->calendar->q_relative_calendar += replacement_percent; if (params->cal_cyc->calendar_choice == calendar_cycle_params::MODEL) state->calendar->q_relative_calendar = fmin(params->cal_cyc->calendar_q0 * 100, state->calendar->q_relative_calendar); if (params->cal_cyc->calendar_choice == calendar_cycle_params::TABLE) state->calendar->q_relative_calendar = fmin(100, state->calendar->q_relative_calendar); } /* Define Lifetime Model */ void lifetime_calendar_cycle_t::initialize() { state = std::make_shared<lifetime_state>(); if (params->cal_cyc->cycling_matrix.nrows() < 3 || params->cal_cyc->cycling_matrix.ncols() != 3) throw std::runtime_error("lifetime_cycle_t error: Battery lifetime matrix must have three columns and at least three rows"); cycle_model = std::unique_ptr<lifetime_cycle_t>(new lifetime_cycle_t(params, state)); cycle_model->initialize(); calendar_model = std::unique_ptr<lifetime_calendar_t>(new lifetime_calendar_t(params, state)); calendar_model->initialize(); state->q_relative = fmin(state->cycle->q_relative_cycle, state->calendar->q_relative_calendar); } lifetime_calendar_cycle_t::lifetime_calendar_cycle_t(const util::matrix_t<double> &batt_lifetime_matrix, double dt_hour, const util::matrix_t<double> &calendar_matrix) { params = std::make_shared<lifetime_params>(); params->model_choice = lifetime_params::CALCYC; params->dt_hr = dt_hour; params->cal_cyc->cycling_matrix = batt_lifetime_matrix; params->cal_cyc->calendar_choice = calendar_cycle_params::CALENDAR_CHOICE::TABLE; params->cal_cyc->calendar_matrix = calendar_matrix; initialize(); } lifetime_calendar_cycle_t::lifetime_calendar_cycle_t(const util::matrix_t<double> &batt_lifetime_matrix, double dt_hour, double q0, double a, double b, double c) { params = std::make_shared<lifetime_params>(); params->model_choice = lifetime_params::CALCYC; params->dt_hr = dt_hour; params->cal_cyc->cycling_matrix = batt_lifetime_matrix; params->cal_cyc->calendar_choice = calendar_cycle_params::CALENDAR_CHOICE::MODEL; params->cal_cyc->calendar_q0 = q0; params->cal_cyc->calendar_a = a; params->cal_cyc->calendar_b = b; params->cal_cyc->calendar_c = c; initialize(); } lifetime_calendar_cycle_t::lifetime_calendar_cycle_t(const util::matrix_t<double> &batt_lifetime_matrix, double dt_hour) { params = std::make_shared<lifetime_params>(); params->model_choice = lifetime_params::CALCYC; params->dt_hr = dt_hour; params->cal_cyc->cycling_matrix = batt_lifetime_matrix; params->cal_cyc->calendar_choice = calendar_cycle_params::CALENDAR_CHOICE::NONE; initialize(); } lifetime_calendar_cycle_t::lifetime_calendar_cycle_t(std::shared_ptr<lifetime_params> params_ptr) { params = std::move(params_ptr); initialize(); } lifetime_calendar_cycle_t::lifetime_calendar_cycle_t(const lifetime_calendar_cycle_t& rhs) : lifetime_t(rhs){ operator=(rhs); } lifetime_calendar_cycle_t& lifetime_calendar_cycle_t::operator=(const lifetime_calendar_cycle_t& rhs) { if (this != &rhs) { *params = *rhs.params; *state = *rhs.state; calendar_model = std::unique_ptr<lifetime_calendar_t>(new lifetime_calendar_t(params, state)); cycle_model = std::unique_ptr<lifetime_cycle_t>(new lifetime_cycle_t(params, state)); } return *this; } lifetime_calendar_cycle_t *lifetime_calendar_cycle_t::clone() { return new lifetime_calendar_cycle_t(*this); } double lifetime_calendar_cycle_t::capacity_percent_cycle() { return cycle_model->capacity_percent(); } double lifetime_calendar_cycle_t::capacity_percent_calendar() { return calendar_model->capacity_percent(); } void lifetime_calendar_cycle_t::runLifetimeModels(size_t lifetimeIndex, bool charge_changed, double prev_DOD, double DOD, double T_battery) { double q_last = state->q_relative; if (q_last > 0) { double q_cycle = cycle_model->capacity_percent(); double q_calendar; if (charge_changed) q_cycle = cycle_model->runCycleLifetime(prev_DOD); else if (lifetimeIndex == 0) q_cycle = cycle_model->runCycleLifetime(DOD); q_calendar = calendar_model->runLifetimeCalendarModel(lifetimeIndex, T_battery, 100. - DOD); // total capacity is min of cycle (Q_neg) and calendar (Q_li) capacity state->q_relative = fmin(q_cycle, q_calendar); } state->q_relative = fmax(state->q_relative, 0); // capacity cannot increase state->q_relative = fmin(state->q_relative, q_last); } double lifetime_calendar_cycle_t::estimateCycleDamage() { return cycle_model->estimateCycleDamage(); } void lifetime_calendar_cycle_t::replaceBattery(double percent_to_replace) { cycle_model->replaceBattery(percent_to_replace); calendar_model->replaceBattery(percent_to_replace); state->q_relative = fmin(cycle_model->capacity_percent(), calendar_model->capacity_percent()); }
#pragma once #include <Register/Utility.hpp> namespace Kvasir { //Serial peripheral interface/Inter-IC sound namespace Spi1Cr1{ ///<control register 1 using Addr = Register::Address<0x40013000,0xffff0000,0x00000000,unsigned>; ///Bidirectional data mode enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> bidimode{}; ///Output enable in bidirectional mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> bidioe{}; ///Hardware CRC calculation enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> crcen{}; ///CRC transfer next constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> crcnext{}; ///Data frame format constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> dff{}; ///Receive only constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> rxonly{}; ///Software slave management constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> ssm{}; ///Internal slave select constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> ssi{}; ///Frame format constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> lsbfirst{}; ///SPI enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> spe{}; ///Baud rate control constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,3),Register::ReadWriteAccess,unsigned> br{}; ///Master selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> mstr{}; ///Clock polarity constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> cpol{}; ///Clock phase constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> cpha{}; } namespace Spi1Cr2{ ///<control register 2 using Addr = Register::Address<0x40013004,0xffff8000,0x00000000,unsigned>; ///Rx buffer DMA enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> rxdmaen{}; ///Tx buffer DMA enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> txdmaen{}; ///SS output enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> ssoe{}; ///NSS pulse management constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> nssp{}; ///Frame format constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> frf{}; ///Error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> errie{}; ///RX buffer not empty interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> rxneie{}; ///Tx buffer empty interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> txeie{}; ///Data size constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,8),Register::ReadWriteAccess,unsigned> ds{}; ///FIFO reception threshold constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> frxth{}; ///Last DMA transfer for reception constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> ldmaRx{}; ///Last DMA transfer for transmission constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> ldmaTx{}; } namespace Spi1Sr{ ///<status register using Addr = Register::Address<0x40013008,0xffffe00c,0x00000000,unsigned>; ///Receive buffer not empty constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> rxne{}; ///Transmit buffer empty constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> txe{}; ///CRC error flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> crcerr{}; ///Mode fault constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> modf{}; ///Overrun flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ovr{}; ///Busy flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> bsy{}; ///TI frame format error constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> tifrfe{}; ///FIFO reception level constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,9),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> frlvl{}; ///FIFO transmission level constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,11),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ftlvl{}; } namespace Spi1Dr{ ///<data register using Addr = Register::Address<0x4001300c,0xffff0000,0x00000000,unsigned>; ///Data register constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> dr{}; } namespace Spi1Crcpr{ ///<CRC polynomial register using Addr = Register::Address<0x40013010,0xffff0000,0x00000000,unsigned>; ///CRC polynomial register constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> crcpoly{}; } namespace Spi1Rxcrcr{ ///<RX CRC register using Addr = Register::Address<0x40013014,0xffff0000,0x00000000,unsigned>; ///Rx CRC register constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> rxcrc{}; } namespace Spi1Txcrcr{ ///<TX CRC register using Addr = Register::Address<0x40013018,0xffff0000,0x00000000,unsigned>; ///Tx CRC register constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> txcrc{}; } }
/** ** \file Ipv4Address.cpp ** \date 2006-09-21 ** \author grymse@alhem.net **/ /* Copyright (C) 2007-2011 Anders Hedstrom This library is made available under the terms of the GNU GPL, with the additional exemption that compiling, linking, and/or using OpenSSL is allowed. If you would like to use this library in a closed-source application, a separate license agreement is available. For information about the closed-source license agreement for the C++ sockets library, please visit http://www.alhem.net/Sockets/license.html and/or email license@alhem.net. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "Ipv4Address.h" #include "Utility.h" #ifndef _WIN32 #include <netdb.h> #endif #ifdef SOCKETS_NAMESPACE namespace SOCKETS_NAMESPACE { #endif Ipv4Address::Ipv4Address(port_t port) : m_valid(true) { memset(&m_addr, 0, sizeof(m_addr)); m_addr.sin_family = AF_INET; m_addr.sin_port = htons( port ); } Ipv4Address::Ipv4Address(ipaddr_t a,port_t port) : m_valid(true) { memset(&m_addr, 0, sizeof(m_addr)); m_addr.sin_family = AF_INET; m_addr.sin_port = htons( port ); memcpy(&m_addr.sin_addr, &a, sizeof(struct in_addr)); } Ipv4Address::Ipv4Address(struct in_addr& a,port_t port) : m_valid(true) { memset(&m_addr, 0, sizeof(m_addr)); m_addr.sin_family = AF_INET; m_addr.sin_port = htons( port ); m_addr.sin_addr = a; } Ipv4Address::Ipv4Address(const std::string& host,port_t port) : m_valid(false) { memset(&m_addr, 0, sizeof(m_addr)); m_addr.sin_family = AF_INET; m_addr.sin_port = htons( port ); { ipaddr_t a; if (Utility::u2ip(host, a)) { memcpy(&m_addr.sin_addr, &a, sizeof(struct in_addr)); m_valid = true; } } } Ipv4Address::Ipv4Address(struct sockaddr_in& sa) { m_addr = sa; m_valid = sa.sin_family == AF_INET; } Ipv4Address::~Ipv4Address() { } Ipv4Address::operator struct sockaddr *() { return (struct sockaddr *)&m_addr; } Ipv4Address::operator socklen_t() { return sizeof(struct sockaddr_in); } void Ipv4Address::SetPort(port_t port) { m_addr.sin_port = htons( port ); } in_addr_t Ipv4Address::GetAddr() { return m_addr.sin_addr.s_addr; } port_t Ipv4Address::GetPort() { return ntohs( m_addr.sin_port ); } bool Ipv4Address::Resolve(const std::string& hostname,struct in_addr& a) { struct sockaddr_in sa; memset(&a, 0, sizeof(a)); if (Utility::isipv4(hostname)) { if (!Utility::u2ip(hostname, sa, AI_NUMERICHOST)) return false; a = sa.sin_addr; return true; } if (!Utility::u2ip(hostname, sa)) return false; a = sa.sin_addr; return true; } bool Ipv4Address::Reverse(struct in_addr& a,std::string& name) { struct sockaddr_in sa; memset(&sa, 0, sizeof(sa)); sa.sin_family = AF_INET; sa.sin_addr = a; return Utility::reverse((struct sockaddr *)&sa, sizeof(sa), name); } std::string Ipv4Address::Convert(bool include_port) { if (include_port) return Convert(m_addr.sin_addr) + ":" + Utility::l2string(GetPort()); return Convert(m_addr.sin_addr); } std::string Ipv4Address::Convert(struct in_addr& a) { struct sockaddr_in sa; memset(&sa, 0, sizeof(sa)); sa.sin_family = AF_INET; sa.sin_addr = a; std::string name; Utility::reverse((struct sockaddr *)&sa, sizeof(sa), name, NI_NUMERICHOST); return name; } void Ipv4Address::SetAddress(uint32_t dwIP, uint16_t wPort) { m_addr.sin_family = PF_INET; m_addr.sin_port = htons(wPort); m_addr.sin_addr.s_addr = dwIP; } void Ipv4Address::SetAddress(struct sockaddr *sa) { memcpy(&m_addr, sa, sizeof(struct sockaddr_in)); } int Ipv4Address::GetFamily() { return m_addr.sin_family; } bool Ipv4Address::IsValid() { return m_valid; } bool Ipv4Address::operator==(SocketAddress& a) { if (a.GetFamily() != GetFamily()) return false; if ((socklen_t)a != sizeof(m_addr)) return false; struct sockaddr *sa = a; struct sockaddr_in *p = (struct sockaddr_in *)sa; if (p -> sin_port != m_addr.sin_port) return false; if (memcmp(&p -> sin_addr, &m_addr.sin_addr, 4)) return false; return true; } std::auto_ptr<SocketAddress> Ipv4Address::GetCopy() { return std::auto_ptr<SocketAddress>(new Ipv4Address(m_addr)); } std::string Ipv4Address::Reverse() { std::string tmp; Reverse(m_addr.sin_addr, tmp); return tmp; } #ifdef SOCKETS_NAMESPACE } // namespace SOCKETS_NAMESPACE { #endif
#include "CitoyenBase.hpp" CitoyenBase::CitoyenBase() : Citoyen(50, 0.15f){ setScale(2,2); }
#include <ncurses.h> int main(void) { initscr(); int c, y, x, cmax; getmaxyx(stdscr,y,x); cmax = (x * y) / 5; for(c = 0; c < cmax; c++) addstr("blah "); refresh(); getch(); clear(); refresh(); getch(); endwin(); return 0; }
#include <algorithm> #include <cassert> #include <cstdio> #include <iostream> #include <sstream> #include <string> #include <vector> #include <cstring> using namespace std; int di[] = { 1, 0, -1, 0 }; int dj[] = { 0, -1, 0, 1 }; bool done[50][50]; class MountainWalk { public: int cellsVisited(vector <string> A, int D) { int M, N; M = A.size(); N = A[0].size(); memset(done, 0, sizeof done); int sol = 0; int i = 0; int j = 0; while (1) { ++sol; done[i][j] = 1; vector<int> pos; for (int d=0; d<4; ++d) { int r = i + di[d]; int c = j + dj[d]; if (r<0 || c<0 || r>=M || c>=N || done[r][c]) { continue; } if (abs(A[r][c]-A[i][j]) <= D) { pos.push_back(d); } } if (pos.size() == 0) { return sol; } i += di[pos[0]]; j += dj[pos[0]]; } return -1; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); if ((Case == -1) || (Case == 6)) test_case_6(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arr0[] = {"056", "135", "234"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; int Arg2 = 5; verify_case(0, Arg2, cellsVisited(Arg0, Arg1)); } void test_case_1() { string Arr0[] = {"056", "195", "234"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; int Arg2 = 8; verify_case(1, Arg2, cellsVisited(Arg0, Arg1)); } void test_case_2() { string Arr0[] = {"865", "123", "111"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 3; int Arg2 = 9; verify_case(2, Arg2, cellsVisited(Arg0, Arg1)); } void test_case_3() { string Arr0[] = {"00009876543210", "00009876543210", "00009876543210", "00009876543210"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 8; int Arg2 = 16; verify_case(3, Arg2, cellsVisited(Arg0, Arg1)); } void test_case_4() { string Arr0[] = {"0000", "0000", "0000", "0000", "9999", "8888", "7777", "6666", "5555", "4444", "3333", "2222", "1111", "0000"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 3; int Arg2 = 16; verify_case(4, Arg2, cellsVisited(Arg0, Arg1)); } void test_case_5() { string Arr0[] = {"173642855131893831828253420", "126290035950506994475683704", "381277675415026563959463393", "019782700912864681764582260", "496448425114634806770407597", "049628433145840178727435051", "117194708226266248973780562", "398138380998246682323622510", "408178777661559971959512111"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 8; int Arg2 = 135; verify_case(5, Arg2, cellsVisited(Arg0, Arg1)); } void test_case_6() { string Arr0[] = {"9"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 0; int Arg2 = 1; verify_case(6, Arg2, cellsVisited(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { MountainWalk ___test; ___test.run_test(-1); } // END CUT HERE
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007,2008, 2009 INRIA, UDcast * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mohamed Amine Ismail <amine.ismail@sophia.inria.fr> * <amine.ismail@udcast.com> */ #include "ns3/propagation-loss-model.h" #include "ns3/log.h" #include "ns3/mobility-model.h" #include "ns3/double.h" #include "ns3/pointer.h" #include <math.h> #include "cost231-propagation-loss-model.h" namespace ns3 { NS_LOG_COMPONENT_DEFINE ("Cost231PropagationLossModel"); NS_OBJECT_ENSURE_REGISTERED (Cost231PropagationLossModel); TypeId Cost231PropagationLossModel::GetTypeId (void) { static TypeId tid = TypeId ("ns3::Cost231PropagationLossModel") .SetParent<PropagationLossModel> () .AddConstructor<Cost231PropagationLossModel> () .AddAttribute ("Lambda", "The wavelength (default is 2.3 GHz at 300 000 km/s).", DoubleValue (300000000.0 / 2.3e9), MakeDoubleAccessor (&Cost231PropagationLossModel::m_lambda), MakeDoubleChecker<double> ()) .AddAttribute ("Frequency", "The Frequency (default is 2.3 GHz).", DoubleValue (2.3e9), MakeDoubleAccessor (&Cost231PropagationLossModel::m_frequency), MakeDoubleChecker<double> ()) .AddAttribute ("BSAntennaHeight", " BS Antenna Height (default is 50m).", DoubleValue (50.0), MakeDoubleAccessor (&Cost231PropagationLossModel::m_BSAntennaHeight), MakeDoubleChecker<double> ()) .AddAttribute ("SSAntennaHeight", " SS Antenna Height (default is 3m).", DoubleValue (3), MakeDoubleAccessor (&Cost231PropagationLossModel::m_SSAntennaHeight), MakeDoubleChecker<double> ()) .AddAttribute ("MinDistance", "The distance under which the propagation model refuses to give results (m) ", DoubleValue (0.5), MakeDoubleAccessor (&Cost231PropagationLossModel::SetMinDistance, &Cost231PropagationLossModel::GetMinDistance), MakeDoubleChecker<double> ()); return tid; } Cost231PropagationLossModel::Cost231PropagationLossModel () { C = 0; m_shadowing = 10; } void Cost231PropagationLossModel::SetLambda (double frequency, double speed) { m_lambda = speed / frequency; m_frequency = frequency; } double Cost231PropagationLossModel::GetShadowing (void) { return m_shadowing; } void Cost231PropagationLossModel::SetShadowing (double shadowing) { m_shadowing = shadowing; } void Cost231PropagationLossModel::SetLambda (double lambda) { m_lambda = lambda; m_frequency = 300000000 / lambda; } double Cost231PropagationLossModel::GetLambda (void) const { return m_lambda; } void Cost231PropagationLossModel::SetMinDistance (double minDistance) { m_minDistance = minDistance; } double Cost231PropagationLossModel::GetMinDistance (void) const { return m_minDistance; } void Cost231PropagationLossModel::SetBSAntennaHeight (double height) { m_BSAntennaHeight = height; } double Cost231PropagationLossModel::GetBSAntennaHeight (void) const { return m_BSAntennaHeight; } void Cost231PropagationLossModel::SetSSAntennaHeight (double height) { m_SSAntennaHeight = height; } double Cost231PropagationLossModel::GetSSAntennaHeight (void) const { return m_SSAntennaHeight; } void Cost231PropagationLossModel::SetEnvironment (Environment env) { m_environment = env; } Cost231PropagationLossModel::Environment Cost231PropagationLossModel::GetEnvironment (void) const { return m_environment; } double Cost231PropagationLossModel::GetLoss (Ptr<MobilityModel> a, Ptr<MobilityModel> b) const { double distance = a->GetDistanceFrom (b); if (distance <= m_minDistance) { return 0.0; } double log_f = log (m_frequency / 1000000000) / 2.302; double C_H = 0.8 + ((1.11 * log_f) - 0.7) * m_SSAntennaHeight - (1.56 * log_f); double log_BSH = log (m_BSAntennaHeight) / 2.303; // from the COST231 wiki entry // 2.303 is for the logarithm base change double loss_in_db = 46.3 + (33.9 * log_f) - (13.82 * log_BSH) - C_H + ((44.9 - 6.55 * log_BSH) * log (distance) / 2.303) + C + m_shadowing; NS_LOG_DEBUG ("dist =" << distance << ", Path Loss = " << loss_in_db); return (0 - loss_in_db); } double Cost231PropagationLossModel::DoCalcRxPower (double txPowerDbm, Ptr<MobilityModel> a, Ptr<MobilityModel> b) const { return txPowerDbm + GetLoss (a, b); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ # include "Flat.h" Flat::Flat() : Material(){ } Flat::Flat(const RGBColor& c) : Material(c){ } const RGBColor Flat::shade(const ShadeRec& sr) const { return color; }
#include "../content/Context.hpp" #include "../view/View.hpp" #include "./Toast_Callback.hpp" #include "../../JString.hpp" #include "./Toast.hpp" namespace android::widget { // Fields jint Toast::LENGTH_LONG() { return getStaticField<jint>( "android.widget.Toast", "LENGTH_LONG" ); } jint Toast::LENGTH_SHORT() { return getStaticField<jint>( "android.widget.Toast", "LENGTH_SHORT" ); } // QJniObject forward Toast::Toast(QJniObject obj) : JObject(obj) {} // Constructors Toast::Toast(android::content::Context arg0) : JObject( "android.widget.Toast", "(Landroid/content/Context;)V", arg0.object() ) {} // Methods android::widget::Toast Toast::makeText(android::content::Context arg0, jint arg1, jint arg2) { return callStaticObjectMethod( "android.widget.Toast", "makeText", "(Landroid/content/Context;II)Landroid/widget/Toast;", arg0.object(), arg1, arg2 ); } android::widget::Toast Toast::makeText(android::content::Context arg0, JString arg1, jint arg2) { return callStaticObjectMethod( "android.widget.Toast", "makeText", "(Landroid/content/Context;Ljava/lang/CharSequence;I)Landroid/widget/Toast;", arg0.object(), arg1.object<jstring>(), arg2 ); } void Toast::addCallback(android::widget::Toast_Callback arg0) const { callMethod<void>( "addCallback", "(Landroid/widget/Toast$Callback;)V", arg0.object() ); } void Toast::cancel() const { callMethod<void>( "cancel", "()V" ); } jint Toast::getDuration() const { return callMethod<jint>( "getDuration", "()I" ); } jint Toast::getGravity() const { return callMethod<jint>( "getGravity", "()I" ); } jfloat Toast::getHorizontalMargin() const { return callMethod<jfloat>( "getHorizontalMargin", "()F" ); } jfloat Toast::getVerticalMargin() const { return callMethod<jfloat>( "getVerticalMargin", "()F" ); } android::view::View Toast::getView() const { return callObjectMethod( "getView", "()Landroid/view/View;" ); } jint Toast::getXOffset() const { return callMethod<jint>( "getXOffset", "()I" ); } jint Toast::getYOffset() const { return callMethod<jint>( "getYOffset", "()I" ); } void Toast::removeCallback(android::widget::Toast_Callback arg0) const { callMethod<void>( "removeCallback", "(Landroid/widget/Toast$Callback;)V", arg0.object() ); } void Toast::setDuration(jint arg0) const { callMethod<void>( "setDuration", "(I)V", arg0 ); } void Toast::setGravity(jint arg0, jint arg1, jint arg2) const { callMethod<void>( "setGravity", "(III)V", arg0, arg1, arg2 ); } void Toast::setMargin(jfloat arg0, jfloat arg1) const { callMethod<void>( "setMargin", "(FF)V", arg0, arg1 ); } void Toast::setText(jint arg0) const { callMethod<void>( "setText", "(I)V", arg0 ); } void Toast::setText(JString arg0) const { callMethod<void>( "setText", "(Ljava/lang/CharSequence;)V", arg0.object<jstring>() ); } void Toast::setView(android::view::View arg0) const { callMethod<void>( "setView", "(Landroid/view/View;)V", arg0.object() ); } void Toast::show() const { callMethod<void>( "show", "()V" ); } } // namespace android::widget
// Copyright (c) 2018 The PIVX developers // Copyright (c) 2018-2019 The Zenon developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "invalid.h" #include "invalid_outpoints.json.h" #include "invalid_serials.json.h" namespace invalid_out { std::set<CBigNum> setInvalidSerials; std::set<COutPoint> setInvalidOutPoints; UniValue read_json(const std::string& jsondata) { UniValue v; if (!v.read(jsondata) || !v.isArray()) { return UniValue(UniValue::VARR); } return v.get_array(); } bool LoadOutpoints() { UniValue v = read_json(LoadInvalidOutPoints()); if (v.empty()) return false; for (unsigned int idx = 0; idx < v.size(); idx++) { const UniValue &val = v[idx]; const UniValue &o = val.get_obj(); const UniValue &vTxid = find_value(o, "txid"); if (!vTxid.isStr()) return false; uint256 txid = uint256(vTxid.get_str()); if (txid == 0) return false; const UniValue &vN = find_value(o, "n"); if (!vN.isNum()) return false; auto n = static_cast<uint32_t>(vN.get_int()); COutPoint out(txid, n); setInvalidOutPoints.insert(out); } return true; } bool LoadSerials() { UniValue v = read_json(LoadInvalidSerials()); if (v.empty()) return false; for (unsigned int idx = 0; idx < v.size(); idx++) { const UniValue &val = v[idx]; const UniValue &o = val.get_obj(); const UniValue &vSerial = find_value(o, "s"); if (!vSerial.isStr()) return false; CBigNum bnSerial = 0; bnSerial.SetHex(vSerial.get_str()); if (bnSerial == 0) return false; setInvalidSerials.insert(bnSerial); } return true; } bool ContainsOutPoint(const COutPoint& out) { return static_cast<bool>(setInvalidOutPoints.count(out)); } bool ContainsSerial(const CBigNum& bnSerial) { return static_cast<bool>(setInvalidSerials.count(bnSerial)); } }
// Copyright 2010-2016, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * 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. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "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 COPYRIGHT // OWNER OR 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. #include "base/cpu_stats.h" #include "testing/base/public/googletest.h" #include "testing/base/public/gunit.h" namespace mozc { namespace { TEST(CPUStats, CPUStatsTest) { CPUStats stats; EXPECT_GE(stats.GetSystemCPULoad(), 0.0); EXPECT_LE(stats.GetSystemCPULoad(), 1.0); EXPECT_GE(stats.GetCurrentProcessCPULoad(), 0.0); EXPECT_GE(stats.GetNumberOfProcessors(), 1); } } // namespace } // namespace mozc
#include "force.h" int main() { Force f; return 0; }
#include "utility.h" #include <cstring> #include <sstream> #include <QRgb> #include <QFileInfo> #include <cmath> namespace utils { QString getFileName(const QString& filepath) { QFileInfo fileInfo(filepath); return fileInfo.baseName(); } QString replaceExt(const QString& filepath, const QString& newExt) { int indexOfDot = filepath.lastIndexOf("."); int indexOfSlash = 0; #ifdef WIN32 indexOfSlash = filepath.lastIndexOf("\\"); #else indexOfSlash = filepath.lastIndexOf("/"); #endif if (indexOfDot > indexOfSlash) { if (newExt.indexOf(".") == -1) return filepath.left(indexOfDot + 1) + newExt; else return filepath.left(indexOfDot) + newExt; } else { if (newExt.indexOf(".") == -1) return filepath + "." + newExt; else return filepath + newExt; } } /************************************/ /* Generate Continuous Number */ /* [start, start+bandsCount) */ /************************************/ unsigned int* newContinuousNumber(unsigned int start, unsigned int count) { if (count < 1) return nullptr; else { unsigned int* ret = new unsigned int[count]; for (unsigned int i = 0; i < count; ++i) { ret[i] = start + i; } return ret; } } /************************************/ /* Color in hex convert ot RGB */ /************************************/ void hex2rgb(std::string hexCode, uchar& r, uchar& g, uchar& b) { if (hexCode[0] == '#') hexCode.erase(0, 1); if (hexCode.size() < 6) return; int iR, iG, iB; std::istringstream(hexCode.substr(0, 2)) >> std::hex >> iR; std::istringstream(hexCode.substr(2, 2)) >> std::hex >> iG; std::istringstream(hexCode.substr(4, 2)) >> std::hex >> iB; r = uchar(iR); g = uchar(iG); b = uchar(iB); } /***************************************/ /* Compare double numbers */ /***************************************/ bool isEqual(double a, double b, double eps/* = EPS*/) { return fabs(a - b) < eps; } /***************************************/ /* Generate random Color */ /***************************************/ //Color getRandColor() //{ // uchar r = getRand(0, 256); // uchar g = getRand(0, 256); // uchar b = getRand(0, 256); // return { r, g, b }; //} QRgb getRandomColor() { return qRgb(getRand(50, 200), getRand(50, 200), getRand(50, 200)); } } // namespace util
#pragma once #include "../../JObject.hpp" class JByteArray; namespace android::content { class Context; } namespace android::graphics { class Bitmap; } namespace android::media { class MediaDataSource; } namespace android::media { class MediaMetadataRetriever_BitmapParams; } namespace android::net { class Uri; } namespace java::io { class FileDescriptor; } class JString; namespace android::media { class MediaMetadataRetriever : public JObject { public: // Fields static jint METADATA_KEY_ALBUM(); static jint METADATA_KEY_ALBUMARTIST(); static jint METADATA_KEY_ARTIST(); static jint METADATA_KEY_AUTHOR(); static jint METADATA_KEY_BITRATE(); static jint METADATA_KEY_CAPTURE_FRAMERATE(); static jint METADATA_KEY_CD_TRACK_NUMBER(); static jint METADATA_KEY_COMPILATION(); static jint METADATA_KEY_COMPOSER(); static jint METADATA_KEY_DATE(); static jint METADATA_KEY_DISC_NUMBER(); static jint METADATA_KEY_DURATION(); static jint METADATA_KEY_GENRE(); static jint METADATA_KEY_HAS_AUDIO(); static jint METADATA_KEY_HAS_IMAGE(); static jint METADATA_KEY_HAS_VIDEO(); static jint METADATA_KEY_IMAGE_COUNT(); static jint METADATA_KEY_IMAGE_HEIGHT(); static jint METADATA_KEY_IMAGE_PRIMARY(); static jint METADATA_KEY_IMAGE_ROTATION(); static jint METADATA_KEY_IMAGE_WIDTH(); static jint METADATA_KEY_LOCATION(); static jint METADATA_KEY_MIMETYPE(); static jint METADATA_KEY_NUM_TRACKS(); static jint METADATA_KEY_TITLE(); static jint METADATA_KEY_VIDEO_FRAME_COUNT(); static jint METADATA_KEY_VIDEO_HEIGHT(); static jint METADATA_KEY_VIDEO_ROTATION(); static jint METADATA_KEY_VIDEO_WIDTH(); static jint METADATA_KEY_WRITER(); static jint METADATA_KEY_YEAR(); static jint OPTION_CLOSEST(); static jint OPTION_CLOSEST_SYNC(); static jint OPTION_NEXT_SYNC(); static jint OPTION_PREVIOUS_SYNC(); // QJniObject forward template<typename ...Ts> explicit MediaMetadataRetriever(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} MediaMetadataRetriever(QJniObject obj); // Constructors MediaMetadataRetriever(); // Methods JString extractMetadata(jint arg0) const; JByteArray getEmbeddedPicture() const; android::graphics::Bitmap getFrameAtIndex(jint arg0) const; android::graphics::Bitmap getFrameAtIndex(jint arg0, android::media::MediaMetadataRetriever_BitmapParams arg1) const; android::graphics::Bitmap getFrameAtTime() const; android::graphics::Bitmap getFrameAtTime(jlong arg0) const; android::graphics::Bitmap getFrameAtTime(jlong arg0, jint arg1) const; JObject getFramesAtIndex(jint arg0, jint arg1) const; JObject getFramesAtIndex(jint arg0, jint arg1, android::media::MediaMetadataRetriever_BitmapParams arg2) const; android::graphics::Bitmap getImageAtIndex(jint arg0) const; android::graphics::Bitmap getImageAtIndex(jint arg0, android::media::MediaMetadataRetriever_BitmapParams arg1) const; android::graphics::Bitmap getPrimaryImage() const; android::graphics::Bitmap getPrimaryImage(android::media::MediaMetadataRetriever_BitmapParams arg0) const; android::graphics::Bitmap getScaledFrameAtTime(jlong arg0, jint arg1, jint arg2, jint arg3) const; void release() const; void setDataSource(android::media::MediaDataSource arg0) const; void setDataSource(java::io::FileDescriptor arg0) const; void setDataSource(JString arg0) const; void setDataSource(android::content::Context arg0, android::net::Uri arg1) const; void setDataSource(JString arg0, JObject arg1) const; void setDataSource(java::io::FileDescriptor arg0, jlong arg1, jlong arg2) const; }; } // namespace android::media
/* * Copyright 2014-present IVK JSC. 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. */ #ifndef __MessageProducerImpl_CPP__ #define __MessageProducerImpl_CPP__ #include "ProducerImpl.h" #include "BytesMessageImpl.h" #include "MapMessageImpl.h" #include "MessageImpl.h" #include "StreamMessageImpl.h" #include "TextMessageImpl.h" #include <decaf/lang/System.h> #include <decaf/util/UUID.h> #include <transport/UPMQCommand.h> ProducerImpl::ProducerImpl(SessionImpl *sessionImpl, const cms::Destination *destination) : _session(sessionImpl), _destination(nullptr), _closed(false), _defaultDeliveryMode(cms::Message::DEFAULT_DELIVERY_MODE), _defaultPriority(cms::Message::DEFAULT_MSG_PRIORITY), _defaultTimeToLive(cms::Message::DEFAULT_TIME_TO_LIVE), _isDisableMessageId(false), _isDisableMessageTimestamp(false), _objectId(UUID::randomUUID().toString()) { if (sessionImpl == nullptr) { throw cms::CMSException("invalid session (is null)"); } try { if (destination == nullptr) { _nullDestProducer = true; _destination = new DestinationImpl(_session, EMPTY_STRING); } else { _nullDestProducer = false; _destination = new DestinationImpl(_session, destination->getName(), destination->getType()); sender(_destination); } // cout << "+ prod id " << _objectId << endl; } CATCH_ALL_THROW_CMSEXCEPTION } ProducerImpl::~ProducerImpl() { try { if (!isClosed()) { ProducerImpl::close(); } delete _destination; } CATCH_ALL_NOTHROW } void ProducerImpl::sender(DestinationImpl *destination) { try { Pointer<UPMQCommand> request(new UPMQCommand()); request->getProtoMessage().set_object_id(_objectId); Proto::Sender &sender = request->getSender(); sender.set_receipt_id(_objectId); sender.set_destination_uri(destination->getUri()); sender.set_session_id(_session->getObjectId()); sender.set_sender_id(_objectId); if (!sender.IsInitialized()) { throw cms::CMSException("request not initialized"); } _session->_connection->syncRequest(request.dynamicCast<Command>())->processReceipt(); } CATCH_ALL_THROW_CMSEXCEPTION } void ProducerImpl::unsender() { try { Pointer<UPMQCommand> request(new UPMQCommand()); request->getProtoMessage().set_object_id(_objectId); Proto::Unsender &unsender = request->getUnsender(); unsender.set_receipt_id(_objectId); unsender.set_destination_uri(_destination != nullptr ? _destination->getUri() : ""); unsender.set_session_id(_session->getObjectId()); unsender.set_sender_id(_objectId); if (!unsender.IsInitialized()) { throw cms::CMSException("request not initialized"); } _session->_connection->syncRequest(request.dynamicCast<Command>())->processReceipt(); } CATCH_ALL_THROW_CMSEXCEPTION } void ProducerImpl::close() { try { if (isClosed()) { return; } if (_session != nullptr && _session->_connection != nullptr && !_session->_connection->isClosed()) { _session->removeProducer(this); try { unsender(); } CATCH_ALL_NOTHROW setClosed(true); if (_destination) { _destination->_session = nullptr; } } // cout << "- prod id " << _objectId << endl; } CATCH_ALL_THROW_CMSEXCEPTION } void ProducerImpl::setDeliveryMode(int mode) { _defaultDeliveryMode = mode; } int ProducerImpl::getDeliveryMode() const { return _defaultDeliveryMode; } void ProducerImpl::setPriority(int priority) { _defaultPriority = priority; } int ProducerImpl::getPriority() const { return _defaultPriority; } void ProducerImpl::setTimeToLive(long long time) { _defaultTimeToLive = time; } long long ProducerImpl::getTimeToLive() const { return _defaultTimeToLive; } void ProducerImpl::setDisableMessageID(bool value) { _isDisableMessageId = value; } bool ProducerImpl::getDisableMessageID() const { return _isDisableMessageId; } void ProducerImpl::setDisableMessageTimeStamp(bool value) { _isDisableMessageTimestamp = value; } bool ProducerImpl::getDisableMessageTimeStamp() const { return _isDisableMessageTimestamp; } void ProducerImpl::send(cms::Message *message) { try { send(message, getDeliveryMode(), getPriority(), getTimeToLive()); } CATCH_ALL_THROW_CMSEXCEPTION } void ProducerImpl::send(cms::Message *message, int deliveryMode, int priority, long long timeToLive) { try { send(getDestination(), message, deliveryMode, priority, timeToLive); } CATCH_ALL_THROW_CMSEXCEPTION } void ProducerImpl::send(const cms::Destination *destination, cms::Message *message) { try { send(destination, message, getDeliveryMode(), getPriority(), getTimeToLive()); } CATCH_ALL_THROW_CMSEXCEPTION } void ProducerImpl::send(const cms::Destination *destination, cms::Message *msg, int deliveryMode, int priority, long long timeToLive) { try { if (isClosed()) { throw cms::IllegalStateException("cannot perform operation - producer has been closed"); } if (destination == nullptr) { if (_destination->getName().empty()) { throw cms::UnsupportedOperationException("destination is null"); } else { throw cms::InvalidDestinationException("destination is null"); } } const DestinationImpl *dest = dynamic_cast<const DestinationImpl *>(destination); if (!dest) { throw cms::InvalidDestinationException("destination is invalid"); } if (_destination->getUri() != dest->getUri()) { if (_nullDestProducer) { delete _destination; _destination = new DestinationImpl(_session, dest->getName(), dest->getType()); sender(_destination); } else { throw cms::UnsupportedOperationException("destination not equal"); } } // Message UPMQCommand *command = dynamic_cast<UPMQCommand *>(msg); if (!command) { throw cms::MessageFormatException("can't cast to UPMQCommand"); } Proto::Message *mutableMessage = command->_header->mutable_message(); mutableMessage->set_sender_id(_objectId); mutableMessage->set_session_id(_session->getObjectId()); mutableMessage->set_persistent(deliveryMode == cms::DeliveryMode::PERSISTENT); mutableMessage->set_priority(priority); auto uuid = assignNewId(); while (_lastMessageId == uuid) { uuid = assignNewId(); } _lastMessageId = std::move(uuid); mutableMessage->set_message_id(_lastMessageId); mutableMessage->set_receipt_id(mutableMessage->message_id()); long long currTimeMillis = 0; if (timeToLive > 0 || !_isDisableMessageTimestamp) { currTimeMillis = System::currentTimeMillis(); } if (timeToLive > 0) { mutableMessage->set_timetolive(timeToLive); mutableMessage->set_expiration(timeToLive + currTimeMillis); } else { mutableMessage->set_timetolive(0); mutableMessage->set_expiration(0); } if (!_isDisableMessageTimestamp) { mutableMessage->set_timestamp(currTimeMillis); } // Destination msg->setCMSDestination(destination); // Send if (!command->_header->message().IsInitialized()) { throw cms::CMSException("message not initialized"); } command->getProtoMessage().set_object_id(_objectId); Pointer<cms::Message> message(msg->clone()); _session->_connection->syncRequest(message.dynamicCast<Command>())->processReceipt(); } CATCH_ALL_THROW_CMSEXCEPTION } string &ProducerImpl::getObjectId() { return _objectId; } bool ProducerImpl::isClosed() { return _closed; } void ProducerImpl::setClosed(bool closed) { _closed = closed; } cms::Destination *ProducerImpl::getDestination() { return _destination; } string ProducerImpl::assignNewId() { return "ID:" + UUID::randomUUID().toString(); } #endif //__MessageProducerImpl_CPP__
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/signin/about_signin_internals.h" #include "base/debug/trace_event.h" #include "base/hash.h" #include "base/i18n/time_formatting.h" #include "base/logging.h" #include "base/utf_string_conversions.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/signin_manager.h" #include "chrome/browser/ui/webui/signin_internals_ui.h" #include "google_apis/gaia/gaia_constants.h" AboutSigninInternals::AboutSigninInternals() : profile_(NULL) {} AboutSigninInternals::~AboutSigninInternals() { DCHECK(signin_observers_.size() == 0); } void AboutSigninInternals::AddSigninObserver(SigninObserver* observer) { signin_observers_.AddObserver(observer); } void AboutSigninInternals::RemoveSigninObserver(SigninObserver* observer) { signin_observers_.RemoveObserver(observer); }
/********************************************************************** Audacity: A Digital Audio Editor ExportMP3.cpp Joshua Haberman This just acts as an interface to LAME. A Lame dynamic library must be present The difficulty in our approach is that we are attempting to use LAME in a way it was not designed to be used. LAME's API is reasonably consistant, so if we were linking directly against it we could expect this code to work with a variety of different LAME versions. However, the data structures change from version to version, and so linking with one version of the header and dynamically linking against a different version of the dynamic library will not work correctly. The solution is to find the lowest common denominator between versions. The bare minimum of functionality we must use is this: 1. Initialize the library. 2. Set, at minimum, the following global options: i. input sample rate ii. input channels 3. Encode the stream 4. Call the finishing routine Just so that it's clear that we're NOT free to use whatever features of LAME we like, I'm not including lame.h, but instead enumerating here the extent of functions and structures that we can rely on being able to import and use from a dynamic library. For the record, we aim to support LAME 3.70 on. Since LAME 3.70 was released in April of 2000, that should be plenty. Copyright 2002, 2003 Joshua Haberman. Some portions may be Copyright 2003 Paolo Patruno. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *******************************************************************//** \class MP3Exporter \brief Class used to export MP3 files *//********************************************************************/ #include "../Audacity.h" #include "ExportMP3.h" #include <wx/defs.h> #include <wx/choice.h> #include <wx/checkbox.h> #include <wx/dynlib.h> #include <wx/ffile.h> #include <wx/intl.h> #include <wx/log.h> #include <wx/mimetype.h> #include <wx/msgdlg.h> #include <wx/radiobut.h> #include <wx/stattext.h> #include <wx/textctrl.h> #include <wx/timer.h> #include <wx/utils.h> #include <wx/window.h> #include "../FileNames.h" #include "../float_cast.h" #include "../Internat.h" #include "../Mix.h" #include "../Prefs.h" #include "../Project.h" #include "../ShuttleGui.h" #include "../Tags.h" #include "../Track.h" #include "../widgets/LinkingHtmlWindow.h" #include "FileDialog.h" #include "Export.h" #include <lame/lame.h> #ifdef USE_LIBID3TAG #include <id3tag.h> #endif //---------------------------------------------------------------------------- // ExportMP3Options //---------------------------------------------------------------------------- #define MODE_SET 0 #define MODE_VBR 1 #define MODE_ABR 2 #define MODE_CBR 3 #define CHANNEL_JOINT 0 #define CHANNEL_STEREO 1 #define CHANNEL_MONO 2 #define QUALITY_0 0 #define QUALITY_1 1 #define QUALITY_2 2 #define QUALITY_3 3 #define QUALITY_4 4 #define QUALITY_5 5 #define QUALITY_6 6 #define QUALITY_7 7 #define QUALITY_8 8 #define QUALITY_9 9 #define ROUTINE_FAST 0 #define ROUTINE_STANDARD 1 #define PRESET_INSANE 0 #define PRESET_EXTREME 1 #define PRESET_STANDARD 2 #define PRESET_MEDIUM 3 // Note: The label field is what will be written to preferences and carries // no numerical significance. It is simply a means to look up a value // in a table. // // The entries should be listed in order you want them to appear in the // choice dropdown based on the name field. typedef struct { wxString name; int label; } CHOICES; static CHOICES fixRates[] = { /* i18n-hint: kbps is the bitrate of the MP3 file, kilobits per second*/ {wxT(""), 320}, {wxT(""), 256}, {wxT(""), 224}, {wxT(""), 192}, {wxT(""), 160}, {wxT(""), 144}, {wxT(""), 128}, {wxT(""), 112}, {wxT(""), 96}, {wxT(""), 80}, {wxT(""), 64}, {wxT(""), 56}, {wxT(""), 48}, {wxT(""), 40}, {wxT(""), 32}, {wxT(""), 24}, {wxT(""), 16}, {wxT(""), 8} }; static CHOICES varRates[] = { {wxT(""), QUALITY_0}, {wxT(""), QUALITY_1}, {wxT(""), QUALITY_2}, {wxT(""), QUALITY_3}, {wxT(""), QUALITY_4}, {wxT(""), QUALITY_5}, {wxT(""), QUALITY_6}, {wxT(""), QUALITY_7}, {wxT(""), QUALITY_8}, {wxT(""), QUALITY_9} }; static CHOICES varModes[] = { {wxT(""), ROUTINE_FAST }, {wxT(""), ROUTINE_STANDARD} }; static CHOICES setRates[] = { {wxT(""), PRESET_INSANE }, {wxT(""), PRESET_EXTREME }, {wxT(""), PRESET_STANDARD}, {wxT(""), PRESET_MEDIUM } }; static CHOICES sampRates[] = { {wxT(""), 8000 }, {wxT(""), 11025 }, {wxT(""), 12000 }, {wxT(""), 16000 }, {wxT(""), 22050 }, {wxT(""), 24000 }, {wxT(""), 32000 }, {wxT(""), 44100 }, {wxT(""), 48000 } }; #define ID_SET 7000 #define ID_VBR 7001 #define ID_ABR 7002 #define ID_CBR 7003 #define ID_QUALITY 7004 #define ID_MONO 7005 static void InitMP3_Statics() { for (size_t i=0; i < WXSIZEOF(fixRates); i++) { fixRates[i].name = wxT(""); fixRates[i].name << fixRates[i].label << wxT(" ") << _("kbps"); } for (size_t i=0; i < WXSIZEOF(varRates); i++) { varRates[i].name = wxT(""); varRates[i].name << i << wxT(", "); } varRates[0].name << wxT("220-260"); varRates[1].name << wxT("200-250"); varRates[2].name << wxT("170-210"); varRates[3].name << wxT("155-195"); varRates[4].name << wxT("145-185"); varRates[5].name << wxT("110-150"); varRates[6].name << wxT("95-135"); varRates[7].name << wxT("80-120"); varRates[8].name << wxT("65-105"); varRates[9].name << wxT("45-85"); for (size_t i=0; i < WXSIZEOF(varRates); i++) varRates[i].name << wxT(" ") << _("kbps"); varRates[0].name << wxT(" ") << _("(Best Quality)"); varRates[9].name << wxT(" ") << _("(Smaller files)"); varModes[0].name = _("Fast"); varModes[1].name = _("Standard"); for (size_t i=0; i < WXSIZEOF(setRates); i++) setRates[i].name = wxT(""); /* i18n-hint: Slightly humorous - as in use an insane precision with MP3.*/ setRates[0].name << _("Insane" ) << wxT(", ") << 320; setRates[1].name << _("Extreme" ) << wxT(", ") << 220 << wxT("-") << 260; setRates[2].name << _("Standard") << wxT(", ") << 170 << wxT("-") << 210; setRates[3].name << _("Medium" ) << wxT(", ") << 145 << wxT("-") << 185; for (size_t i=0; i < WXSIZEOF(setRates); i++) setRates[i].name << wxT(" ") << _("kbps"); for (size_t i=0; i < WXSIZEOF(sampRates); i++) { sampRates[i].name = wxT(""); sampRates[i].name << sampRates[i].label; } } class ExportMP3Options final : public wxPanelWrapper { public: ExportMP3Options(wxWindow *parent, int format); virtual ~ExportMP3Options(); void PopulateOrExchange(ShuttleGui & S); bool TransferDataToWindow(); bool TransferDataFromWindow(); void OnSET(wxCommandEvent& evt); void OnVBR(wxCommandEvent& evt); void OnABR(wxCommandEvent& evt); void OnCBR(wxCommandEvent& evt); void OnQuality(wxCommandEvent& evt); void OnMono(wxCommandEvent& evt); void LoadNames(CHOICES *choices, int count); wxArrayString GetNames(CHOICES *choices, int count); wxArrayInt GetLabels(CHOICES *choices, int count); int FindIndex(CHOICES *choices, int cnt, int needle, int def); private: wxRadioButton *mStereo; wxRadioButton *mJoint; wxCheckBox *mMono; wxRadioButton *mSET; wxRadioButton *mVBR; wxRadioButton *mABR; wxRadioButton *mCBR; wxChoice *mRate; wxChoice *mMode; long mSetRate; long mVbrRate; long mAbrRate; long mCbrRate; DECLARE_EVENT_TABLE() }; BEGIN_EVENT_TABLE(ExportMP3Options, wxPanelWrapper) EVT_RADIOBUTTON(ID_SET, ExportMP3Options::OnSET) EVT_RADIOBUTTON(ID_VBR, ExportMP3Options::OnVBR) EVT_RADIOBUTTON(ID_ABR, ExportMP3Options::OnABR) EVT_RADIOBUTTON(ID_CBR, ExportMP3Options::OnCBR) EVT_CHOICE(wxID_ANY, ExportMP3Options::OnQuality) EVT_CHECKBOX(ID_MONO, ExportMP3Options::OnMono) END_EVENT_TABLE() /// /// ExportMP3Options::ExportMP3Options(wxWindow *parent, int WXUNUSED(format)) : wxPanelWrapper(parent, wxID_ANY) { InitMP3_Statics(); mSetRate = gPrefs->Read(wxT("/FileFormats/MP3SetRate"), PRESET_STANDARD); mVbrRate = gPrefs->Read(wxT("/FileFormats/MP3VbrRate"), QUALITY_2); mAbrRate = gPrefs->Read(wxT("/FileFormats/MP3AbrRate"), 192); mCbrRate = gPrefs->Read(wxT("/FileFormats/MP3CbrRate"), 192); ShuttleGui S(this, eIsCreatingFromPrefs); PopulateOrExchange(S); TransferDataToWindow(); } ExportMP3Options::~ExportMP3Options() { TransferDataFromWindow(); } /// /// void ExportMP3Options::PopulateOrExchange(ShuttleGui & S) { S.StartVerticalLay(); { S.StartHorizontalLay(wxCENTER); { S.StartMultiColumn(2, wxCENTER); { S.SetStretchyCol(1); S.StartTwoColumn(); { S.AddPrompt(_("Bit Rate Mode:")); S.StartHorizontalLay(); { S.StartRadioButtonGroup(wxT("/FileFormats/MP3RateMode"), MODE_SET); { mSET = S.Id(ID_SET).TieRadioButton(_("Preset"), MODE_SET); mVBR = S.Id(ID_VBR).TieRadioButton(_("Variable"), MODE_VBR); mABR = S.Id(ID_ABR).TieRadioButton(_("Average"), MODE_ABR); mCBR = S.Id(ID_CBR).TieRadioButton(_("Constant"), MODE_CBR); } S.EndRadioButtonGroup(); } S.EndHorizontalLay(); CHOICES *choices; int cnt; bool enable; int defrate; if (mSET->GetValue()) { choices = setRates; cnt = WXSIZEOF(setRates); enable = true; defrate = mSetRate; } else if (mVBR->GetValue()) { choices = varRates; cnt = WXSIZEOF(varRates); enable = true; defrate = mVbrRate; } else if (mABR->GetValue()) { choices = fixRates; cnt = WXSIZEOF(fixRates); enable = false; defrate = mAbrRate; } else { mCBR->SetValue(true); choices = fixRates; cnt = WXSIZEOF(fixRates); enable = false; defrate = mCbrRate; } mRate = S.Id(ID_QUALITY).TieChoice(_("Quality"), wxT("/FileFormats/MP3Bitrate"), defrate, GetNames(choices, cnt), GetLabels(choices, cnt)); mMode = S.TieChoice(_("Variable Speed:"), wxT("/FileFormats/MP3VarMode"), ROUTINE_FAST, GetNames(varModes, WXSIZEOF(varModes)), GetLabels(varModes, WXSIZEOF(varModes))); mMode->Enable(enable); S.AddPrompt(_("Channel Mode:")); S.StartMultiColumn(3, wxEXPAND); { bool mono = false; gPrefs->Read(wxT("/FileFormats/MP3ForceMono"), &mono, 0); S.StartRadioButtonGroup(wxT("/FileFormats/MP3ChannelMode"), CHANNEL_JOINT); { mJoint = S.TieRadioButton(_("Joint Stereo"), CHANNEL_JOINT); mStereo = S.TieRadioButton(_("Stereo"), CHANNEL_STEREO); mJoint->Enable(!mono); mStereo->Enable(!mono); } S.EndRadioButtonGroup(); mMono = S.Id(ID_MONO).AddCheckBox(_("Force export to mono"), mono? wxT("true") : wxT("false")); } S.EndTwoColumn(); } S.EndTwoColumn(); } S.EndMultiColumn(); } S.EndHorizontalLay(); } S.EndVerticalLay(); } /// /// bool ExportMP3Options::TransferDataToWindow() { return true; } bool ExportMP3Options::TransferDataFromWindow() { ShuttleGui S(this, eIsSavingToPrefs); PopulateOrExchange(S); gPrefs->Write(wxT("/FileFormats/MP3SetRate"), mSetRate); gPrefs->Write(wxT("/FileFormats/MP3VbrRate"), mVbrRate); gPrefs->Write(wxT("/FileFormats/MP3AbrRate"), mAbrRate); gPrefs->Write(wxT("/FileFormats/MP3CbrRate"), mCbrRate); gPrefs->Flush(); return true; } /// /// void ExportMP3Options::OnSET(wxCommandEvent& WXUNUSED(event)) { LoadNames(setRates, WXSIZEOF(setRates)); mRate->SetSelection(FindIndex(setRates, WXSIZEOF(setRates), mSetRate, 2)); mRate->Refresh(); mMode->Enable(true); } /// /// void ExportMP3Options::OnVBR(wxCommandEvent& WXUNUSED(event)) { LoadNames(varRates, WXSIZEOF(varRates)); mRate->SetSelection(FindIndex(varRates, WXSIZEOF(varRates), mVbrRate, 2)); mRate->Refresh(); mMode->Enable(true); } /// /// void ExportMP3Options::OnABR(wxCommandEvent& WXUNUSED(event)) { LoadNames(fixRates, WXSIZEOF(fixRates)); mRate->SetSelection(FindIndex(fixRates, WXSIZEOF(fixRates), mAbrRate, 10)); mRate->Refresh(); mMode->Enable(false); } /// /// void ExportMP3Options::OnCBR(wxCommandEvent& WXUNUSED(event)) { LoadNames(fixRates, WXSIZEOF(fixRates)); mRate->SetSelection(FindIndex(fixRates, WXSIZEOF(fixRates), mCbrRate, 10)); mRate->Refresh(); mMode->Enable(false); } void ExportMP3Options::OnQuality(wxCommandEvent& WXUNUSED(event)) { int sel = mRate->GetSelection(); if (mSET->GetValue()) { mSetRate = setRates[sel].label; } else if (mVBR->GetValue()) { mVbrRate = varRates[sel].label; } else if (mABR->GetValue()) { mAbrRate = fixRates[sel].label; } else { mCbrRate = fixRates[sel].label; } } void ExportMP3Options::OnMono(wxCommandEvent& evt) { bool mono = false; mono = mMono->GetValue(); mJoint->Enable(!mono); mStereo->Enable(!mono); gPrefs->Write(wxT("/FileFormats/MP3ForceMono"), mono); gPrefs->Flush(); } void ExportMP3Options::LoadNames(CHOICES *choices, int count) { mRate->Clear(); for (int i = 0; i < count; i++) { mRate->Append(choices[i].name); } } wxArrayString ExportMP3Options::GetNames(CHOICES *choices, int count) { wxArrayString names; for (int i = 0; i < count; i++) { names.Add(choices[i].name); } return names; } wxArrayInt ExportMP3Options::GetLabels(CHOICES *choices, int count) { wxArrayInt labels; for (int i = 0; i < count; i++) { labels.Add(choices[i].label); } return labels; } int ExportMP3Options::FindIndex(CHOICES *choices, int cnt, int needle, int def) { for (int i = 0; i < cnt; i++) { if (choices[i].label == needle) { return i; } } return def; } //---------------------------------------------------------------------------- // FindDialog //---------------------------------------------------------------------------- #define ID_BROWSE 5000 #define ID_DLOAD 5001 class FindDialog final : public wxDialogWrapper { public: #ifndef DISABLE_DYNAMIC_LOADING_LAME FindDialog(wxWindow *parent, wxString path, wxString name, wxString type) : wxDialogWrapper(parent, wxID_ANY, /* i18n-hint: LAME is the name of an MP3 converter and should not be translated*/ wxString(_("Locate Lame"))) { SetName(GetTitle()); ShuttleGui S(this, eIsCreating); mPath = path; mName = name; mType = type; mLibPath.Assign(mPath, mName); PopulateOrExchange(S); } void PopulateOrExchange(ShuttleGui & S) { wxString text; S.SetBorder(10); S.StartVerticalLay(true); { text.Printf(_("Audacity needs the file %s to create MP3s."), mName.c_str()); S.AddTitle(text); S.SetBorder(3); S.StartHorizontalLay(wxALIGN_LEFT, true); { text.Printf(_("Location of %s:"), mName.c_str()); S.AddTitle(text); } S.EndHorizontalLay(); S.StartMultiColumn(2, wxEXPAND); S.SetStretchyCol(0); { if (mLibPath.GetFullPath().IsEmpty()) { /* i18n-hint: There is a button to the right of the arrow.*/ text.Printf(_("To find %s, click here -->"), mName.c_str()); mPathText = S.AddTextBox(wxT(""), text, 0); } else { mPathText = S.AddTextBox(wxT(""), mLibPath.GetFullPath(), 0); } S.Id(ID_BROWSE).AddButton(_("Browse..."), wxALIGN_RIGHT); /* i18n-hint: There is a button to the right of the arrow.*/ S.AddVariableText(_("To get a free copy of Lame, click here -->"), true); /* i18n-hint: (verb)*/ S.Id(ID_DLOAD).AddButton(_("Download"), wxALIGN_RIGHT); } S.EndMultiColumn(); S.AddStandardButtons(); } S.EndVerticalLay(); Layout(); Fit(); SetMinSize(GetSize()); Center(); return; } void OnBrowse(wxCommandEvent & WXUNUSED(event)) { wxString question; /* i18n-hint: It's asking for the location of a file, for * example, "Where is lame_enc.dll?" - you could translate * "Where would I find the file %s" instead if you want. */ question.Printf(_("Where is %s?"), mName.c_str()); wxString path = FileSelector(question, mLibPath.GetPath(), mLibPath.GetName(), wxT(""), mType, wxFD_OPEN | wxRESIZE_BORDER, this); if (!path.IsEmpty()) { mLibPath = path; mPathText->SetValue(path); } } void OnDownload(wxCommandEvent & WXUNUSED(event)) { wxString page = wxT("http://manual.audacityteam.org/man/faq_installation_and_plug_ins.html#lame"); ::OpenInDefaultBrowser(page); } wxString GetLibPath() { return mLibPath.GetFullPath(); } #endif // DISABLE_DYNAMIC_LOADING_LAME private: #ifndef DISABLE_DYNAMIC_LOADING_LAME wxFileName mLibPath; wxString mPath; wxString mName; wxString mType; #endif // DISABLE_DYNAMIC_LOADING_LAME wxTextCtrl *mPathText; DECLARE_EVENT_TABLE() }; #ifndef DISABLE_DYNAMIC_LOADING_LAME BEGIN_EVENT_TABLE(FindDialog, wxDialogWrapper) EVT_BUTTON(ID_BROWSE, FindDialog::OnBrowse) EVT_BUTTON(ID_DLOAD, FindDialog::OnDownload) END_EVENT_TABLE() #endif // DISABLE_DYNAMIC_LOADING_LAME //---------------------------------------------------------------------------- // MP3Exporter //---------------------------------------------------------------------------- #ifndef DISABLE_DYNAMIC_LOADING_LAME typedef lame_global_flags *lame_init_t(void); typedef int lame_init_params_t(lame_global_flags*); typedef const char* get_lame_version_t(void); typedef int lame_encode_buffer_t ( lame_global_flags* gf, const short int buffer_l [], const short int buffer_r [], const int nsamples, unsigned char * mp3buf, const int mp3buf_size ); typedef int lame_encode_buffer_interleaved_t( lame_global_flags* gf, short int pcm[], int num_samples, /* per channel */ unsigned char* mp3buf, int mp3buf_size ); typedef int lame_encode_flush_t( lame_global_flags *gf, unsigned char* mp3buf, int size ); typedef int lame_close_t(lame_global_flags*); typedef int lame_set_in_samplerate_t(lame_global_flags*, int); typedef int lame_set_out_samplerate_t(lame_global_flags*, int); typedef int lame_set_num_channels_t(lame_global_flags*, int ); typedef int lame_set_quality_t(lame_global_flags*, int); typedef int lame_set_brate_t(lame_global_flags*, int); typedef int lame_set_VBR_t(lame_global_flags *, vbr_mode); typedef int lame_set_VBR_q_t(lame_global_flags *, int); typedef int lame_set_VBR_min_bitrate_kbps_t(lame_global_flags *, int); typedef int lame_set_mode_t(lame_global_flags *, MPEG_mode); typedef int lame_set_preset_t(lame_global_flags *, int); typedef int lame_set_error_protection_t(lame_global_flags *, int); typedef int lame_set_disable_reservoir_t(lame_global_flags *, int); typedef int lame_set_padding_type_t(lame_global_flags *, Padding_type); typedef int lame_set_bWriteVbrTag_t(lame_global_flags *, int); typedef size_t lame_get_lametag_frame_t(const lame_global_flags *, unsigned char* buffer, size_t size); typedef void lame_mp3_tags_fid_t(lame_global_flags *, FILE *); #endif // DISABLE_DYNAMIC_LOADING_LAME #if defined(__WXMSW__) // An alternative solution to give Windows an additional chance of writing the tag before // falling bato to lame_mp3_tag_fid(). The latter can have DLL sharing issues when mixing // Debug/Release builds of Audacity and the lame DLL. typedef unsigned long beWriteInfoTag_t(lame_global_flags *, char *); // We use this to determine if the user has selected an older, Blade API only, lame_enc.dll // so we can be more specific about why their library isn't acceptable. typedef struct { // BladeEnc DLL Version number BYTE byDLLMajorVersion; BYTE byDLLMinorVersion; // BladeEnc Engine Version Number BYTE byMajorVersion; BYTE byMinorVersion; // DLL Release date BYTE byDay; BYTE byMonth; WORD wYear; // BladeEnc Homepage URL CHAR zHomepage[129]; BYTE byAlphaLevel; BYTE byBetaLevel; BYTE byMMXEnabled; BYTE btReserved[125]; } be_version; typedef void beVersion_t(be_version *); #endif class MP3Exporter { public: enum AskUser { No, Maybe, Yes }; MP3Exporter(); virtual ~MP3Exporter(); #ifndef DISABLE_DYNAMIC_LOADING_LAME bool FindLibrary(wxWindow *parent); bool LoadLibrary(wxWindow *parent, AskUser askuser); bool ValidLibraryLoaded(); #endif // DISABLE_DYNAMIC_LOADING_LAME /* These global settings keep state over the life of the object */ void SetMode(int mode); void SetBitrate(int rate); void SetQuality(int q, int r); void SetChannel(int mode); /* Virtual methods that must be supplied by library interfaces */ /* initialize the library interface */ bool InitLibrary(wxString libpath); void FreeLibrary(); /* get library info */ wxString GetLibraryVersion(); wxString GetLibraryName(); wxString GetLibraryPath(); wxString GetLibraryTypeString(); /* returns the number of samples PER CHANNEL to send for each call to EncodeBuffer */ int InitializeStream(int channels, int sampleRate); /* In bytes. must be called AFTER InitializeStream */ int GetOutBufferSize(); /* returns the number of bytes written. input is interleaved if stereo*/ int EncodeBuffer(short int inbuffer[], unsigned char outbuffer[]); int EncodeRemainder(short int inbuffer[], int nSamples, unsigned char outbuffer[]); int EncodeBufferMono(short int inbuffer[], unsigned char outbuffer[]); int EncodeRemainderMono(short int inbuffer[], int nSamples, unsigned char outbuffer[]); int FinishStream(unsigned char outbuffer[]); void CancelEncoding(); void PutInfoTag(wxFFile & f, wxFileOffset off); private: #ifndef DISABLE_DYNAMIC_LOADING_LAME wxString mLibPath; wxDynamicLibrary lame_lib; bool mLibraryLoaded; #endif // DISABLE_DYNAMIC_LOADING_LAME #if defined(__WXMSW__) wxString mBladeVersion; #endif bool mEncoding; int mMode; int mBitrate; int mQuality; int mRoutine; int mChannel; #ifndef DISABLE_DYNAMIC_LOADING_LAME /* function pointers to the symbols we get from the library */ lame_init_t* lame_init; lame_init_params_t* lame_init_params; lame_encode_buffer_t* lame_encode_buffer; lame_encode_buffer_interleaved_t* lame_encode_buffer_interleaved; lame_encode_flush_t* lame_encode_flush; lame_close_t* lame_close; get_lame_version_t* get_lame_version; lame_set_in_samplerate_t* lame_set_in_samplerate; lame_set_out_samplerate_t* lame_set_out_samplerate; lame_set_num_channels_t* lame_set_num_channels; lame_set_quality_t* lame_set_quality; lame_set_brate_t* lame_set_brate; lame_set_VBR_t* lame_set_VBR; lame_set_VBR_q_t* lame_set_VBR_q; lame_set_VBR_min_bitrate_kbps_t* lame_set_VBR_min_bitrate_kbps; lame_set_mode_t* lame_set_mode; lame_set_preset_t* lame_set_preset; lame_set_error_protection_t* lame_set_error_protection; lame_set_disable_reservoir_t *lame_set_disable_reservoir; lame_set_padding_type_t *lame_set_padding_type; lame_set_bWriteVbrTag_t *lame_set_bWriteVbrTag; lame_get_lametag_frame_t *lame_get_lametag_frame; lame_mp3_tags_fid_t *lame_mp3_tags_fid; #if defined(__WXMSW__) beWriteInfoTag_t *beWriteInfoTag; beVersion_t *beVersion; #endif #endif // DISABLE_DYNAMIC_LOADING_LAME lame_global_flags *mGF; static const int mSamplesPerChunk = 220500; // See lame.h/lame_encode_buffer() for further explanation // As coded here, this should be the worst case. static const int mOutBufferSize = mSamplesPerChunk * (320 / 8) / 8 + 4 * 1152 * (320 / 8) / 8 + 512; // See MAXFRAMESIZE in libmp3lame/VbrTag.c for explanation of 2880. unsigned char mInfoTagBuf[2880]; size_t mInfoTagLen; }; MP3Exporter::MP3Exporter() { #ifndef DISABLE_DYNAMIC_LOADING_LAME mLibraryLoaded = false; #endif // DISABLE_DYNAMIC_LOADING_LAME mEncoding = false; mGF = NULL; #ifndef DISABLE_DYNAMIC_LOADING_LAME if (gPrefs) { mLibPath = gPrefs->Read(wxT("/MP3/MP3LibPath"), wxT("")); } #endif // DISABLE_DYNAMIC_LOADING_LAME mBitrate = 128; mQuality = QUALITY_2; mChannel = CHANNEL_STEREO; mMode = MODE_CBR; mRoutine = ROUTINE_FAST; } MP3Exporter::~MP3Exporter() { FreeLibrary(); } #ifndef DISABLE_DYNAMIC_LOADING_LAME bool MP3Exporter::FindLibrary(wxWindow *parent) { wxString path; wxString name; if (!mLibPath.IsEmpty()) { wxFileName fn = mLibPath; path = fn.GetPath(); name = fn.GetFullName(); } else { path = GetLibraryPath(); name = GetLibraryName(); } FindDialog fd(parent, path, name, GetLibraryTypeString()); if (fd.ShowModal() == wxID_CANCEL) { return false; } path = fd.GetLibPath(); if (!::wxFileExists(path)) { return false; } mLibPath = path; return (gPrefs->Write(wxT("/MP3/MP3LibPath"), mLibPath) && gPrefs->Flush()); } bool MP3Exporter::LoadLibrary(wxWindow *parent, AskUser askuser) { if (ValidLibraryLoaded()) { FreeLibrary(); mLibraryLoaded = false; } #if defined(__WXMSW__) mBladeVersion.Empty(); #endif // First try loading it from a previously located path if (!mLibPath.IsEmpty()) { wxLogMessage(wxT("Attempting to load LAME from previously defined path")); mLibraryLoaded = InitLibrary(mLibPath); } // If not successful, try loading using system search paths if (!ValidLibraryLoaded()) { wxLogMessage(wxT("Attempting to load LAME from system search paths")); mLibPath = GetLibraryName(); mLibraryLoaded = InitLibrary(mLibPath); } // If not successful, try loading using compiled in path if (!ValidLibraryLoaded()) { wxLogMessage(wxT("Attempting to load LAME from builtin path")); wxFileName fn(GetLibraryPath(), GetLibraryName()); mLibPath = fn.GetFullPath(); mLibraryLoaded = InitLibrary(mLibPath); } // If not successful, must ask the user if (!ValidLibraryLoaded()) { wxLogMessage(wxT("(Maybe) ask user for library")); if (askuser == MP3Exporter::Maybe && FindLibrary(parent)) { mLibraryLoaded = InitLibrary(mLibPath); } } // Oh well, just give up if (!ValidLibraryLoaded()) { #if defined(__WXMSW__) if (askuser && !mBladeVersion.IsEmpty()) { wxMessageBox(mBladeVersion); } #endif wxLogMessage(wxT("Failed to locate LAME library")); return false; } wxLogMessage(wxT("LAME library successfully loaded")); return true; } bool MP3Exporter::ValidLibraryLoaded() { return mLibraryLoaded; } #endif // DISABLE_DYNAMIC_LOADING_LAME void MP3Exporter::SetMode(int mode) { mMode = mode; } void MP3Exporter::SetBitrate(int rate) { mBitrate = rate; } void MP3Exporter::SetQuality(int q, int r) { mQuality = q; mRoutine = r; } void MP3Exporter::SetChannel(int mode) { mChannel = mode; } bool MP3Exporter::InitLibrary(wxString libpath) { wxLogMessage(wxT("Loading LAME from %s"), libpath.c_str()); #ifndef DISABLE_DYNAMIC_LOADING_LAME if (!lame_lib.Load(libpath, wxDL_LAZY)) { wxLogMessage(wxT("load failed")); return false; } wxLogMessage(wxT("Actual LAME path %s"), FileNames::PathFromAddr(lame_lib.GetSymbol(wxT("lame_init"))).c_str()); lame_init = (lame_init_t *) lame_lib.GetSymbol(wxT("lame_init")); get_lame_version = (get_lame_version_t *) lame_lib.GetSymbol(wxT("get_lame_version")); lame_init_params = (lame_init_params_t *) lame_lib.GetSymbol(wxT("lame_init_params")); lame_encode_buffer = (lame_encode_buffer_t *) lame_lib.GetSymbol(wxT("lame_encode_buffer")); lame_encode_buffer_interleaved = (lame_encode_buffer_interleaved_t *) lame_lib.GetSymbol(wxT("lame_encode_buffer_interleaved")); lame_encode_flush = (lame_encode_flush_t *) lame_lib.GetSymbol(wxT("lame_encode_flush")); lame_close = (lame_close_t *) lame_lib.GetSymbol(wxT("lame_close")); lame_set_in_samplerate = (lame_set_in_samplerate_t *) lame_lib.GetSymbol(wxT("lame_set_in_samplerate")); lame_set_out_samplerate = (lame_set_out_samplerate_t *) lame_lib.GetSymbol(wxT("lame_set_out_samplerate")); lame_set_num_channels = (lame_set_num_channels_t *) lame_lib.GetSymbol(wxT("lame_set_num_channels")); lame_set_quality = (lame_set_quality_t *) lame_lib.GetSymbol(wxT("lame_set_quality")); lame_set_brate = (lame_set_brate_t *) lame_lib.GetSymbol(wxT("lame_set_brate")); lame_set_VBR = (lame_set_VBR_t *) lame_lib.GetSymbol(wxT("lame_set_VBR")); lame_set_VBR_q = (lame_set_VBR_q_t *) lame_lib.GetSymbol(wxT("lame_set_VBR_q")); lame_set_VBR_min_bitrate_kbps = (lame_set_VBR_min_bitrate_kbps_t *) lame_lib.GetSymbol(wxT("lame_set_VBR_min_bitrate_kbps")); lame_set_mode = (lame_set_mode_t *) lame_lib.GetSymbol(wxT("lame_set_mode")); lame_set_preset = (lame_set_preset_t *) lame_lib.GetSymbol(wxT("lame_set_preset")); lame_set_error_protection = (lame_set_error_protection_t *) lame_lib.GetSymbol(wxT("lame_set_error_protection")); lame_set_disable_reservoir = (lame_set_disable_reservoir_t *) lame_lib.GetSymbol(wxT("lame_set_disable_reservoir")); lame_set_padding_type = (lame_set_padding_type_t *) lame_lib.GetSymbol(wxT("lame_set_padding_type")); lame_set_bWriteVbrTag = (lame_set_bWriteVbrTag_t *) lame_lib.GetSymbol(wxT("lame_set_bWriteVbrTag")); // These are optional lame_get_lametag_frame = (lame_get_lametag_frame_t *) lame_lib.GetSymbol(wxT("lame_get_lametag_frame")); lame_mp3_tags_fid = (lame_mp3_tags_fid_t *) lame_lib.GetSymbol(wxT("lame_mp3_tags_fid")); #if defined(__WXMSW__) beWriteInfoTag = (beWriteInfoTag_t *) lame_lib.GetSymbol(wxT("beWriteInfoTag")); beVersion = (beVersion_t *) lame_lib.GetSymbol(wxT("beVersion")); #endif if (!lame_init || !get_lame_version || !lame_init_params || !lame_encode_buffer || !lame_encode_buffer_interleaved || !lame_encode_flush || !lame_close || !lame_set_in_samplerate || !lame_set_out_samplerate || !lame_set_num_channels || !lame_set_quality || !lame_set_brate || !lame_set_VBR || !lame_set_VBR_q || !lame_set_mode || !lame_set_preset || !lame_set_error_protection || !lame_set_disable_reservoir || !lame_set_padding_type || !lame_set_bWriteVbrTag) { wxLogMessage(wxT("Failed to find a required symbol in the LAME library.")); #if defined(__WXMSW__) if (beVersion) { be_version v; beVersion(&v); mBladeVersion.Printf(_("You are linking to lame_enc.dll v%d.%d. This version is not compatible with Audacity %d.%d.%d.\nPlease download the latest version of the LAME MP3 library."), v.byMajorVersion, v.byMinorVersion, AUDACITY_VERSION, AUDACITY_RELEASE, AUDACITY_REVISION); } #endif lame_lib.Unload(); return false; } #endif // DISABLE_DYNAMIC_LOADING_LAME mGF = lame_init(); if (mGF == NULL) { return false; } return true; } void MP3Exporter::FreeLibrary() { if (mGF) { lame_close(mGF); mGF = NULL; } #ifndef DISABLE_DYNAMIC_LOADING_LAME lame_lib.Unload(); #endif // DISABLE_DYNAMIC_LOADING_LAME return; } wxString MP3Exporter::GetLibraryVersion() { #ifndef DISABLE_DYNAMIC_LOADING_LAME if (!mLibraryLoaded) { return wxT(""); } #endif // DISABLE_DYNAMIC_LOADING_LAME return wxString::Format(wxT("LAME %hs"), get_lame_version()); } int MP3Exporter::InitializeStream(int channels, int sampleRate) { #ifndef DISABLE_DYNAMIC_LOADING_LAME if (!mLibraryLoaded) { return -1; } #endif // DISABLE_DYNAMIC_LOADING_LAME if (channels > 2) { return -1; } lame_set_error_protection(mGF, false); lame_set_num_channels(mGF, channels); lame_set_in_samplerate(mGF, sampleRate); lame_set_out_samplerate(mGF, sampleRate); lame_set_disable_reservoir(mGF, false); #ifndef DISABLE_DYNAMIC_LOADING_LAME // TODO: Make this configurable (detect the existance of this function) lame_set_padding_type(mGF, PAD_NO); #endif // DISABLE_DYNAMIC_LOADING_LAME // Add the VbrTag for all types. For ABR/VBR, a Xing tag will be created. // For CBR, it will be a Lame Info tag. lame_set_bWriteVbrTag(mGF, true); // Set the VBR quality or ABR/CBR bitrate switch (mMode) { case MODE_SET: { int preset; if (mQuality == PRESET_INSANE) { preset = INSANE; } else if (mRoutine == ROUTINE_FAST) { if (mQuality == PRESET_EXTREME) { preset = EXTREME_FAST; } else if (mQuality == PRESET_STANDARD) { preset = STANDARD_FAST; } else { preset = 1007; // Not defined until 3.96 } } else { if (mQuality == PRESET_EXTREME) { preset = EXTREME; } else if (mQuality == PRESET_STANDARD) { preset = STANDARD; } else { preset = 1006; // Not defined until 3.96 } } lame_set_preset(mGF, preset); } break; case MODE_VBR: lame_set_VBR(mGF, (mRoutine == ROUTINE_STANDARD ? vbr_rh : vbr_mtrh )); lame_set_VBR_q(mGF, mQuality); break; case MODE_ABR: lame_set_preset(mGF, mBitrate ); break; default: lame_set_VBR(mGF, vbr_off); lame_set_brate(mGF, mBitrate); break; } // Set the channel mode MPEG_mode mode; if (channels == 1 || mChannel == CHANNEL_MONO) { mode = MONO; } else if (mChannel == CHANNEL_JOINT) { mode = JOINT_STEREO; } else { mode = STEREO; } lame_set_mode(mGF, mode); int rc = lame_init_params(mGF); if (rc < 0) { return rc; } #if 0 dump_config(mGF); #endif mInfoTagLen = 0; mEncoding = true; return mSamplesPerChunk; } int MP3Exporter::GetOutBufferSize() { if (!mEncoding) return -1; return mOutBufferSize; } int MP3Exporter::EncodeBuffer(short int inbuffer[], unsigned char outbuffer[]) { if (!mEncoding) { return -1; } return lame_encode_buffer_interleaved(mGF, inbuffer, mSamplesPerChunk, outbuffer, mOutBufferSize); } int MP3Exporter::EncodeRemainder(short int inbuffer[], int nSamples, unsigned char outbuffer[]) { if (!mEncoding) { return -1; } return lame_encode_buffer_interleaved(mGF, inbuffer, nSamples, outbuffer, mOutBufferSize); } int MP3Exporter::EncodeBufferMono(short int inbuffer[], unsigned char outbuffer[]) { if (!mEncoding) { return -1; } return lame_encode_buffer(mGF, inbuffer,inbuffer, mSamplesPerChunk, outbuffer, mOutBufferSize); } int MP3Exporter::EncodeRemainderMono(short int inbuffer[], int nSamples, unsigned char outbuffer[]) { if (!mEncoding) { return -1; } return lame_encode_buffer(mGF, inbuffer, inbuffer, nSamples, outbuffer, mOutBufferSize); } int MP3Exporter::FinishStream(unsigned char outbuffer[]) { if (!mEncoding) { return -1; } mEncoding = false; int result = lame_encode_flush(mGF, outbuffer, mOutBufferSize); #if defined(DISABLE_DYNAMIC_LOADING_LAME) mInfoTagLen = lame_get_lametag_frame(mGF, mInfoTagBuf, sizeof(mInfoTagBuf)); #else if (lame_get_lametag_frame) { mInfoTagLen = lame_get_lametag_frame(mGF, mInfoTagBuf, sizeof(mInfoTagBuf)); } #endif return result; } void MP3Exporter::CancelEncoding() { mEncoding = false; } void MP3Exporter::PutInfoTag(wxFFile & f, wxFileOffset off) { if (mGF) { if (mInfoTagLen > 0) { // FIXME: TRAP_ERR Seek and writ ein MP3 exporter could fail. f.Seek(off, wxFromStart); f.Write(mInfoTagBuf, mInfoTagLen); } #if defined(__WXMSW__) else if (beWriteInfoTag) { f.Flush(); beWriteInfoTag(mGF, OSOUTPUT(f.GetName())); mGF = NULL; } #endif else if (lame_mp3_tags_fid != NULL) { lame_mp3_tags_fid(mGF, f.fp()); } } f.SeekEnd(); } #if defined(__WXMSW__) /* values for Windows */ wxString MP3Exporter::GetLibraryPath() { wxRegKey reg(wxT("HKEY_LOCAL_MACHINE\\Software\\Lame for Audacity")); wxString path; if (reg.Exists()) { wxLogMessage(wxT("LAME registry key exists.")); reg.QueryValue(wxT("InstallPath"), path); } else { wxLogMessage(wxT("LAME registry key does not exist.")); } wxLogMessage(wxT("Library path is: ") + path); return path; } wxString MP3Exporter::GetLibraryName() { return wxT("lame_enc.dll"); } wxString MP3Exporter::GetLibraryTypeString() { return _("Only lame_enc.dll|lame_enc.dll|Dynamically Linked Libraries (*.dll)|*.dll|All Files|*"); } #elif defined(__WXMAC__) /* values for Mac OS X */ wxString MP3Exporter::GetLibraryPath() { return wxT("/usr/local/lib/audacity"); } wxString MP3Exporter::GetLibraryName() { return wxT("libmp3lame.dylib"); } wxString MP3Exporter::GetLibraryTypeString() { return wxString(_("Only libmp3lame.dylib|libmp3lame.dylib|Dynamic Libraries (*.dylib)|*.dylib|All Files (*)|*")); } #else //!__WXMAC__ /* Values for Linux / Unix systems */ wxString MP3Exporter::GetLibraryPath() { return wxT(LIBDIR); } wxString MP3Exporter::GetLibraryName() { return wxT("libmp3lame.so.0"); } wxString MP3Exporter::GetLibraryTypeString() { return wxString(_("Only libmp3lame.so.0|libmp3lame.so.0|Primary Shared Object files (*.so)|*.so|Extended Libraries (*.so*)|*.so*|All Files (*)|*")); } #endif #if 0 // Debug routine from BladeMP3EncDLL.c in the libmp3lame distro static void dump_config( lame_global_flags* gfp ) { wxPrintf(wxT("\n\nLame_enc configuration options:\n")); wxPrintf(wxT("==========================================================\n")); wxPrintf(wxT("version =%d\n"),lame_get_version( gfp ) ); wxPrintf(wxT("Layer =3\n")); wxPrintf(wxT("mode =")); switch ( lame_get_mode( gfp ) ) { case STEREO: wxPrintf(wxT( "Stereo\n" )); break; case JOINT_STEREO: wxPrintf(wxT( "Joint-Stereo\n" )); break; case DUAL_CHANNEL: wxPrintf(wxT( "Forced Stereo\n" )); break; case MONO: wxPrintf(wxT( "Mono\n" )); break; case NOT_SET: /* FALLTROUGH */ default: wxPrintf(wxT( "Error (unknown)\n" )); break; } wxPrintf(wxT("Input sample rate =%.1f kHz\n"), lame_get_in_samplerate( gfp ) /1000.0 ); wxPrintf(wxT("Output sample rate =%.1f kHz\n"), lame_get_out_samplerate( gfp ) /1000.0 ); wxPrintf(wxT("bitrate =%d kbps\n"), lame_get_brate( gfp ) ); wxPrintf(wxT("Quality Setting =%d\n"), lame_get_quality( gfp ) ); wxPrintf(wxT("Low pass frequency =%d\n"), lame_get_lowpassfreq( gfp ) ); wxPrintf(wxT("Low pass width =%d\n"), lame_get_lowpasswidth( gfp ) ); wxPrintf(wxT("High pass frequency =%d\n"), lame_get_highpassfreq( gfp ) ); wxPrintf(wxT("High pass width =%d\n"), lame_get_highpasswidth( gfp ) ); wxPrintf(wxT("No short blocks =%d\n"), lame_get_no_short_blocks( gfp ) ); wxPrintf(wxT("Force short blocks =%d\n"), lame_get_force_short_blocks( gfp ) ); wxPrintf(wxT("de-emphasis =%d\n"), lame_get_emphasis( gfp ) ); wxPrintf(wxT("private flag =%d\n"), lame_get_extension( gfp ) ); wxPrintf(wxT("copyright flag =%d\n"), lame_get_copyright( gfp ) ); wxPrintf(wxT("original flag =%d\n"), lame_get_original( gfp ) ); wxPrintf(wxT("CRC =%s\n"), lame_get_error_protection( gfp ) ? wxT("on") : wxT("off") ); wxPrintf(wxT("Fast mode =%s\n"), ( lame_get_quality( gfp ) )? wxT("enabled") : wxT("disabled") ); wxPrintf(wxT("Force mid/side stereo =%s\n"), ( lame_get_force_ms( gfp ) )?wxT("enabled"):wxT("disabled") ); wxPrintf(wxT("Padding Type =%d\n"), (int) lame_get_padding_type( gfp ) ); wxPrintf(wxT("Disable Reservoir =%d\n"), lame_get_disable_reservoir( gfp ) ); wxPrintf(wxT("Allow diff-short =%d\n"), lame_get_allow_diff_short( gfp ) ); wxPrintf(wxT("Interchannel masking =%d\n"), lame_get_interChRatio( gfp ) ); // supposed to be a float, but in lib-src/lame/lame/lame.h it's int wxPrintf(wxT("Strict ISO Encoding =%s\n"), ( lame_get_strict_ISO( gfp ) ) ?wxT("Yes"):wxT("No")); wxPrintf(wxT("Scale =%5.2f\n"), lame_get_scale( gfp ) ); wxPrintf(wxT("VBR =%s, VBR_q =%d, VBR method ="), ( lame_get_VBR( gfp ) !=vbr_off ) ? wxT("enabled"): wxT("disabled"), lame_get_VBR_q( gfp ) ); switch ( lame_get_VBR( gfp ) ) { case vbr_off: wxPrintf(wxT( "vbr_off\n" )); break; case vbr_mt : wxPrintf(wxT( "vbr_mt \n" )); break; case vbr_rh : wxPrintf(wxT( "vbr_rh \n" )); break; case vbr_mtrh: wxPrintf(wxT( "vbr_mtrh \n" )); break; case vbr_abr: wxPrintf(wxT( "vbr_abr (average bitrate %d kbps)\n"), lame_get_VBR_mean_bitrate_kbps( gfp ) ); break; default: wxPrintf(wxT("error, unknown VBR setting\n")); break; } wxPrintf(wxT("Vbr Min bitrate =%d kbps\n"), lame_get_VBR_min_bitrate_kbps( gfp ) ); wxPrintf(wxT("Vbr Max bitrate =%d kbps\n"), lame_get_VBR_max_bitrate_kbps( gfp ) ); wxPrintf(wxT("Write VBR Header =%s\n"), ( lame_get_bWriteVbrTag( gfp ) ) ?wxT("Yes"):wxT("No")); wxPrintf(wxT("VBR Hard min =%d\n"), lame_get_VBR_hard_min( gfp ) ); wxPrintf(wxT("ATH Only =%d\n"), lame_get_ATHonly( gfp ) ); wxPrintf(wxT("ATH short =%d\n"), lame_get_ATHshort( gfp ) ); wxPrintf(wxT("ATH no =%d\n"), lame_get_noATH( gfp ) ); wxPrintf(wxT("ATH type =%d\n"), lame_get_ATHtype( gfp ) ); wxPrintf(wxT("ATH lower =%f\n"), lame_get_ATHlower( gfp ) ); wxPrintf(wxT("ATH aa =%d\n"), lame_get_athaa_type( gfp ) ); wxPrintf(wxT("ATH aa loudapprox =%d\n"), lame_get_athaa_loudapprox( gfp ) ); wxPrintf(wxT("ATH aa sensitivity =%f\n"), lame_get_athaa_sensitivity( gfp ) ); wxPrintf(wxT("Experimental nspsytune =%d\n"), lame_get_exp_nspsytune( gfp ) ); wxPrintf(wxT("Experimental X =%d\n"), lame_get_experimentalX( gfp ) ); wxPrintf(wxT("Experimental Y =%d\n"), lame_get_experimentalY( gfp ) ); wxPrintf(wxT("Experimental Z =%d\n"), lame_get_experimentalZ( gfp ) ); } #endif //---------------------------------------------------------------------------- // ExportMP3 //---------------------------------------------------------------------------- class ExportMP3 final : public ExportPlugin { public: ExportMP3(); bool CheckFileName(wxFileName & filename, int format); // Required wxWindow *OptionsCreate(wxWindow *parent, int format); int Export(AudacityProject *project, int channels, const wxString &fName, bool selectedOnly, double t0, double t1, MixerSpec *mixerSpec = NULL, const Tags *metadata = NULL, int subformat = 0) override; private: int FindValue(CHOICES *choices, int cnt, int needle, int def); wxString FindName(CHOICES *choices, int cnt, int needle); int AskResample(int bitrate, int rate, int lowrate, int highrate); int AddTags(AudacityProject *project, char **buffer, bool *endOfFile, const Tags *tags); #ifdef USE_LIBID3TAG void AddFrame(struct id3_tag *tp, const wxString & n, const wxString & v, const char *name); #endif int SetNumExportChannels() override; }; ExportMP3::ExportMP3() : ExportPlugin() { InitMP3_Statics(); AddFormat(); SetFormat(wxT("MP3"),0); AddExtension(wxT("mp3"),0); SetMaxChannels(2,0); SetCanMetaData(true,0); SetDescription(_("MP3 Files"),0); } bool ExportMP3::CheckFileName(wxFileName & WXUNUSED(filename), int WXUNUSED(format)) { #ifndef DISABLE_DYNAMIC_LOADING_LAME MP3Exporter exporter; if (!exporter.LoadLibrary(wxTheApp->GetTopWindow(), MP3Exporter::Maybe)) { wxMessageBox(_("Could not open MP3 encoding library!")); gPrefs->Write(wxT("/MP3/MP3LibPath"), wxString(wxT(""))); gPrefs->Flush(); return false; } #endif // DISABLE_DYNAMIC_LOADING_LAME return true; } int ExportMP3::SetNumExportChannels() { bool mono; gPrefs->Read(wxT("/FileFormats/MP3ForceMono"), &mono, 0); return (mono)? 1 : -1; } int ExportMP3::Export(AudacityProject *project, int channels, const wxString &fName, bool selectionOnly, double t0, double t1, MixerSpec *mixerSpec, const Tags *metadata, int WXUNUSED(subformat)) { int rate = lrint(project->GetRate()); #ifndef DISABLE_DYNAMIC_LOADING_LAME wxWindow *parent = project; #endif // DISABLE_DYNAMIC_LOADING_LAME const TrackList *tracks = project->GetTracks(); MP3Exporter exporter; #ifdef DISABLE_DYNAMIC_LOADING_LAME if (!exporter.InitLibrary(wxT(""))) { wxMessageBox(_("Could not initialize MP3 encoding library!")); gPrefs->Write(wxT("/MP3/MP3LibPath"), wxString(wxT(""))); gPrefs->Flush(); return false; } #else if (!exporter.LoadLibrary(parent, MP3Exporter::Maybe)) { wxMessageBox(_("Could not open MP3 encoding library!")); gPrefs->Write(wxT("/MP3/MP3LibPath"), wxString(wxT(""))); gPrefs->Flush(); return false; } if (!exporter.ValidLibraryLoaded()) { wxMessageBox(_("Not a valid or supported MP3 encoding library!")); gPrefs->Write(wxT("/MP3/MP3LibPath"), wxString(wxT(""))); gPrefs->Flush(); return false; } #endif // DISABLE_DYNAMIC_LOADING_LAME // Retrieve preferences int highrate = 48000; int lowrate = 8000; int bitrate = 0; int brate; int rmode; int vmode; int cmode; bool forceMono; gPrefs->Read(wxT("/FileFormats/MP3Bitrate"), &brate, 128); gPrefs->Read(wxT("/FileFormats/MP3RateMode"), &rmode, MODE_CBR); gPrefs->Read(wxT("/FileFormats/MP3VarMode"), &vmode, ROUTINE_FAST); gPrefs->Read(wxT("/FileFormats/MP3ChannelMode"), &cmode, CHANNEL_STEREO); gPrefs->Read(wxT("/FileFormats/MP3ForceMono"), &forceMono, 0); // Set the bitrate/quality and mode if (rmode == MODE_SET) { int q = FindValue(setRates, WXSIZEOF(setRates), brate, PRESET_STANDARD); int r = FindValue(varModes, WXSIZEOF(varModes), vmode, ROUTINE_FAST); exporter.SetMode(MODE_SET); exporter.SetQuality(q, r); } else if (rmode == MODE_VBR) { int q = FindValue(varRates, WXSIZEOF(varRates), brate, QUALITY_2); int r = FindValue(varModes, WXSIZEOF(varModes), vmode, ROUTINE_FAST); exporter.SetMode(MODE_VBR); exporter.SetQuality(q, r); } else if (rmode == MODE_ABR) { bitrate = FindValue(fixRates, WXSIZEOF(fixRates), brate, 128); exporter.SetMode(MODE_ABR); exporter.SetBitrate(bitrate); if (bitrate > 160) { lowrate = 32000; } else if (bitrate < 32 || bitrate == 144) { highrate = 24000; } } else { bitrate = FindValue(fixRates, WXSIZEOF(fixRates), brate, 128); exporter.SetMode(MODE_CBR); exporter.SetBitrate(bitrate); if (bitrate > 160) { lowrate = 32000; } else if (bitrate < 32 || bitrate == 144) { highrate = 24000; } } // Verify sample rate if (FindName(sampRates, WXSIZEOF(sampRates), rate).IsEmpty() || (rate < lowrate) || (rate > highrate)) { rate = AskResample(bitrate, rate, lowrate, highrate); if (rate == 0) { return false; } } // Set the channel mode if (forceMono) { exporter.SetChannel(CHANNEL_MONO); } else if (cmode == CHANNEL_JOINT) { exporter.SetChannel(CHANNEL_JOINT); } else { exporter.SetChannel(CHANNEL_STEREO); } auto inSamples = exporter.InitializeStream(channels, rate); if (((int)inSamples) < 0) { wxMessageBox(_("Unable to initialize MP3 stream")); return false; } // Put ID3 tags at beginning of file if (metadata == NULL) metadata = project->GetTags(); // Open file for writing wxFFile outFile(fName, wxT("w+b")); if (!outFile.IsOpened()) { wxMessageBox(_("Unable to open target file for writing")); return false; } char *id3buffer = NULL; int id3len; bool endOfFile; id3len = AddTags(project, &id3buffer, &endOfFile, metadata); if (id3len && !endOfFile) { outFile.Write(id3buffer, id3len); } wxFileOffset pos = outFile.Tell(); int updateResult = eProgressSuccess; long bytes; int bufferSize = exporter.GetOutBufferSize(); unsigned char *buffer = new unsigned char[bufferSize]; wxASSERT(buffer); const WaveTrackConstArray waveTracks = tracks->GetWaveTrackConstArray(selectionOnly, false); { auto mixer = CreateMixer(waveTracks, tracks->GetTimeTrack(), t0, t1, channels, inSamples, true, rate, int16Sample, true, mixerSpec); wxString title; if (rmode == MODE_SET) { title.Printf(selectionOnly ? _("Exporting selected audio with %s preset") : _("Exporting entire file with %s preset"), FindName(setRates, WXSIZEOF(setRates), brate).c_str()); } else if (rmode == MODE_VBR) { title.Printf(selectionOnly ? _("Exporting selected audio with VBR quality %s") : _("Exporting entire file with VBR quality %s"), FindName(varRates, WXSIZEOF(varRates), brate).c_str()); } else { title.Printf(selectionOnly ? _("Exporting selected audio at %d Kbps") : _("Exporting entire file at %d Kbps"), brate); } ProgressDialog progress(wxFileName(fName).GetName(), title); while (updateResult == eProgressSuccess) { auto blockLen = mixer->Process(inSamples); if (blockLen == 0) { break; } short *mixed = (short *)mixer->GetBuffer(); if (blockLen < inSamples) { if (channels > 1) { bytes = exporter.EncodeRemainder(mixed, blockLen, buffer); } else { bytes = exporter.EncodeRemainderMono(mixed, blockLen, buffer); } } else { if (channels > 1) { bytes = exporter.EncodeBuffer(mixed, buffer); } else { bytes = exporter.EncodeBufferMono(mixed, buffer); } } if (bytes < 0) { wxString msg; msg.Printf(_("Error %ld returned from MP3 encoder"), bytes); wxMessageBox(msg); break; } outFile.Write(buffer, bytes); updateResult = progress.Update(mixer->MixGetCurrentTime() - t0, t1 - t0); } } bytes = exporter.FinishStream(buffer); if (bytes) { outFile.Write(buffer, bytes); } // Write ID3 tag if it was supposed to be at the end of the file if (id3len && endOfFile) { outFile.Write(id3buffer, id3len); } if (id3buffer) { free(id3buffer); } // Always write the info (Xing/Lame) tag. Until we stop supporting Lame // versions before 3.98, we must do this after the MP3 file has been // closed. // // Also, if beWriteInfoTag() is used, mGF will no longer be valid after // this call, so do not use it. exporter.PutInfoTag(outFile, pos); // Close the file outFile.Close(); delete [] buffer; return updateResult; } wxWindow *ExportMP3::OptionsCreate(wxWindow *parent, int format) { wxASSERT(parent); // to justify safenew return safenew ExportMP3Options(parent, format); } int ExportMP3::FindValue(CHOICES *choices, int cnt, int needle, int def) { for (int i = 0; i < cnt; i++) { if (choices[i].label == needle) { return needle; } } return def; } wxString ExportMP3::FindName(CHOICES *choices, int cnt, int needle) { for (int i = 0; i < cnt; i++) { if (choices[i].label == needle) { return choices[i].name.BeforeFirst(wxT(',')); } } return wxT(""); } int ExportMP3::AskResample(int bitrate, int rate, int lowrate, int highrate) { wxDialogWrapper d(nullptr, wxID_ANY, wxString(_("Invalid sample rate"))); d.SetName(d.GetTitle()); wxChoice *choice; ShuttleGui S(&d, eIsCreating); wxString text; S.StartVerticalLay(); { S.SetBorder(10); S.StartStatic(_("Resample")); { S.StartHorizontalLay(wxALIGN_CENTER, false); { if (bitrate == 0) { text.Printf(_("The project sample rate (%d) is not supported by the MP3\nfile format. "), rate); } else { text.Printf(_("The project sample rate (%d) and bit rate (%d kbps) combination is not\nsupported by the MP3 file format. "), rate, bitrate); } text += _("You may resample to one of the rates below."); S.AddTitle(text); } S.EndHorizontalLay(); wxArrayString choices; wxString selected = wxT(""); for (size_t i = 0; i < WXSIZEOF(sampRates); i++) { int label = sampRates[i].label; if (label >= lowrate && label <= highrate) { choices.Add(sampRates[i].name); if (label <= rate) { selected = sampRates[i].name; } } } if (selected.IsEmpty()) { selected = choices[0]; } S.StartHorizontalLay(wxALIGN_CENTER, false); { choice = S.AddChoice(_("Sample Rates"), selected, &choices); } S.EndHorizontalLay(); } S.EndStatic(); S.AddStandardButtons(); } S.EndVerticalLay(); d.Layout(); d.Fit(); d.SetMinSize(d.GetSize()); d.Center(); if (d.ShowModal() == wxID_CANCEL) { return 0; } return wxAtoi(choice->GetStringSelection()); } // returns buffer len; caller frees int ExportMP3::AddTags(AudacityProject *WXUNUSED(project), char **buffer, bool *endOfFile, const Tags *tags) { #ifdef USE_LIBID3TAG struct id3_tag *tp = id3_tag_new(); for (const auto &pair : tags->GetRange()) { const auto &n = pair.first; const auto &v = pair.second; const char *name = "TXXX"; if (n.CmpNoCase(TAG_TITLE) == 0) { name = ID3_FRAME_TITLE; } else if (n.CmpNoCase(TAG_ARTIST) == 0) { name = ID3_FRAME_ARTIST; } else if (n.CmpNoCase(TAG_ALBUM) == 0) { name = ID3_FRAME_ALBUM; } else if (n.CmpNoCase(TAG_YEAR) == 0) { // LLL: Some apps do not like the newer frame ID (ID3_FRAME_YEAR), // so we add old one as well. AddFrame(tp, n, v, "TYER"); name = ID3_FRAME_YEAR; } else if (n.CmpNoCase(TAG_GENRE) == 0) { name = ID3_FRAME_GENRE; } else if (n.CmpNoCase(TAG_COMMENTS) == 0) { name = ID3_FRAME_COMMENT; } else if (n.CmpNoCase(TAG_TRACK) == 0) { name = ID3_FRAME_TRACK; } AddFrame(tp, n, v, name); } tp->options &= (~ID3_TAG_OPTION_COMPRESSION); // No compression // If this version of libid3tag supports it, use v2.3 ID3 // tags instead of the newer, but less well supported, v2.4 // that libid3tag uses by default. #ifdef ID3_TAG_HAS_TAG_OPTION_ID3V2_3 tp->options |= ID3_TAG_OPTION_ID3V2_3; #endif *endOfFile = false; id3_length_t len; len = id3_tag_render(tp, 0); *buffer = (char *)malloc(len); len = id3_tag_render(tp, (id3_byte_t *)*buffer); id3_tag_delete(tp); return len; #else //ifdef USE_LIBID3TAG return 0; #endif } #ifdef USE_LIBID3TAG void ExportMP3::AddFrame(struct id3_tag *tp, const wxString & n, const wxString & v, const char *name) { struct id3_frame *frame = id3_frame_new(name); if (!n.IsAscii() || !v.IsAscii()) { id3_field_settextencoding(id3_frame_field(frame, 0), ID3_FIELD_TEXTENCODING_UTF_16); } else { id3_field_settextencoding(id3_frame_field(frame, 0), ID3_FIELD_TEXTENCODING_ISO_8859_1); } id3_ucs4_t *ucs4 = id3_utf8_ucs4duplicate((id3_utf8_t *) (const char *) v.mb_str(wxConvUTF8)); if (strcmp(name, ID3_FRAME_COMMENT) == 0) { // A hack to get around iTunes not recognizing the comment. The // language defaults to XXX and, since it's not a valid language, // iTunes just ignores the tag. So, either set it to a valid language // (which one???) or just clear it. Unfortunately, there's no supported // way of clearing the field, so do it directly. struct id3_frame *frame2 = id3_frame_new(name); id3_field_setfullstring(id3_frame_field(frame2, 3), ucs4); id3_field *f2 = id3_frame_field(frame2, 1); memset(f2->immediate.value, 0, sizeof(f2->immediate.value)); id3_tag_attachframe(tp, frame2); // Now install a second frame with the standard default language = "XXX" id3_field_setfullstring(id3_frame_field(frame, 3), ucs4); } else if (strcmp(name, "TXXX") == 0) { id3_field_setstring(id3_frame_field(frame, 2), ucs4); free(ucs4); ucs4 = id3_utf8_ucs4duplicate((id3_utf8_t *) (const char *) n.mb_str(wxConvUTF8)); id3_field_setstring(id3_frame_field(frame, 1), ucs4); } else { id3_field_setstrings(id3_frame_field(frame, 1), 1, &ucs4); } free(ucs4); id3_tag_attachframe(tp, frame); } #endif movable_ptr<ExportPlugin> New_ExportMP3() { return make_movable<ExportMP3>(); } //---------------------------------------------------------------------------- // Return library version //---------------------------------------------------------------------------- wxString GetMP3Version(wxWindow *parent, bool prompt) { MP3Exporter exporter; wxString versionString = _("MP3 export library not found"); #ifndef DISABLE_DYNAMIC_LOADING_LAME if (prompt) { exporter.FindLibrary(parent); } if (exporter.LoadLibrary(parent, prompt ? MP3Exporter::Yes : MP3Exporter::No)) { #endif // DISABLE_DYNAMIC_LOADING_LAME versionString = exporter.GetLibraryVersion(); #ifndef DISABLE_DYNAMIC_LOADING_LAME } #endif // DISABLE_DYNAMIC_LOADING_LAME return versionString; }
#include "editor_ui_factory.h" #include "halley/core/resources/resources.h" #include <halley/file_formats/config_file.h> #include "scroll_background.h" #include "select_asset_widget.h" #include "src/assets/animation_editor.h" #include "src/assets/asset_editor_window.h" #include "src/assets/metadata_editor.h" #include "src/scene/entity_editor.h" #include "src/scene/entity_list.h" #include "src/scene/scene_editor_canvas.h" using namespace Halley; EditorUIFactory::EditorUIFactory(const HalleyAPI& api, Resources& resources, I18N& i18n, const String& colourSchemeName) : UIFactory(api, resources, i18n) { loadColourSchemes(); setColourScheme(colourSchemeName); UIInputButtons listButtons; setInputButtons("list", listButtons); addFactory("scrollBackground", [=] (const ConfigNode& node) { return makeScrollBackground(node); }); addFactory("animationEditorDisplay", [=] (const ConfigNode& node) { return makeAnimationEditorDisplay(node); }); addFactory("metadataEditor", [=] (const ConfigNode& node) { return makeMetadataEditor(node); }); addFactory("sceneEditorCanvas", [=](const ConfigNode& node) { return makeSceneEditorCanvas(node); }); addFactory("entityList", [=](const ConfigNode& node) { return makeEntityList(node); }); addFactory("entityEditor", [=](const ConfigNode& node) { return makeEntityEditor(node); }); addFactory("selectAsset", [=](const ConfigNode& node) { return makeSelectAsset(node); }); } Sprite EditorUIFactory::makeAssetTypeIcon(AssetType type) const { return Sprite() .setImage(getResources(), Path("ui") / "assetTypes" / toString(type) + ".png") .setColour(colourScheme->getColour("icon_" + toString(type))); } Sprite EditorUIFactory::makeImportAssetTypeIcon(ImportAssetType type) const { return Sprite() .setImage(getResources(), Path("ui") / "assetTypes" / toString(type) + ".png") .setColour(colourScheme->getColour("icon_" + toString(type))); } Sprite EditorUIFactory::makeDirectoryIcon(bool up) const { return Sprite() .setImage(getResources(), Path("ui") / "assetTypes" / (up ? "directoryUp" : "directory") + ".png") .setColour(colourScheme->getColour("icon_directory")); } std::shared_ptr<UIWidget> EditorUIFactory::makeScrollBackground(const ConfigNode& entryNode) { return std::make_shared<ScrollBackground>("scrollBackground", resources, makeSizerOrDefault(entryNode, UISizer(UISizerType::Vertical)), getColourScheme()->getColour("scrollBackground")); } std::shared_ptr<UIWidget> EditorUIFactory::makeAnimationEditorDisplay(const ConfigNode& entryNode) { auto& node = entryNode["widget"]; auto id = node["id"].asString(); return std::make_shared<AnimationEditorDisplay>(id, resources); } std::shared_ptr<UIWidget> EditorUIFactory::makeMetadataEditor(const ConfigNode& entryNode) { return std::make_shared<MetadataEditor>(*this); } std::shared_ptr<UIWidget> EditorUIFactory::makeSceneEditorCanvas(const ConfigNode& entryNode) { auto& node = entryNode["widget"]; auto id = node["id"].asString(); return std::make_shared<SceneEditorCanvas>(id, *this, resources, api, makeSizer(entryNode)); } std::shared_ptr<UIWidget> EditorUIFactory::makeEntityList(const ConfigNode& entryNode) { auto& node = entryNode["widget"]; auto id = node["id"].asString(); return std::make_shared<EntityList>(id, *this); } std::shared_ptr<UIWidget> EditorUIFactory::makeEntityEditor(const ConfigNode& entryNode) { auto& node = entryNode["widget"]; auto id = node["id"].asString(); return std::make_shared<EntityEditor>(id, *this); } std::shared_ptr<UIWidget> EditorUIFactory::makeSelectAsset(const ConfigNode& entryNode) { auto& node = entryNode["widget"]; auto id = node["id"].asString(); return std::make_shared<SelectAssetWidget>(id, *this, fromString<AssetType>(node["assetType"].asString())); } void EditorUIFactory::loadColourSchemes() { for (const auto& assetId: resources.enumerate<ConfigFile>()) { if (assetId.startsWith("colour_schemes/")) { auto scheme = std::make_shared<UIColourScheme>(resources.get<ConfigFile>(assetId)->getRoot(), resources); if (scheme->isEnabled()) { colourSchemes.push_back(scheme); } } } } std::vector<String> EditorUIFactory::getColourSchemeNames() const { std::vector<String> result; for (auto& scheme: colourSchemes) { result.push_back(scheme->getName()); } std::sort(result.begin(), result.end()); return result; } void EditorUIFactory::setColourScheme(const String& name) { bool found = false; for (auto& scheme: colourSchemes) { if (scheme->getName() == name) { colourScheme = scheme; found = true; break; } } if (!found && !colourSchemes.empty()) { colourScheme = colourSchemes.front(); found = true; } if (found) { reloadStyleSheet(); } } void EditorUIFactory::reloadStyleSheet() { const auto cur = getStyleSheet(); if (true || !cur) { auto styleSheet = std::make_shared<UIStyleSheet>(resources); for (auto& style: resources.enumerate<ConfigFile>()) { if (style.startsWith("ui_style/")) { styleSheet->load(*resources.get<ConfigFile>(style), colourScheme); } } setStyleSheet(std::move(styleSheet)); } else { // This doesn't work properly atm cur->reload(colourScheme); } }
// Benchmark for integer sorting speed across parallel threads. // // Copyright Steven Ross 2014 // // 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) // See http://www.boost.org/libs/sort for library home page. #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_int_distribution.hpp> #include <boost/sort/spreadsort/spreadsort.hpp> #include <boost/thread.hpp> #include <time.h> #include <stdio.h> #include <stdlib.h> #include <algorithm> #include <vector> #include <iostream> #include <fstream> #include <string> using std::string; using namespace boost::sort::spreadsort; #define DATA_TYPE string static bool is_sorted(const std::vector<DATA_TYPE> &array) { for (unsigned u = 0; u + 1 < array.size(); ++u) { if (array[u] > array[u + 1]) { return false; } } return true; } static void sort_core(std::vector<DATA_TYPE> &array, bool stdSort, unsigned loopCount) { if (stdSort) std::sort(array.begin(), array.end()); else boost::sort::spreadsort::spreadsort(array.begin(), array.end()); if (!is_sorted(array)) { fprintf(stderr, "sort failed!\n"); exit(1); } } static void sort_loop(const std::vector<DATA_TYPE> &base_array, bool stdSort, unsigned loopCount) { std::vector<DATA_TYPE> array(base_array); for (unsigned u = 0; u < loopCount; ++u) { for (unsigned v = 0; v < base_array.size(); ++v) { array[v] = base_array[v]; } sort_core(array, stdSort, loopCount); } } //Pass in an argument to test std::sort int main(int argc, const char ** argv) { std::ifstream indata; std::ofstream outfile; bool stdSort = false; int constant_to_random_ratio = -1; int threadCount = -1; unsigned loopCount = 0; for (int u = 1; u < argc; ++u) { if (std::string(argv[u]) == "-std") stdSort = true; else if(threadCount < 0) threadCount = atoi(argv[u]); else if (!loopCount) loopCount = atoi(argv[u]); else constant_to_random_ratio = atoi(argv[u]); } if (!loopCount) { loopCount = 1; } printf("threads: %d loops: %d\n", threadCount, loopCount); std::vector<DATA_TYPE> base_array; if (constant_to_random_ratio >= 0) { //Test for random data with gaps of identical data. random::mt19937 generator; random::uniform_int_distribution<int> distribution(0,255); const int constant_to_random_count = 1000000; const int string_length = 1000; for (int i = 0; i < constant_to_random_count; ++i) { DATA_TYPE temp(string_length, 'x'); // fill with default character. for (int j = constant_to_random_ratio; j < string_length;) { int val = distribution(generator); temp[j] = val; j += (val * constant_to_random_ratio)/128 + 1; } base_array.push_back(temp); } } else { indata.open("input.txt", std::ios_base::in | std::ios_base::binary); if (indata.bad()) { printf("input.txt could not be opened\n"); return 1; } DATA_TYPE inval; while (!indata.eof() ) { indata >> inval; base_array.push_back(inval); } } // Sort the input clock_t start, end; double elapsed; std::vector<boost::thread *> workers; start = clock(); if (threadCount == 0) { if (loopCount > 1) { sort_loop(base_array, stdSort, loopCount); } else { sort_core(base_array, stdSort, loopCount); } threadCount = 1; } else { for (int i = 0; i < threadCount; ++i) { workers.push_back(new boost::thread(sort_loop, base_array, stdSort, loopCount)); } for (int i = 0; i < threadCount; ++i) { workers[i]->join(); delete workers[i]; } } end = clock(); elapsed = static_cast<double>(end - start) ; printf("for %lu strings\n", base_array.size()); if (stdSort) printf("std::sort clock time %lf\n", elapsed/CLOCKS_PER_SEC/threadCount); else printf("spreadsort clock time %lf\n", elapsed/CLOCKS_PER_SEC/threadCount); return 0; }
class Solution { public: int fib(int n) { //声明n+1+1大小的vector(第一个+1是要存储0至n共n+1个数据;第二个+1是考虑n==0的情况,保证v[1]不越界) vector<int> v(n + 1 + 1, 0); v[1] = 1; for(int i = 2; i <= n; i++) v[i] = (v[i - 1] + v[i - 2]) % 1000000007;//注意别忘记取余 return v[n];//直接返回最后一个数,即最终结果 } };
// MIT License // // Copyright (c) 2020 Mechatronics and Haptic Interfaces Lab - Rice University // // 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. // // Author(s): Evan Pezent (epezent@rice.edu) #define MAHI_GUI_NO_CONSOLE #include <Mahi/Gui.hpp> #include <Mahi/Util.hpp> #include <fstream> #if defined(__linux__) #include <experimental/filesystem> namespace fs = std::experimental::filesystem; #else #include <filesystem> namespace fs = std::filesystem; #endif using namespace mahi::gui; using namespace mahi::util; /// Basic Likert survey application class Likert : public Application { public: enum Gender { NoGender, Male, Female }; enum Response { NoResponse = -3, StronglyDisagree = -2, Disagree = -1, Neutral = 0, Agree = 1, StronglyAgree = 2 }; /// Constructor Likert() : Application(500,500,"",false) { ImGui::DisableViewports(); loaded = load(); } /// GUI code void update() override { ImGui::BeginFixed("##Likert", ImGui::GetMainViewport()->Pos, {width, height}, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings); if (loaded) { // Subject Info ImGui::SetNextItemWidth(100); ImGui::InputText("Subject ", &subject); ImGui::SameLine(); ImGui::SetNextItemWidth(50); if (ImGui::BeginCombo("Age ", age != -1 ? std::to_string(age).c_str() : "")) { for (int i = 0; i < 100; ++i) { if (ImGui::Selectable(std::to_string(i).c_str(), i == age)) age = i; if (age == i) ImGui::SetItemDefaultFocus(); } ImGui::EndCombo(); } ImGui::SameLine(); if (ImGui::RadioButton("Male", sex == Male)) sex = Male; ImGui::SameLine(); if (ImGui::RadioButton("Female", sex == Female)) sex = Female; ImGui::SameLine(); ImGui::SameLine(ImGui::GetWindowWidth() - 105); if (ImGui::ButtonColored("Submit", Reds::FireBrick, {100,0})) { bool result = saveResponse(); if (result && autoClose) quit(); } // Header ImGui::Separator(); ImGui::Separator(); ImGui::Text("\nQuestion"); ImGui::SameLine(qWidth - 20); ImGui::Text("Strongly\nDiagree"); ImGui::SameLine(qWidth + 65); ImGui::Text("\nDisagree"); ImGui::SameLine(qWidth + 145); ImGui::Text("\nNeutral"); ImGui::SameLine(qWidth + 230); ImGui::Text("\nAgree"); ImGui::SameLine(qWidth + 305); ImGui::Text("Strongly\n Agree"); // render questions float initialY = ImGui::GetCursorPos().y; for (unsigned int i = 0; i < questions.size(); ++i) { ImGui::PushID(i); ImGui::SetCursorPosY(initialY + rowHeight * i); ImGui::Separator(); ImGui::PushStyleVar(ImGuiStyleVar_Alpha, 0.5); ImGui::Text("[Q.%02d]",i+1); ImGui::PopStyleVar(); ImGui::SameLine(); ImGui::TextUnformatted(questions[i].c_str()); ImGui::SameLine(qWidth); if (ImGui::RadioButton("##SD",responses[i] == StronglyDisagree)) responses[i] = StronglyDisagree; ImGui::SameLine(qWidth+80); if (ImGui::RadioButton("##D",responses[i] == Disagree)) responses[i] = Disagree; ImGui::SameLine(qWidth+160); if (ImGui::RadioButton("##N",responses[i] == Neutral)) responses[i] = Neutral; ImGui::SameLine(qWidth+240); if (ImGui::RadioButton("##A",responses[i] == Agree)) responses[i] = Agree; ImGui::SameLine(qWidth+320); if (ImGui::RadioButton("##SA",responses[i] == StronglyAgree)) responses[i] = StronglyAgree; ImGui::PopID(); } // begin message modal if opened this frame bool dummy = true; if (ImGui::BeginPopupModal("Message", &dummy, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::TextUnformatted(message.c_str()); ImGui::EndPopup(); } } else { ImGui::Text("Likert survey failed to load! :("); } ImGui::End(); } /// Load in Likert config file bool load() { if (fs::exists("likert.json")) { try { std::ifstream file("likert.json"); json j; file >> j; title = j["title"].get<std::string>(); questions = j["questions"].get<std::vector<std::string>>(); autoClose = j["autoClose"].get<bool>(); rowHeight = j.count("rowHeight") > 0 ? j["rowHeight"].get<float>() : 30; for (auto& q : questions) qWidth = 7 * q.length() > qWidth ? 7 * q.length() : qWidth; qWidth += 75; width = qWidth + 385; height = 85 + rowHeight * questions.size(); responses = std::vector<Response>(questions.size(), NoResponse); set_window_title(title); set_window_size((int)width, (int)height); center_window(); } catch(...) { return false; } return true; } return false; } bool saveResponse() { // make sure subject has value if (subject == "") { message = "Please enter your subject identifier"; ImGui::OpenPopup("Message"); return false; } // make sure subject has age if (age == -1) { message = "Please enter your age"; ImGui::OpenPopup("Message"); return false; } if (sex == NoGender) { message = "Please enter your gender"; ImGui::OpenPopup("Message"); return false; } // make sure every question answered for (unsigned int i = 0; i < responses.size(); ++i) { if (responses[i] == NoResponse) { message = "Please respond to Question " + std::to_string(i+1); ImGui::OpenPopup("Message"); return false; } } // generate text responses std::vector<std::string> responsesText(responses.size()); static std::map<Response, std::string> responseMap = { {StronglyDisagree, "Strongly Disagree"}, {Disagree, "Disagree"}, {Neutral, "Neutral"}, {Agree, "Agree"}, {StronglyAgree, "Strongly Agree"} }; for (unsigned int i = 0; i < responses.size(); ++i) responsesText[i] = responseMap[responses[i]]; // save data json j; j["subject"] = subject; j["age"] = age; j["gender"] = (sex == Male ? "Male" : "Female"); j["responses"] = responses; j["responsesText"] = responsesText; std::ofstream file(subject + ".json"); if (file.is_open()) file << std::setw(4) << j << std::endl; // reset state subject = ""; sex = NoGender; age = -1; responses = std::vector<Response>(responses.size(), NoResponse); message = "Thank you for participating!"; ImGui::OpenPopup("Message"); return true; } std::string subject; ///< subject input text bool loaded = false; ///< was the Likert config loaded? std::string title; ///< survey title std::vector<std::string> questions; ///< survey questions std::vector<Response> responses; ///< survey responses Gender sex = NoGender; ///< is subject male? int age = -1; ///< subject age bool autoClose = false; ///< should the app close when the user submits a response? float width, height; ///< window width/height float qWidth, rowHeight;; ///< row width/height std::string message; ///< error message to dispaly }; int main(int argc, char const *argv[]) { // if there doesn't exist a "likert.json" file, make a default one if (!fs::exists("likert.json")) { json j; j["title"] = "My Likert Survey"; j["questions"] = {"Making GUIs with mahi-gui is easy", "I found it difficult to make GUIs with mahi-gui", "Jelly beans are the best candy", "Jelly beans are disgusting", "I like turtles", "Turtles are disappointing", "These questions are ridiculous", "These questions are thought provoking"}; j["autoClose"] = true; j["rowHeight"] = 30; std::ofstream file("likert.json"); if (file.is_open()) file << std::setw(4) << j; } // run the GUI Likert likert; likert.run(); return 0; }
#include "R3D/Water/ShallowWaterEngine/ShallowWaterEngine.h" namespace r3 { }
// (C) Copyright Gennadiy Rozental 2001. // 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) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision$ // // Description : implements framework API - main driver for the test // *************************************************************************** #ifndef BOOST_TEST_FRAMEWORK_IPP_021005GER #define BOOST_TEST_FRAMEWORK_IPP_021005GER // Boost.Test #include <boost/test/framework.hpp> #include <boost/test/execution_monitor.hpp> #include <boost/test/debug.hpp> #include <boost/test/unit_test_parameters.hpp> #include <boost/test/unit_test_log.hpp> #include <boost/test/unit_test_monitor.hpp> #include <boost/test/results_collector.hpp> #include <boost/test/progress_monitor.hpp> #include <boost/test/results_reporter.hpp> #include <boost/test/tree/observer.hpp> #include <boost/test/tree/test_unit.hpp> #include <boost/test/tree/visitor.hpp> #include <boost/test/tree/traverse.hpp> #include <boost/test/tree/test_case_counter.hpp> #if BOOST_TEST_SUPPORT_TOKEN_ITERATOR #include <boost/test/utils/iterator/token_iterator.hpp> #endif #include <boost/test/utils/foreach.hpp> #include <boost/test/utils/basic_cstring/io.hpp> #include <boost/test/detail/global_typedef.hpp> #include <boost/test/detail/throw_exception.hpp> // Boost #include <boost/timer.hpp> #include <boost/bind.hpp> // STL #include <limits> #include <map> #include <set> #include <cstdlib> #include <ctime> #ifdef BOOST_NO_STDC_NAMESPACE namespace std { using ::time; using ::srand; } #endif #include <boost/test/detail/suppress_warnings.hpp> //____________________________________________________________________________// namespace boost { namespace unit_test { namespace framework { namespace impl { // ************************************************************************** // // ************** order detection helpers ************** // // ************************************************************************** // struct order_info { order_info() : depth(-1) {} int depth; std::vector<test_unit_id> dependant_siblings; }; typedef std::set<test_unit_id> tu_id_set; typedef std::map<test_unit_id,order_info> order_info_per_tu; // !! ?? unordered map //____________________________________________________________________________// static test_unit_id get_tu_parent( test_unit_id tu_id ) { return framework::get( tu_id, TUT_ANY ).p_parent_id; } //____________________________________________________________________________// static int tu_depth( test_unit_id tu_id, test_unit_id master_tu_id, order_info_per_tu& tuoi ) { if( tu_id == master_tu_id ) return 0; order_info& info = tuoi[tu_id]; if( info.depth == -1 ) info.depth = tu_depth( get_tu_parent( tu_id ), master_tu_id, tuoi ) + 1; return info.depth; } //____________________________________________________________________________// static void collect_dependant_siblings( test_unit_id from, test_unit_id to, test_unit_id master_tu_id, order_info_per_tu& tuoi ) { int from_depth = tu_depth( from, master_tu_id, tuoi ); int to_depth = tu_depth( to, master_tu_id, tuoi ); while(from_depth > to_depth) { from = get_tu_parent( from ); --from_depth; } while(from_depth < to_depth) { to = get_tu_parent( to ); --to_depth; } while(true) { test_unit_id from_parent = get_tu_parent( from ); test_unit_id to_parent = get_tu_parent( to ); if( from_parent == to_parent ) break; from = from_parent; to = to_parent; } tuoi[from].dependant_siblings.push_back( to ); } //____________________________________________________________________________// static counter_t assign_sibling_rank( test_unit_id tu_id, order_info_per_tu& tuoi ) { test_unit& tu = framework::get( tu_id, TUT_ANY ); BOOST_TEST_SETUP_ASSERT( tu.p_sibling_rank != (std::numeric_limits<counter_t>::max)(), "Cyclic dependency detected involving test unit \"" + tu.full_name() + "\"" ); if( tu.p_sibling_rank != 0 ) return tu.p_sibling_rank; order_info const& info = tuoi[tu_id]; // indicate in progress tu.p_sibling_rank.value = (std::numeric_limits<counter_t>::max)(); counter_t new_rank = 1; BOOST_TEST_FOREACH( test_unit_id, sibling_id, info.dependant_siblings ) new_rank = (std::max)(new_rank, assign_sibling_rank( sibling_id, tuoi ) + 1); return tu.p_sibling_rank.value = new_rank; } //____________________________________________________________________________// // ************************************************************************** // // ************** test_init call wrapper ************** // // ************************************************************************** // static void invoke_init_func( init_unit_test_func init_func ) { #ifdef BOOST_TEST_ALTERNATIVE_INIT_API BOOST_TEST_I_ASSRT( (*init_func)(), std::runtime_error( "test module initialization failed" ) ); #else test_suite* manual_test_units = (*init_func)( framework::master_test_suite().argc, framework::master_test_suite().argv ); if( manual_test_units ) framework::master_test_suite().add( manual_test_units ); #endif } // ************************************************************************** // // ************** name_filter ************** // // ************************************************************************** // class name_filter : public test_tree_visitor { struct component { component( const_string name ) // has to be implicit { if( name == "*" ) m_kind = SFK_ALL; else if( first_char( name ) == '*' && last_char( name ) == '*' ) { m_kind = SFK_SUBSTR; m_name = name.substr( 1, name.size()-1 ); } else if( first_char( name ) == '*' ) { m_kind = SFK_TRAILING; m_name = name.substr( 1 ); } else if( last_char( name ) == '*' ) { m_kind = SFK_LEADING; m_name = name.substr( 0, name.size()-1 ); } else { m_kind = SFK_MATCH; m_name = name; } } bool pass( test_unit const& tu ) const { const_string name( tu.p_name ); switch( m_kind ) { default: case SFK_ALL: return true; case SFK_LEADING: return name.substr( 0, m_name.size() ) == m_name; case SFK_TRAILING: return name.size() >= m_name.size() && name.substr( name.size() - m_name.size() ) == m_name; case SFK_SUBSTR: return name.find( m_name ) != const_string::npos; case SFK_MATCH: return m_name == tu.p_name.get(); } } enum kind { SFK_ALL, SFK_LEADING, SFK_TRAILING, SFK_SUBSTR, SFK_MATCH }; kind m_kind; const_string m_name; }; public: // Constructor name_filter( test_unit_id_list& targ_list, const_string filter_expr ) : m_targ_list( targ_list ), m_depth( 0 ) { #ifdef BOOST_TEST_SUPPORT_TOKEN_ITERATOR utils::string_token_iterator tit( filter_expr, (utils::dropped_delimeters = "/", utils::kept_delimeters = utils::dt_none) ); while( tit != utils::string_token_iterator() ) { m_components.push_back( std::vector<component>( utils::string_token_iterator( *tit, (utils::dropped_delimeters = ",", utils::kept_delimeters = utils::dt_none) ), utils::string_token_iterator() ) ); ++tit; } #endif } private: bool filter_unit( test_unit const& tu ) { // skip master test suite if( m_depth == 0 ) return true; // corresponding name filters are at level m_depth-1 std::vector<component> const& filters = m_components[m_depth-1]; // look for match return std::find_if( filters.begin(), filters.end(), bind( &component::pass, _1, boost::ref(tu) ) ) != filters.end(); } // test_tree_visitor interface virtual void visit( test_case const& tc ) { // make sure we only accept test cases if we match last component of the filter if( m_depth == m_components.size() && filter_unit( tc ) ) m_targ_list.push_back( tc.p_id ); // found a test case } virtual bool test_suite_start( test_suite const& ts ) { if( !filter_unit( ts ) ) return false; if( m_depth < m_components.size() ) { ++m_depth; return true; } m_targ_list.push_back( ts.p_id ); // found a test suite return false; } virtual void test_suite_finish( test_suite const& /*ts*/ ) { --m_depth; } // Data members typedef std::vector<std::vector<component> > components_per_level; components_per_level m_components; test_unit_id_list& m_targ_list; unsigned m_depth; }; // ************************************************************************** // // ************** label_filter ************** // // ************************************************************************** // class label_filter : public test_tree_visitor { public: label_filter( test_unit_id_list& targ_list, const_string label ) : m_targ_list( targ_list ) , m_label( label ) {} private: // test_tree_visitor interface virtual bool visit( test_unit const& tu ) { if( tu.has_label( m_label ) ) { // found a test unit; add it to list of tu to enable with children and stop recursion in case of suites m_targ_list.push_back( tu.p_id ); return false; } return true; } // Data members test_unit_id_list& m_targ_list; const_string m_label; }; // ************************************************************************** // // ************** set_run_status ************** // // ************************************************************************** // class set_run_status : public test_tree_visitor { public: explicit set_run_status( test_unit::run_status rs, test_unit_id_list* dep_collector = 0 ) : m_new_status( rs ) , m_dep_collector( dep_collector ) {} private: // test_tree_visitor interface virtual bool visit( test_unit const& tu ) { const_cast<test_unit&>(tu).p_run_status.value = m_new_status == test_unit::RS_INVALID ? tu.p_default_status : m_new_status; if( m_dep_collector ) { BOOST_TEST_FOREACH( test_unit_id, dep_id, tu.p_dependencies.get() ) { test_unit const& dep = framework::get( dep_id, TUT_ANY ); if( dep.p_run_status == tu.p_run_status ) continue; BOOST_TEST_MESSAGE( "Including test " << dep.p_type_name << ' ' << dep.full_name() << " as a dependency of test " << tu.p_type_name << ' ' << tu.full_name() ); m_dep_collector->push_back( dep_id ); } } return true; } // Data members test_unit::run_status m_new_status; test_unit_id_list* m_dep_collector; }; // ************************************************************************** // // ************** parse_filters ************** // // ************************************************************************** // static void add_filtered_test_units( test_unit_id master_tu_id, const_string filter, test_unit_id_list& targ ) { // Choose between two kinds of filters if( filter[0] == '@' ) { filter.trim_left( 1 ); label_filter lf( targ, filter ); traverse_test_tree( master_tu_id, lf, true ); } else { name_filter nf( targ, filter ); traverse_test_tree( master_tu_id, nf, true ); } } //____________________________________________________________________________// static bool parse_filters( test_unit_id master_tu_id, test_unit_id_list& tu_to_enable, test_unit_id_list& tu_to_disable ) { // 10. collect tu to enable and disable based on filters bool had_selector_filter = false; std::vector<std::string> const& filters = runtime_config::get<std::vector<std::string> >( runtime_config::RUN_FILTERS ); BOOST_TEST_FOREACH( const_string, filter, filters ) { BOOST_TEST_SETUP_ASSERT( !filter.is_empty(), "Invalid filter specification" ); enum { SELECTOR, ENABLER, DISABLER } filter_type = SELECTOR; // 11. Deduce filter type if( filter[0] == '!' || filter[0] == '+' ) { filter_type = filter[0] == '+' ? ENABLER : DISABLER; filter.trim_left( 1 ); BOOST_TEST_SETUP_ASSERT( !filter.is_empty(), "Invalid filter specification" ); } had_selector_filter |= filter_type == SELECTOR; // 12. Add test units to corresponding list switch( filter_type ) { case SELECTOR: case ENABLER: add_filtered_test_units( master_tu_id, filter, tu_to_enable ); break; case DISABLER: add_filtered_test_units( master_tu_id, filter, tu_to_disable ); break; } } return had_selector_filter; } //____________________________________________________________________________// } // namespace impl // ************************************************************************** // // ************** framework::state ************** // // ************************************************************************** // unsigned const TIMEOUT_EXCEEDED = static_cast<unsigned>( -1 ); class state { public: state() : m_curr_test_case( INV_TEST_UNIT_ID ) , m_next_test_case_id( MIN_TEST_CASE_ID ) , m_next_test_suite_id( MIN_TEST_SUITE_ID ) , m_test_in_progress( false ) , m_context_idx( 0 ) , m_log_sink( std::cout ) , m_report_sink( std::cerr ) { } ~state() { clear(); } void clear() { while( !m_test_units.empty() ) { test_unit_store::value_type const& tu = *m_test_units.begin(); test_unit const* tu_ptr = tu.second; // the delete will erase this element from map if( ut_detail::test_id_2_unit_type( tu.second->p_id ) == TUT_SUITE ) delete static_cast<test_suite const*>(tu_ptr); else delete static_cast<test_case const*>(tu_ptr); } } void set_tu_id( test_unit& tu, test_unit_id id ) { tu.p_id.value = id; } ////////////////////////////////////////////////////////////////// // Validates the dependency graph and deduces the sibling dependency rank for each child void deduce_siblings_order( test_unit_id tu_id, test_unit_id master_tu_id, impl::order_info_per_tu& tuoi ) { test_unit& tu = framework::get( tu_id, TUT_ANY ); // collect all sibling dependancy from tu own list BOOST_TEST_FOREACH( test_unit_id, dep_id, tu.p_dependencies.get() ) collect_dependant_siblings( tu_id, dep_id, master_tu_id, tuoi ); if( tu.p_type != TUT_SUITE ) return; test_suite& ts = static_cast<test_suite&>(tu); // recursive call to children first BOOST_TEST_FOREACH( test_unit_id, chld_id, ts.m_children ) deduce_siblings_order( chld_id, master_tu_id, tuoi ); BOOST_TEST_FOREACH( test_unit_id, chld_id, ts.m_children ) { counter_t rank = assign_sibling_rank( chld_id, tuoi ); ts.m_ranked_children.insert( std::make_pair( rank, chld_id ) ); } } ////////////////////////////////////////////////////////////////// // Finalize default run status: // 1) inherit run status from parent where applicable // 2) if any of test units in test suite enabled enable it as well bool finalize_default_run_status( test_unit_id tu_id, test_unit::run_status parent_status ) { test_unit& tu = framework::get( tu_id, TUT_ANY ); if( tu.p_default_status == test_suite::RS_INHERIT ) tu.p_default_status.value = parent_status; // go through list of children if( tu.p_type == TUT_SUITE ) { bool has_enabled_child = false; BOOST_TEST_FOREACH( test_unit_id, chld_id, static_cast<test_suite const&>(tu).m_children ) has_enabled_child |= finalize_default_run_status( chld_id, tu.p_default_status ); tu.p_default_status.value = has_enabled_child ? test_suite::RS_ENABLED : test_suite::RS_DISABLED; } return tu.p_default_status == test_suite::RS_ENABLED; } ////////////////////////////////////////////////////////////////// bool finalize_run_status( test_unit_id tu_id ) { test_unit& tu = framework::get( tu_id, TUT_ANY ); // go through list of children if( tu.p_type == TUT_SUITE ) { bool has_enabled_child = false; BOOST_TEST_FOREACH( test_unit_id, chld_id, static_cast<test_suite const&>(tu).m_children) has_enabled_child |= finalize_run_status( chld_id ); tu.p_run_status.value = has_enabled_child ? test_suite::RS_ENABLED : test_suite::RS_DISABLED; } return tu.is_enabled(); } ////////////////////////////////////////////////////////////////// void deduce_run_status( test_unit_id master_tu_id ) { using namespace framework::impl; test_unit_id_list tu_to_enable; test_unit_id_list tu_to_disable; // 10. If there are any filters supplied, figure out lists of test units to enable/disable bool had_selector_filter = !runtime_config::get<std::vector<std::string> >( runtime_config::RUN_FILTERS ).empty() && parse_filters( master_tu_id, tu_to_enable, tu_to_disable ); // 20. Set the stage: either use default run status or disable all test units set_run_status initial_setter( had_selector_filter ? test_unit::RS_DISABLED : test_unit::RS_INVALID ); traverse_test_tree( master_tu_id, initial_setter, true ); // 30. Apply all selectors and enablers. while( !tu_to_enable.empty() ) { test_unit& tu = framework::get( tu_to_enable.back(), TUT_ANY ); tu_to_enable.pop_back(); // 35. Ignore test units which already enabled if( tu.is_enabled() ) continue; // set new status and add all dependencies into tu_to_enable set_run_status enabler( test_unit::RS_ENABLED, &tu_to_enable ); traverse_test_tree( tu.p_id, enabler, true ); } // 40. Apply all disablers while( !tu_to_disable.empty() ) { test_unit const& tu = framework::get( tu_to_disable.back(), TUT_ANY ); tu_to_disable.pop_back(); // 35. Ignore test units which already disabled if( !tu.is_enabled() ) continue; set_run_status disabler( test_unit::RS_DISABLED ); traverse_test_tree( tu.p_id, disabler, true ); } // 50. Make sure parents of enabled test units are also enabled finalize_run_status( master_tu_id ); } ////////////////////////////////////////////////////////////////// typedef unit_test_monitor_t::error_level execution_result; // Executed the test tree with the root at specified test unit execution_result execute_test_tree( test_unit_id tu_id, unsigned timeout = 0 ) { test_unit const& tu = framework::get( tu_id, TUT_ANY ); execution_result result = unit_test_monitor_t::test_ok; if( !tu.is_enabled() ) return result; // 10. Check preconditions, including zero time left for execution and // successful execution of all dependencies if( timeout == TIMEOUT_EXCEEDED ) { // notify all observers about skipped test unit BOOST_TEST_FOREACH( test_observer*, to, m_observers ) to->test_unit_skipped( tu, "timeout for the test unit is exceeded" ); return unit_test_monitor_t::os_timeout; } else if( timeout == 0 || timeout > tu.p_timeout ) // deduce timeout for this test unit timeout = tu.p_timeout; test_tools::assertion_result const precondition_res = tu.check_preconditions(); if( !precondition_res ) { // notify all observers about skipped test unit BOOST_TEST_FOREACH( test_observer*, to, m_observers ) to->test_unit_skipped( tu, precondition_res.message() ); return unit_test_monitor_t::precondition_failure; } // 20. Notify all observers about the start of the test unit BOOST_TEST_FOREACH( test_observer*, to, m_observers ) to->test_unit_start( tu ); // 30. Execute setup fixtures if any; any failure here leads to test unit abortion BOOST_TEST_FOREACH( test_unit_fixture_ptr, F, tu.p_fixtures.get() ) { result = unit_test_monitor.execute_and_translate( boost::bind( &test_unit_fixture::setup, F ) ); if( result != unit_test_monitor_t::test_ok ) break; } // This is the time we are going to spend executing the test unit unsigned long elapsed = 0; if( result == unit_test_monitor_t::test_ok ) { // 40. We are going to time the execution boost::timer tu_timer; if( tu.p_type == TUT_SUITE ) { test_suite const& ts = static_cast<test_suite const&>( tu ); if( runtime_config::get<unsigned>( runtime_config::RANDOM_SEED ) == 0 ) { typedef std::pair<counter_t,test_unit_id> value_type; BOOST_TEST_FOREACH( value_type, chld, ts.m_ranked_children ) { unsigned chld_timeout = child_timeout( timeout, tu_timer.elapsed() ); result = (std::min)( result, execute_test_tree( chld.second, chld_timeout ) ); if( unit_test_monitor.is_critical_error( result ) ) break; } } else { // Go through ranges of chldren with the same dependency rank and shuffle them // independently. Execute each subtree in this order test_unit_id_list children_with_the_same_rank; typedef test_suite::children_per_rank::const_iterator it_type; it_type it = ts.m_ranked_children.begin(); while( it != ts.m_ranked_children.end() ) { children_with_the_same_rank.clear(); std::pair<it_type,it_type> range = ts.m_ranked_children.equal_range( it->first ); it = range.first; while( it != range.second ) { children_with_the_same_rank.push_back( it->second ); it++; } std::random_shuffle( children_with_the_same_rank.begin(), children_with_the_same_rank.end() ); BOOST_TEST_FOREACH( test_unit_id, chld, children_with_the_same_rank ) { unsigned chld_timeout = child_timeout( timeout, tu_timer.elapsed() ); result = (std::min)( result, execute_test_tree( chld, chld_timeout ) ); if( unit_test_monitor.is_critical_error( result ) ) break; } } } elapsed = static_cast<unsigned long>( tu_timer.elapsed() * 1e6 ); } else { // TUT_CASE test_case const& tc = static_cast<test_case const&>( tu ); // setup contexts m_context_idx = 0; // setup current test case test_unit_id bkup = m_curr_test_case; m_curr_test_case = tc.p_id; // execute the test case body result = unit_test_monitor.execute_and_translate( tc.p_test_func, timeout ); elapsed = static_cast<unsigned long>( tu_timer.elapsed() * 1e6 ); // cleanup leftover context m_context.clear(); // restore state and abort if necessary m_curr_test_case = bkup; } } // if run error is critical skip teardown, who knows what the state of the program at this point if( !unit_test_monitor.is_critical_error( result ) ) { // execute teardown fixtures if any in reverse order BOOST_TEST_REVERSE_FOREACH( test_unit_fixture_ptr, F, tu.p_fixtures.get() ) { result = (std::min)( result, unit_test_monitor.execute_and_translate( boost::bind( &test_unit_fixture::teardown, F ), 0 ) ); if( unit_test_monitor.is_critical_error( result ) ) break; } } // notify all observers about abortion if( unit_test_monitor.is_critical_error( result ) ) { BOOST_TEST_FOREACH( test_observer*, to, m_observers ) to->test_aborted(); } // notify all observers about completion BOOST_TEST_REVERSE_FOREACH( test_observer*, to, m_observers ) to->test_unit_finish( tu, elapsed ); return result; } ////////////////////////////////////////////////////////////////// unsigned child_timeout( unsigned tu_timeout, double elapsed ) { if( tu_timeout == 0U ) return 0U; unsigned elpsed_sec = static_cast<unsigned>(elapsed); // rounding to number of whole seconds return tu_timeout > elpsed_sec ? tu_timeout - elpsed_sec : TIMEOUT_EXCEEDED; } struct priority_order { bool operator()( test_observer* lhs, test_observer* rhs ) const { return (lhs->priority() < rhs->priority()) || ((lhs->priority() == rhs->priority()) && (lhs < rhs)); } }; // Data members typedef std::map<test_unit_id,test_unit*> test_unit_store; typedef std::set<test_observer*,priority_order> observer_store; struct context_frame { context_frame( std::string const& d, int id, bool sticky ) : descr( d ) , frame_id( id ) , is_sticky( sticky ) {} std::string descr; int frame_id; bool is_sticky; }; typedef std::vector<context_frame> context_data; master_test_suite_t* m_master_test_suite; std::vector<test_suite*> m_auto_test_suites; test_unit_id m_curr_test_case; test_unit_store m_test_units; test_unit_id m_next_test_case_id; test_unit_id m_next_test_suite_id; bool m_test_in_progress; observer_store m_observers; context_data m_context; int m_context_idx; boost::execution_monitor m_aux_em; runtime_config::stream_holder m_log_sink; runtime_config::stream_holder m_report_sink; }; //____________________________________________________________________________// namespace impl { namespace { #if defined(__CYGWIN__) framework::state& s_frk_state() { static framework::state* the_inst = 0; if(!the_inst) the_inst = new framework::state; return *the_inst; } #else framework::state& s_frk_state() { static framework::state the_inst; return the_inst; } #endif } // local namespace void setup_for_execution( test_unit const& tu ) { s_frk_state().deduce_run_status( tu.p_id ); } //____________________________________________________________________________// } // namespace impl //____________________________________________________________________________// // ************************************************************************** // // ************** framework::init ************** // // ************************************************************************** // void init( init_unit_test_func init_func, int argc, char* argv[] ) { using namespace impl; // 10. Set up runtime parameters runtime_config::init( argc, argv ); // 20. Set the desired log level, format and sink unit_test_log.set_threshold_level( runtime_config::get<log_level>( runtime_config::LOG_LEVEL ) ); unit_test_log.set_format( runtime_config::get<output_format>( runtime_config::LOG_FORMAT ) ); s_frk_state().m_log_sink.setup( runtime_config::LOG_SINK ); unit_test_log.set_stream( s_frk_state().m_log_sink.ref() ); // 30. Set the desired report level, format and sink results_reporter::set_level( runtime_config::get<report_level>( runtime_config::REPORT_LEVEL ) ); results_reporter::set_format( runtime_config::get<output_format>( runtime_config::REPORT_FORMAT ) ); s_frk_state().m_report_sink.setup( runtime_config::REPORT_SINK ); results_reporter::set_stream( s_frk_state().m_report_sink.ref() ); // 40. Register default test observers register_observer( results_collector ); register_observer( unit_test_log ); if( runtime_config::get<bool>( runtime_config::SHOW_PROGRESS ) ) { progress_monitor.set_stream( s_frk_state().m_log_sink.ref() ); register_observer( progress_monitor ); } // 50. Set up memory leak detection unsigned long detect_mem_leak = runtime_config::get<unsigned long>( runtime_config::DETECT_MEM_LEAKS ); if( detect_mem_leak > 0 ) { debug::detect_memory_leaks( true, runtime_config::get<std::string>( runtime_config::REPORT_MEM_LEAKS ) ); debug::break_memory_alloc( (long)detect_mem_leak ); } // 60. Initialize master unit test suite master_test_suite().argc = argc; master_test_suite().argv = argv; // 70. Invoke test module initialization routine BOOST_TEST_I_TRY { s_frk_state().m_aux_em.vexecute( boost::bind( &impl::invoke_init_func, init_func ) ); } BOOST_TEST_I_CATCH( execution_exception, ex ) { BOOST_TEST_SETUP_ASSERT( false, ex.what() ); } } //____________________________________________________________________________// void finalize_setup_phase( test_unit_id master_tu_id ) { if( master_tu_id == INV_TEST_UNIT_ID ) master_tu_id = master_test_suite().p_id; // 10. Apply all decorators to the auto test units class apply_decorators : public test_tree_visitor { private: // test_tree_visitor interface virtual bool visit( test_unit const& tu ) { BOOST_TEST_FOREACH( decorator::base_ptr, d, tu.p_decorators.get() ) d->apply( const_cast<test_unit&>(tu) ); return true; } } ad; traverse_test_tree( master_tu_id, ad, true ); // 20. Finalize setup phase impl::order_info_per_tu tuoi; impl::s_frk_state().deduce_siblings_order( master_tu_id, master_tu_id, tuoi ); impl::s_frk_state().finalize_default_run_status( master_tu_id, test_unit::RS_INVALID ); } // ************************************************************************** // // ************** test_in_progress ************** // // ************************************************************************** // bool test_in_progress() { return impl::s_frk_state().m_test_in_progress; } //____________________________________________________________________________// // ************************************************************************** // // ************** framework::shutdown ************** // // ************************************************************************** // void shutdown() { // eliminating some fake memory leak reports. See for more details: // http://connect.microsoft.com/VisualStudio/feedback/details/106937/memory-leaks-reported-by-debug-crt-inside-typeinfo-name # if BOOST_WORKAROUND(BOOST_MSVC, <= 1600 ) && !defined(_DLL) && defined(_DEBUG) # if BOOST_WORKAROUND(BOOST_MSVC, < 1600 ) #define _Next next #define _MemPtr memPtr #endif __type_info_node* pNode = __type_info_root_node._Next; __type_info_node* tmpNode = &__type_info_root_node; for( ; pNode!=NULL; pNode = tmpNode ) { tmpNode = pNode->_Next; delete pNode->_MemPtr; delete pNode; } # if BOOST_WORKAROUND(BOOST_MSVC, < 1600 ) #undef _Next #undef _MemPtr #endif # endif } //____________________________________________________________________________// // ************************************************************************** // // ************** register_test_unit ************** // // ************************************************************************** // void register_test_unit( test_case* tc ) { BOOST_TEST_SETUP_ASSERT( tc->p_id == INV_TEST_UNIT_ID, BOOST_TEST_L( "test case already registered" ) ); test_unit_id new_id = impl::s_frk_state().m_next_test_case_id; BOOST_TEST_SETUP_ASSERT( new_id != MAX_TEST_CASE_ID, BOOST_TEST_L( "too many test cases" ) ); typedef state::test_unit_store::value_type map_value_type; impl::s_frk_state().m_test_units.insert( map_value_type( new_id, tc ) ); impl::s_frk_state().m_next_test_case_id++; impl::s_frk_state().set_tu_id( *tc, new_id ); } //____________________________________________________________________________// // ************************************************************************** // // ************** register_test_unit ************** // // ************************************************************************** // void register_test_unit( test_suite* ts ) { BOOST_TEST_SETUP_ASSERT( ts->p_id == INV_TEST_UNIT_ID, BOOST_TEST_L( "test suite already registered" ) ); test_unit_id new_id = impl::s_frk_state().m_next_test_suite_id; BOOST_TEST_SETUP_ASSERT( new_id != MAX_TEST_SUITE_ID, BOOST_TEST_L( "too many test suites" ) ); typedef state::test_unit_store::value_type map_value_type; impl::s_frk_state().m_test_units.insert( map_value_type( new_id, ts ) ); impl::s_frk_state().m_next_test_suite_id++; impl::s_frk_state().set_tu_id( *ts, new_id ); } //____________________________________________________________________________// // ************************************************************************** // // ************** deregister_test_unit ************** // // ************************************************************************** // void deregister_test_unit( test_unit* tu ) { impl::s_frk_state().m_test_units.erase( tu->p_id ); } //____________________________________________________________________________// // ************************************************************************** // // ************** clear ************** // // ************************************************************************** // void clear() { impl::s_frk_state().clear(); } //____________________________________________________________________________// // ************************************************************************** // // ************** register_observer ************** // // ************************************************************************** // void register_observer( test_observer& to ) { impl::s_frk_state().m_observers.insert( &to ); } //____________________________________________________________________________// // ************************************************************************** // // ************** deregister_observer ************** // // ************************************************************************** // void deregister_observer( test_observer& to ) { impl::s_frk_state().m_observers.erase( &to ); } //____________________________________________________________________________// // ************************************************************************** // // ************** add_context ************** // // ************************************************************************** // int add_context( ::boost::unit_test::lazy_ostream const& context_descr, bool sticky ) { std::stringstream buffer; context_descr( buffer ); int res_idx = impl::s_frk_state().m_context_idx++; impl::s_frk_state().m_context.push_back( state::context_frame( buffer.str(), res_idx, sticky ) ); return res_idx; } //____________________________________________________________________________// // ************************************************************************** // // ************** clear_context ************** // // ************************************************************************** // struct frame_with_id { explicit frame_with_id( int id ) : m_id( id ) {} bool operator()( state::context_frame const& f ) { return f.frame_id == m_id; } int m_id; }; //____________________________________________________________________________// void clear_context( int frame_id ) { if( frame_id == -1 ) { // clear all non sticky frames for( int i=static_cast<int>(impl::s_frk_state().m_context.size())-1; i>=0; i-- ) if( !impl::s_frk_state().m_context[i].is_sticky ) impl::s_frk_state().m_context.erase( impl::s_frk_state().m_context.begin()+i ); } else { // clear specific frame state::context_data::iterator it = std::find_if( impl::s_frk_state().m_context.begin(), impl::s_frk_state().m_context.end(), frame_with_id( frame_id ) ); if( it != impl::s_frk_state().m_context.end() ) // really an internal error if this is not true impl::s_frk_state().m_context.erase( it ); } } //____________________________________________________________________________// // ************************************************************************** // // ************** get_context ************** // // ************************************************************************** // context_generator get_context() { return context_generator(); } //____________________________________________________________________________// // ************************************************************************** // // ************** context_generator ************** // // ************************************************************************** // bool context_generator::is_empty() const { return impl::s_frk_state().m_context.empty(); } //____________________________________________________________________________// const_string context_generator::next() const { return m_curr_frame < impl::s_frk_state().m_context.size() ? impl::s_frk_state().m_context[m_curr_frame++].descr : const_string(); } //____________________________________________________________________________// // ************************************************************************** // // ************** master_test_suite ************** // // ************************************************************************** // master_test_suite_t& master_test_suite() { if( !impl::s_frk_state().m_master_test_suite ) impl::s_frk_state().m_master_test_suite = new master_test_suite_t; return *impl::s_frk_state().m_master_test_suite; } //____________________________________________________________________________// // ************************************************************************** // // ************** current_auto_test_suite ************** // // ************************************************************************** // test_suite& current_auto_test_suite( test_suite* ts, bool push_or_pop ) { if( impl::s_frk_state().m_auto_test_suites.empty() ) impl::s_frk_state().m_auto_test_suites.push_back( &framework::master_test_suite() ); if( !push_or_pop ) impl::s_frk_state().m_auto_test_suites.pop_back(); else if( ts ) impl::s_frk_state().m_auto_test_suites.push_back( ts ); return *impl::s_frk_state().m_auto_test_suites.back(); } //____________________________________________________________________________// // ************************************************************************** // // ************** current_test_case ************** // // ************************************************************************** // test_case const& current_test_case() { return get<test_case>( impl::s_frk_state().m_curr_test_case ); } //____________________________________________________________________________// test_unit_id current_test_case_id() { return impl::s_frk_state().m_curr_test_case; } //____________________________________________________________________________// // ************************************************************************** // // ************** framework::get ************** // // ************************************************************************** // test_unit& get( test_unit_id id, test_unit_type t ) { test_unit* res = impl::s_frk_state().m_test_units[id]; BOOST_TEST_I_ASSRT( (res->p_type & t) != 0, internal_error( "Invalid test unit type" ) ); return *res; } //____________________________________________________________________________// // ************************************************************************** // // ************** framework::run ************** // // ************************************************************************** // void run( test_unit_id id, bool continue_test ) { if( id == INV_TEST_UNIT_ID ) id = master_test_suite().p_id; // Figure out run status for execution phase impl::s_frk_state().deduce_run_status( id ); test_case_counter tcc; traverse_test_tree( id, tcc ); BOOST_TEST_SETUP_ASSERT( tcc.p_count != 0 , runtime_config::get<std::vector<std::string> >( runtime_config::RUN_FILTERS ).empty() ? BOOST_TEST_L( "test tree is empty" ) : BOOST_TEST_L( "no test cases matching filter or all test cases were disabled" ) ); bool was_in_progress = framework::test_in_progress(); bool call_start_finish = !continue_test || !was_in_progress; impl::s_frk_state().m_test_in_progress = true; if( call_start_finish ) { BOOST_TEST_FOREACH( test_observer*, to, impl::s_frk_state().m_observers ) { BOOST_TEST_I_TRY { impl::s_frk_state().m_aux_em.vexecute( boost::bind( &test_observer::test_start, to, tcc.p_count ) ); } BOOST_TEST_I_CATCH( execution_exception, ex ) { BOOST_TEST_SETUP_ASSERT( false, ex.what() ); } } } unsigned seed = runtime_config::get<unsigned>( runtime_config::RANDOM_SEED ); switch( seed ) { case 0: break; case 1: seed = static_cast<unsigned>( std::time( 0 ) ); default: BOOST_TEST_MESSAGE( "Test cases order is shuffled using seed: " << seed ); std::srand( seed ); } impl::s_frk_state().execute_test_tree( id ); if( call_start_finish ) { BOOST_TEST_REVERSE_FOREACH( test_observer*, to, impl::s_frk_state().m_observers ) to->test_finish(); } impl::s_frk_state().m_test_in_progress = was_in_progress; } //____________________________________________________________________________// void run( test_unit const* tu, bool continue_test ) { run( tu->p_id, continue_test ); } //____________________________________________________________________________// // ************************************************************************** // // ************** assertion_result ************** // // ************************************************************************** // void assertion_result( unit_test::assertion_result ar ) { BOOST_TEST_FOREACH( test_observer*, to, impl::s_frk_state().m_observers ) to->assertion_result( ar ); } //____________________________________________________________________________// // ************************************************************************** // // ************** exception_caught ************** // // ************************************************************************** // void exception_caught( execution_exception const& ex ) { BOOST_TEST_FOREACH( test_observer*, to, impl::s_frk_state().m_observers ) to->exception_caught( ex ); } //____________________________________________________________________________// // ************************************************************************** // // ************** test_unit_aborted ************** // // ************************************************************************** // void test_unit_aborted( test_unit const& tu ) { BOOST_TEST_FOREACH( test_observer*, to, impl::s_frk_state().m_observers ) to->test_unit_aborted( tu ); } //____________________________________________________________________________// } // namespace framework } // namespace unit_test } // namespace boost #include <boost/test/detail/enable_warnings.hpp> #endif // BOOST_TEST_FRAMEWORK_IPP_021005GER
/* * 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/mongodb/v20190725/model/ModifyNetworkAddress.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Mongodb::V20190725::Model; using namespace std; ModifyNetworkAddress::ModifyNetworkAddress() : m_newIPAddressHasBeenSet(false), m_oldIpAddressHasBeenSet(false) { } CoreInternalOutcome ModifyNetworkAddress::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("NewIPAddress") && !value["NewIPAddress"].IsNull()) { if (!value["NewIPAddress"].IsString()) { return CoreInternalOutcome(Core::Error("response `ModifyNetworkAddress.NewIPAddress` IsString=false incorrectly").SetRequestId(requestId)); } m_newIPAddress = string(value["NewIPAddress"].GetString()); m_newIPAddressHasBeenSet = true; } if (value.HasMember("OldIpAddress") && !value["OldIpAddress"].IsNull()) { if (!value["OldIpAddress"].IsString()) { return CoreInternalOutcome(Core::Error("response `ModifyNetworkAddress.OldIpAddress` IsString=false incorrectly").SetRequestId(requestId)); } m_oldIpAddress = string(value["OldIpAddress"].GetString()); m_oldIpAddressHasBeenSet = true; } return CoreInternalOutcome(true); } void ModifyNetworkAddress::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_newIPAddressHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "NewIPAddress"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_newIPAddress.c_str(), allocator).Move(), allocator); } if (m_oldIpAddressHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "OldIpAddress"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_oldIpAddress.c_str(), allocator).Move(), allocator); } } string ModifyNetworkAddress::GetNewIPAddress() const { return m_newIPAddress; } void ModifyNetworkAddress::SetNewIPAddress(const string& _newIPAddress) { m_newIPAddress = _newIPAddress; m_newIPAddressHasBeenSet = true; } bool ModifyNetworkAddress::NewIPAddressHasBeenSet() const { return m_newIPAddressHasBeenSet; } string ModifyNetworkAddress::GetOldIpAddress() const { return m_oldIpAddress; } void ModifyNetworkAddress::SetOldIpAddress(const string& _oldIpAddress) { m_oldIpAddress = _oldIpAddress; m_oldIpAddressHasBeenSet = true; } bool ModifyNetworkAddress::OldIpAddressHasBeenSet() const { return m_oldIpAddressHasBeenSet; }
/* ///////////////////////////////////////////////////////////////////////// * File: src/util/be.parse.cpp * * Purpose: Utility functions for use in Pantheios back-ends. * * Created: 19th August 2007 * Updated: 17th December 2016 * * Home: http://www.pantheios.org/ * * Copyright (c) 2007-2016, Matthew Wilson and Synesis Software * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - 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. * - Neither the name(s) of Matthew Wilson and Synesis Software nor the * names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR * 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. * * ////////////////////////////////////////////////////////////////////// */ #include <pantheios/pantheios.h> #include <pantheios/internal/nox.h> #include <pantheios/backend.h> #include <pantheios/quality/contract.h> #include <pantheios/util/backends/arguments.h> #include <pantheios/util/memory/memcopy.h> #include <stlsoft/string/string_view.hpp> #include <stlsoft/string/split_functions.hpp> #include <stlsoft/string/view_slice_functions.hpp> #ifdef STLSOFT_CF_EXCEPTION_SUPPORT # include <new> #endif /* STLSOFT_CF_EXCEPTION_SUPPORT */ #include <ctype.h> #ifdef PANTHEIOS_USE_WIDE_STRINGS # include <wchar.h> #endif /* PANTHEIOS_USE_WIDE_STRINGS */ /* ///////////////////////////////////////////////////////////////////////// * compiler compatibility */ #if defined(STLSOFT_COMPILER_IS_MSVC) && \ _MSC_VER >= 1300 # pragma warning(disable : 4702) #endif /* _MSC_VER >= 1400 */ /* ///////////////////////////////////////////////////////////////////////// * string encoding compatibility */ #ifdef PANTHEIOS_USE_WIDE_STRINGS # define pan_toupper_ towupper typedef stlsoft::wstring_view string_view_t; #else /* ? PANTHEIOS_USE_WIDE_STRINGS */ # define pan_toupper_ toupper typedef stlsoft::string_view string_view_t; #endif /* PANTHEIOS_USE_WIDE_STRINGS */ /* ///////////////////////////////////////////////////////////////////////// * namespace */ #ifndef PANTHEIOS_NO_NAMESPACE using pantheios::util::pantheios_onBailOut3; using pantheios::util::pantheios_onBailOut4; #endif /* !PANTHEIOS_NO_NAMESPACE */ /* ///////////////////////////////////////////////////////////////////////// * forward declarations */ #ifdef STLSOFT_CF_EXCEPTION_SUPPORT static int pantheios_be_parseBooleanArg_( size_t numArgs , pantheios_slice_t args[] , PAN_CHAR_T const* argName , int flagSuppressesAction , pantheios_uint32_t flagValue , pantheios_uint32_t* flags ); static int pantheios_be_parseStringArg_( size_t numArgs , pantheios_slice_t args[] , PAN_CHAR_T const* argName , pantheios_slice_t* argValue ); static int pantheios_be_parseStockArgs_( size_t numArgs , pantheios_slice_t args[] , pantheios_uint32_t* flags ); #endif /* STLSOFT_CF_EXCEPTION_SUPPORT */ /* ///////////////////////////////////////////////////////////////////////// * helper functions */ namespace { bool has_boolean_flag_value(string_view_t const& value, bool &flagIsOn) { // Can be one of: yes, true, on, 1, no, false, off, 0 (in any case) size_t n = value.size(); if(n < 6) { PAN_CHAR_T copy[6]; PANTHEIOS_char_copy(&copy[0], value.data(), n); ::memset(&copy[0] + n, '\0', (6 - n) * sizeof(PAN_CHAR_T)); PANTHEIOS_CONTRACT_ENFORCE_POSTCONDITION_STATE_INTERNAL('\0' == copy[5], "the character at [5] must be the nul-terminator"); { for(size_t i = 0; '\0' != copy[i]; ++i) { copy[i] = static_cast<PAN_CHAR_T>(pan_toupper_(copy[i])); }} const string_view_t val2(&copy[0], n); if( PANTHEIOS_LITERAL_STRING("1") == val2 || PANTHEIOS_LITERAL_STRING("ON") == val2 || PANTHEIOS_LITERAL_STRING("YES") == val2 || PANTHEIOS_LITERAL_STRING("TRUE") == val2) { flagIsOn = true; return true; } else if(PANTHEIOS_LITERAL_STRING("0") == val2 || PANTHEIOS_LITERAL_STRING("OFF") == val2 || PANTHEIOS_LITERAL_STRING("NO") == val2 || PANTHEIOS_LITERAL_STRING("FALSE") == val2) { flagIsOn = false; return true; } } return false; } } /* anonymous namespace */ /* ///////////////////////////////////////////////////////////////////////// * API functions */ PANTHEIOS_CALL(int) pantheios_be_parseBooleanArg( size_t numArgs , pantheios_slice_t args[] , PAN_CHAR_T const* argName , int flagSuppressesAction , pantheios_uint32_t flagValue , pantheios_uint32_t* flags ) #ifdef STLSOFT_CF_EXCEPTION_SUPPORT { try { return pantheios_be_parseBooleanArg_(numArgs, args, argName, flagSuppressesAction, flagValue, flags); } catch(std::bad_alloc&) { pantheios_onBailOut3(PANTHEIOS_SEV_CRITICAL, "Out of memory when parsing boolean argument", NULL); } catch(std::exception& x) { pantheios_onBailOut4(PANTHEIOS_SEV_CRITICAL, "Unspecified exception when parsing boolean argument", NULL, x.what()); } # ifdef PANTHEIOS_USE_CATCHALL catch(...) { pantheios_onBailOut3(PANTHEIOS_SEV_EMERGENCY, "Unknown failure when parsing boolean argument", NULL); # if defined(PANTHEIOS_CATCHALL_TRANSLATE_UNKNOWN_EXCEPTIONS_TO_FAILURE_CODE) ; # elif defined(PANTHEIOS_CATCHALL_RETHROW_UNKNOWN_EXCEPTIONS) throw; # else pantheios_exitProcess(EXIT_FAILURE); # endif } # endif /* PANTHEIOS_USE_CATCHALL */ return 0; } static int pantheios_be_parseBooleanArg_( size_t numArgs , pantheios_slice_t args[] , PAN_CHAR_T const* argName , int flagSuppressesAction , pantheios_uint32_t flagValue , pantheios_uint32_t* flags ) #endif /* STLSOFT_CF_EXCEPTION_SUPPORT */ { PANTHEIOS_CONTRACT_ENFORCE_PRECONDITION_PARAMS_API((NULL != args || 0 == numArgs), "arguments pointer may only be null if the number of arguments is 0"); PANTHEIOS_CONTRACT_ENFORCE_PRECONDITION_PARAMS_API(NULL != argName, "argument name may not be the null string"); PANTHEIOS_CONTRACT_ENFORCE_PRECONDITION_PARAMS_API('\0' != 0[argName], "argument name may not be the empty string"); PANTHEIOS_CONTRACT_ENFORCE_PRECONDITION_PARAMS_API(NULL != flags, "flags pointer may not be null"); int numProcessed = 0; { for(size_t i = 0; i < numArgs; ++i) { pantheios_slice_t& slice = *(args + i); if(0 != slice.len) { string_view_t arg(slice.ptr, slice.len); string_view_t name; string_view_t value; if(!stlsoft::split(arg, PANTHEIOS_LITERAL_CHAR('='), name, value)) { value = PANTHEIOS_LITERAL_STRING("yes"); } if(name == argName) { // Now read what is required, compare it with the // default flag, and bool flagIsOn; if(!has_boolean_flag_value(value, flagIsOn)) { continue; // Invalid value. Mark to ignore } ++numProcessed; if((!flagIsOn) != (!flagSuppressesAction)) { *flags |= flagValue; } slice.len = 0; // Mark this slice as having been processed successfully break; } } }} return numProcessed; } PANTHEIOS_CALL(int) pantheios_be_parseStringArg( size_t numArgs , pantheios_slice_t args[] , PAN_CHAR_T const* argName , pantheios_slice_t* argValue ) #ifdef STLSOFT_CF_EXCEPTION_SUPPORT { try { return pantheios_be_parseStringArg_(numArgs, args, argName, argValue); } catch(std::bad_alloc&) { pantheios_onBailOut3(PANTHEIOS_SEV_CRITICAL, "Out of memory when parsing string argument", NULL); } catch(std::exception& x) { pantheios_onBailOut4(PANTHEIOS_SEV_CRITICAL, "Unspecified exception when parsing string argument", NULL, x.what()); } # ifdef PANTHEIOS_USE_CATCHALL catch(...) { pantheios_onBailOut3(PANTHEIOS_SEV_EMERGENCY, "Unknown failure when parsing boolean argument", NULL); # if defined(PANTHEIOS_CATCHALL_TRANSLATE_UNKNOWN_EXCEPTIONS_TO_FAILURE_CODE) ; # elif defined(PANTHEIOS_CATCHALL_RETHROW_UNKNOWN_EXCEPTIONS) throw; # else pantheios_exitProcess(EXIT_FAILURE); # endif } # endif /* PANTHEIOS_USE_CATCHALL */ return 0; } static int pantheios_be_parseStringArg_( size_t numArgs , pantheios_slice_t args[] , PAN_CHAR_T const* argName , pantheios_slice_t* argValue ) #endif /* STLSOFT_CF_EXCEPTION_SUPPORT */ { PANTHEIOS_CONTRACT_ENFORCE_PRECONDITION_PARAMS_API((NULL != args || 0 == numArgs), "arguments pointer may only be null if the number of arguments is 0"); PANTHEIOS_CONTRACT_ENFORCE_PRECONDITION_PARAMS_API(NULL != argName, "argument name may not be the null string"); PANTHEIOS_CONTRACT_ENFORCE_PRECONDITION_PARAMS_API('\0' != 0[argName], "argument name may not be the empty string"); PANTHEIOS_CONTRACT_ENFORCE_PRECONDITION_PARAMS_API(NULL != argValue, "argument value pointer may not be null"); int numProcessed = 0; { for(size_t i = 0; i < numArgs; ++i) { pantheios_slice_t& slice = *(args + i); if(0 != slice.len) { string_view_t arg(slice.ptr, slice.len); string_view_t name; string_view_t value; stlsoft::split(arg, PANTHEIOS_LITERAL_CHAR('='), name, value); if(name == argName) { ++numProcessed; argValue->len = value.size(); argValue->ptr = value.data(); slice.len = 0; // Mark this slice as having been processed successfully break; } } }} return numProcessed; } PANTHEIOS_CALL(int) pantheios_be_parseStockArgs( size_t numArgs , pantheios_slice_t args[] , pantheios_uint32_t* flags ) #ifdef STLSOFT_CF_EXCEPTION_SUPPORT { try { return pantheios_be_parseStockArgs_(numArgs, args, flags); } catch(std::bad_alloc&) { pantheios_onBailOut3(PANTHEIOS_SEV_CRITICAL, "Out of memory when parsing stock argument", NULL); } catch(std::exception& x) { pantheios_onBailOut4(PANTHEIOS_SEV_CRITICAL, "Unspecified exception when parsing stock argument", NULL, x.what()); } # ifdef PANTHEIOS_USE_CATCHALL catch(...) { pantheios_onBailOut3(PANTHEIOS_SEV_EMERGENCY, "Unknown failure when parsing stock argument", NULL); # if defined(PANTHEIOS_CATCHALL_TRANSLATE_UNKNOWN_EXCEPTIONS_TO_FAILURE_CODE) ; # elif defined(PANTHEIOS_CATCHALL_RETHROW_UNKNOWN_EXCEPTIONS) throw; # else pantheios_exitProcess(EXIT_FAILURE); # endif } # endif /* PANTHEIOS_USE_CATCHALL */ return 0; } static int pantheios_be_parseStockArgs_( size_t numArgs , pantheios_slice_t args[] , pantheios_uint32_t* flags ) #endif /* STLSOFT_CF_EXCEPTION_SUPPORT */ { PANTHEIOS_CONTRACT_ENFORCE_PRECONDITION_PARAMS_API((NULL != args || 0 == numArgs), "arguments pointer may only be null if the number of arguments is 0"); PANTHEIOS_CONTRACT_ENFORCE_PRECONDITION_PARAMS_API(NULL != flags, "flags pointer may not be null"); int numProcessed = 0; { for(size_t i = 0; i < numArgs; ++i) { pantheios_slice_t& slice = *(args + i); if(0 != slice.len) { string_view_t arg(slice.ptr, slice.len); string_view_t name; string_view_t value; bool flagSuppresses; int flagValue; if(!stlsoft::split(arg, PANTHEIOS_LITERAL_CHAR('='), name, value)) { value = PANTHEIOS_LITERAL_STRING("yes"); } if(!name.empty()) { // PANTHEIOS_BE_INIT_F_NO_PROCESS_ID if(name == PANTHEIOS_LITERAL_STRING("showProcessId")) { flagSuppresses = true; flagValue = PANTHEIOS_BE_INIT_F_NO_PROCESS_ID; } // PANTHEIOS_BE_INIT_F_NO_THREAD_ID else if(name == PANTHEIOS_LITERAL_STRING("showThreadId")) { flagSuppresses = true; flagValue = PANTHEIOS_BE_INIT_F_NO_PROCESS_ID; } // PANTHEIOS_BE_INIT_F_NO_DATETIME else if(name == PANTHEIOS_LITERAL_STRING("showDateTime")) { flagSuppresses = true; flagValue = PANTHEIOS_BE_INIT_F_NO_DATETIME; } // PANTHEIOS_BE_INIT_F_NO_SEVERITY else if(name == PANTHEIOS_LITERAL_STRING("showSeverity")) { flagSuppresses = true; flagValue = PANTHEIOS_BE_INIT_F_NO_SEVERITY; } // PANTHEIOS_BE_INIT_F_USE_SYSTEM_TIME else if(name == PANTHEIOS_LITERAL_STRING("useSystemTime")) { flagSuppresses = false; flagValue = PANTHEIOS_BE_INIT_F_USE_SYSTEM_TIME; } // PANTHEIOS_BE_INIT_F_DETAILS_AT_START else if(name == PANTHEIOS_LITERAL_STRING("showDetailsAtStart")) { flagSuppresses = false; flagValue = PANTHEIOS_BE_INIT_F_DETAILS_AT_START; } // PANTHEIOS_BE_INIT_F_USE_UNIX_FORMAT else if(name == PANTHEIOS_LITERAL_STRING("useUnixFormat") || name == PANTHEIOS_LITERAL_STRING("useUNIXFormat")) { flagSuppresses = false; flagValue = PANTHEIOS_BE_INIT_F_USE_UNIX_FORMAT; } // PANTHEIOS_BE_INIT_F_HIDE_DATE else if(name == PANTHEIOS_LITERAL_STRING("showDate")) { flagSuppresses = true; flagValue = PANTHEIOS_BE_INIT_F_HIDE_DATE; } // PANTHEIOS_BE_INIT_F_HIDE_TIME else if(name == PANTHEIOS_LITERAL_STRING("showTime")) { flagSuppresses = true; flagValue = PANTHEIOS_BE_INIT_F_HIDE_TIME; } // PANTHEIOS_BE_INIT_F_HIGH_RESOLUTION else if(name == PANTHEIOS_LITERAL_STRING("highResolution")) { flagSuppresses = false; flagValue = PANTHEIOS_BE_INIT_F_HIGH_RESOLUTION; } // PANTHEIOS_BE_INIT_F_LOW_RESOLUTION else if(name == PANTHEIOS_LITERAL_STRING("lowResolution")) { flagSuppresses = false; flagValue = PANTHEIOS_BE_INIT_F_LOW_RESOLUTION; } // PANTHEIOS_BE_INIT_F_NUMERIC_SEVERITY else if(name == PANTHEIOS_LITERAL_STRING("numericSeverity")) { flagSuppresses = false; flagValue = PANTHEIOS_BE_INIT_F_NUMERIC_SEVERITY; } else { continue; // We ignore any non-stock flags } // Now read what is required, compare it with the // default flag, and bool flagIsOn; if(!has_boolean_flag_value(value, flagIsOn)) { continue; // Invalid value. Mark to ignore } ++numProcessed; if((!flagIsOn) != (!flagSuppresses)) { *flags |= flagValue; } slice.len = 0; // Mark this slice as having been processed successfully } } }} return numProcessed; } /* ///////////////////////////// end of file //////////////////////////// */
#include <iostream> #include <cstdio> #include <algorithm> #include <cmath> #include <string> #include <cstring> #include <iomanip> #include <climits> #include <vector> #include <queue> #include <map> #include <set> #include <stack> #include <functional> #include <iterator> #define SIZE 1005 using namespace std; int dp[SIZE][SIZE << 1][2]; const int mod = 100000007; void init() { memset(dp, 0, sizeof(dp)); dp[1][1][1] = 1; dp[1][2][0] = 1; for (int i = 2; i <= 1000; i++) { for (int j = 1; j <= (i << 1); j++) { dp[i][j][1] = (dp[i - 1][j][0] << 1) + dp[i - 1][j][1] + dp[i - 1][j - 1][0] + dp[i - 1][j - 1][1]; if (dp[i][j][1] >= mod) dp[i][j][1] %= mod; dp[i][j][0] = dp[i - 1][j][0] + (dp[i - 1][j - 1][1] << 1) + (dp[i - 1][j - 1][0] << 1) + dp[i - 1][j - 2][0] + dp[i - 1][j - 2][1]; if (dp[i][j][0] >= mod) dp[i][j][0] %= mod; } } } int main() { ios::sync_with_stdio(false); init(); int caseNum; cin >> caseNum; while (caseNum--) { int len, num; cin >> len >> num; cout << (dp[len][num][0] + dp[len][num][1]) % mod << endl; } return 0; }
#include <deque> #include <vector> #include <algorithm> #include <assert.h> #include "Entry.h" std::vector<bool> map; std::vector<int> visited; std::vector<xyLoc> succ; int width, height; void GetSuccessors(xyLoc s, std::vector<xyLoc> &neighbors); int GetIndex(xyLoc s); void ExtractPath(xyLoc end, std::vector<xyLoc> &finalPath); const char *GetName() { return "TestProgram"; } void PreprocessMap(std::vector<bool> &bits, int width, int height, const char *filename) { printf("Not writing to file '%s'\n", filename); } void *PrepareForSearch(std::vector<bool> &bits, int w, int h, const char *filename) { printf("Not reading from file '%s'\n", filename); map = bits; width = w; height = h; return (void *)13182; } bool GetPath(void *data, xyLoc s, xyLoc g, std::vector<xyLoc> &path) { assert((long)data == 13182); std::deque<xyLoc> q; if (path.size() > 0) { path.push_back(g); return true; } visited.assign(map.size(),0); visited[GetIndex(s)] = 1; q.push_back(s); while (q.size() > 0) { xyLoc next = q.front(); q.pop_front(); GetSuccessors(next, succ); for (unsigned int x = 0; x < succ.size(); x++) { if (visited[GetIndex(succ[x])]) continue; visited[GetIndex(succ[x])] = visited[GetIndex(next)]+1; if (succ[x].x == g.x && succ[x].y == g.y) // goal found { ExtractPath(g, path); if (path.size() > 0) { path.pop_back(); return false; } return true; // empty path } q.push_back(succ[x]); } } return true; // no path returned, but we're done } int GetIndex(xyLoc s) { return s.y*width+s.x; } // generates 4-connected neighbors // doesn't generate 8-connected neighbors (which ARE allowed) // a diagonal move must have both cardinal neighbors free to be legal void GetSuccessors(xyLoc s, std::vector<xyLoc> &neighbors) { neighbors.resize(0); xyLoc next = s; next.x++; if (next.x < width && map[GetIndex(next)]) neighbors.push_back(next); next = s; next.x--; if (next.x >= 0 && map[GetIndex(next)]) neighbors.push_back(next); next = s; next.y--; if (next.y >= 0 && map[GetIndex(next)]) neighbors.push_back(next); next = s; next.y++; if (next.y < height && map[GetIndex(next)]) neighbors.push_back(next); } void ExtractPath(xyLoc end, std::vector<xyLoc> &finalPath) { int currCost = visited[GetIndex(end)]; finalPath.resize(0); finalPath.push_back(end); while (currCost != 1) { GetSuccessors(finalPath.back(), succ); for (unsigned int x = 0; x < succ.size(); x++) { if (visited[GetIndex(succ[x])] == currCost-1) { finalPath.push_back(succ[x]); currCost--; break; } } } std::reverse(finalPath.begin(), finalPath.end()); }
/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. */ #include <cstdint> #include <cstring> #include <iostream> #include <stdexcept> #include <adios2.h> #include <gtest/gtest.h> #include "../SmallTestData.h" std::string engineName; // comes from command line namespace { template <class T> inline void AssignStep1D(const size_t step, std::vector<T> &vector, const size_t ghostCells = 0) { std::for_each(vector.begin() + ghostCells, vector.end() - ghostCells, [step](T &value) { value = static_cast<T>(step); }); } template <> void AssignStep1D(const size_t step, std::vector<std::complex<float>> &vector, const size_t ghostCells) { std::for_each(vector.begin() + ghostCells, vector.end() - ghostCells, [step](std::complex<float> &value) { value = std::complex<float>(static_cast<float>(step), static_cast<float>(step)); }); } template <> void AssignStep1D(const size_t step, std::vector<std::complex<double>> &vector, const size_t ghostCells) { std::for_each(vector.begin() + ghostCells, vector.end() - ghostCells, [step](std::complex<double> &value) { value = std::complex<double>(static_cast<double>(step), static_cast<double>(step)); }); } template <class T> inline void AssignStep2D(const size_t step, std::vector<T> &vector, const size_t Nx, const size_t Ny, const size_t ghostCellsX, const size_t ghostCellsY) { for (size_t j = ghostCellsY; j < Ny + ghostCellsY; ++j) { const size_t indexJ = j * (Nx + 2 * ghostCellsX); for (size_t i = ghostCellsX; i < Nx + ghostCellsX; ++i) { const size_t index = indexJ + i; vector[index] = static_cast<T>(step); } } } template <> void AssignStep2D(const size_t step, std::vector<std::complex<float>> &vector, const size_t Nx, const size_t Ny, const size_t ghostCellsX, const size_t ghostCellsY) { for (size_t j = ghostCellsY; j < Ny + ghostCellsY; ++j) { const size_t indexJ = j * (Nx + 2 * ghostCellsX); for (size_t i = ghostCellsX; i < Nx + ghostCellsX; ++i) { const size_t index = indexJ + i; vector[index] = std::complex<float>(static_cast<float>(step), static_cast<float>(step)); } } } template <> void AssignStep2D(const size_t step, std::vector<std::complex<double>> &vector, const size_t Nx, const size_t Ny, const size_t ghostCellsX, const size_t ghostCellsY) { for (size_t j = ghostCellsY; j < Ny + ghostCellsY; ++j) { const size_t indexJ = j * (Nx + 2 * ghostCellsX); for (size_t i = ghostCellsX; i < Nx + ghostCellsX; ++i) { const size_t index = indexJ + i; vector[index] = std::complex<double>(static_cast<double>(step), static_cast<double>(step)); } } } template <class T> inline void AssignStep3D(const size_t step, std::vector<T> &vector, const size_t Nx, const size_t Ny, const size_t Nz, const size_t ghostCellsX, const size_t ghostCellsY, const size_t ghostCellsZ) { for (size_t k = ghostCellsZ; k < Nz + ghostCellsZ; ++k) { const size_t indexK = k * (Ny + 2 * ghostCellsY) * (Nx + 2 * ghostCellsX); for (size_t j = ghostCellsY; j < Ny + ghostCellsY; ++j) { const size_t indexJ = j * (Nx + 2 * ghostCellsX); for (size_t i = ghostCellsX; i < Nx + ghostCellsX; ++i) { const size_t index = indexK + indexJ + i; vector[index] = static_cast<T>(step); } } } } template <> void AssignStep3D(const size_t step, std::vector<std::complex<float>> &vector, const size_t Nx, const size_t Ny, const size_t Nz, const size_t ghostCellsX, const size_t ghostCellsY, const size_t ghostCellsZ) { for (size_t k = ghostCellsZ; k < Nz + ghostCellsZ; ++k) { const size_t indexK = k * (Ny + 2 * ghostCellsY) * (Nx + 2 * ghostCellsX); for (size_t j = ghostCellsY; j < Ny + ghostCellsY; ++j) { const size_t indexJ = j * (Nx + 2 * ghostCellsX); for (size_t i = ghostCellsX; i < Nx + ghostCellsX; ++i) { const size_t index = indexK + indexJ + i; vector[index] = std::complex<float>(static_cast<float>(step), static_cast<float>(step)); } } } } template <> void AssignStep3D(const size_t step, std::vector<std::complex<double>> &vector, const size_t Nx, const size_t Ny, const size_t Nz, const size_t ghostCellsX, const size_t ghostCellsY, const size_t ghostCellsZ) { for (size_t k = ghostCellsZ; k < Nz + ghostCellsZ; ++k) { const size_t indexK = k * (Ny + 2 * ghostCellsY) * (Nx + 2 * ghostCellsX); for (size_t j = ghostCellsY; j < Ny + ghostCellsY; ++j) { const size_t indexJ = j * (Nx + 2 * ghostCellsX); for (size_t i = ghostCellsX; i < Nx + ghostCellsX; ++i) { const size_t index = indexK + indexJ + i; vector[index] = std::complex<double>(static_cast<double>(step), static_cast<double>(step)); } } } } } // end anonymous namespace void BPSteps1D(const size_t ghostCells) { const std::string fname("BPSteps1D_" + std::to_string(ghostCells) + ".bp"); int mpiRank = 0, mpiSize = 1; // Number of rows const size_t Nx = 10; // Number of steps const size_t NSteps = 3; #if ADIOS2_USE_MPI MPI_Comm_rank(MPI_COMM_WORLD, &mpiRank); MPI_Comm_size(MPI_COMM_WORLD, &mpiSize); #endif #if ADIOS2_USE_MPI adios2::ADIOS adios(MPI_COMM_WORLD); #else adios2::ADIOS adios(true); #endif { adios2::IO io = adios.DeclareIO("WriteIO"); if (!engineName.empty()) { io.SetEngine(engineName); } const adios2::Dims shape{static_cast<size_t>(Nx * mpiSize)}; const adios2::Dims start{static_cast<size_t>(Nx * mpiRank)}; const adios2::Dims count{Nx}; auto var_i8 = io.DefineVariable<int8_t>("i8", shape, start, count); auto var_i16 = io.DefineVariable<int16_t>("i16", shape, start, count); auto var_i32 = io.DefineVariable<int32_t>("i32", shape, start, count); auto var_i64 = io.DefineVariable<int64_t>("i64", shape, start, count); auto var_r32 = io.DefineVariable<float>("r32", shape, start, count); auto var_r64 = io.DefineVariable<double>("r64", shape, start, count); auto var_cr32 = io.DefineVariable<std::complex<float>>("cr32", shape, start, count); auto var_cr64 = io.DefineVariable<std::complex<double>>("cr64", shape, start, count); const adios2::Dims memoryStart = {ghostCells}; const adios2::Dims memoryCount = {Nx + 2 * ghostCells}; var_i8.SetMemorySelection({memoryStart, memoryCount}); var_i16.SetMemorySelection({memoryStart, memoryCount}); var_i32.SetMemorySelection({memoryStart, memoryCount}); var_i64.SetMemorySelection({memoryStart, memoryCount}); var_r32.SetMemorySelection({memoryStart, memoryCount}); var_r64.SetMemorySelection({memoryStart, memoryCount}); var_cr32.SetMemorySelection({memoryStart, memoryCount}); var_cr64.SetMemorySelection({memoryStart, memoryCount}); std::vector<int8_t> dataI8(Nx + 2 * ghostCells, -1); std::vector<int16_t> dataI16(Nx + 2 * ghostCells, -1); std::vector<int32_t> dataI32(Nx + 2 * ghostCells, -1); std::vector<int64_t> dataI64(Nx + 2 * ghostCells, -1); std::vector<float> dataR32(Nx + 2 * ghostCells, -1.f); std::vector<double> dataR64(Nx + 2 * ghostCells, -1.); std::vector<std::complex<float>> dataCR32(Nx + 2 * ghostCells, {-1.f, -1.f}); std::vector<std::complex<double>> dataCR64(Nx + 2 * ghostCells, {-1., -1.}); adios2::Engine bpWriter = io.Open(fname, adios2::Mode::Write); for (size_t i = 0; i < NSteps; ++i) { AssignStep1D(i, dataI8, ghostCells); AssignStep1D(i, dataI16, ghostCells); AssignStep1D(i, dataI32, ghostCells); AssignStep1D(i, dataI64, ghostCells); AssignStep1D(i, dataR32, ghostCells); AssignStep1D(i, dataR64, ghostCells); AssignStep1D(i, dataCR32, ghostCells); AssignStep1D(i, dataCR64, ghostCells); bpWriter.BeginStep(); bpWriter.Put(var_i8, dataI8.data()); bpWriter.Put(var_i16, dataI16.data()); bpWriter.Put(var_i32, dataI32.data()); bpWriter.Put(var_i64, dataI64.data()); bpWriter.Put(var_r32, dataR32.data()); bpWriter.Put(var_r64, dataR64.data()); bpWriter.Put(var_cr32, dataCR32.data()); bpWriter.Put(var_cr64, dataCR64.data()); bpWriter.EndStep(); } bpWriter.Close(); } #if ADIOS2_USE_MPI MPI_Barrier(MPI_COMM_WORLD); #endif // Reader { adios2::IO io = adios.DeclareIO("ReadIO"); if (!engineName.empty()) { io.SetEngine(engineName); } adios2::Engine bpReader = io.Open(fname, adios2::Mode::Read); auto var_i8 = io.InquireVariable<int8_t>("i8"); EXPECT_TRUE(var_i8); ASSERT_EQ(var_i8.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_i8.Steps(), NSteps); ASSERT_EQ(var_i8.Shape()[0], mpiSize * Nx); auto var_i16 = io.InquireVariable<int16_t>("i16"); EXPECT_TRUE(var_i16); ASSERT_EQ(var_i16.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_i16.Steps(), NSteps); ASSERT_EQ(var_i16.Shape()[0], mpiSize * Nx); auto var_i32 = io.InquireVariable<int32_t>("i32"); EXPECT_TRUE(var_i32); ASSERT_EQ(var_i32.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_i32.Steps(), NSteps); ASSERT_EQ(var_i32.Shape()[0], mpiSize * Nx); auto var_i64 = io.InquireVariable<int64_t>("i64"); EXPECT_TRUE(var_i64); ASSERT_EQ(var_i64.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_i64.Steps(), NSteps); ASSERT_EQ(var_i64.Shape()[0], mpiSize * Nx); auto var_r32 = io.InquireVariable<float>("r32"); EXPECT_TRUE(var_r32); ASSERT_EQ(var_r32.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_r32.Steps(), NSteps); ASSERT_EQ(var_r32.Shape()[0], mpiSize * Nx); auto var_r64 = io.InquireVariable<double>("r64"); EXPECT_TRUE(var_r64); ASSERT_EQ(var_r64.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_r64.Steps(), NSteps); ASSERT_EQ(var_r64.Shape()[0], mpiSize * Nx); auto var_cr32 = io.InquireVariable<std::complex<float>>("cr32"); EXPECT_TRUE(var_cr32); ASSERT_EQ(var_cr32.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_cr32.Steps(), NSteps); ASSERT_EQ(var_cr32.Shape()[0], mpiSize * Nx); auto var_cr64 = io.InquireVariable<std::complex<double>>("cr64"); EXPECT_TRUE(var_cr64); ASSERT_EQ(var_cr64.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_cr64.Steps(), NSteps); ASSERT_EQ(var_cr64.Shape()[0], mpiSize * Nx); while (bpReader.BeginStep() == adios2::StepStatus::OK) { std::vector<int8_t> I8; std::vector<int16_t> I16; std::vector<int32_t> I32; std::vector<int64_t> I64; std::vector<float> R32; std::vector<double> R64; std::vector<std::complex<float>> CR32; std::vector<std::complex<double>> CR64; bpReader.Get(var_i8, I8); bpReader.Get(var_i16, I16); bpReader.Get(var_i32, I32); bpReader.Get(var_i64, I64); bpReader.Get(var_r32, R32); bpReader.Get(var_r64, R64); bpReader.Get(var_cr32, CR32); bpReader.Get(var_cr64, CR64); bpReader.EndStep(); EXPECT_EQ(I8.size(), mpiSize * Nx); EXPECT_EQ(I16.size(), mpiSize * Nx); EXPECT_EQ(I32.size(), mpiSize * Nx); EXPECT_EQ(I64.size(), mpiSize * Nx); EXPECT_EQ(R32.size(), mpiSize * Nx); EXPECT_EQ(R64.size(), mpiSize * Nx); EXPECT_EQ(CR32.size(), mpiSize * Nx); EXPECT_EQ(CR64.size(), mpiSize * Nx); const size_t step = bpReader.CurrentStep(); EXPECT_EQ(I8.front(), static_cast<int8_t>(step)); EXPECT_EQ(I16.front(), static_cast<int16_t>(step)); EXPECT_EQ(I32.front(), static_cast<int32_t>(step)); EXPECT_EQ(I64.front(), static_cast<int64_t>(step)); EXPECT_EQ(R32.front(), static_cast<float>(step)); EXPECT_EQ(R64.front(), static_cast<double>(step)); EXPECT_EQ(CR32.front(), std::complex<float>(static_cast<float>(step), static_cast<float>(step))); EXPECT_EQ(CR64.front(), std::complex<double>(static_cast<double>(step), static_cast<double>(step))); EXPECT_EQ(std::adjacent_find(I8.begin(), I8.end(), std::not_equal_to<int8_t>()), I8.end()); EXPECT_EQ(std::adjacent_find(I16.begin(), I16.end(), std::not_equal_to<int16_t>()), I16.end()); EXPECT_EQ(std::adjacent_find(I32.begin(), I32.end(), std::not_equal_to<int32_t>()), I32.end()); EXPECT_EQ(std::adjacent_find(I64.begin(), I64.end(), std::not_equal_to<int64_t>()), I64.end()); EXPECT_EQ(std::adjacent_find(R32.begin(), R32.end(), std::not_equal_to<float>()), R32.end()); EXPECT_EQ(std::adjacent_find(R64.begin(), R64.end(), std::not_equal_to<double>()), R64.end()); EXPECT_EQ( std::adjacent_find(CR32.begin(), CR32.end(), std::not_equal_to<std::complex<float>>()), CR32.end()); EXPECT_EQ( std::adjacent_find(CR64.begin(), CR64.end(), std::not_equal_to<std::complex<double>>()), CR64.end()); } bpReader.Close(); } } void BPSteps2D4x2(const size_t ghostCells) { const std::string fname("BPSteps2D4x2_" + std::to_string(ghostCells) + ".bp"); int mpiRank = 0, mpiSize = 1; // Number of rows const size_t Nx = 2; const size_t Ny = 4; const size_t ghostCellsX = ghostCells; const size_t ghostCellsY = 2 * ghostCells; // Number of steps const size_t NSteps = 3; #if ADIOS2_USE_MPI MPI_Comm_rank(MPI_COMM_WORLD, &mpiRank); MPI_Comm_size(MPI_COMM_WORLD, &mpiSize); #endif #if ADIOS2_USE_MPI adios2::ADIOS adios(MPI_COMM_WORLD); #else adios2::ADIOS adios; #endif { adios2::IO io = adios.DeclareIO("WriteIO"); if (!engineName.empty()) { io.SetEngine(engineName); } const adios2::Dims shape{static_cast<size_t>(Ny * mpiSize), Nx}; const adios2::Dims start{static_cast<size_t>(Ny * mpiRank), 0}; const adios2::Dims count{Ny, Nx}; auto var_i8 = io.DefineVariable<int8_t>("i8", shape, start, count); auto var_i16 = io.DefineVariable<int16_t>("i16", shape, start, count); auto var_i32 = io.DefineVariable<int32_t>("i32", shape, start, count); auto var_i64 = io.DefineVariable<int64_t>("i64", shape, start, count); auto var_r32 = io.DefineVariable<float>("r32", shape, start, count); auto var_r64 = io.DefineVariable<double>("r64", shape, start, count); auto var_cr32 = io.DefineVariable<std::complex<float>>("cr32", shape, start, count); auto var_cr64 = io.DefineVariable<std::complex<double>>("cr64", shape, start, count); const adios2::Dims memoryStart = {ghostCellsY, ghostCellsX}; const adios2::Dims memoryCount = {Ny + 2 * ghostCellsY, Nx + 2 * ghostCellsX}; var_i8.SetMemorySelection({memoryStart, memoryCount}); var_i16.SetMemorySelection({memoryStart, memoryCount}); var_i32.SetMemorySelection({memoryStart, memoryCount}); var_i64.SetMemorySelection({memoryStart, memoryCount}); var_r32.SetMemorySelection({memoryStart, memoryCount}); var_r64.SetMemorySelection({memoryStart, memoryCount}); var_cr32.SetMemorySelection({memoryStart, memoryCount}); var_cr64.SetMemorySelection({memoryStart, memoryCount}); const size_t dataSize = (Ny + 2 * ghostCellsY) * (Nx + 2 * ghostCellsX); std::vector<int8_t> dataI8(dataSize, -1); std::vector<int16_t> dataI16(dataSize, -1); std::vector<int32_t> dataI32(dataSize, -1); std::vector<int64_t> dataI64(dataSize, -1); std::vector<float> dataR32(dataSize, -1.f); std::vector<double> dataR64(dataSize, -1.); std::vector<std::complex<float>> dataCR32(dataSize, {-1.f, -1.f}); std::vector<std::complex<double>> dataCR64(dataSize, {-1., -1.}); adios2::Engine bpWriter = io.Open(fname, adios2::Mode::Write); for (size_t i = 0; i < NSteps; ++i) { AssignStep2D(i, dataI8, Nx, Ny, ghostCellsX, ghostCellsY); AssignStep2D(i, dataI16, Nx, Ny, ghostCellsX, ghostCellsY); AssignStep2D(i, dataI32, Nx, Ny, ghostCellsX, ghostCellsY); AssignStep2D(i, dataI64, Nx, Ny, ghostCellsX, ghostCellsY); AssignStep2D(i, dataR32, Nx, Ny, ghostCellsX, ghostCellsY); AssignStep2D(i, dataR64, Nx, Ny, ghostCellsX, ghostCellsY); AssignStep2D(i, dataCR32, Nx, Ny, ghostCellsX, ghostCellsY); AssignStep2D(i, dataCR64, Nx, Ny, ghostCellsX, ghostCellsY); bpWriter.BeginStep(); bpWriter.Put(var_i8, dataI8.data()); bpWriter.Put(var_i16, dataI16.data()); bpWriter.Put(var_i32, dataI32.data()); bpWriter.Put(var_i64, dataI64.data()); bpWriter.Put(var_r32, dataR32.data()); bpWriter.Put(var_r64, dataR64.data()); bpWriter.Put(var_cr32, dataCR32.data(), adios2::Mode::Sync); bpWriter.Put(var_cr64, dataCR64.data(), adios2::Mode::Sync); bpWriter.EndStep(); } bpWriter.Close(); } #if ADIOS2_USE_MPI MPI_Barrier(MPI_COMM_WORLD); #endif // Reader { adios2::IO io = adios.DeclareIO("ReadIO"); if (!engineName.empty()) { io.SetEngine(engineName); } adios2::Engine bpReader = io.Open(fname, adios2::Mode::Read); auto var_i8 = io.InquireVariable<int8_t>("i8"); EXPECT_TRUE(var_i8); ASSERT_EQ(var_i8.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_i8.Steps(), NSteps); ASSERT_EQ(var_i8.Shape()[0], mpiSize * Ny); ASSERT_EQ(var_i8.Shape()[1], Nx); auto var_i16 = io.InquireVariable<int16_t>("i16"); EXPECT_TRUE(var_i16); ASSERT_EQ(var_i16.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_i16.Steps(), NSteps); ASSERT_EQ(var_i16.Shape()[0], mpiSize * Ny); ASSERT_EQ(var_i16.Shape()[1], Nx); auto var_i32 = io.InquireVariable<int32_t>("i32"); EXPECT_TRUE(var_i32); ASSERT_EQ(var_i32.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_i32.Steps(), NSteps); ASSERT_EQ(var_i32.Shape()[0], mpiSize * Ny); ASSERT_EQ(var_i32.Shape()[1], Nx); auto var_i64 = io.InquireVariable<int64_t>("i64"); EXPECT_TRUE(var_i64); ASSERT_EQ(var_i64.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_i64.Steps(), NSteps); ASSERT_EQ(var_i64.Shape()[0], mpiSize * Ny); ASSERT_EQ(var_i64.Shape()[1], Nx); auto var_r32 = io.InquireVariable<float>("r32"); EXPECT_TRUE(var_r32); ASSERT_EQ(var_r32.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_r32.Steps(), NSteps); ASSERT_EQ(var_r32.Shape()[0], mpiSize * Ny); ASSERT_EQ(var_r32.Shape()[1], Nx); auto var_r64 = io.InquireVariable<double>("r64"); EXPECT_TRUE(var_r64); ASSERT_EQ(var_r64.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_r64.Steps(), NSteps); ASSERT_EQ(var_r64.Shape()[0], mpiSize * Ny); ASSERT_EQ(var_r64.Shape()[1], Nx); auto var_cr32 = io.InquireVariable<std::complex<float>>("cr32"); EXPECT_TRUE(var_cr32); ASSERT_EQ(var_cr32.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_cr32.Steps(), NSteps); ASSERT_EQ(var_cr32.Shape()[0], mpiSize * Ny); ASSERT_EQ(var_cr32.Shape()[1], Nx); auto var_cr64 = io.InquireVariable<std::complex<double>>("cr64"); EXPECT_TRUE(var_cr64); ASSERT_EQ(var_cr64.ShapeID(), adios2::ShapeID::GlobalArray); ASSERT_EQ(var_cr64.Steps(), NSteps); ASSERT_EQ(var_cr64.Shape()[0], mpiSize * Ny); ASSERT_EQ(var_cr64.Shape()[1], Nx); while (bpReader.BeginStep() == adios2::StepStatus::OK) { std::vector<int8_t> I8; std::vector<int16_t> I16; std::vector<int32_t> I32; std::vector<int64_t> I64; std::vector<float> R32; std::vector<double> R64; std::vector<std::complex<float>> CR32; std::vector<std::complex<double>> CR64; bpReader.Get(var_i8, I8); bpReader.Get(var_i16, I16); bpReader.Get(var_i32, I32); bpReader.Get(var_i64, I64); bpReader.Get(var_r32, R32); bpReader.Get(var_r64, R64); bpReader.Get(var_cr32, CR32); bpReader.Get(var_cr64, CR64); bpReader.EndStep(); const size_t dataSize = mpiSize * Ny * Nx; EXPECT_EQ(I8.size(), dataSize); EXPECT_EQ(I16.size(), dataSize); EXPECT_EQ(I32.size(), dataSize); EXPECT_EQ(I64.size(), dataSize); EXPECT_EQ(R32.size(), dataSize); EXPECT_EQ(R64.size(), dataSize); EXPECT_EQ(CR32.size(), dataSize); EXPECT_EQ(CR64.size(), dataSize); const size_t step = bpReader.CurrentStep(); EXPECT_EQ(I8.front(), static_cast<int8_t>(step)); EXPECT_EQ(I16.front(), static_cast<int16_t>(step)); EXPECT_EQ(I32.front(), static_cast<int32_t>(step)); EXPECT_EQ(I64.front(), static_cast<int64_t>(step)); EXPECT_EQ(R32.front(), static_cast<float>(step)); EXPECT_EQ(R64.front(), static_cast<double>(step)); EXPECT_EQ(CR32.front(), std::complex<float>(static_cast<float>(step), static_cast<float>(step))); EXPECT_EQ(CR64.front(), std::complex<double>(static_cast<double>(step), static_cast<double>(step))); EXPECT_EQ(std::adjacent_find(I8.begin(), I8.end(), std::not_equal_to<int8_t>()), I8.end()); EXPECT_EQ(std::adjacent_find(I16.begin(), I16.end(), std::not_equal_to<int16_t>()), I16.end()); EXPECT_EQ(std::adjacent_find(I32.begin(), I32.end(), std::not_equal_to<int32_t>()), I32.end()); EXPECT_EQ(std::adjacent_find(I64.begin(), I64.end(), std::not_equal_to<int64_t>()), I64.end()); EXPECT_EQ(std::adjacent_find(R32.begin(), R32.end(), std::not_equal_to<float>()), R32.end()); EXPECT_EQ(std::adjacent_find(R64.begin(), R64.end(), std::not_equal_to<double>()), R64.end()); EXPECT_EQ( std::adjacent_find(CR32.begin(), CR32.end(), std::not_equal_to<std::complex<float>>()), CR32.end()); EXPECT_EQ( std::adjacent_find(CR64.begin(), CR64.end(), std::not_equal_to<std::complex<double>>()), CR64.end()); } bpReader.Close(); } } void BPSteps3D8x2x4(const size_t ghostCells) { const std::string fname("BPSteps3D8x2x4_" + std::to_string(ghostCells) + ".bp"); int mpiRank = 0, mpiSize = 1; // Number of rows const size_t Nx = 4; const size_t Ny = 2; const size_t Nz = 8; const size_t ghostCellsX = 2 * ghostCells; const size_t ghostCellsY = 4 * ghostCells; const size_t ghostCellsZ = ghostCells; // Number of steps const size_t NSteps = 3; #if ADIOS2_USE_MPI MPI_Comm_rank(MPI_COMM_WORLD, &mpiRank); MPI_Comm_size(MPI_COMM_WORLD, &mpiSize); #endif #if ADIOS2_USE_MPI adios2::ADIOS adios(MPI_COMM_WORLD); #else adios2::ADIOS adios; #endif { adios2::IO io = adios.DeclareIO("WriteIO"); if (!engineName.empty()) { io.SetEngine(engineName); } const adios2::Dims shape{static_cast<size_t>(Nz * mpiSize), Ny, Nx}; const adios2::Dims start{static_cast<size_t>(Nz * mpiRank), 0, 0}; const adios2::Dims count{Nz, Ny, Nx}; auto var_i8 = io.DefineVariable<int8_t>("i8", shape, start, count); auto var_i16 = io.DefineVariable<int16_t>("i16", shape, start, count); auto var_i32 = io.DefineVariable<int32_t>("i32", shape, start, count); auto var_i64 = io.DefineVariable<int64_t>("i64", shape, start, count); auto var_r32 = io.DefineVariable<float>("r32", shape, start, count); auto var_r64 = io.DefineVariable<double>("r64", shape, start, count); auto var_cr32 = io.DefineVariable<std::complex<float>>("cr32", shape, start, count); auto var_cr64 = io.DefineVariable<std::complex<double>>("cr64", shape, start, count); const adios2::Dims memoryStart = {ghostCellsZ, ghostCellsY, ghostCellsX}; const adios2::Dims memoryCount = { Nz + 2 * ghostCellsZ, Ny + 2 * ghostCellsY, Nx + 2 * ghostCellsX}; var_i8.SetMemorySelection({memoryStart, memoryCount}); var_i16.SetMemorySelection({memoryStart, memoryCount}); var_i32.SetMemorySelection({memoryStart, memoryCount}); var_i64.SetMemorySelection({memoryStart, memoryCount}); var_r32.SetMemorySelection({memoryStart, memoryCount}); var_r64.SetMemorySelection({memoryStart, memoryCount}); var_cr32.SetMemorySelection({memoryStart, memoryCount}); var_cr64.SetMemorySelection({memoryStart, memoryCount}); const size_t dataSize = (Nz + 2 * ghostCellsZ) * (Ny + 2 * ghostCellsY) * (Nx + 2 * ghostCellsX); std::vector<int8_t> dataI8(dataSize, -1); std::vector<int16_t> dataI16(dataSize, -1); std::vector<int32_t> dataI32(dataSize, -1); std::vector<int64_t> dataI64(dataSize, -1); std::vector<float> dataR32(dataSize, -1.f); std::vector<double> dataR64(dataSize, -1.); std::vector<std::complex<float>> dataCR32(dataSize, {-1.f, -1.f}); std::vector<std::complex<double>> dataCR64(dataSize, {-1., -1.}); adios2::Engine bpWriter = io.Open(fname, adios2::Mode::Write); for (size_t i = 0; i < NSteps; ++i) { AssignStep3D(i, dataI8, Nx, Ny, Nz, ghostCellsX, ghostCellsY, ghostCellsZ); AssignStep3D(i, dataI16, Nx, Ny, Nz, ghostCellsX, ghostCellsY, ghostCellsZ); AssignStep3D(i, dataI32, Nx, Ny, Nz, ghostCellsX, ghostCellsY, ghostCellsZ); AssignStep3D(i, dataI64, Nx, Ny, Nz, ghostCellsX, ghostCellsY, ghostCellsZ); AssignStep3D(i, dataR32, Nx, Ny, Nz, ghostCellsX, ghostCellsY, ghostCellsZ); AssignStep3D(i, dataR64, Nx, Ny, Nz, ghostCellsX, ghostCellsY, ghostCellsZ); AssignStep3D(i, dataCR32, Nx, Ny, Nz, ghostCellsX, ghostCellsY, ghostCellsZ); AssignStep3D(i, dataCR64, Nx, Ny, Nz, ghostCellsX, ghostCellsY, ghostCellsZ); bpWriter.BeginStep(); bpWriter.Put(var_i8, dataI8.data()); bpWriter.Put(var_i16, dataI16.data()); bpWriter.Put(var_i32, dataI32.data()); bpWriter.Put(var_i64, dataI64.data()); bpWriter.Put(var_r32, dataR32.data()); bpWriter.Put(var_r64, dataR64.data()); bpWriter.Put(var_cr32, dataCR32.data()); bpWriter.Put(var_cr64, dataCR64.data()); bpWriter.EndStep(); } bpWriter.Close(); } #if ADIOS2_USE_MPI MPI_Barrier(MPI_COMM_WORLD); #endif // Reader { adios2::IO io = adios.DeclareIO("ReadIO"); if (!engineName.empty()) { io.SetEngine(engineName); } adios2::Engine bpReader = io.Open(fname, adios2::Mode::Read); while (bpReader.BeginStep() == adios2::StepStatus::OK) { const size_t currentStep = bpReader.CurrentStep(); auto var_i8 = io.InquireVariable<int8_t>("i8"); EXPECT_TRUE(var_i8); EXPECT_EQ(var_i8.ShapeID(), adios2::ShapeID::GlobalArray); EXPECT_EQ(var_i8.Steps(), NSteps); EXPECT_EQ(var_i8.Shape()[0], mpiSize * Nz); EXPECT_EQ(var_i8.Shape()[1], Ny); EXPECT_EQ(var_i8.Shape()[2], Nx); EXPECT_EQ(var_i8.Min(), static_cast<int8_t>(currentStep)); EXPECT_EQ(var_i8.Max(), static_cast<int8_t>(currentStep)); auto var_i16 = io.InquireVariable<int16_t>("i16"); EXPECT_TRUE(var_i16); EXPECT_EQ(var_i16.ShapeID(), adios2::ShapeID::GlobalArray); EXPECT_EQ(var_i16.Steps(), NSteps); EXPECT_EQ(var_i16.Shape()[0], mpiSize * Nz); EXPECT_EQ(var_i16.Shape()[1], Ny); EXPECT_EQ(var_i16.Shape()[2], Nx); EXPECT_EQ(var_i16.Min(), static_cast<int16_t>(currentStep)); EXPECT_EQ(var_i16.Max(), static_cast<int16_t>(currentStep)); auto var_i32 = io.InquireVariable<int32_t>("i32"); EXPECT_TRUE(var_i32); EXPECT_EQ(var_i32.ShapeID(), adios2::ShapeID::GlobalArray); EXPECT_EQ(var_i32.Steps(), NSteps); EXPECT_EQ(var_i32.Shape()[0], mpiSize * Nz); EXPECT_EQ(var_i32.Shape()[1], Ny); EXPECT_EQ(var_i32.Shape()[2], Nx); EXPECT_EQ(var_i32.Min(), static_cast<int32_t>(currentStep)); EXPECT_EQ(var_i32.Max(), static_cast<int32_t>(currentStep)); auto var_i64 = io.InquireVariable<int64_t>("i64"); EXPECT_TRUE(var_i64); EXPECT_EQ(var_i64.ShapeID(), adios2::ShapeID::GlobalArray); EXPECT_EQ(var_i64.Steps(), NSteps); EXPECT_EQ(var_i64.Shape()[0], mpiSize * Nz); EXPECT_EQ(var_i64.Shape()[1], Ny); EXPECT_EQ(var_i64.Shape()[2], Nx); EXPECT_EQ(var_i64.Min(), static_cast<int64_t>(currentStep)); EXPECT_EQ(var_i64.Max(), static_cast<int64_t>(currentStep)); auto var_r32 = io.InquireVariable<float>("r32"); EXPECT_TRUE(var_r32); EXPECT_EQ(var_r32.ShapeID(), adios2::ShapeID::GlobalArray); EXPECT_EQ(var_r32.Steps(), NSteps); EXPECT_EQ(var_r32.Shape()[0], mpiSize * Nz); EXPECT_EQ(var_r32.Shape()[1], Ny); EXPECT_EQ(var_r32.Shape()[2], Nx); EXPECT_EQ(var_r32.Min(), static_cast<float>(currentStep)); EXPECT_EQ(var_r32.Max(), static_cast<float>(currentStep)); auto var_r64 = io.InquireVariable<double>("r64"); EXPECT_TRUE(var_r64); EXPECT_EQ(var_r64.ShapeID(), adios2::ShapeID::GlobalArray); EXPECT_EQ(var_r64.Steps(), NSteps); EXPECT_EQ(var_r64.Shape()[0], mpiSize * Nz); EXPECT_EQ(var_r64.Shape()[1], Ny); EXPECT_EQ(var_r64.Shape()[2], Nx); EXPECT_EQ(var_r64.Min(), static_cast<double>(currentStep)); EXPECT_EQ(var_r64.Max(), static_cast<double>(currentStep)); auto var_cr32 = io.InquireVariable<std::complex<float>>("cr32"); EXPECT_TRUE(var_cr32); EXPECT_EQ(var_cr32.ShapeID(), adios2::ShapeID::GlobalArray); EXPECT_EQ(var_cr32.Steps(), NSteps); EXPECT_EQ(var_cr32.Shape()[0], mpiSize * Nz); EXPECT_EQ(var_cr32.Shape()[1], Ny); EXPECT_EQ(var_cr32.Shape()[2], Nx); EXPECT_EQ(var_cr32.Min(), std::complex<float>(static_cast<float>(currentStep), static_cast<float>(currentStep))); EXPECT_EQ(var_cr32.Max(), std::complex<float>(static_cast<float>(currentStep), static_cast<float>(currentStep))); auto var_cr64 = io.InquireVariable<std::complex<double>>("cr64"); EXPECT_TRUE(var_cr64); EXPECT_EQ(var_cr64.ShapeID(), adios2::ShapeID::GlobalArray); EXPECT_EQ(var_cr64.Steps(), NSteps); EXPECT_EQ(var_cr64.Shape()[0], mpiSize * Nz); EXPECT_EQ(var_cr64.Shape()[1], Ny); EXPECT_EQ(var_cr64.Shape()[2], Nx); EXPECT_EQ(var_cr64.Min(), std::complex<double>(static_cast<double>(currentStep), static_cast<double>(currentStep))); EXPECT_EQ(var_cr64.Max(), std::complex<double>(static_cast<double>(currentStep), static_cast<double>(currentStep))); std::vector<int8_t> I8; std::vector<int16_t> I16; std::vector<int32_t> I32; std::vector<int64_t> I64; std::vector<float> R32; std::vector<double> R64; std::vector<std::complex<float>> CR32; std::vector<std::complex<double>> CR64; bpReader.Get(var_i8, I8); bpReader.Get(var_i16, I16); bpReader.Get(var_i32, I32); bpReader.Get(var_i64, I64); bpReader.Get(var_r32, R32); bpReader.Get(var_r64, R64); bpReader.Get(var_cr32, CR32); bpReader.Get(var_cr64, CR64); bpReader.EndStep(); const size_t dataSize = mpiSize * Nz * Ny * Nx; EXPECT_EQ(I8.size(), dataSize); EXPECT_EQ(I16.size(), dataSize); EXPECT_EQ(I32.size(), dataSize); EXPECT_EQ(I64.size(), dataSize); EXPECT_EQ(R32.size(), dataSize); EXPECT_EQ(R64.size(), dataSize); EXPECT_EQ(CR32.size(), dataSize); EXPECT_EQ(CR64.size(), dataSize); const size_t step = bpReader.CurrentStep(); EXPECT_EQ(I8.front(), static_cast<int8_t>(step)); EXPECT_EQ(I16.front(), static_cast<int16_t>(step)); EXPECT_EQ(I32.front(), static_cast<int32_t>(step)); EXPECT_EQ(I64.front(), static_cast<int64_t>(step)); EXPECT_EQ(R32.front(), static_cast<float>(step)); EXPECT_EQ(R64.front(), static_cast<double>(step)); EXPECT_EQ(CR32.front(), std::complex<float>(static_cast<float>(step), static_cast<float>(step))); EXPECT_EQ(CR64.front(), std::complex<double>(static_cast<double>(step), static_cast<double>(step))); EXPECT_EQ(std::adjacent_find(I8.begin(), I8.end(), std::not_equal_to<int8_t>()), I8.end()); EXPECT_EQ(std::adjacent_find(I16.begin(), I16.end(), std::not_equal_to<int16_t>()), I16.end()); EXPECT_EQ(std::adjacent_find(I32.begin(), I32.end(), std::not_equal_to<int32_t>()), I32.end()); EXPECT_EQ(std::adjacent_find(I64.begin(), I64.end(), std::not_equal_to<int64_t>()), I64.end()); EXPECT_EQ(std::adjacent_find(R32.begin(), R32.end(), std::not_equal_to<float>()), R32.end()); EXPECT_EQ(std::adjacent_find(R64.begin(), R64.end(), std::not_equal_to<double>()), R64.end()); EXPECT_EQ( std::adjacent_find(CR32.begin(), CR32.end(), std::not_equal_to<std::complex<float>>()), CR32.end()); EXPECT_EQ( std::adjacent_find(CR64.begin(), CR64.end(), std::not_equal_to<std::complex<double>>()), CR64.end()); } bpReader.Close(); } } class BPWriteMemSelReadVector : public ::testing::TestWithParam<size_t> { public: BPWriteMemSelReadVector() = default; virtual void SetUp() {} virtual void TearDown() {} }; TEST_P(BPWriteMemSelReadVector, BPMemorySelectionSteps1D) { BPSteps1D(GetParam()); } TEST_P(BPWriteMemSelReadVector, BPMemorySelectionSteps2D4x2) { BPSteps2D4x2(GetParam()); } TEST_P(BPWriteMemSelReadVector, BPMemorySelectionSteps3D4x2x8) { BPSteps3D8x2x4(GetParam()); } INSTANTIATE_TEST_CASE_P(ghostCells, BPWriteMemSelReadVector, ::testing::Values(1)); int main(int argc, char **argv) { #if ADIOS2_USE_MPI MPI_Init(nullptr, nullptr); #endif int result; ::testing::InitGoogleTest(&argc, argv); if (argc > 1) { engineName = std::string(argv[1]); } result = RUN_ALL_TESTS(); #if ADIOS2_USE_MPI MPI_Finalize(); #endif return result; }
// // Integer number functions. // // Copyright (C) 2001-2007 Peter Johnson // // 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. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND OTHER CONTRIBUTORS ``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 OR OTHER 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. // #include "yasmx/IntNum.h" #include <cctype> #include <climits> #include <cstdio> #include <cstdlib> #include <cstring> #include <limits> #include "llvm/ADT/SmallString.h" #include "llvm/Support/raw_ostream.h" #include "yasmx/Basic/Diagnostic.h" using namespace yasm; /// Static bitvect used for conversions. static llvm::APInt conv_bv(IntNum::BITVECT_NATIVE_SIZE, 0); /// Static bitvects used for computation. static llvm::APInt result(IntNum::BITVECT_NATIVE_SIZE, 0); static llvm::APInt spare(IntNum::BITVECT_NATIVE_SIZE, 0); static llvm::APInt op1static(IntNum::BITVECT_NATIVE_SIZE, 0); static llvm::APInt op2static(IntNum::BITVECT_NATIVE_SIZE, 0); /// Static bitvect used for sign extension. static llvm::APInt signext_bv(IntNum::BITVECT_NATIVE_SIZE, 0); enum { SV_BITS = std::numeric_limits<IntNumData::SmallValue>::digits, LONG_BITS = std::numeric_limits<long>::digits, ULONG_BITS = std::numeric_limits<unsigned long>::digits }; bool yasm::isOkSize(const llvm::APInt& intn, unsigned int size, unsigned int rshift, int rangetype) { unsigned int intn_size; switch (rangetype) { case 0: intn_size = intn.getActiveBits(); break; case 1: intn_size = intn.getMinSignedBits(); break; case 2: if (intn.isNegative()) intn_size = intn.getMinSignedBits(); else intn_size = intn.getActiveBits(); break; default: assert(false && "invalid range type"); return false; } return (intn_size <= (size-rshift)); } void IntNum::setBV(const llvm::APInt& bv) { if (bv.getMinSignedBits() <= SV_BITS) { if (m_type == INTNUM_BV) delete m_val.bv; m_type = INTNUM_SV; m_val.sv = static_cast<SmallValue>(bv.getSExtValue()); return; } else if (m_type == INTNUM_BV) { *m_val.bv = bv; } else { m_type = INTNUM_BV; m_val.bv = new llvm::APInt(bv); } m_val.bv->sextOrTrunc(BITVECT_NATIVE_SIZE); } const llvm::APInt* IntNum::getBV(llvm::APInt* bv) const { if (m_type == INTNUM_BV) return m_val.bv; if (m_val.sv >= 0) *bv = static_cast<USmallValue>(m_val.sv); else { *bv = static_cast<USmallValue>(~m_val.sv); bv->flip(); } return bv; } llvm::APInt* IntNum::getBV(llvm::APInt* bv) { if (m_type == INTNUM_BV) return m_val.bv; if (m_val.sv >= 0) *bv = static_cast<USmallValue>(m_val.sv); else { *bv = static_cast<USmallValue>(~m_val.sv); bv->flip(); } return bv; } /// Return the value of the specified hex digit, or -1 if it's not valid. static unsigned int HexDigitValue(char ch) { if (ch >= '0' && ch <= '9') return ch-'0'; if (ch >= 'a' && ch <= 'f') return ch-'a'+10; if (ch >= 'A' && ch <= 'F') return ch-'A'+10; if (ch == '_') return 0; return ~0; } bool IntNum::setStr(llvm::StringRef str, unsigned int radix) { // Each computation below needs to know if its negative bool is_neg = (str[0] == '-'); unsigned int minbits = is_neg ? 1 : 0; size_t len = str.size(); llvm::StringRef::iterator begin = str.begin(); if (is_neg) { ++begin; --len; } // For radixes of power-of-two values, the bits required is accurately and // easily computed. For radix 10, we use a rough approximation. switch (radix) { case 2: minbits += (len-minbits); break; case 8: minbits += (len-minbits) * 3; break; case 16: minbits += (len-minbits) * 4; break; case 10: minbits += ((len-minbits) * 64) / 22; break; default: { unsigned int max_bits_per_digit = 1; while ((1U << max_bits_per_digit) < radix) max_bits_per_digit += 1; minbits += len * max_bits_per_digit; } } if (minbits > BITVECT_NATIVE_SIZE) return false; if (minbits < SV_BITS) { // shortcut "short" case SmallValue v = 0; for (llvm::StringRef::iterator i = begin, end = str.end(); i != end; ++i) { unsigned int c = HexDigitValue(*i); assert(c < radix && "invalid digit for given radix"); v = v*radix + c; } set(is_neg ? -v : v); return true; } // long case conv_bv = 0; // Figure out if we can shift instead of multiply unsigned int shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0); llvm::APInt& radixval = op1static; llvm::APInt& charval = op2static; llvm::APInt& oldval = spare; radixval = radix; oldval = 0; bool overflowed = false; for (llvm::StringRef::iterator i=begin, end=str.end(); i != end; ++i) { unsigned int c = HexDigitValue(*i); // If this letter is out of bound for this radix, reject it. assert(c < radix && "invalid digit for given radix"); charval = c; // Add the digit to the value in the appropriate radix. If adding in // digits made the value smaller, then this overflowed. oldval = conv_bv; // Shift or multiply by radix, did overflow occur on the multiply? if (shift) conv_bv <<= shift; else conv_bv *= radixval; overflowed |= conv_bv.udiv(radixval) != oldval; // Add value, did overflow occur on the value? // (a + b) ult b <=> overflow conv_bv += charval; overflowed |= conv_bv.ult(charval); } // If it's negative, put it in two's complement form if (is_neg) { --conv_bv; conv_bv.flip(); } setBV(conv_bv); return overflowed; } IntNum::IntNum(const IntNum& rhs) { m_type = rhs.m_type; if (rhs.m_type == INTNUM_BV) m_val.bv = new llvm::APInt(*rhs.m_val.bv); else m_val.sv = rhs.m_val.sv; } // Speedup function for non-bitvect calculations. // Always makes conservative assumptions; we fall back to bitvect if this // function does not set handled to true. static bool CalcSmallValue(bool* handled, Op::Op op, IntNumData::SmallValue* lhs, IntNumData::SmallValue rhs, SourceLocation source, Diagnostic* diags) { static const IntNumData::SmallValue SV_MAX = std::numeric_limits<IntNumData::SmallValue>::max(); static const IntNumData::SmallValue SV_MIN = std::numeric_limits<IntNumData::SmallValue>::min(); *handled = false; switch (op) { case Op::ADD: if (*lhs >= SV_MAX/2 || *lhs <= SV_MIN/2 || rhs >= SV_MAX/2 || rhs <= SV_MIN/2) return true; *lhs += rhs; break; case Op::SUB: if (*lhs >= SV_MAX/2 || *lhs <= SV_MIN/2 || rhs >= SV_MAX/2 || rhs <= SV_MIN/2) return true; *lhs -= rhs; break; case Op::MUL: { // half range IntNumData::SmallValue minmax = 1; minmax <<= SV_BITS/2; if (*lhs > -minmax && *lhs < minmax) { if (rhs <= -minmax || rhs >= minmax) return true; *lhs *= rhs; break; } // maybe someday? return true; } case Op::DIV: // TODO: make sure lhs and rhs are unsigned case Op::SIGNDIV: if (rhs == 0) { assert(diags && "divide by zero"); diags->Report(source, diag::err_divide_by_zero); return false; } *lhs /= rhs; break; case Op::MOD: // TODO: make sure lhs and rhs are unsigned case Op::SIGNMOD: if (rhs == 0) { assert(diags && "divide by zero"); diags->Report(source, diag::err_divide_by_zero); return false; } *lhs %= rhs; break; case Op::NEG: *lhs = -(*lhs); break; case Op::NOT: *lhs = ~(*lhs); break; case Op::OR: *lhs |= rhs; break; case Op::AND: *lhs &= rhs; break; case Op::XOR: *lhs ^= rhs; break; case Op::XNOR: *lhs = ~(*lhs ^ rhs); break; case Op::NOR: *lhs = ~(*lhs | rhs); break; case Op::SHL: // maybe someday? return true; case Op::SHR: *lhs >>= rhs; break; case Op::LOR: *lhs = (*lhs || rhs); break; case Op::LAND: *lhs = (*lhs && rhs); break; case Op::LNOT: *lhs = !*lhs; break; case Op::LXOR: *lhs = (!!(*lhs) ^ !!rhs); break; case Op::LXNOR: *lhs = !(!!(*lhs) ^ !!rhs); break; case Op::LNOR: *lhs = !(*lhs || rhs); break; case Op::EQ: *lhs = (*lhs == rhs); break; case Op::LT: *lhs = (*lhs < rhs); break; case Op::GT: *lhs = (*lhs > rhs); break; case Op::LE: *lhs = (*lhs <= rhs); break; case Op::GE: *lhs = (*lhs >= rhs); break; case Op::NE: *lhs = (*lhs != rhs); break; case Op::IDENT: break; default: return true; } *handled = true; return true; } /*@-nullderef -nullpass -branchstate@*/ bool IntNum::CalcImpl(Op::Op op, const IntNum* operand, SourceLocation source, Diagnostic* diags) { assert((operand || op == Op::NEG || op == Op::NOT || op == Op::LNOT) && "operation needs an operand"); if (m_type == INTNUM_SV && (!operand || operand->m_type == INTNUM_SV)) { bool handled = false; if (!CalcSmallValue(&handled, op, &m_val.sv, operand ? operand->m_val.sv : 0, source, diags)) return false; if (handled) return true; } // Always do computations with in full bit vector. // Bit vector results must be calculated through intermediate storage. const llvm::APInt* op1 = getBV(&op1static); const llvm::APInt* op2 = 0; if (operand) op2 = operand->getBV(&op2static); // A operation does a bitvector computation if result is allocated. switch (op) { case Op::ADD: { result = *op1; result += *op2; break; } case Op::SUB: { result = *op1; result -= *op2; break; } case Op::MUL: result = *op1; result *= *op2; break; case Op::DIV: // TODO: make sure op1 and op2 are unsigned if (!*op2) { assert(diags && "divide by zero"); diags->Report(source, diag::err_divide_by_zero); return false; } result = op1->udiv(*op2); break; case Op::SIGNDIV: if (!*op2) { assert(diags && "divide by zero"); diags->Report(source, diag::err_divide_by_zero); return false; } result = op1->sdiv(*op2); break; case Op::MOD: // TODO: make sure op1 and op2 are unsigned if (!*op2) { assert(diags && "divide by zero"); diags->Report(source, diag::err_divide_by_zero); return false; } result = op1->urem(*op2); break; case Op::SIGNMOD: if (!*op2) { assert(diags && "divide by zero"); diags->Report(source, diag::err_divide_by_zero); return false; } result = op1->srem(*op2); break; case Op::NEG: result = -*op1; break; case Op::NOT: result = *op1; result.flip(); break; case Op::OR: result = *op1; result |= *op2; break; case Op::AND: result = *op1; result &= *op2; break; case Op::XOR: result = *op1; result ^= *op2; break; case Op::XNOR: result = *op1; result ^= *op2; result.flip(); break; case Op::NOR: result = *op1; result |= *op2; result.flip(); break; case Op::SHL: if (operand->m_type == INTNUM_SV) { if (operand->m_val.sv >= 0) result = op1->shl(operand->m_val.sv); else result = op1->ashr(-operand->m_val.sv); } else // don't even bother, just zero result result.clear(); break; case Op::SHR: if (operand->m_type == INTNUM_SV) { if (operand->m_val.sv >= 0) result = op1->ashr(operand->m_val.sv); else result = op1->shl(-operand->m_val.sv); } else // don't even bother, just zero result result.clear(); break; case Op::LOR: set(static_cast<SmallValue>((!!*op1) || (!!*op2))); return true; case Op::LAND: set(static_cast<SmallValue>((!!*op1) && (!!*op2))); return true; case Op::LNOT: set(static_cast<SmallValue>(!*op1)); return true; case Op::LXOR: set(static_cast<SmallValue>((!!*op1) ^ (!!*op2))); return true; case Op::LXNOR: set(static_cast<SmallValue>(!((!!*op1) ^ (!!*op2)))); return true; case Op::LNOR: set(static_cast<SmallValue>(!((!!*op1) || (!!*op2)))); return true; case Op::EQ: set(static_cast<SmallValue>(op1->eq(*op2))); return true; case Op::LT: set(static_cast<SmallValue>(op1->slt(*op2))); return true; case Op::GT: set(static_cast<SmallValue>(op1->sgt(*op2))); return true; case Op::LE: set(static_cast<SmallValue>(op1->sle(*op2))); return true; case Op::GE: set(static_cast<SmallValue>(op1->sge(*op2))); return true; case Op::NE: set(static_cast<SmallValue>(op1->ne(*op2))); return true; case Op::SEG: assert(diags && "invalid use of operator 'SEG'"); diags->Report(source, diag::err_invalid_op_use) << "SEG"; return false; case Op::WRT: assert(diags && "invalid use of operator 'WRT'"); diags->Report(source, diag::err_invalid_op_use) << "WRT"; return false; case Op::SEGOFF: assert(diags && "invalid use of operator ':'"); diags->Report(source, diag::err_invalid_op_use) << ":"; return false; case Op::IDENT: result = *op1; break; default: assert(diags && "invalid integer operation"); diags->Report(source, diag::err_int_invalid_op); return false; } // Try to fit the result into long if possible setBV(result); return true; } /*@=nullderef =nullpass =branchstate@*/ void IntNum::SignExtend(unsigned int size) { // For now, always implement with full bit vector. llvm::APInt* bv = getBV(&signext_bv); bv->trunc(size); bv->sext(BITVECT_NATIVE_SIZE); setBV(*bv); } void IntNum::set(IntNum::USmallValue val) { if (val > static_cast<USmallValue>(std::numeric_limits<SmallValue>::max())) { if (m_type == INTNUM_BV) *m_val.bv = val; else { m_val.bv = new llvm::APInt(BITVECT_NATIVE_SIZE, val); m_type = INTNUM_BV; } } else { if (m_type == INTNUM_BV) { delete m_val.bv; m_type = INTNUM_SV; } m_val.sv = static_cast<SmallValue>(val); } } int IntNum::getSign() const { if (m_type == INTNUM_SV) { if (m_val.sv == 0) return 0; else if (m_val.sv < 0) return -1; else return 1; } else if (m_val.bv->isNegative()) return -1; else return 1; } unsigned long IntNum::getUInt() const { if (m_type == INTNUM_SV) { if (m_val.sv < 0) return 0; return static_cast<unsigned long>(m_val.sv); } // Handle bigval if (m_val.bv->isNegative()) return 0; if (m_val.bv->getActiveBits() > ULONG_BITS) return ULONG_MAX; return static_cast<unsigned long>(m_val.bv->getZExtValue()); } long IntNum::getInt() const { if (m_type == INTNUM_SV) { if (m_val.sv < LONG_MIN) return LONG_MIN; if (m_val.sv > LONG_MAX) return LONG_MAX; return m_val.sv; } // since it's a BV, it must be >0x7FFFFFFF or <0x80000000 if (m_val.bv->isNegative()) return LONG_MIN; return LONG_MAX; } bool IntNum::isInt() const { if (m_type != INTNUM_SV) return false; return (m_val.sv >= LONG_MIN && m_val.sv <= LONG_MAX); } bool IntNum::isOkSize(unsigned int size, unsigned int rshift, int rangetype) const { static const IntNumData::SmallValue SV_MIN = std::numeric_limits<IntNumData::SmallValue>::min(); // Non-bigval (for speed) if (m_type == INTNUM_SV) { SmallValue one = 1; SmallValue v = m_val.sv; v >>= rshift; switch (rangetype) { case 0: if (v < 0) return false; if (size >= SV_BITS) return true; return (v < (one<<size)); case 1: if (v < 0) { if (size >= SV_BITS+1) return true; if (v == SV_MIN) return size >= SV_BITS; v = 0-v; return (v <= (one<<(size-1))); } if (size >= SV_BITS+1) return true; return (v < (one<<(size-1))); case 2: if (v < 0) { if (size >= SV_BITS+1) return true; if (v == SV_MIN) return size >= SV_BITS; v = 0-v; return (v <= (one<<(size-1))); } if (size >= SV_BITS) return true; return (v < (one<<size)); default: assert(false && "invalid range type"); return false; } } return yasm::isOkSize(*getBV(&conv_bv), size, rshift, rangetype); } bool IntNum::isInRange(long low, long high) const { if (m_type == INTNUM_SV) return (m_val.sv >= low && m_val.sv <= high); // bigval can't be in range return false; } IntNum& IntNum::operator++() { if (m_type == INTNUM_SV && m_val.sv < std::numeric_limits<SmallValue>::max()) ++m_val.sv; else { if (m_type == INTNUM_SV) { m_val.bv = getBV(new llvm::APInt(BITVECT_NATIVE_SIZE, 0)); m_type = INTNUM_BV; } ++(*m_val.bv); } return *this; } IntNum& IntNum::operator--() { if (m_type == INTNUM_SV && m_val.sv > std::numeric_limits<SmallValue>::min()) --m_val.sv; else { if (m_type == INTNUM_SV) { m_val.bv = getBV(new llvm::APInt(BITVECT_NATIVE_SIZE, 0)); m_type = INTNUM_BV; } --(*m_val.bv); } return *this; } int yasm::Compare(const IntNum& lhs, const IntNum& rhs) { if (lhs.m_type == IntNum::INTNUM_SV && rhs.m_type == IntNum::INTNUM_SV) { if (lhs.m_val.sv < rhs.m_val.sv) return -1; if (lhs.m_val.sv > rhs.m_val.sv) return 1; return 0; } const llvm::APInt* op1 = lhs.getBV(&op1static); const llvm::APInt* op2 = rhs.getBV(&op2static); if (op1->slt(*op2)) return -1; if (op1->sgt(*op2)) return 1; return 0; } bool yasm::operator==(const IntNum& lhs, const IntNum& rhs) { if (lhs.m_type == IntNum::INTNUM_SV && rhs.m_type == IntNum::INTNUM_SV) return lhs.m_val.sv == rhs.m_val.sv; const llvm::APInt* op1 = lhs.getBV(&op1static); const llvm::APInt* op2 = rhs.getBV(&op2static); return op1->eq(*op2); } bool yasm::operator<(const IntNum& lhs, const IntNum& rhs) { if (lhs.m_type == IntNum::INTNUM_SV && rhs.m_type == IntNum::INTNUM_SV) return lhs.m_val.sv < rhs.m_val.sv; const llvm::APInt* op1 = lhs.getBV(&op1static); const llvm::APInt* op2 = rhs.getBV(&op2static); return op1->slt(*op2); } bool yasm::operator>(const IntNum& lhs, const IntNum& rhs) { if (lhs.m_type == IntNum::INTNUM_SV && rhs.m_type == IntNum::INTNUM_SV) return lhs.m_val.sv > rhs.m_val.sv; const llvm::APInt* op1 = lhs.getBV(&op1static); const llvm::APInt* op2 = rhs.getBV(&op2static); return op1->sgt(*op2); } void IntNum::getStr(llvm::SmallVectorImpl<char>& str, int base, bool lowercase) const { if (m_type == INTNUM_BV) { m_val.bv->toString(str, static_cast<unsigned>(base), true, lowercase); return; } long v = m_val.sv; if (v < 0) { v = -v; str.push_back('-'); } const char* fmt = "%ld"; switch (base) { case 8: fmt = "%lo"; break; case 10: fmt = "%ld"; break; case 16: if (lowercase) fmt = "%lx"; else fmt = "%lX"; break; default: // fall back to bigval getBV(&conv_bv)->toString(str, static_cast<unsigned>(base), true, lowercase); return; } char s[40]; std::sprintf(s, fmt, m_val.sv); str.append(s, s+std::strlen(s)); } std::string IntNum::getStr(int base, bool lowercase) const { llvm::SmallString<40> s; getStr(s, base, lowercase); return s.str(); } unsigned long IntNum::Extract(unsigned int width, unsigned int lsb) const { assert(width <= ULONG_BITS); if (m_type == INTNUM_SV) { // cast after shift to preserve sign bits unsigned long rv = static_cast<unsigned long>(m_val.sv >> lsb); if (width < ULONG_BITS) rv &= ((1UL << width) - 1); return rv; } else { uint64_t v; llvm::APInt::tcExtract(&v, 1, m_val.bv->getRawData(), width, lsb); return static_cast<unsigned long>(v); } } #ifdef WITH_XML pugi::xml_node IntNum::Write(pugi::xml_node out) const { llvm::SmallString<40> s; getStr(s); s += '\0'; return append_data(out, s.str().data()); } #endif // WITH_XML void IntNum::Print(llvm::raw_ostream& os, int base, bool lowercase, bool showbase, int bits) const { const llvm::APInt* bv = getBV(&conv_bv); if (bv->isNegative()) { // negate in place conv_bv = *bv; conv_bv.flip(); ++conv_bv; bv = &conv_bv; os << '-'; } llvm::SmallString<40> s; bv->toString(s, base, true, lowercase); // prefix and 0 padding, if required int padding = 0; if (base == 2) { if (showbase) os << '0' << (lowercase ? 'b' : 'B'); if (bits > 0) padding = bits-s.size(); } else if (base == 8) { if (showbase) os << '0'; if (bits > 0) padding = (bits-s.size()*3+2)/3; } else if (base == 16) { if (showbase) os << '0' << (lowercase ? 'x' : 'X'); if (bits > 0) padding = (bits-s.size()*4+3)/4; } for (int i=0; i<padding; ++i) os << '0'; // value os << s.str(); }
#include <okui/applications/Native.h> #include <okui/applications/SDL.h> #include <okui/StateMachine.h> class Application : public okui::applications::Native<okui::applications::SDL> { public: virtual std::string name() const override { return "StateMachine Example"; } virtual std::string organization() const override { return "BitTorrent Inc."; } }; struct State { double x, y, opacity; constexpr auto members() { return std::tie(x, y, opacity); } }; class View final : public okui::View, public okui::StateMachine<State> { public: View() : okui::StateMachine<State>("Above") { setTransition("Above", "Normal", 200ms, okui::interpolation::Quadratic::EaseOut); setTransition("Normal", "Left", 200ms, okui::interpolation::Quadratic::EaseIn); } void setState(std::string state) { okui::StateMachine<State>::setState(std::move(state)); addUpdateHook("StateMachine", [this]{ if (!drive()) { removeUpdateHook("StateMachine"); } }); } private: virtual void update(stdts::string_view id, State& state, bool& isAnimated) override { state.opacity = id == "Normal" ? 1.0 : 0.0; state.x = id == "Left" ? -100.0 : 300.0; state.y = id == "Above" ? -100.0 : 300.0; } virtual void apply(State state) override { setOpacity(state.opacity); setBounds(state.x, state.y, 100.0, 100.0); } }; int main() { Application application; okui::Window window{&application}; window.open(); View view; view.setBackgroundColor(okui::Color::kBlue); window.contentView()->addSubview(&view); view.asyncAfter(2s, [&] { view.setState("Normal"); }); view.asyncAfter(4s, [&] { view.setState("Left"); }); application.run(); return 0; }
#include "Renderer.hpp" #include "Singleton.hpp" #include "GlobalShaderParams.hpp" #include "Config.h" #include "Scene.hpp" #include "Model.hpp" #include "Material.hpp" #include "Transform.hpp" #include "Mesh.hpp" #include "CGL.h" namespace CpuRasterizer { Renderer::Renderer() : gizmos(true) {} Renderer::Renderer(std::shared_ptr<Model> model) : Renderer() { this->target = model; upload_mesh(); } Renderer::Renderer(const Renderer& other) { copy(other); } Renderer::~Renderer() { if (target != nullptr) { for (auto& vid : vertex_buffer_ids) { cglFreeVertexBuffer(vid); } for (auto& iid : index_buffer_ids) { cglFreeIndexBuffer(iid); } } } void Renderer::upload_mesh() { if (target != nullptr) { for (auto& mesh : target->meshes) { // check indices for (int idx = 0; idx < mesh.indices.size(); ++idx) { if (mesh.indices[idx] < 0 || mesh.indices[idx] >= mesh.vertices.size()) { mesh.indices[idx] = 0; } } auto vid = cglBindVertexBuffer(mesh.vertices); auto iid = cglBindIndexBuffer(mesh.indices); vertex_buffer_ids.emplace_back(vid); index_buffer_ids.emplace_back(iid); } } } std::unique_ptr<Renderer> Renderer::create(std::shared_ptr<Model> model) { return std::make_unique<Renderer>(model); } std::unique_ptr<Renderer> Renderer::create(const Renderer& other) { return std::make_unique<Renderer>(other); } tinymath::mat4x4 Renderer::view_matrix(RenderPass render_pass) const { if (render_pass == RenderPass::kShadow) { return CpuRasterSharedData.main_light.view_matrix(); } return CpuRasterSharedData.view_matrix; } tinymath::mat4x4 Renderer::projection_matrix(RenderPass render_pass) const { if (render_pass == RenderPass::kShadow) { return CpuRasterSharedData.main_light.projection_matrix(); } return CpuRasterSharedData.proj_matrix; } tinymath::mat4x4 Renderer::model_matrix() const { return target->transform->world_trs; } void Renderer::render_shadow() const { render_internal(RenderPass::kShadow); } void Renderer::render() const { render_internal(RenderPass::kObject); } void Renderer::render_internal(RenderPass render_pass) const { if (!target->material->cast_shadow && render_pass == RenderPass::kShadow) { return; } before_render(); auto m = model_matrix(); auto v = view_matrix(render_pass); auto p = projection_matrix(render_pass); target->material->local_properties.set_mat4x4(mat_model_prop, m); target->material->local_properties.set_mat4x4(mat_view_prop, v); target->material->local_properties.set_mat4x4(mat_projection_prop, p); target->material->local_properties.set_mat4x4(mat_vp_prop, p * v); target->material->local_properties.set_mat4x4(mat_mvp_prop, p * v * m); target->material->use(render_pass); for(size_t i = 0; i < index_buffer_ids.size(); ++i) { auto iid = index_buffer_ids[i]; auto vid = vertex_buffer_ids[i]; cglUseVertexBuffer(vid); cglUseIndexBuffer(iid); cglDrawPrimitive(); } cglFencePrimitives(); } void Renderer::draw_gizmos() const { if (!CpuRasterSharedData.enable_gizmos) { return; } auto view = CpuRasterSharedData.view_matrix; auto proj = CpuRasterSharedData.proj_matrix; auto pos = tinymath::kVec3fZero; auto up = tinymath::kVec3fUp; auto forward = tinymath::kVec3fForward; auto right = tinymath::kVec3fRight; auto scale = tinymath::scale(model_matrix().get_scale()); tinymath::mat4x4 m = model_matrix() * tinymath::inverse(scale); cglDrawCoordinates(pos, forward, up, right, m, view, proj); } Renderer& Renderer::operator =(const Renderer& other) { copy(other); return *this; } void Renderer::copy(const Renderer& other) { this->target = other.target; } }
#include "pch.h" #include "sybil.h" #include "content/d2dmisc.h" #include "internet.h" #include "httputil.h" using namespace V4; namespace sybil { DLLEXPORT bool WINAPI CreateTextFromat(IDWriteFactory* wfac, LPCWSTR fontname, float height, int weight, IDWriteTextFormat** tf ) { auto hr = wfac->CreateTextFormat( fontname, nullptr, (DWRITE_FONT_WEIGHT)weight, // 400:normal DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, height, DEFAULTLOCALE, tf ); return ( S_OK == hr ); } DLLEXPORT bool WINAPI CreateSingleTextLayout(IDWriteFactory* wfac, LPCWSTR str, int length, IDWriteTextFormat* tf, IDWriteTextLayout** tl ) { return (S_OK == wfac->CreateTextLayout( str,length, tf, 32000,32000, tl )); } DLLEXPORT void WINAPI DrawTextLayoutCenter( ID2D1RenderTarget* p, const D2D1_RECT_F& rc, IDWriteTextLayout* tl, ID2D1Brush* br ) { DWRITE_TEXT_METRICS tm; tl->GetMetrics(&tm); FPointF pt; pt.x = ((rc.right - rc.left) - tm.width)/2.0f; pt.y = ((rc.bottom - rc.top) - tm.height)/2.0f; p->DrawTextLayout( pt, tl, br ); } DLLEXPORT void WINAPI DrawTextCenter( ID2D1RenderTarget* p, const D2D1_RECT_F& rc, LPCWSTR str, int length, IDWriteTextFormat* tf, ID2D1Brush* br ) { auto old = tf->GetTextAlignment(); tf->SetTextAlignment( DWRITE_TEXT_ALIGNMENT::DWRITE_TEXT_ALIGNMENT_CENTER ); p->DrawText( str, length, tf, rc, br, D2D1_DRAW_TEXT_OPTIONS::D2D1_DRAW_TEXT_OPTIONS_CLIP ); tf->SetTextAlignment( old ); } DLLEXPORT HANDLE WINAPI DrawDriftRect( HANDLE cxt, D2D1_RECT_F* ret, DWORD ticknow, const D2D1_RECT_F& rcs,const D2D1_RECT_F& rce, DWORD tick_distance ) { struct st { WORD magic; DWORD starttmm; float offr,offt,offb,offl; D2D1_RECT_F rcs; }; st* _c = (st*)cxt; if ( _c == nullptr ) { _c = new st(); _c->magic = 598; _c->starttmm = ticknow; _c->rcs = rcs; _c->offl = (rce.left - rcs.left); _c->offr = (rce.right - rcs.right); _c->offt = (rce.top - rcs.top); _c->offb = (rce.bottom - rcs.bottom); *ret = rcs; } else { _ASSERT(_c->magic == 598); float t = (float)(ticknow - _c->starttmm ) / tick_distance; if ( 1.0f <= t ) { *ret = rce; delete _c; _c = nullptr; } else { const double halfpai = 3.14159/2.0; auto t2 = sin(halfpai*t); ret->top = _c->rcs.top + (float)(_c->offt * t2); ret->left = _c->rcs.left + (float)(_c->offl * t2); ret->right = _c->rcs.right + (float)(_c->offr * t2); ret->bottom = _c->rcs.bottom + (float)(_c->offb * t2); } } return (HANDLE)_c; } /////////////////////////////////////////////////////////////////////////////////////////////////////// // header[0] = "Authorization : xxxx"; // header[0] = "Content-Type : xxxx"; struct InnerComplete { ResponseData* res; LPVOID complete; }; //DLLEXPORT int GETInternet( BSTR url, BSTR* header,int headercnt, ResponseData* ret, LPVOID complete ) //{ // std::map<std::wstring,std::wstring> hd; // for( int i = 0; i < headercnt; i++ ) // { // std::wstring s = header[i]; // int pos = s.find( ':' ); // if ( pos > 0 ) // { // auto h = s.substr( 0, pos ); // auto v = s.substr( pos+1, s.length()-(pos+1) ); // // hd[h] = v; // } // } // // InnerComplete rc1; // rc1.complete = complete; // rc1.res = ret; // // ret->seqno = GETInternetEx((LPCWSTR)url, hd, &ret->result, &ret->data, &ret->callback, (LPVOID)&rc1); // return ret->seqno; //} struct _InnerCallbackObject { ResponseData* sender; LPVOID complete; }; static void _innerInetCallback(void* sender, int result, LPCWSTR content, LPCWSTR res_headers, IBinary& res_body) { typedef void(*cmpl)(void*); cmpl complete; ResponseData* rd; _InnerCallbackObject* p = (_InnerCallbackObject*)sender; { rd = p->sender; complete = (cmpl)p->complete; rd->result = result; BSTR bs; Utf8ToBSTR(res_body, &bs); rd->data = bs; } delete p; complete(rd); } DLLEXPORT int WINAPI GETInternet( BSTR url, BSTR headers_CRLF, ResponseData* sender, LPVOID complete ) { _InnerCallbackObject* p = new _InnerCallbackObject(); p->complete = complete; p->sender = sender; int a = GETInternetEx((LPCWSTR)url, headers_CRLF, p, _innerInetCallback); return a; } /////////////////////////////////////////////////////////////////////////////////////////////////////// // header[0] = "Content-Type : xxxx"; // header[1] = "Content-Length : xxxx"; DLLEXPORT void WINAPI POSTInternet( BSTR url, BSTR* header,int headercnt, ResponseData* ret ) { std::map<std::wstring,std::wstring> hd; for( int i = 0; i < headercnt; i++ ) { std::wstring s = header[i]; int pos = s.find( ':' ); if ( pos > 0 ) { auto h = s.substr( 0, pos ); auto v = s.substr( pos+1, s.length()-(pos+1) ); hd[h] = v; } } //POSTInternetEx((LPCWSTR)url, hd, &ret->result, &ret->data, &ret->callback); } DLLEXPORT void WINAPI ResponseDataInit(ResponseData* data) { ZeroMemory(data,sizeof(ResponseData)); } DLLEXPORT void WINAPI ResponseDataClear(ResponseData* data) { if ( data == nullptr ) return; if ( data->callback ) data->callback->Release(); if ( data->data ) ::SysFreeString(data->data); data->result = 0; } DLLEXPORT bool WINAPI WriteFileWStore( LPCWSTR fnm, const byte* src, DWORD src_length, int typ ) { // fnmはtemporary path以下でないと失敗する。 if ( fnm == nullptr || src_length == 0 || src == nullptr ) return false; std::wstring dirfnm; if ( fnm[1] != ':' ) { WCHAR cb[MAX_PATH]; ::GetTempPath(MAX_PATH, cb); dirfnm = cb; dirfnm += fnm; } else dirfnm = fnm; bool bNew = false; CREATEFILE2_EXTENDED_PARAMETERS pms = {0}; pms.dwSize = sizeof(pms); pms.dwFileAttributes = FILE_ATTRIBUTE_NORMAL; HANDLE h = ::CreateFile2( dirfnm.c_str(), GENERIC_WRITE,0,OPEN_EXISTING,&pms ); if ( INVALID_HANDLE_VALUE != h ) { LARGE_INTEGER x; x.QuadPart = 0; SetFilePointerEx(h,x,nullptr, FILE_END); } else if ( ERROR_FILE_NOT_FOUND == ::GetLastError()) { h = ::CreateFile2( dirfnm.c_str(), GENERIC_WRITE,0,CREATE_ALWAYS,&pms ); bNew = true; } DWORD dw = 0; if ( INVALID_HANDLE_VALUE != h ) { if ( typ == 1 && bNew ) { // BOM utf8 BYTE bom[] = {0xEF, 0xBB, 0xBF}; ::WriteFile(h, bom, 3, &dw, nullptr ); } //::WriteFile(h, IBinaryPtr(src), IBinaryLen(src), &dw, nullptr ); ::WriteFile(h, src, src_length, &dw, nullptr ); ::CloseHandle(h); return true; } return false; } DLLEXPORT bool WINAPI DateTimeInit(DateTime* datetime) { if (!SystemTimeToFileTime(&datetime->inDatetime, &datetime->ft)) return false; datetime->hikaku = datetime->ft.dwHighDateTime; datetime->hikaku = (datetime->hikaku << 32) + datetime->ft.dwLowDateTime; datetime->string = nullptr; DateTime utc = *datetime; if (utc.bLocaltime) { utc = LTCtoUTC(*datetime); } WCHAR cb[200]; if (utc.format_string == DATETIME_FORMAT::RFC1123) { //Thu, 16 May 2013 03:36:09 GMT auto& d = utc.inDatetime; WCHAR* week[] = { L"Sun", L"Mon", L"Tue", L"Wed", L"Thu", L"Fri", L"Sat" }; WCHAR* month[] = { L"Jan",L"Feb", L"Mar", L"Apr", L"May", L"Jun", L"Jul", L"Aug", L"Sep", L"Oct", L"Nov", L"Dec" }; StringCbPrintf(cb, _countof(cb), L"%s, %02d %s %04d %02d:%02d:%02d GMT", week[d.wDayOfWeek], d.wDay, month[d.wMonth - 1], d.wYear, d.wHour, d.wMinute, d.wSecond); } else if (utc.format_string == DATETIME_FORMAT::ISO8601) { auto& d = utc.inDatetime; StringCbPrintf(cb, _countof(cb), L"%04d-%02d-%02dT%02d:%02d:%02dZ", d.wYear, d.wMonth, d.wDay, d.wHour, d.wMinute, d.wSecond); } else { // DATETIME_FORMAT::YYYYMMDD StringCbPrintf(cb, _countof(cb), L"%04d/%02d/%02d", datetime->inDatetime.wYear, datetime->inDatetime.wMonth, datetime->inDatetime.wDay); } datetime->string = ::SysAllocString(cb); return true; } DLLEXPORT void WINAPI Now(DateTime* datetime) { SYSTEMTIME systime = { 0 }; GetLocalTime(&systime); //現在日時の取得 datetime->inDatetime = systime; datetime->bLocaltime = true; DateTimeInit(datetime); } DLLEXPORT bool WINAPI DateTimeParse(LPCWSTR cdate, DateTime* datetime) { VARIANT d, dst; VariantInit(&d); d.vt = VT_BSTR; d.bstrVal = ::SysAllocString(cdate); VariantInit(&dst); if (S_OK != ::VariantChangeType(&dst, &d, 0, VT_DATE)) return false; SYSTEMTIME systime = { 0 }; if (VariantTimeToSystemTime(d.date, &systime)) { datetime->inDatetime = systime; datetime->bLocaltime = true; DateTimeInit(datetime); } else return false; return true; } DLLEXPORT DateTime WINAPI LTCtoUTC(const DateTime& datetime) { _ASSERT(datetime.bLocaltime == true); SYSTEMTIME t = datetime.inDatetime; DateTime ret; TzSpecificLocalTimeToSystemTime(NULL, &t, &ret.inDatetime); ret.bLocaltime = false; ret.format_string = datetime.format_string; DateTimeInit(&ret); return ret; } DLLEXPORT DateTime WINAPI UTCtoLTC(const DateTime& datetime) { _ASSERT(datetime.bLocaltime == false); SYSTEMTIME t = datetime.inDatetime; DateTime ret; SystemTimeToTzSpecificLocalTime(NULL, &t, &ret.inDatetime); ret.bLocaltime = true; ret.format_string = datetime.format_string; DateTimeInit(&ret); return ret; } }
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chain.h> #include <clientversion.h> #include <core_io.h> #include <crypto/ripemd160.h> #include <key_io.h> #include <validation.h> #include <httpserver.h> #include <net.h> #include <netbase.h> #include <outputtype.h> #include <rpc/blockchain.h> #include <rpc/server.h> #include <rpc/util.h> #include <timedata.h> #include <util.h> #include <utilstrencodings.h> #ifdef ENABLE_WALLET #include <wallet/rpcwallet.h> #include <wallet/wallet.h> #include <wallet/walletdb.h> #endif #include <warnings.h> #include <stdint.h> #ifdef HAVE_MALLOC_INFO #include <malloc.h> #endif #include <univalue.h> static UniValue validateaddress(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "validateaddress \"address\"\n" "\nReturn information about the given learncoin address.\n" "DEPRECATION WARNING: Parts of this command have been deprecated and moved to getaddressinfo. Clients must\n" "transition to using getaddressinfo to access this information before upgrading to v0.18. The following deprecated\n" "fields have moved to getaddressinfo and will only be shown here with -deprecatedrpc=validateaddress: ismine, iswatchonly,\n" "script, hex, pubkeys, sigsrequired, pubkey, addresses, embedded, iscompressed, account, timestamp, hdkeypath, kdmasterkeyid.\n" "\nArguments:\n" "1. \"address\" (string, required) The learncoin address to validate\n" "\nResult:\n" "{\n" " \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\n" " \"address\" : \"address\", (string) The learncoin address validated\n" " \"scriptPubKey\" : \"hex\", (string) The hex encoded scriptPubKey generated by the address\n" " \"isscript\" : true|false, (boolean) If the key is a script\n" " \"iswitness\" : true|false, (boolean) If the address is a witness address\n" " \"witness_version\" : version (numeric, optional) The version number of the witness program\n" " \"witness_program\" : \"hex\" (string, optional) The hex value of the witness program\n" "}\n" "\nExamples:\n" + HelpExampleCli("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"") + HelpExampleRpc("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"") ); CTxDestination dest = DecodeDestination(request.params[0].get_str()); bool isValid = IsValidDestination(dest); UniValue ret(UniValue::VOBJ); ret.pushKV("isvalid", isValid); if (isValid) { #ifdef ENABLE_WALLET if (HasWallets() && IsDeprecatedRPCEnabled("validateaddress")) { ret.pushKVs(getaddressinfo(request)); } #endif if (ret["address"].isNull()) { std::string currentAddress = EncodeDestination(dest); ret.pushKV("address", currentAddress); CScript scriptPubKey = GetScriptForDestination(dest); ret.pushKV("scriptPubKey", HexStr(scriptPubKey.begin(), scriptPubKey.end())); UniValue detail = DescribeAddress(dest); ret.pushKVs(detail); } } return ret; } // Needed even with !ENABLE_WALLET, to pass (ignored) pointers around class CWallet; static UniValue createmultisig(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 2 || request.params.size() > 3) { std::string msg = "createmultisig nrequired [\"key\",...] ( \"address_type\" )\n" "\nCreates a multi-signature address with n signature of m keys required.\n" "It returns a json object with the address and redeemScript.\n" "\nArguments:\n" "1. nrequired (numeric, required) The number of required signatures out of the n keys.\n" "2. \"keys\" (string, required) A json array of hex-encoded public keys\n" " [\n" " \"key\" (string) The hex-encoded public key\n" " ,...\n" " ]\n" "3. \"address_type\" (string, optional) The address type to use. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\". Default is legacy.\n" "\nResult:\n" "{\n" " \"address\":\"multisigaddress\", (string) The value of the new multisig address.\n" " \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n" "}\n" "\nExamples:\n" "\nCreate a multisig address from 2 public keys\n" + HelpExampleCli("createmultisig", "2 \"[\\\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd342cf11ae157a7ace5fd\\\",\\\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e17e107ef3f6aa5a61626\\\"]\"") + "\nAs a json rpc call\n" + HelpExampleRpc("createmultisig", "2, \"[\\\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd342cf11ae157a7ace5fd\\\",\\\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e17e107ef3f6aa5a61626\\\"]\"") ; throw std::runtime_error(msg); } int required = request.params[0].get_int(); // Get the public keys const UniValue& keys = request.params[1].get_array(); std::vector<CPubKey> pubkeys; for (unsigned int i = 0; i < keys.size(); ++i) { if (IsHex(keys[i].get_str()) && (keys[i].get_str().length() == 66 || keys[i].get_str().length() == 130)) { pubkeys.push_back(HexToPubKey(keys[i].get_str())); } else { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Invalid public key: %s\nNote that from v0.16, createmultisig no longer accepts addresses." " Users must use addmultisigaddress to create multisig addresses with addresses known to the wallet.", keys[i].get_str())); } } // Get the output type OutputType output_type = OutputType::LEGACY; if (!request.params[2].isNull()) { if (!ParseOutputType(request.params[2].get_str(), output_type)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[2].get_str())); } } // Construct using pay-to-script-hash: const CScript inner = CreateMultisigRedeemscript(required, pubkeys); CBasicKeyStore keystore; const CTxDestination dest = AddAndGetDestinationForScript(keystore, inner, output_type); UniValue result(UniValue::VOBJ); result.pushKV("address", EncodeDestination(dest)); result.pushKV("redeemScript", HexStr(inner.begin(), inner.end())); return result; } static UniValue verifymessage(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 3) throw std::runtime_error( "verifymessage \"address\" \"signature\" \"message\"\n" "\nVerify a signed message\n" "\nArguments:\n" "1. \"address\" (string, required) The learncoin address to use for the signature.\n" "2. \"signature\" (string, required) The signature provided by the signer in base 64 encoding (see signmessage).\n" "3. \"message\" (string, required) The message that was signed.\n" "\nResult:\n" "true|false (boolean) If the signature is verified or not.\n" "\nExamples:\n" "\nUnlock the wallet for 30 seconds\n" + HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") + "\nCreate the signature\n" + HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"my message\"") + "\nVerify the signature\n" + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"signature\" \"my message\"") + "\nAs json rpc\n" + HelpExampleRpc("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\", \"signature\", \"my message\"") ); LOCK(cs_main); std::string strAddress = request.params[0].get_str(); std::string strSign = request.params[1].get_str(); std::string strMessage = request.params[2].get_str(); CTxDestination destination = DecodeDestination(strAddress); if (!IsValidDestination(destination)) { throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); } const CKeyID *keyID = boost::get<CKeyID>(&destination); if (!keyID) { throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); } bool fInvalid = false; std::vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid); if (fInvalid) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding"); CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; CPubKey pubkey; if (!pubkey.RecoverCompact(ss.GetHash(), vchSig)) return false; return (pubkey.GetID() == *keyID); } static UniValue signmessagewithprivkey(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 2) throw std::runtime_error( "signmessagewithprivkey \"privkey\" \"message\"\n" "\nSign a message with the private key of an address\n" "\nArguments:\n" "1. \"privkey\" (string, required) The private key to sign the message with.\n" "2. \"message\" (string, required) The message to create a signature of.\n" "\nResult:\n" "\"signature\" (string) The signature of the message encoded in base 64\n" "\nExamples:\n" "\nCreate the signature\n" + HelpExampleCli("signmessagewithprivkey", "\"privkey\" \"my message\"") + "\nVerify the signature\n" + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"signature\" \"my message\"") + "\nAs json rpc\n" + HelpExampleRpc("signmessagewithprivkey", "\"privkey\", \"my message\"") ); std::string strPrivkey = request.params[0].get_str(); std::string strMessage = request.params[1].get_str(); CKey key = DecodeSecret(strPrivkey); if (!key.IsValid()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); } CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; std::vector<unsigned char> vchSig; if (!key.SignCompact(ss.GetHash(), vchSig)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed"); return EncodeBase64(vchSig.data(), vchSig.size()); } static UniValue setmocktime(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "setmocktime timestamp\n" "\nSet the local time to given timestamp (-regtest only)\n" "\nArguments:\n" "1. timestamp (integer, required) Unix seconds-since-epoch timestamp\n" " Pass 0 to go back to using the system time." ); if (!Params().MineBlocksOnDemand()) throw std::runtime_error("setmocktime for regression testing (-regtest mode) only"); // For now, don't change mocktime if we're in the middle of validation, as // this could have an effect on mempool time-based eviction, as well as // IsCurrentForFeeEstimation() and IsInitialBlockDownload(). // TODO: figure out the right way to synchronize around mocktime, and // ensure all call sites of GetTime() are accessing this safely. LOCK(cs_main); RPCTypeCheck(request.params, {UniValue::VNUM}); SetMockTime(request.params[0].get_int64()); return NullUniValue; } static UniValue RPCLockedMemoryInfo() { LockedPool::Stats stats = LockedPoolManager::Instance().stats(); UniValue obj(UniValue::VOBJ); obj.pushKV("used", uint64_t(stats.used)); obj.pushKV("free", uint64_t(stats.free)); obj.pushKV("total", uint64_t(stats.total)); obj.pushKV("locked", uint64_t(stats.locked)); obj.pushKV("chunks_used", uint64_t(stats.chunks_used)); obj.pushKV("chunks_free", uint64_t(stats.chunks_free)); return obj; } #ifdef HAVE_MALLOC_INFO static std::string RPCMallocInfo() { char *ptr = nullptr; size_t size = 0; FILE *f = open_memstream(&ptr, &size); if (f) { malloc_info(0, f); fclose(f); if (ptr) { std::string rv(ptr, size); free(ptr); return rv; } } return ""; } #endif static UniValue getmemoryinfo(const JSONRPCRequest& request) { /* Please, avoid using the word "pool" here in the RPC interface or help, * as users will undoubtedly confuse it with the other "memory pool" */ if (request.fHelp || request.params.size() > 1) throw std::runtime_error( "getmemoryinfo (\"mode\")\n" "Returns an object containing information about memory usage.\n" "Arguments:\n" "1. \"mode\" determines what kind of information is returned. This argument is optional, the default mode is \"stats\".\n" " - \"stats\" returns general statistics about memory usage in the daemon.\n" " - \"mallocinfo\" returns an XML string describing low-level heap state (only available if compiled with glibc 2.10+).\n" "\nResult (mode \"stats\"):\n" "{\n" " \"locked\": { (json object) Information about locked memory manager\n" " \"used\": xxxxx, (numeric) Number of bytes used\n" " \"free\": xxxxx, (numeric) Number of bytes available in current arenas\n" " \"total\": xxxxxxx, (numeric) Total number of bytes managed\n" " \"locked\": xxxxxx, (numeric) Amount of bytes that succeeded locking. If this number is smaller than total, locking pages failed at some point and key data could be swapped to disk.\n" " \"chunks_used\": xxxxx, (numeric) Number allocated chunks\n" " \"chunks_free\": xxxxx, (numeric) Number unused chunks\n" " }\n" "}\n" "\nResult (mode \"mallocinfo\"):\n" "\"<malloc version=\"1\">...\"\n" "\nExamples:\n" + HelpExampleCli("getmemoryinfo", "") + HelpExampleRpc("getmemoryinfo", "") ); std::string mode = request.params[0].isNull() ? "stats" : request.params[0].get_str(); if (mode == "stats") { UniValue obj(UniValue::VOBJ); obj.pushKV("locked", RPCLockedMemoryInfo()); return obj; } else if (mode == "mallocinfo") { #ifdef HAVE_MALLOC_INFO return RPCMallocInfo(); #else throw JSONRPCError(RPC_INVALID_PARAMETER, "mallocinfo is only available when compiled with glibc 2.10+"); #endif } else { throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown mode " + mode); } } static void EnableOrDisableLogCategories(UniValue cats, bool enable) { cats = cats.get_array(); for (unsigned int i = 0; i < cats.size(); ++i) { std::string cat = cats[i].get_str(); bool success; if (enable) { success = g_logger->EnableCategory(cat); } else { success = g_logger->DisableCategory(cat); } if (!success) { throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown logging category " + cat); } } } UniValue logging(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() > 2) { throw std::runtime_error( "logging ( <include> <exclude> )\n" "Gets and sets the logging configuration.\n" "When called without an argument, returns the list of categories with status that are currently being debug logged or not.\n" "When called with arguments, adds or removes categories from debug logging and return the lists above.\n" "The arguments are evaluated in order \"include\", \"exclude\".\n" "If an item is both included and excluded, it will thus end up being excluded.\n" "The valid logging categories are: " + ListLogCategories() + "\n" "In addition, the following are available as category names with special meanings:\n" " - \"all\", \"1\" : represent all logging categories.\n" " - \"none\", \"0\" : even if other logging categories are specified, ignore all of them.\n" "\nArguments:\n" "1. \"include\" (array of strings, optional) A json array of categories to add debug logging\n" " [\n" " \"category\" (string) the valid logging category\n" " ,...\n" " ]\n" "2. \"exclude\" (array of strings, optional) A json array of categories to remove debug logging\n" " [\n" " \"category\" (string) the valid logging category\n" " ,...\n" " ]\n" "\nResult:\n" "{ (json object where keys are the logging categories, and values indicates its status\n" " \"category\": 0|1, (numeric) if being debug logged or not. 0:inactive, 1:active\n" " ...\n" "}\n" "\nExamples:\n" + HelpExampleCli("logging", "\"[\\\"all\\\"]\" \"[\\\"http\\\"]\"") + HelpExampleRpc("logging", "[\"all\"], \"[libevent]\"") ); } uint32_t original_log_categories = g_logger->GetCategoryMask(); if (request.params[0].isArray()) { EnableOrDisableLogCategories(request.params[0], true); } if (request.params[1].isArray()) { EnableOrDisableLogCategories(request.params[1], false); } uint32_t updated_log_categories = g_logger->GetCategoryMask(); uint32_t changed_log_categories = original_log_categories ^ updated_log_categories; // Update libevent logging if BCLog::LIBEVENT has changed. // If the library version doesn't allow it, UpdateHTTPServerLogging() returns false, // in which case we should clear the BCLog::LIBEVENT flag. // Throw an error if the user has explicitly asked to change only the libevent // flag and it failed. if (changed_log_categories & BCLog::LIBEVENT) { if (!UpdateHTTPServerLogging(g_logger->WillLogCategory(BCLog::LIBEVENT))) { g_logger->DisableCategory(BCLog::LIBEVENT); if (changed_log_categories == BCLog::LIBEVENT) { throw JSONRPCError(RPC_INVALID_PARAMETER, "libevent logging cannot be updated when using libevent before v2.1.1."); } } } UniValue result(UniValue::VOBJ); std::vector<CLogCategoryActive> vLogCatActive = ListActiveLogCategories(); for (const auto& logCatActive : vLogCatActive) { result.pushKV(logCatActive.category, logCatActive.active); } return result; } static UniValue echo(const JSONRPCRequest& request) { if (request.fHelp) throw std::runtime_error( "echo|echojson \"message\" ...\n" "\nSimply echo back the input arguments. This command is for testing.\n" "\nThe difference between echo and echojson is that echojson has argument conversion enabled in the client-side table in" "learncoin-cli and the GUI. There is no server-side difference." ); return request.params; } static UniValue getinfo_deprecated(const JSONRPCRequest& request) { throw JSONRPCError(RPC_METHOD_NOT_FOUND, "getinfo\n" "\nThis call was removed in version 0.16.0. Use the appropriate fields from:\n" "- getblockchaininfo: blocks, difficulty, chain\n" "- getnetworkinfo: version, protocolversion, timeoffset, connections, proxy, relayfee, warnings\n" "- getwalletinfo: balance, keypoololdest, keypoolsize, paytxfee, unlocked_until, walletversion\n" "\nlearncoin-cli has the option -getinfo to collect and format these in the old format." ); } static const CRPCCommand commands[] = { // category name actor (function) argNames // --------------------- ------------------------ ----------------------- ---------- { "control", "getmemoryinfo", &getmemoryinfo, {"mode"} }, { "control", "logging", &logging, {"include", "exclude"}}, { "util", "validateaddress", &validateaddress, {"address"} }, /* uses wallet if enabled */ { "util", "createmultisig", &createmultisig, {"nrequired","keys","address_type"} }, { "util", "verifymessage", &verifymessage, {"address","signature","message"} }, { "util", "signmessagewithprivkey", &signmessagewithprivkey, {"privkey","message"} }, /* Not shown in help */ { "hidden", "setmocktime", &setmocktime, {"timestamp"}}, { "hidden", "echo", &echo, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}}, { "hidden", "echojson", &echo, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}}, { "hidden", "getinfo", &getinfo_deprecated, {}}, }; void RegisterMiscRPCCommands(CRPCTable &t) { for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++) t.appendCommand(commands[vcidx].name, &commands[vcidx]); }
////////////////////////////////////////////////////////////////////////////// /// Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand /// Copyright 2009 and onward LRI UMR 8623 CNRS/Univ Paris Sud XI /// /// Distributed under the Boost Software License, Version 1.0 /// See accompanying file LICENSE.txt or copy at /// http://www.boost.org/LICENSE_1_0.txt ////////////////////////////////////////////////////////////////////////////// #ifndef NT2_TOOLBOX_GSL_SPECFUN_INCLUDE_GSL_SF_BESSEL_K0_SCALED_HPP_INCLUDED #define NT2_TOOLBOX_GSL_SPECFUN_INCLUDE_GSL_SF_BESSEL_K0_SCALED_HPP_INCLUDED #include <nt2/toolbox/gsl_specfun/function/gsl_sf_bessel_k0_scaled.hpp> #endif
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2020 Scientific Computing and Imaging Institute, University of Utah. 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 <iostream> #include <vector> #include <string> #include <Cleaver/Cleaver.h> #include <Cleaver/InverseField.h> #include <Cleaver/FloatField.h> //#include "nrrd2cleaver.h" #include "MyFunction.h" using namespace std; //using namespace Cleaver; const std::string scirun = "scirun"; const std::string tetgen = "tetgen"; const std::string matlab = "matlab"; int main(int argc, char *argv[]) { cerr<<"THIS IS VOLUMEMESH"<<endl; int dim_x=31; int dim_y=31; int dim_z=31; float v_x=1.0; float v_y=1.0; float v_z=1.0; bool verbose=true; string format="tetgen"; string outputFileName="meshOutput"; //vector<float> outsideVec(dim_x*dim_y*dim_x,0); vector<float> insideVec(dim_x*dim_y*dim_z,0.0); int idx=0; //filling volumetric mateiral definition - a sphere centered in the middle of the lattice for (int x = 0 ; x < dim_x ; ++x ) for (int y = 0 ; y < dim_y ; ++y ) for (int z = 0 ; z < dim_z ; ++z ){ // Current Cleaver Limitation - Can't have material transitions on the boundary. // Will fix ASAP, but for now pad data with constant boundary. if(x < 2 || y < 2 || z < 2 || x > (dim_x - 3) || y > (dim_y - 3) || z > (dim_z - 3)) { insideVec[idx] = 1.0; ++idx; continue; } if ((x-dim_x/2)*(x-dim_x/2)+(y-dim_y/2)*(y-dim_y/2)+(z-dim_z/2)<0.4*dim_x){ insideVec[idx]=1.0; }else{ insideVec[idx]=-1.0; //insideVec[idx]=1; //outsideVec[idx]=0; } ++idx; } Cleaver::FloatField insideField=Cleaver::FloatField(dim_x,dim_y,dim_z,&insideVec[0]); //Cleaver::FloatField outsideField=Cleaver::FloatField(dim_x,dim_y,dim_z,&outsideVec[0]); MyFunction myfunction; //Cleaver::InverseField inverseField=Cleaver::InverseField(&insideField); Cleaver::InverseField inverseField = Cleaver::InverseField(&myfunction); std::vector<Cleaver::ScalarField*> fields; fields.push_back(&insideField); fields.push_back(&inverseField); Cleaver::Volume volume(fields, Cleaver::vec3(127,127,127)); Cleaver::TetMesh *mesh = Cleaver::createMeshFromVolume(&volume, verbose); //------------------ // Compute Angles //------------------ mesh->computeAngles(); if(verbose){ std::cout.precision(12); std::cout << "Worst Angles:" << std::endl; std::cout << "min: " << mesh->min_angle << std::endl; std::cout << "max: " << mesh->max_angle << std::endl; } //---------------------- // Write Info File //---------------------- mesh->writeInfo(outputFileName, verbose); //---------------------- // Write Tet Mesh Files //---------------------- if(format == tetgen) mesh->writeNodeEle(outputFileName, verbose); else if(format == scirun) mesh->writePtsEle(outputFileName, verbose); else if(format == matlab) mesh->writeMatlab(outputFileName, verbose); //---------------------- // Write Surface Files //---------------------- mesh->constructFaces(); mesh->writePly(outputFileName, verbose); }
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 "core/FlowConfiguration.h" #include <memory> #include <vector> #include <string> #include "core/ClassLoader.h" #include "utils/StringUtils.h" #include "processors/ProcessorUtils.h" namespace org { namespace apache { namespace nifi { namespace minifi { namespace core { FlowConfiguration::FlowConfiguration( std::shared_ptr<core::Repository> /*repo*/, std::shared_ptr<core::Repository> flow_file_repo, std::shared_ptr<core::ContentRepository> content_repo, std::shared_ptr<io::StreamFactory> stream_factory, std::shared_ptr<Configure> configuration, const std::optional<std::string>& path, std::shared_ptr<utils::file::FileSystem> filesystem) : CoreComponent(core::getClassName<FlowConfiguration>()), flow_file_repo_(std::move(flow_file_repo)), content_repo_(std::move(content_repo)), stream_factory_(std::move(stream_factory)), configuration_(configuration), filesystem_(std::move(filesystem)), logger_(logging::LoggerFactory<FlowConfiguration>::getLogger()) { controller_services_ = std::make_shared<core::controller::ControllerServiceMap>(); service_provider_ = std::make_shared<core::controller::StandardControllerServiceProvider>(controller_services_, nullptr, configuration); std::string flowUrl = "", bucket_id = "default", flowId = ""; configuration->get(Configure::nifi_c2_flow_id, flowId); configuration->get(Configure::nifi_c2_flow_url, flowUrl); flow_version_ = std::make_shared<state::response::FlowVersion>(flowUrl, bucket_id, flowId); if (!path) { logger_->log_error("Configuration path is not specified."); } else { config_path_ = utils::file::PathUtils::canonicalize(*path); if (!config_path_) { logger_->log_error("Couldn't find config file \"%s\".", *path); config_path_ = path; } checksum_calculator_.setFileLocation(*config_path_); } } static_initializers &get_static_functions() { static static_initializers static_sl_funcs; return static_sl_funcs; } FlowConfiguration::~FlowConfiguration() { if (service_provider_ != nullptr) { /* This is needed to counteract the StandardControllerServiceProvider <-> StandardControllerServiceNode shared_ptr cycle */ service_provider_->clearControllerServices(); } } std::unique_ptr<core::Processor> FlowConfiguration::createProcessor(const std::string &name, const utils::Identifier &uuid) { auto processor = minifi::processors::ProcessorUtils::createProcessor(name, name, uuid, stream_factory_); if (nullptr == processor) { logger_->log_error("No Processor defined for %s", name); return nullptr; } return processor; } std::unique_ptr<core::Processor> FlowConfiguration::createProcessor(const std::string &name, const std::string &fullname, const utils::Identifier &uuid) { auto processor = minifi::processors::ProcessorUtils::createProcessor(name, fullname, uuid, stream_factory_); if (nullptr == processor) { logger_->log_error("No Processor defined for %s", fullname); return nullptr; } return processor; } std::unique_ptr<core::reporting::SiteToSiteProvenanceReportingTask> FlowConfiguration::createProvenanceReportTask() { auto processor = std::make_unique<org::apache::nifi::minifi::core::reporting::SiteToSiteProvenanceReportingTask>(stream_factory_, this->configuration_); processor->initialize(); return processor; } std::unique_ptr<core::ProcessGroup> FlowConfiguration::updateFromPayload(const std::string& url, const std::string& yamlConfigPayload) { auto old_services = controller_services_; auto old_provider = service_provider_; controller_services_ = std::make_shared<core::controller::ControllerServiceMap>(); service_provider_ = std::make_shared<core::controller::StandardControllerServiceProvider>(controller_services_, nullptr, configuration_); auto payload = getRootFromPayload(yamlConfigPayload); if (!url.empty() && payload != nullptr) { std::string flow_id, bucket_id; auto path_split = utils::StringUtils::split(url, "/"); for (auto it = path_split.cbegin(); it != path_split.cend(); ++it) { if (*it == "flows" && std::next(it) != path_split.cend()) { flow_id = *++it; } else if (*it == "buckets" && std::next(it) != path_split.cend()) { bucket_id = *++it; } } flow_version_->setFlowVersion(url, bucket_id, flow_id); } else { controller_services_ = old_services; service_provider_ = old_provider; } return payload; } bool FlowConfiguration::persist(const std::string &configuration) { if (!config_path_) { logger_->log_error("No flow configuration path is specified, cannot persist changes."); return false; } std::string config_file_backup = *config_path_ + ".bak"; bool backup_file = (configuration_->get(minifi::Configure::nifi_flow_configuration_file_backup_update) | utils::flatMap(utils::StringUtils::toBool)).value_or(false); if (backup_file) { if (utils::file::FileUtils::copy_file(*config_path_, config_file_backup) != 0) { logger_->log_debug("Cannot copy %s to %s", *config_path_, config_file_backup); return false; } logger_->log_debug("Copy %s to %s", *config_path_, config_file_backup); } const bool status = filesystem_->write(*config_path_, configuration); checksum_calculator_.invalidateChecksum(); return status; } std::unique_ptr<core::ProcessGroup> FlowConfiguration::createRootProcessGroup(const std::string &name, const utils::Identifier &uuid, int version) { return std::make_unique<core::ProcessGroup>(core::ROOT_PROCESS_GROUP, name, uuid, version); } std::unique_ptr<core::ProcessGroup> FlowConfiguration::createSimpleProcessGroup(const std::string &name, const utils::Identifier &uuid, int version) { return std::make_unique<core::ProcessGroup>(core::SIMPLE_PROCESS_GROUP, name, uuid, version); } std::unique_ptr<core::ProcessGroup> FlowConfiguration::createRemoteProcessGroup(const std::string &name, const utils::Identifier &uuid) { return std::make_unique<core::ProcessGroup>(core::REMOTE_PROCESS_GROUP, name, uuid); } std::unique_ptr<minifi::Connection> FlowConfiguration::createConnection(const std::string& name, const utils::Identifier& uuid) const { return std::make_unique<minifi::Connection>(flow_file_repo_, content_repo_, name, uuid); } std::shared_ptr<core::controller::ControllerServiceNode> FlowConfiguration::createControllerService(const std::string &class_name, const std::string &full_class_name, const std::string &name, const utils::Identifier& uuid) { std::shared_ptr<core::controller::ControllerServiceNode> controllerServicesNode = service_provider_->createControllerService(class_name, full_class_name, name, true); if (nullptr != controllerServicesNode) controllerServicesNode->setUUID(uuid); return controllerServicesNode; } } /* namespace core */ } /* namespace minifi */ } /* namespace nifi */ } /* namespace apache */ } /* namespace org */
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. */ #if defined(FEAT_OLE) && defined(FEAT_GUI_MSWIN) /* * OLE server implementation. * * See os_mswin.c for the client side. */ extern "C" { # include "vim.h" } #include <windows.h> #include <oleauto.h> extern "C" { extern HWND s_hwnd; extern HWND vim_parent_hwnd; } #if (defined(_MSC_VER) && (_MSC_VER >= 1700)) || (__cplusplus >= 201103L) # define FINAL final #else # define FINAL #endif #if (defined(_MSC_VER) && _MSC_VER < 1300) || !defined(MAXULONG_PTR) /* Work around old versions of basetsd.h which wrongly declares * UINT_PTR as unsigned long */ # undef UINT_PTR # define UINT_PTR UINT #endif #include "if_ole.h" // Interface definitions #include "iid_ole.c" // UUID definitions (compile here) /* Supply function prototype to work around bug in Mingw oleauto.h header */ #ifdef __MINGW32__ WINOLEAUTAPI UnRegisterTypeLib(REFGUID libID, WORD wVerMajor, WORD wVerMinor, LCID lcid, SYSKIND syskind); #endif /***************************************************************************** 1. Internal definitions for this file *****************************************************************************/ class CVim; class CVimCF; /* Internal data */ // The identifier of the registered class factory static unsigned long cf_id = 0; // The identifier of the running application object static unsigned long app_id = 0; // The single global instance of the class factory static CVimCF *cf = 0; // The single global instance of the application object static CVim *app = 0; /* GUIDs, versions and type library information */ #define MYCLSID CLSID_Vim #define MYLIBID LIBID_Vim #define MYIID IID_IVim #define MAJORVER 1 #define MINORVER 0 #define LOCALE 0x0409 #define MYNAME "Vim" #define MYPROGID "Vim.Application.1" #define MYVIPROGID "Vim.Application" #define MAX_CLSID_LEN 100 /***************************************************************************** 2. The application object *****************************************************************************/ /* Definition * ---------- */ class CVim FINAL : public IVim { public: virtual ~CVim(); static CVim *Create(int *pbDoRestart); // IUnknown members STDMETHOD(QueryInterface)(REFIID riid, void ** ppv); STDMETHOD_(unsigned long, AddRef)(void); STDMETHOD_(unsigned long, Release)(void); // IDispatch members STDMETHOD(GetTypeInfoCount)(UINT *pCount); STDMETHOD(GetTypeInfo)(UINT iTypeInfo, LCID, ITypeInfo **ppITypeInfo); STDMETHOD(GetIDsOfNames)(const IID &iid, OLECHAR **names, UINT n, LCID, DISPID *dispids); STDMETHOD(Invoke)(DISPID member, const IID &iid, LCID, WORD flags, DISPPARAMS *dispparams, VARIANT *result, EXCEPINFO *excepinfo, UINT *argerr); // IVim members STDMETHOD(SendKeys)(BSTR keys); STDMETHOD(Eval)(BSTR expr, BSTR *result); STDMETHOD(SetForeground)(void); STDMETHOD(GetHwnd)(UINT_PTR *result); private: // Constructor is private - create using CVim::Create() CVim() : ref(0), typeinfo(0) {}; // Reference count unsigned long ref; // The object's TypeInfo ITypeInfo *typeinfo; }; /* Implementation * -------------- */ CVim *CVim::Create(int *pbDoRestart) { HRESULT hr; CVim *me = 0; ITypeLib *typelib = 0; ITypeInfo *typeinfo = 0; *pbDoRestart = FALSE; // Create the object me = new CVim(); if (me == NULL) { MessageBox(0, "Cannot create application object", "Vim Initialisation", 0); return NULL; } // Load the type library from the registry hr = LoadRegTypeLib(MYLIBID, 1, 0, 0x00, &typelib); if (FAILED(hr)) { HKEY hKey; // Check we can write to the registry. // RegCreateKeyEx succeeds even if key exists. W.Briscoe W2K 20021011 if (RegCreateKeyEx(HKEY_CLASSES_ROOT, MYVIPROGID, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, NULL)) { delete me; return NULL; // Unable to write to registry. Quietly fail. } RegCloseKey(hKey); if (MessageBox(0, "Cannot load registered type library.\nDo you want to register Vim now?", "Vim Initialisation", MB_YESNO | MB_ICONQUESTION) != IDYES) { delete me; return NULL; } RegisterMe(FALSE); // Load the type library from the registry hr = LoadRegTypeLib(MYLIBID, 1, 0, 0x00, &typelib); if (FAILED(hr)) { MessageBox(0, "You must restart Vim in order for the registration to take effect.", "Vim Initialisation", 0); *pbDoRestart = TRUE; delete me; return NULL; } } // Get the type info of the vtable interface hr = typelib->GetTypeInfoOfGuid(MYIID, &typeinfo); typelib->Release(); if (FAILED(hr)) { MessageBox(0, "Cannot get interface type information", "Vim Initialisation", 0); delete me; return NULL; } // Save the type information me->typeinfo = typeinfo; return me; } CVim::~CVim() { if (typeinfo && vim_parent_hwnd == NULL) typeinfo->Release(); typeinfo = 0; } STDMETHODIMP CVim::QueryInterface(REFIID riid, void **ppv) { if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IDispatch) || IsEqualIID(riid, MYIID)) { AddRef(); *ppv = this; return S_OK; } *ppv = 0; return E_NOINTERFACE; } STDMETHODIMP_(ULONG) CVim::AddRef() { return ++ref; } STDMETHODIMP_(ULONG) CVim::Release() { // Don't delete the object when the reference count reaches zero, as there // is only a single application object, and its lifetime is controlled by // the running instance, not by its reference count. if (ref > 0) --ref; return ref; } STDMETHODIMP CVim::GetTypeInfoCount(UINT *pCount) { *pCount = 1; return S_OK; } STDMETHODIMP CVim::GetTypeInfo(UINT iTypeInfo, LCID, ITypeInfo **ppITypeInfo) { *ppITypeInfo = 0; if (iTypeInfo != 0) return DISP_E_BADINDEX; typeinfo->AddRef(); *ppITypeInfo = typeinfo; return S_OK; } STDMETHODIMP CVim::GetIDsOfNames( const IID &iid, OLECHAR **names, UINT n, LCID, DISPID *dispids) { if (iid != IID_NULL) return DISP_E_UNKNOWNINTERFACE; return typeinfo->GetIDsOfNames(names, n, dispids); } STDMETHODIMP CVim::Invoke( DISPID member, const IID &iid, LCID, WORD flags, DISPPARAMS *dispparams, VARIANT *result, EXCEPINFO *excepinfo, UINT *argerr) { if (iid != IID_NULL) return DISP_E_UNKNOWNINTERFACE; ::SetErrorInfo(0, NULL); return typeinfo->Invoke(static_cast<IDispatch*>(this), member, flags, dispparams, result, excepinfo, argerr); } STDMETHODIMP CVim::GetHwnd(UINT_PTR *result) { *result = (UINT_PTR)s_hwnd; return S_OK; } STDMETHODIMP CVim::SetForeground(void) { /* Make the Vim window come to the foreground */ gui_mch_set_foreground(); return S_OK; } STDMETHODIMP CVim::SendKeys(BSTR keys) { int len; char *buffer; char_u *str; char_u *ptr; /* Get a suitable buffer */ len = WideCharToMultiByte(CP_ACP, 0, keys, -1, 0, 0, 0, 0); buffer = (char *)alloc(len+1); if (buffer == NULL) return E_OUTOFMEMORY; len = WideCharToMultiByte(CP_ACP, 0, keys, -1, buffer, len, 0, 0); if (len == 0) { vim_free(buffer); return E_INVALIDARG; } /* Translate key codes like <Esc> */ str = replace_termcodes((char_u *)buffer, &ptr, REPTERM_DO_LT, NULL); /* If ptr was set, then a new buffer was allocated, * so we can free the old one. */ if (ptr) vim_free((char_u *)(buffer)); /* Reject strings too long to fit in the input buffer. Allow 10 bytes * space to cover for the (remote) possibility that characters may enter * the input buffer between now and when the WM_OLE message is actually * processed. If more that 10 characters enter the input buffer in that * time, the WM_OLE processing will simply fail to insert the characters. */ if ((int)(STRLEN(str)) > (vim_free_in_input_buf() - 10)) { vim_free(str); return E_INVALIDARG; } /* Pass the string to the main input loop. The memory will be freed when * the message is processed. Except for an empty message, we don't need * to post it then. */ if (*str == NUL) vim_free(str); else PostMessage(NULL, WM_OLE, 0, (LPARAM)str); return S_OK; } STDMETHODIMP CVim::Eval(BSTR expr, BSTR *result) { #ifdef FEAT_EVAL int len; char *buffer; char *str; wchar_t *w_buffer; /* Get a suitable buffer */ len = WideCharToMultiByte(CP_ACP, 0, expr, -1, 0, 0, 0, 0); if (len == 0) return E_INVALIDARG; buffer = (char *)alloc(len); if (buffer == NULL) return E_OUTOFMEMORY; /* Convert the (wide character) expression to an ASCII string */ len = WideCharToMultiByte(CP_ACP, 0, expr, -1, buffer, len, 0, 0); if (len == 0) return E_INVALIDARG; /* Evaluate the expression */ ++emsg_skip; str = (char *)eval_to_string((char_u *)buffer, TRUE); --emsg_skip; vim_free(buffer); if (str == NULL) return E_FAIL; /* Convert the result to wide characters */ MultiByteToWideChar_alloc(CP_ACP, 0, str, -1, &w_buffer, &len); vim_free(str); if (w_buffer == NULL) return E_OUTOFMEMORY; if (len == 0) { vim_free(w_buffer); return E_FAIL; } /* Store the result */ *result = SysAllocString(w_buffer); vim_free(w_buffer); return S_OK; #else return E_NOTIMPL; #endif } /***************************************************************************** 3. The class factory *****************************************************************************/ /* Definition * ---------- */ class CVimCF FINAL : public IClassFactory { public: static CVimCF *Create(); virtual ~CVimCF() {}; STDMETHOD(QueryInterface)(REFIID riid, void ** ppv); STDMETHOD_(unsigned long, AddRef)(void); STDMETHOD_(unsigned long, Release)(void); STDMETHOD(CreateInstance)(IUnknown *punkOuter, REFIID riid, void ** ppv); STDMETHOD(LockServer)(BOOL lock); private: // Constructor is private - create via Create() CVimCF() : ref(0) {}; // Reference count unsigned long ref; }; /* Implementation * -------------- */ CVimCF *CVimCF::Create() { CVimCF *me = new CVimCF(); if (me == NULL) MessageBox(0, "Cannot create class factory", "Vim Initialisation", 0); return me; } STDMETHODIMP CVimCF::QueryInterface(REFIID riid, void **ppv) { if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IClassFactory)) { AddRef(); *ppv = this; return S_OK; } *ppv = 0; return E_NOINTERFACE; } STDMETHODIMP_(ULONG) CVimCF::AddRef() { return ++ref; } STDMETHODIMP_(ULONG) CVimCF::Release() { // Don't delete the object when the reference count reaches zero, as there // is only a single application object, and its lifetime is controlled by // the running instance, not by its reference count. if (ref > 0) --ref; return ref; } /*ARGSUSED*/ STDMETHODIMP CVimCF::CreateInstance(IUnknown *punkOuter, REFIID riid, void **ppv) { return app->QueryInterface(riid, ppv); } /*ARGSUSED*/ STDMETHODIMP CVimCF::LockServer(BOOL lock) { return S_OK; } /***************************************************************************** 4. Registry manipulation code *****************************************************************************/ // Internal use only static void SetKeyAndValue(const char *path, const char *subkey, const char *value); static void GUIDtochar(const GUID &guid, char *GUID, int length); static void RecursiveDeleteKey(HKEY hKeyParent, const char *child); static const int GUID_STRING_SIZE = 39; // Register the component in the registry // When "silent" is TRUE don't give any messages. extern "C" void RegisterMe(int silent) { BOOL ok = TRUE; // Get the application startup command char module[MAX_PATH]; ::GetModuleFileName(NULL, module, MAX_PATH); // Unregister first (quietly) UnregisterMe(FALSE); // Convert the CLSID into a char char clsid[GUID_STRING_SIZE]; GUIDtochar(MYCLSID, clsid, sizeof(clsid)); // Convert the LIBID into a char char libid[GUID_STRING_SIZE]; GUIDtochar(MYLIBID, libid, sizeof(libid)); // Build the key CLSID\\{...} char Key[MAX_CLSID_LEN]; strcpy(Key, "CLSID\\"); strcat(Key, clsid); // Add the CLSID to the registry SetKeyAndValue(Key, NULL, MYNAME); SetKeyAndValue(Key, "LocalServer32", module); SetKeyAndValue(Key, "ProgID", MYPROGID); SetKeyAndValue(Key, "VersionIndependentProgID", MYVIPROGID); SetKeyAndValue(Key, "TypeLib", libid); // Add the version-independent ProgID subkey under HKEY_CLASSES_ROOT SetKeyAndValue(MYVIPROGID, NULL, MYNAME); SetKeyAndValue(MYVIPROGID, "CLSID", clsid); SetKeyAndValue(MYVIPROGID, "CurVer", MYPROGID); // Add the versioned ProgID subkey under HKEY_CLASSES_ROOT SetKeyAndValue(MYPROGID, NULL, MYNAME); SetKeyAndValue(MYPROGID, "CLSID", clsid); wchar_t w_module[MAX_PATH]; MultiByteToWideChar(CP_ACP, 0, module, -1, w_module, MAX_PATH); ITypeLib *typelib = NULL; if (LoadTypeLib(w_module, &typelib) != S_OK) { if (!silent) MessageBox(0, "Cannot load type library to register", "Vim Registration", 0); ok = FALSE; } else { if (RegisterTypeLib(typelib, w_module, NULL) != S_OK) { if (!silent) MessageBox(0, "Cannot register type library", "Vim Registration", 0); ok = FALSE; } typelib->Release(); } if (ok && !silent) MessageBox(0, "Registered successfully", "Vim", 0); } // Remove the component from the registry // // Note: There is little error checking in this code, to allow incomplete // or failed registrations to be undone. extern "C" void UnregisterMe(int bNotifyUser) { // Unregister the type library ITypeLib *typelib; if (SUCCEEDED(LoadRegTypeLib(MYLIBID, MAJORVER, MINORVER, LOCALE, &typelib))) { TLIBATTR *tla; if (SUCCEEDED(typelib->GetLibAttr(&tla))) { UnRegisterTypeLib(tla->guid, tla->wMajorVerNum, tla->wMinorVerNum, tla->lcid, tla->syskind); typelib->ReleaseTLibAttr(tla); } typelib->Release(); } // Convert the CLSID into a char char clsid[GUID_STRING_SIZE]; GUIDtochar(MYCLSID, clsid, sizeof(clsid)); // Build the key CLSID\\{...} char Key[MAX_CLSID_LEN]; strcpy(Key, "CLSID\\"); strcat(Key, clsid); // Delete the CLSID Key - CLSID\{...} RecursiveDeleteKey(HKEY_CLASSES_ROOT, Key); // Delete the version-independent ProgID Key RecursiveDeleteKey(HKEY_CLASSES_ROOT, MYVIPROGID); // Delete the ProgID key RecursiveDeleteKey(HKEY_CLASSES_ROOT, MYPROGID); if (bNotifyUser) MessageBox(0, "Unregistered successfully", "Vim", 0); } /****************************************************************************/ // Convert a GUID to a char string static void GUIDtochar(const GUID &guid, char *GUID, int length) { // Get wide string version LPOLESTR wGUID = NULL; StringFromCLSID(guid, &wGUID); // Convert from wide characters to non-wide wcstombs(GUID, wGUID, length); // Free memory CoTaskMemFree(wGUID); } // Delete a key and all of its descendants static void RecursiveDeleteKey(HKEY hKeyParent, const char *child) { // Open the child HKEY hKeyChild; LONG result = RegOpenKeyEx(hKeyParent, child, 0, KEY_ALL_ACCESS, &hKeyChild); if (result != ERROR_SUCCESS) return; // Enumerate all of the descendants of this child FILETIME time; char buffer[1024]; DWORD size = 1024; while (RegEnumKeyEx(hKeyChild, 0, buffer, &size, NULL, NULL, NULL, &time) == S_OK) { // Delete the descendants of this child RecursiveDeleteKey(hKeyChild, buffer); size = 256; } // Close the child RegCloseKey(hKeyChild); // Delete this child RegDeleteKey(hKeyParent, child); } // Create a key and set its value static void SetKeyAndValue(const char *key, const char *subkey, const char *value) { HKEY hKey; char buffer[1024]; strcpy(buffer, key); // Add subkey name to buffer. if (subkey) { strcat(buffer, "\\"); strcat(buffer, subkey); } // Create and open key and subkey. long result = RegCreateKeyEx(HKEY_CLASSES_ROOT, buffer, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, NULL); if (result != ERROR_SUCCESS) return; // Set the value if (value) RegSetValueEx(hKey, NULL, 0, REG_SZ, (BYTE *)value, (DWORD)STRLEN(value)+1); RegCloseKey(hKey); } /***************************************************************************** 5. OLE Initialisation and shutdown processing *****************************************************************************/ extern "C" void InitOLE(int *pbDoRestart) { HRESULT hr; *pbDoRestart = FALSE; // Initialize the OLE libraries hr = OleInitialize(NULL); if (FAILED(hr)) { MessageBox(0, "Cannot initialise OLE", "Vim Initialisation", 0); goto error0; } // Create the application object app = CVim::Create(pbDoRestart); if (app == NULL) goto error1; // Create the class factory cf = CVimCF::Create(); if (cf == NULL) goto error1; // Register the class factory hr = CoRegisterClassObject( MYCLSID, cf, CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE, &cf_id); if (FAILED(hr)) { MessageBox(0, "Cannot register class factory", "Vim Initialisation", 0); goto error1; } // Register the application object as active hr = RegisterActiveObject( app, MYCLSID, 0, &app_id); if (FAILED(hr)) { MessageBox(0, "Cannot register application object", "Vim Initialisation", 0); goto error1; } return; // Errors: tidy up as much as needed and return error1: UninitOLE(); error0: return; } extern "C" void UninitOLE() { // Unregister the application object if (app_id) { RevokeActiveObject(app_id, NULL); app_id = 0; } // Unregister the class factory if (cf_id) { CoRevokeClassObject(cf_id); cf_id = 0; } // Shut down the OLE libraries OleUninitialize(); // Delete the application object if (app) { delete app; app = NULL; } // Delete the class factory if (cf) { delete cf; cf = NULL; } } #endif /* FEAT_OLE */
//===- LoopExtractor.cpp - Extract each loop into a new function ----------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // A pass wrapper around the ExtractLoop() scalar transformation to extract each // top-level loop into its own new function. If the loop is the ONLY loop in a // given function, it is not touched. This is a pass most useful for debugging // via bugpoint. // //===----------------------------------------------------------------------===// #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/AssumptionCache.h" #include "llvm/Analysis/LoopPass.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Module.h" #include "llvm/InitializePasses.h" #include "llvm/Pass.h" #include "llvm/Support/CommandLine.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Utils.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/Transforms/Utils/CodeExtractor.h" #include <fstream> #include <set> using namespace llvm; #define DEBUG_TYPE "loop-extract" STATISTIC(NumExtracted, "Number of loops extracted"); namespace { struct LoopExtractor : public LoopPass { static char ID; // Pass identification, replacement for typeid unsigned NumLoops; explicit LoopExtractor(unsigned numLoops = ~0) : LoopPass(ID), NumLoops(numLoops) { initializeLoopExtractorPass(*PassRegistry::getPassRegistry()); } bool runOnLoop(Loop *L, LPPassManager &) override; void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequiredID(BreakCriticalEdgesID); AU.addRequiredID(LoopSimplifyID); AU.addRequired<DominatorTreeWrapperPass>(); AU.addRequired<LoopInfoWrapperPass>(); AU.addUsedIfAvailable<AssumptionCacheTracker>(); } }; } char LoopExtractor::ID = 0; INITIALIZE_PASS_BEGIN(LoopExtractor, "loop-extract", "Extract loops into new functions", false, false) INITIALIZE_PASS_DEPENDENCY(BreakCriticalEdges) INITIALIZE_PASS_DEPENDENCY(LoopSimplify) INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) INITIALIZE_PASS_END(LoopExtractor, "loop-extract", "Extract loops into new functions", false, false) namespace { /// SingleLoopExtractor - For bugpoint. struct SingleLoopExtractor : public LoopExtractor { static char ID; // Pass identification, replacement for typeid SingleLoopExtractor() : LoopExtractor(1) {} }; } // End anonymous namespace char SingleLoopExtractor::ID = 0; INITIALIZE_PASS(SingleLoopExtractor, "loop-extract-single", "Extract at most one loop into a new function", false, false) // createLoopExtractorPass - This pass extracts all natural loops from the // program into a function if it can. // Pass *llvm::createLoopExtractorPass() { return new LoopExtractor(); } bool LoopExtractor::runOnLoop(Loop *L, LPPassManager &LPM) { if (skipLoop(L)) return false; // Only visit top-level loops. if (L->getParentLoop()) return false; // If LoopSimplify form is not available, stay out of trouble. if (!L->isLoopSimplifyForm()) return false; DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); bool Changed = false; // If there is more than one top-level loop in this function, extract all of // the loops. Otherwise there is exactly one top-level loop; in this case if // this function is more than a minimal wrapper around the loop, extract // the loop. bool ShouldExtractLoop = false; // Extract the loop if the entry block doesn't branch to the loop header. Instruction *EntryTI = L->getHeader()->getParent()->getEntryBlock().getTerminator(); if (!isa<BranchInst>(EntryTI) || !cast<BranchInst>(EntryTI)->isUnconditional() || EntryTI->getSuccessor(0) != L->getHeader()) { ShouldExtractLoop = true; } else { // Check to see if any exits from the loop are more than just return // blocks. SmallVector<BasicBlock*, 8> ExitBlocks; L->getExitBlocks(ExitBlocks); for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) if (!isa<ReturnInst>(ExitBlocks[i]->getTerminator())) { ShouldExtractLoop = true; break; } } if (ShouldExtractLoop) { // We must omit EH pads. EH pads must accompany the invoke // instruction. But this would result in a loop in the extracted // function. An infinite cycle occurs when it tries to extract that loop as // well. SmallVector<BasicBlock*, 8> ExitBlocks; L->getExitBlocks(ExitBlocks); for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) if (ExitBlocks[i]->isEHPad()) { ShouldExtractLoop = false; break; } } if (ShouldExtractLoop) { if (NumLoops == 0) return Changed; --NumLoops; AssumptionCache *AC = nullptr; Function &Func = *L->getHeader()->getParent(); if (auto *ACT = getAnalysisIfAvailable<AssumptionCacheTracker>()) AC = ACT->lookupAssumptionCache(Func); CodeExtractorAnalysisCache CEAC(Func); CodeExtractor Extractor(DT, *L, false, nullptr, nullptr, AC); if (Extractor.extractCodeRegion(CEAC) != nullptr) { Changed = true; // After extraction, the loop is replaced by a function call, so // we shouldn't try to run any more loop passes on it. LPM.markLoopAsDeleted(*L); LI.erase(L); } ++NumExtracted; } return Changed; } // createSingleLoopExtractorPass - This pass extracts one natural loop from the // program into a function if it can. This is used by bugpoint. // Pass *llvm::createSingleLoopExtractorPass() { return new SingleLoopExtractor(); }
/** * @file subscribe.hpp * @author Jichan (development@jc-lab.net / http://ablog.jc-lab.net/ ) * @date 2019/07/08 * @copyright Copyright (C) 2019 jichan.\n * This software may be modified and distributed under the terms * of the Apache License 2.0. See the LICENSE file for details. */ #pragma once #include <string> #include "base.hpp" #include "../frame.hpp" #include "../client.hpp" namespace stomp { namespace command { class Ack : public Base { public: Ack(Client *client) : Base(Frame::Commands::SUBSCRIBE) { } Ack& transaction(const std::string& value) { frame_.header("transaction", value); return *this; } const std::string& transaction() { return frame_.header("transaction"); } }; } }
#pragma once #include <Register/Utility.hpp> namespace Kvasir { //Analog to digital converter namespace Adc1Sr{ ///<status register using Addr = Register::Address<0x40012400,0xffffffe0,0x00000000,std::uint32_t>; ///Regular channel start flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> strt{}; ///Injected channel start flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> jstrt{}; ///Injected channel end of conversion constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> jeoc{}; ///Regular channel end of conversion constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> eoc{}; ///Analog watchdog flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> awd{}; } namespace Adc1Cr1{ ///<control register 1 using Addr = Register::Address<0x40012404,0xff300000,0x00000000,std::uint32_t>; ///Analog watchdog enable on regular channels constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> awden{}; ///Analog watchdog enable on injected channels constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> jawden{}; ///Dual mode selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::ReadWriteAccess,unsigned> dualmod{}; ///Discontinuous mode channel count constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,13),Register::ReadWriteAccess,unsigned> discnum{}; ///Discontinuous mode on injected channels constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> jdiscen{}; ///Discontinuous mode on regular channels constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> discen{}; ///Automatic injected group conversion constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> jauto{}; ///Enable the watchdog on a single channel in scan mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> awdsgl{}; ///Scan mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> scan{}; ///Interrupt enable for injected channels constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> jeocie{}; ///Analog watchdog interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> awdie{}; ///Interrupt enable for EOC constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> eocie{}; ///Analog watchdog channel select bits constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,0),Register::ReadWriteAccess,unsigned> awdch{}; } namespace Adc1Cr2{ ///<control register 2 using Addr = Register::Address<0x40012408,0xff0106f0,0x00000000,std::uint32_t>; ///Temperature sensor and VREFINT enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> tsvrefe{}; ///Start conversion of regular channels constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> swstart{}; ///Start conversion of injected channels constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> jswstart{}; ///External trigger conversion mode for regular channels constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> exttrig{}; ///External event select for regular group constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,17),Register::ReadWriteAccess,unsigned> extsel{}; ///External trigger conversion mode for injected channels constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> jexttrig{}; ///External event select for injected group constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,12),Register::ReadWriteAccess,unsigned> jextsel{}; ///Data alignment constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> align{}; ///Direct memory access mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> dma{}; ///Reset calibration constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> rstcal{}; ///A/D calibration constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> cal{}; ///Continuous conversion constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> cont{}; ///A/D converter ON / OFF constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> adon{}; } namespace Adc1Smpr1{ ///<sample time register 1 using Addr = Register::Address<0x4001240c,0xff000000,0x00000000,std::uint32_t>; ///Channel 10 sample time selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,0),Register::ReadWriteAccess,unsigned> smp10{}; ///Channel 11 sample time selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,3),Register::ReadWriteAccess,unsigned> smp11{}; ///Channel 12 sample time selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,6),Register::ReadWriteAccess,unsigned> smp12{}; ///Channel 13 sample time selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,9),Register::ReadWriteAccess,unsigned> smp13{}; ///Channel 14 sample time selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,12),Register::ReadWriteAccess,unsigned> smp14{}; ///Channel 15 sample time selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,15),Register::ReadWriteAccess,unsigned> smp15{}; ///Channel 16 sample time selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,18),Register::ReadWriteAccess,unsigned> smp16{}; ///Channel 17 sample time selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,21),Register::ReadWriteAccess,unsigned> smp17{}; } namespace Adc1Smpr2{ ///<sample time register 2 using Addr = Register::Address<0x40012410,0xc0000000,0x00000000,std::uint32_t>; ///Channel 0 sample time selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,0),Register::ReadWriteAccess,unsigned> smp0{}; ///Channel 1 sample time selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,3),Register::ReadWriteAccess,unsigned> smp1{}; ///Channel 2 sample time selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,6),Register::ReadWriteAccess,unsigned> smp2{}; ///Channel 3 sample time selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,9),Register::ReadWriteAccess,unsigned> smp3{}; ///Channel 4 sample time selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,12),Register::ReadWriteAccess,unsigned> smp4{}; ///Channel 5 sample time selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,15),Register::ReadWriteAccess,unsigned> smp5{}; ///Channel 6 sample time selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,18),Register::ReadWriteAccess,unsigned> smp6{}; ///Channel 7 sample time selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,21),Register::ReadWriteAccess,unsigned> smp7{}; ///Channel 8 sample time selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,24),Register::ReadWriteAccess,unsigned> smp8{}; ///Channel 9 sample time selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,27),Register::ReadWriteAccess,unsigned> smp9{}; } namespace Adc1Jofr1{ ///<injected channel data offset register x using Addr = Register::Address<0x40012414,0xfffff000,0x00000000,std::uint32_t>; ///Data offset for injected channel x constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,0),Register::ReadWriteAccess,unsigned> joffset1{}; } namespace Adc1Jofr2{ ///<injected channel data offset register x using Addr = Register::Address<0x40012418,0xfffff000,0x00000000,std::uint32_t>; ///Data offset for injected channel x constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,0),Register::ReadWriteAccess,unsigned> joffset2{}; } namespace Adc1Jofr3{ ///<injected channel data offset register x using Addr = Register::Address<0x4001241c,0xfffff000,0x00000000,std::uint32_t>; ///Data offset for injected channel x constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,0),Register::ReadWriteAccess,unsigned> joffset3{}; } namespace Adc1Jofr4{ ///<injected channel data offset register x using Addr = Register::Address<0x40012420,0xfffff000,0x00000000,std::uint32_t>; ///Data offset for injected channel x constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,0),Register::ReadWriteAccess,unsigned> joffset4{}; } namespace Adc1Htr{ ///<watchdog higher threshold register using Addr = Register::Address<0x40012424,0xfffff000,0x00000000,std::uint32_t>; ///Analog watchdog higher threshold constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,0),Register::ReadWriteAccess,unsigned> ht{}; } namespace Adc1Ltr{ ///<watchdog lower threshold register using Addr = Register::Address<0x40012428,0xfffff000,0x00000000,std::uint32_t>; ///Analog watchdog lower threshold constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,0),Register::ReadWriteAccess,unsigned> lt{}; } namespace Adc1Sqr1{ ///<regular sequence register 1 using Addr = Register::Address<0x4001242c,0xff000000,0x00000000,std::uint32_t>; ///Regular channel sequence length constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,20),Register::ReadWriteAccess,unsigned> l{}; ///16th conversion in regular sequence constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,15),Register::ReadWriteAccess,unsigned> sq16{}; ///15th conversion in regular sequence constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,10),Register::ReadWriteAccess,unsigned> sq15{}; ///14th conversion in regular sequence constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,5),Register::ReadWriteAccess,unsigned> sq14{}; ///13th conversion in regular sequence constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,0),Register::ReadWriteAccess,unsigned> sq13{}; } namespace Adc1Sqr2{ ///<regular sequence register 2 using Addr = Register::Address<0x40012430,0xc0000000,0x00000000,std::uint32_t>; ///12th conversion in regular sequence constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,25),Register::ReadWriteAccess,unsigned> sq12{}; ///11th conversion in regular sequence constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,20),Register::ReadWriteAccess,unsigned> sq11{}; ///10th conversion in regular sequence constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,15),Register::ReadWriteAccess,unsigned> sq10{}; ///9th conversion in regular sequence constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,10),Register::ReadWriteAccess,unsigned> sq9{}; ///8th conversion in regular sequence constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,5),Register::ReadWriteAccess,unsigned> sq8{}; ///7th conversion in regular sequence constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,0),Register::ReadWriteAccess,unsigned> sq7{}; } namespace Adc1Sqr3{ ///<regular sequence register 3 using Addr = Register::Address<0x40012434,0xc0000000,0x00000000,std::uint32_t>; ///6th conversion in regular sequence constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,25),Register::ReadWriteAccess,unsigned> sq6{}; ///5th conversion in regular sequence constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,20),Register::ReadWriteAccess,unsigned> sq5{}; ///4th conversion in regular sequence constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,15),Register::ReadWriteAccess,unsigned> sq4{}; ///3rd conversion in regular sequence constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,10),Register::ReadWriteAccess,unsigned> sq3{}; ///2nd conversion in regular sequence constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,5),Register::ReadWriteAccess,unsigned> sq2{}; ///1st conversion in regular sequence constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,0),Register::ReadWriteAccess,unsigned> sq1{}; } namespace Adc1Jsqr{ ///<injected sequence register using Addr = Register::Address<0x40012438,0xffc00000,0x00000000,std::uint32_t>; ///Injected sequence length constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,20),Register::ReadWriteAccess,unsigned> jl{}; ///4th conversion in injected sequence constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,15),Register::ReadWriteAccess,unsigned> jsq4{}; ///3rd conversion in injected sequence constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,10),Register::ReadWriteAccess,unsigned> jsq3{}; ///2nd conversion in injected sequence constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,5),Register::ReadWriteAccess,unsigned> jsq2{}; ///1st conversion in injected sequence constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,0),Register::ReadWriteAccess,unsigned> jsq1{}; } namespace Adc1Jdr1{ ///<injected data register x using Addr = Register::Address<0x4001243c,0xffff0000,0x00000000,std::uint32_t>; ///Injected data constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> jdata{}; } namespace Adc1Jdr2{ ///<injected data register x using Addr = Register::Address<0x40012440,0xffff0000,0x00000000,std::uint32_t>; ///Injected data constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> jdata{}; } namespace Adc1Jdr3{ ///<injected data register x using Addr = Register::Address<0x40012444,0xffff0000,0x00000000,std::uint32_t>; ///Injected data constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> jdata{}; } namespace Adc1Jdr4{ ///<injected data register x using Addr = Register::Address<0x40012448,0xffff0000,0x00000000,std::uint32_t>; ///Injected data constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> jdata{}; } namespace Adc1Dr{ ///<regular data register using Addr = Register::Address<0x4001244c,0x00000000,0x00000000,std::uint32_t>; ///Regular data constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> data{}; ///ADC2 data constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> adc2data{}; } }
/*========================================================================= Program: Visualization Toolkit Module: vtkVolumeMapperNode.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkVolumeMapperNode.h" #include "vtkActor.h" #include "vtkCellArray.h" #include "vtkMath.h" #include "vtkMatrix4x4.h" #include "vtkObjectFactory.h" #include "vtkPoints.h" #include "vtkPolyData.h" #include "vtkPolygon.h" #include "vtkProperty.h" //============================================================================ vtkStandardNewMacro(vtkVolumeMapperNode); //------------------------------------------------------------------------------ vtkVolumeMapperNode::vtkVolumeMapperNode() = default; //------------------------------------------------------------------------------ vtkVolumeMapperNode::~vtkVolumeMapperNode() = default; //------------------------------------------------------------------------------ void vtkVolumeMapperNode::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); }
#include <cstdio> #include <cstdlib> using namespace std; struct rec { int sum, inc; }; rec tree[1 << 21]; int m, n, i; int u, v, w; bool finish; inline void read(int &x) { x = 0; char ch = getchar(); while (ch < '0' || ch > '9') ch = getchar(); while (ch <= '9' && ch >= '0') x = x * 10 + ch - '0', ch = getchar(); return ; } inline int mymin(int a, int b) { return a < b ? a : b; } void Build_A_Tree(int u, int l, int r) { if (l + 1 == r) { read(tree[u].sum); return ; } int mid = (l + r) >> 1; Build_A_Tree(u << 1, l, mid); Build_A_Tree(u << 1 | 1, mid, r); tree[u].sum = mymin(tree[u << 1].sum, tree[u << 1 | 1].sum); return ; } inline void update(int u) { if (!tree[u].inc) return ; tree[u << 1].inc += tree[u].inc; tree[u << 1 | 1].inc += tree[u].inc; tree[u << 1].sum += tree[u].inc; tree[u << 1 | 1].sum += tree[u].inc; tree[u].inc = 0; return ; } void modify(int u, int l, int r, int ll, int rr, int delta) { if (finish) return ; if (l >= ll && r <= rr) { tree[u].sum += delta; if (tree[u].sum < 0) { printf("-1\n%d\n", i); exit(0); } tree[u].inc += delta; return ; } update(u); int mid = (l + r) >> 1; if (ll < mid) modify(u << 1, l, mid, ll, rr, delta); if (rr > mid) modify(u << 1 | 1, mid, r, ll, rr, delta); tree[u].sum = mymin(tree[u << 1].sum, tree[u << 1 | 1].sum); return ; } int main() { read(n); read(m); Build_A_Tree(1, 1, n + 1); for (i = 1; i <= m; i++) { read(u); read(v); read(w); modify(1, 1, n + 1, v, w + 1, -u); } printf("0\n"); return 0; }
#ifndef SPHERE_HPP #define SPHERE_HPP // Generate a sphere with a precision level of n // The total number of triangles is 20*pow(4, n) struct SphereVertex { } class Sphere { public: Sphere(); virtual ~Sphere(); // set precision level void setPrecision(n); // increase precision by one level void increasePrecision(); // compile triangle void compile(); private: std::vector< }; #endif /* end of include guard: SPHERE_HPP */
/** * @file scrnmng_dd.cpp * @brief Screen Manager (DirectDraw2) * * @author $Author: yui (modified by SimK)$ * @date $Date: 2011/03/07 09:54:11 $ */ #include <compiler.h> #include <ddraw.h> #ifndef __GNUC__ #include <winnls32.h> #endif #include "resource.h" #include <np2.h> #include <np2mt.h> #include "winloc.h" #include <mousemng.h> #include <scrnmng.h> #include "scrnmng_dd.h" // #include <sysmng.h> #include "dialog/np2class.h" #include <pccore.h> #include <vram/scrndraw.h> #include <vram/palettes.h> #if defined(SUPPORT_DCLOCK) #include "subwnd/dclock.h" #endif #include "recvideo.h" #ifdef SUPPORT_WAB #include <wab/wab.h> #endif #include <shlwapi.h> #if !defined(__GNUC__) #pragma comment(lib, "ddraw.lib") #pragma comment(lib, "dxguid.lib") #endif // !defined(__GNUC__) //! 8BPP パレット数 #define PALLETES_8BPP NP2PAL_TEXT3 static int req_enter_criticalsection = 0; extern WINLOCEX np2_winlocexallwin(HWND base); typedef struct { LPDIRECTDRAW ddraw1; LPDIRECTDRAW2 ddraw2; LPDIRECTDRAWSURFACE primsurf; LPDIRECTDRAWSURFACE backsurf; #if defined(SUPPORT_DCLOCK) LPDIRECTDRAWSURFACE clocksurf; #endif #if defined(SUPPORT_WAB) LPDIRECTDRAWSURFACE wabsurf; #endif LPDIRECTDRAWCLIPPER clipper; LPDIRECTDRAWPALETTE palette; UINT scrnmode; int width; int height; int extend; int cliping; RGB32 pal16mask; UINT8 r16b; UINT8 l16r; UINT8 l16g; UINT8 menudisp; int menusize; RECT scrn; RECT rect; RECT scrnclip; RECT rectclip; PALETTEENTRY pal[256]; } DDRAW; static DDRAW ddraw; static SCRNSURF scrnsurf; #ifdef SUPPORT_WAB static int mt_wabdrawing = 0; static int mt_wabpausedrawing = 0; #endif static int dd_cs_initialized = 0; static CRITICAL_SECTION dd_cs; static BOOL dd_tryenter_criticalsection(void){ if(!dd_cs_initialized) return TRUE; return TryEnterCriticalSection(&dd_cs); } static void dd_enter_criticalsection(void){ if(!dd_cs_initialized) return; EnterCriticalSection(&dd_cs); } static void dd_leave_criticalsection(void){ if(!dd_cs_initialized) return; LeaveCriticalSection(&dd_cs); } // プライマリサーフェイスのDirectDraw DDBLT_COLORFILLで例外が出る環境があるようなので代替 //#define DDBLT_COLORFILL_FIX #ifdef DDBLT_COLORFILL_FIX static void DDBlt_ColorFill(LPDIRECTDRAWSURFACE lpDst, LPRECT lpDstRect, LPDDBLTFX lpDDBltFx, LPDIRECTDRAWSURFACE lpOffScrBuf) { HDC hDC = NULL; RECT src; src.left = src.top = 0; src.right = 4; src.bottom = 4; if(lpOffScrBuf->GetDC(&hDC)==DD_OK){ HBRUSH hBrs = CreateSolidBrush(lpDDBltFx->dwFillColor); FillRect(hDC, &src, hBrs); DeleteObject(hBrs); lpOffScrBuf->ReleaseDC(hDC); src.left += 1; src.top += 1; src.right -= 1; src.bottom -= 1; lpDst->Blt(lpDstRect, lpOffScrBuf, &src, DDBLT_WAIT, NULL); } } #else static void DDBlt_ColorFill(LPDIRECTDRAWSURFACE lpDst, LPRECT lpRect, LPDDBLTFX lpDDBltFx, LPDIRECTDRAWSURFACE lpOffScrBuf) { lpDst->Blt(lpRect,NULL,NULL, DDBLT_COLORFILL | DDBLT_WAIT, lpDDBltFx); } #endif static void renewalclientsize(BOOL winloc) { int width; int height; int extend; UINT fscrnmod; int multiple; int scrnwidth; int scrnheight; int tmpcy; WINLOCEX wlex; width = min(scrnstat.width, ddraw.width); height = min(scrnstat.height, ddraw.height); extend = 0; // 描画範囲〜 if (ddraw.scrnmode & SCRNMODE_FULLSCREEN) { ddraw.rect.right = width; ddraw.rect.bottom = height; scrnwidth = width; scrnheight = height; fscrnmod = FSCRNCFG_fscrnmod & FSCRNMOD_ASPECTMASK; switch(fscrnmod) { default: case FSCRNMOD_NORESIZE: break; case FSCRNMOD_ASPECTFIX8: scrnwidth = (ddraw.width << 3) / width; scrnheight = (ddraw.height << 3) / height; multiple = min(scrnwidth, scrnheight); scrnwidth = (width * multiple) >> 3; scrnheight = (height * multiple) >> 3; break; case FSCRNMOD_ASPECTFIX: scrnwidth = ddraw.width; scrnheight = (scrnwidth * height) / width; if (scrnheight >= ddraw.height) { scrnheight = ddraw.height; scrnwidth = (scrnheight * width) / height; } break; case FSCRNMOD_INTMULTIPLE: scrnwidth = (ddraw.width / width) * width; scrnheight = (scrnwidth * height) / width; if (scrnheight >= ddraw.height) { scrnheight = (ddraw.height / height) * height; scrnwidth = (scrnheight * width) / height; } break; case FSCRNMOD_FORCE43: if(ddraw.width*3 > ddraw.height*4){ scrnwidth = ddraw.height*4/3; scrnheight = ddraw.height; }else{ scrnwidth = ddraw.width; scrnheight = ddraw.width*3/4; } break; case FSCRNMOD_LARGE: scrnwidth = ddraw.width; scrnheight = ddraw.height; break; } ddraw.scrn.left = (ddraw.width - scrnwidth) / 2; ddraw.scrn.top = (ddraw.height - scrnheight) / 2; ddraw.scrn.right = ddraw.scrn.left + scrnwidth; ddraw.scrn.bottom = ddraw.scrn.top + scrnheight; // メニュー表示時の描画領域 ddraw.rectclip = ddraw.rect; ddraw.scrnclip = ddraw.scrn; if (ddraw.scrnclip.top < ddraw.menusize) { ddraw.scrnclip.top = ddraw.menusize; tmpcy = ddraw.height - ddraw.menusize; if (scrnheight > tmpcy) { switch(fscrnmod) { default: case FSCRNMOD_NORESIZE: tmpcy = min(tmpcy, height); ddraw.rectclip.bottom = tmpcy; break; case FSCRNMOD_ASPECTFIX8: case FSCRNMOD_ASPECTFIX: case FSCRNMOD_INTMULTIPLE: case FSCRNMOD_FORCE43: ddraw.rectclip.bottom = (tmpcy * height) / scrnheight; break; case FSCRNMOD_LARGE: break; } } ddraw.scrnclip.bottom = ddraw.menusize + tmpcy; } } else { fscrnmod = FSCRNCFG_fscrnmod & FSCRNMOD_ASPECTMASK; multiple = scrnstat.multiple; if (!(ddraw.scrnmode & SCRNMODE_ROTATE)) { if ((np2oscfg.paddingx) && (multiple == 8)) { extend = min(scrnstat.extend, ddraw.extend); } scrnwidth = (width * multiple) >> 3; scrnheight = (height * multiple) >> 3; if(fscrnmod==FSCRNMOD_FORCE43) { // Force 4:3 Screen if(((width * multiple) >> 3)*3 < ((height * multiple) >> 3)*4){ scrnwidth = ((height * multiple) >> 3)*4/3; scrnheight = ((height * multiple) >> 3); }else{ scrnwidth = ((width * multiple) >> 3); scrnheight = ((width * multiple) >> 3)*3/4; } } ddraw.rect.right = width + extend; ddraw.rect.bottom = height; ddraw.scrn.left = np2oscfg.paddingx - extend; ddraw.scrn.top = np2oscfg.paddingy; } else { if ((np2oscfg.paddingy) && (multiple == 8)) { extend = min(scrnstat.extend, ddraw.extend); } scrnwidth = (height * multiple) >> 3; scrnheight = (width * multiple) >> 3; if(fscrnmod==FSCRNMOD_FORCE43) { // Force 4:3 Screen if(((width * multiple) >> 3)*4 < ((height * multiple) >> 3)*3){ scrnwidth = ((height * multiple) >> 3)*3/4; scrnheight = ((height * multiple) >> 3); }else{ scrnwidth = ((width * multiple) >> 3); scrnheight = ((width * multiple) >> 3)*4/3; } } ddraw.rect.right = height; ddraw.rect.bottom = width + extend; ddraw.scrn.left = np2oscfg.paddingx; ddraw.scrn.top = np2oscfg.paddingy - extend; } ddraw.scrn.right = np2oscfg.paddingx + scrnwidth; ddraw.scrn.bottom = np2oscfg.paddingy + scrnheight; wlex = NULL; if (winloc) { wlex = np2_winlocexallwin(g_hWndMain); } winlocex_setholdwnd(wlex, g_hWndMain); scrnmng_setwindowsize(g_hWndMain, scrnwidth, scrnheight); winlocex_move(wlex); winlocex_destroy(wlex); } scrnsurf.width = width; scrnsurf.height = height; scrnsurf.extend = extend; } static void clearoutofrect(const RECT *target, const RECT *base) { LPDIRECTDRAWSURFACE primsurf; DDBLTFX ddbf; RECT rect; dd_enter_criticalsection(); primsurf = ddraw.primsurf; if (primsurf == NULL) { dd_leave_criticalsection(); return; } ZeroMemory(&ddbf, sizeof(ddbf)); ddbf.dwSize = sizeof(ddbf); ddbf.dwFillColor = 0; rect.left = base->left; rect.right = base->right; rect.top = base->top; rect.bottom = target->top; if (rect.top < rect.bottom) { //primsurf->Blt(&rect, NULL, NULL, DDBLT_WAIT | DDBLT_COLORFILL, &ddbf); DDBlt_ColorFill(primsurf, &rect, &ddbf, ddraw.backsurf); } rect.top = target->bottom; rect.bottom = base->bottom; if (rect.top < rect.bottom) { //primsurf->Blt(&rect, NULL, NULL, DDBLT_WAIT | DDBLT_COLORFILL, &ddbf); DDBlt_ColorFill(primsurf, &rect, &ddbf, ddraw.backsurf); } rect.top = max(base->top, target->top); rect.bottom = min(base->bottom, target->bottom); if (rect.top < rect.bottom) { rect.left = base->left; rect.right = target->left; if (rect.left < rect.right) { //primsurf->Blt(&rect, NULL, NULL, DDBLT_WAIT | DDBLT_COLORFILL, &ddbf); DDBlt_ColorFill(primsurf, &rect, &ddbf, ddraw.backsurf); } rect.left = target->right; rect.right = base->right; if (rect.left < rect.right) { //primsurf->Blt(&rect, NULL, NULL, DDBLT_WAIT | DDBLT_COLORFILL, &ddbf); DDBlt_ColorFill(primsurf, &rect, &ddbf, ddraw.backsurf); } } dd_leave_criticalsection(); } static void clearoutscreen(void) { RECT base; POINT clipt; RECT target; GetClientRect(g_hWndMain, &base); clipt.x = 0; clipt.y = 0; ClientToScreen(g_hWndMain, &clipt); base.left += clipt.x; base.top += clipt.y; base.right += clipt.x; base.bottom += clipt.y; target.left = base.left + ddraw.scrn.left; target.top = base.top + ddraw.scrn.top; target.right = base.left + ddraw.scrn.right; target.bottom = base.top + ddraw.scrn.bottom; clearoutofrect(&target, &base); } static void clearoutfullscreen(void) { RECT base; const RECT *scrn; base.left = 0; base.top = 0; base.right = ddraw.width; base.bottom = ddraw.height; if (GetWindowLongPtr(g_hWndMain, NP2GWLP_HMENU)) { scrn = &ddraw.scrn; base.top = 0; } else { scrn = &ddraw.scrnclip; base.top = ddraw.menusize; } clearoutofrect(scrn, &base); #if defined(SUPPORT_DCLOCK) DispClock::GetInstance()->Redraw(); #endif } static void paletteinit() { HDC hdc = GetDC(g_hWndMain); dd_enter_criticalsection(); GetSystemPaletteEntries(hdc, 0, 256, ddraw.pal); ReleaseDC(g_hWndMain, hdc); #if defined(SUPPORT_DCLOCK) const RGB32* pal32 = DispClock::GetInstance()->GetPalettes(); for (UINT i = 0; i < 4; i++) { ddraw.pal[i + START_PALORG].peBlue = pal32[i].p.b; ddraw.pal[i + START_PALORG].peRed = pal32[i].p.r; ddraw.pal[i + START_PALORG].peGreen = pal32[i].p.g; ddraw.pal[i + START_PALORG].peFlags = PC_RESERVED | PC_NOCOLLAPSE; } #endif for (UINT i = 0; i < PALLETES_8BPP; i++) { ddraw.pal[i + START_PAL].peFlags = PC_RESERVED | PC_NOCOLLAPSE; } ddraw.ddraw2->CreatePalette(DDPCAPS_8BIT, ddraw.pal, &ddraw.palette, 0); ddraw.primsurf->SetPalette(ddraw.palette); dd_leave_criticalsection(); } static void paletteset() { dd_enter_criticalsection(); if (ddraw.palette != NULL) { for (UINT i = 0; i < PALLETES_8BPP; i++) { ddraw.pal[i + START_PAL].peRed = np2_pal32[i].p.r; ddraw.pal[i + START_PAL].peBlue = np2_pal32[i].p.b; ddraw.pal[i + START_PAL].peGreen = np2_pal32[i].p.g; } ddraw.palette->SetEntries(0, START_PAL, PALLETES_8BPP, &ddraw.pal[START_PAL]); } dd_leave_criticalsection(); } static void make16mask(DWORD bmask, DWORD rmask, DWORD gmask) { UINT8 sft; dd_enter_criticalsection(); sft = 0; while((!(bmask & 0x80)) && (sft < 32)) { bmask <<= 1; sft++; } ddraw.pal16mask.p.b = (UINT8)bmask; ddraw.r16b = sft; sft = 0; while((rmask & 0xffffff00) && (sft < 32)) { rmask >>= 1; sft++; } ddraw.pal16mask.p.r = (UINT8)rmask; ddraw.l16r = sft; sft = 0; while((gmask & 0xffffff00) && (sft < 32)) { gmask >>= 1; sft++; } ddraw.pal16mask.p.g = (UINT8)gmask; ddraw.l16g = sft; dd_leave_criticalsection(); } static void restoresurfaces() { dd_enter_criticalsection(); ddraw.backsurf->Restore(); ddraw.primsurf->Restore(); #if defined(SUPPORT_WAB) ddraw.wabsurf->Restore(); #endif scrndraw_updateallline(); dd_leave_criticalsection(); } // ---- static TCHAR dd_displayName[32] = {0}; BOOL WINAPI DDEnumDisplayCallbackA(GUID FAR *lpGUID, LPSTR lpDriverDescription, LPSTR lpDriverName, LPVOID lpContext, HMONITOR hm) { MONITORINFOEX monitorInfoEx; RECT rc; RECT rcwnd; if(hm){ GetWindowRect(g_hWndMain, &rcwnd); monitorInfoEx.cbSize = sizeof(MONITORINFOEX); GetMonitorInfo(hm, &monitorInfoEx); _tcscpy(dd_displayName, monitorInfoEx.szDevice); if(IntersectRect(&rc, &monitorInfoEx.rcWork, &rcwnd)){ *((LPGUID)lpContext) = *lpGUID; return FALSE; } } return TRUE; } BRESULT scrnmngDD_create(UINT8 scrnmode) { DWORD winstyle; DWORD winstyleex; LPDIRECTDRAW2 ddraw2; DDSURFACEDESC ddsd; DDPIXELFORMAT ddpf; int width; int height; UINT bitcolor; UINT fscrnmod; DEVMODE devmode; GUID devguid = {0}; LPGUID devlpguid; HRESULT r; static UINT8 lastscrnmode = 0; static WINDOWPLACEMENT wp = {sizeof(WINDOWPLACEMENT)}; if(!dd_cs_initialized){ memset(&dd_cs, 0, sizeof(dd_cs)); InitializeCriticalSection(&dd_cs); dd_cs_initialized = 1; } dd_enter_criticalsection(); ZeroMemory(&scrnmng, sizeof(scrnmng)); winstyle = GetWindowLong(g_hWndMain, GWL_STYLE); winstyleex = GetWindowLong(g_hWndMain, GWL_EXSTYLE); if (scrnmode & SCRNMODE_FULLSCREEN) { //if(np2oscfg.mouse_nc){ // winstyle &= ~CS_DBLCLKS; //}else{ winstyle |= CS_DBLCLKS; //} if(!(lastscrnmode & SCRNMODE_FULLSCREEN)){ GetWindowPlacement(g_hWndMain, &wp); } scrnmode &= ~SCRNMODE_ROTATEMASK; scrnmng.flag = SCRNFLAG_FULLSCREEN; winstyle &= ~(WS_CAPTION | WS_SYSMENU | WS_THICKFRAME); winstyle |= WS_POPUP; winstyleex |= WS_EX_TOPMOST; ddraw.menudisp = 0; ddraw.menusize = GetSystemMetrics(SM_CYMENU); np2class_enablemenu(g_hWndMain, FALSE); SetWindowLong(g_hWndMain, GWL_STYLE, winstyle); SetWindowLong(g_hWndMain, GWL_EXSTYLE, winstyleex); } else { scrnmng.flag = SCRNFLAG_HAVEEXTEND; winstyle |= WS_SYSMENU; if(np2oscfg.mouse_nc){ winstyle &= ~CS_DBLCLKS; if (np2oscfg.wintype != 0) { WINLOCEX wlex; // XXX: メニューが出せなくなって詰むのを回避(暫定) np2oscfg.wintype = 0; np2oscfg.wintype = 0; wlex = np2_winlocexallwin(g_hWndMain); winlocex_setholdwnd(wlex, g_hWndMain); np2class_windowtype(g_hWndMain, np2oscfg.wintype); winlocex_move(wlex); winlocex_destroy(wlex); } }else{ winstyle |= CS_DBLCLKS; } if (np2oscfg.thickframe) { winstyle |= WS_THICKFRAME; } if (np2oscfg.wintype < 2) { winstyle |= WS_CAPTION; } winstyle &= ~WS_POPUP; winstyleex &= ~WS_EX_TOPMOST; if(lastscrnmode & SCRNMODE_FULLSCREEN){ char *strtmp; char szModulePath[MAX_PATH]; GetModuleFileNameA(NULL, szModulePath, sizeof(szModulePath)/sizeof(szModulePath[0])); strtmp = strrchr(szModulePath, '¥¥'); if(strtmp){ *strtmp = 0; }else{ szModulePath[0] = 0; } strcat(szModulePath, "¥¥ddraw.dll"); if(PathFileExistsA(szModulePath) && !PathIsDirectoryA(szModulePath)){ // DXGLが使われていそうなので素直なコードに変更 SetWindowLong(g_hWndMain, GWL_STYLE, winstyle); SetWindowLong(g_hWndMain, GWL_EXSTYLE, winstyleex); }else{ ShowWindow(g_hWndMain, SW_HIDE); // Aeroな環境でフルスクリーン→ウィンドウの時にシステムアイコンが消える対策のためのおまじない(その1) SetWindowLong(g_hWndMain, GWL_STYLE, winstyle); SetWindowLong(g_hWndMain, GWL_EXSTYLE, winstyleex); ShowWindow(g_hWndMain, SW_SHOWNORMAL); // Aeroな環境で(ry(その2) ShowWindow(g_hWndMain, SW_HIDE); // Aeroな環境で(ry(その3) ShowWindow(g_hWndMain, SW_SHOWNORMAL); // Aeroな環境で(ry(その4) } SetWindowPlacement(g_hWndMain, &wp); }else{ SetWindowLong(g_hWndMain, GWL_STYLE, winstyle); SetWindowLong(g_hWndMain, GWL_EXSTYLE, winstyleex); GetWindowPlacement(g_hWndMain, &wp); } } if(np2oscfg.emuddraw){ devlpguid = (LPGUID)DDCREATE_EMULATIONONLY; }else{ devlpguid = NULL; if(scrnmode & SCRNMODE_FULLSCREEN){ r = DirectDrawEnumerateExA(DDEnumDisplayCallbackA, &devguid, DDENUM_ATTACHEDSECONDARYDEVICES); if(devguid != GUID_NULL){ devlpguid = &devguid; } } } if ((r = DirectDrawCreate(devlpguid, &ddraw.ddraw1, NULL)) != DD_OK) { // プライマリで再挑戦 if (DirectDrawCreate(np2oscfg.emuddraw ? (LPGUID)DDCREATE_EMULATIONONLY : NULL, &ddraw.ddraw1, NULL) != DD_OK) { goto scre_err; } } ddraw.ddraw1->QueryInterface(IID_IDirectDraw2, (void **)&ddraw2); ddraw.ddraw2 = ddraw2; if (scrnmode & SCRNMODE_FULLSCREEN) { #if defined(SUPPORT_DCLOCK) DispClock::GetInstance()->Initialize(); #endif ddraw2->SetCooperativeLevel(g_hWndMain, DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN | DDSCL_MULTITHREADED); width = np2oscfg.fscrn_cx; height = np2oscfg.fscrn_cy; #ifdef SUPPORT_WAB if(!np2wabwnd.multiwindow && (np2wab.relay&0x3)){ if(np2wab.realWidth>=640 && np2wab.realHeight>=400){ width = np2wab.realWidth; height = np2wab.realHeight; }else{ width = 640; height = 480; } } #endif bitcolor = np2oscfg.fscrnbpp; fscrnmod = FSCRNCFG_fscrnmod; if (((fscrnmod & (FSCRNMOD_SAMERES | FSCRNMOD_SAMEBPP)) || np2_multithread_Enabled()) && (dd_displayName[0] ? EnumDisplaySettings(dd_displayName, ENUM_REGISTRY_SETTINGS, &devmode) : EnumDisplaySettings(NULL, ENUM_REGISTRY_SETTINGS, &devmode))) { if ((fscrnmod & FSCRNMOD_SAMERES) || np2_multithread_Enabled()) { width = devmode.dmPelsWidth; height = devmode.dmPelsHeight; } if ((fscrnmod & FSCRNMOD_SAMEBPP) || np2_multithread_Enabled()) { bitcolor = devmode.dmBitsPerPel; } } if ((width == 0) || (height == 0)) { width = 640; height = (np2oscfg.force400)?400:480; } if (bitcolor == 0) { #if !defined(SUPPORT_PC9821) bitcolor = (scrnmode & SCRNMODE_HIGHCOLOR)?16:8; #else bitcolor = 16; #endif } if (ddraw2->SetDisplayMode(width, height, bitcolor, 0, 0) != DD_OK) { width = 640; height = 480; if (ddraw2->SetDisplayMode(width, height, bitcolor, 0, 0) != DD_OK) { goto scre_err; } } ddraw2->CreateClipper(0, &ddraw.clipper, NULL); ddraw.clipper->SetHWnd(0, g_hWndMain); ZeroMemory(&ddsd, sizeof(ddsd)); ddsd.dwSize = sizeof(ddsd); ddsd.dwFlags = DDSD_CAPS; ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE; if (ddraw2->CreateSurface(&ddsd, &ddraw.primsurf, NULL) != DD_OK) { goto scre_err; } // fullscrn_clearblank(); ZeroMemory(&ddpf, sizeof(ddpf)); ddpf.dwSize = sizeof(DDPIXELFORMAT); if (ddraw.primsurf->GetPixelFormat(&ddpf) != DD_OK) { goto scre_err; } ZeroMemory(&ddsd, sizeof(ddsd)); ddsd.dwSize = sizeof(ddsd); ddsd.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT; ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN; #ifdef SUPPORT_WAB if(!np2wabwnd.multiwindow){ if((FSCRNCFG_fscrnmod & FSCRNMOD_SAMERES) || np2_multithread_Enabled()){ int maxx = GetSystemMetrics(SM_CXSCREEN); int maxy = GetSystemMetrics(SM_CYSCREEN); ddsd.dwWidth = (WAB_MAX_WIDTH > maxx ? maxx : WAB_MAX_WIDTH); ddsd.dwHeight = (WAB_MAX_HEIGHT > maxy ? maxy : WAB_MAX_HEIGHT); }else{ if((np2wab.relay&0x3)!=0 && np2wab.realWidth>=640 && np2wab.realHeight>=400){ // 実サイズに ddsd.dwWidth = np2wab.realWidth; ddsd.dwHeight = np2wab.realHeight; }else{ ddsd.dwWidth = 640; ddsd.dwHeight = 480; } } }else{ ddsd.dwWidth = 640; ddsd.dwHeight = 480; } #else ddsd.dwWidth = 640; ddsd.dwHeight = 480; #endif if (ddraw2->CreateSurface(&ddsd, &ddraw.backsurf, NULL) != DD_OK) { goto scre_err; } #ifdef SUPPORT_WAB if (ddraw2->CreateSurface(&ddsd, &ddraw.wabsurf, NULL) != DD_OK) { goto scre_err; }else{ DDBLTFX ddbf = {0}; ddbf.dwSize = sizeof(ddbf); ddbf.dwFillColor = 0; ddraw.wabsurf->Blt(NULL, NULL, NULL, DDBLT_WAIT | DDBLT_COLORFILL, &ddbf); } #endif if (bitcolor == 8) { paletteinit(); } else if (bitcolor == 16) { make16mask(ddpf.dwBBitMask, ddpf.dwRBitMask, ddpf.dwGBitMask); } else if (bitcolor == 24) { } else if (bitcolor == 32) { } else { goto scre_err; } #if defined(SUPPORT_DCLOCK) DispClock::GetInstance()->SetPalettes(bitcolor); ZeroMemory(&ddsd, sizeof(ddsd)); ddsd.dwSize = sizeof(ddsd); ddsd.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT; ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN; ddsd.dwWidth = DCLOCK_WIDTH; ddsd.dwHeight = DCLOCK_HEIGHT; ddraw2->CreateSurface(&ddsd, &ddraw.clocksurf, NULL); DispClock::GetInstance()->Reset(); #endif } else { ddraw2->SetCooperativeLevel(g_hWndMain, DDSCL_NORMAL | DDSCL_MULTITHREADED); ZeroMemory(&ddsd, sizeof(ddsd)); ddsd.dwSize = sizeof(ddsd); ddsd.dwFlags = DDSD_CAPS; ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE; if (ddraw2->CreateSurface(&ddsd, &ddraw.primsurf, NULL) != DD_OK) { goto scre_err; } ddraw2->CreateClipper(0, &ddraw.clipper, NULL); ddraw.clipper->SetHWnd(0, g_hWndMain); ddraw.primsurf->SetClipper(ddraw.clipper); ZeroMemory(&ddpf, sizeof(ddpf)); ddpf.dwSize = sizeof(DDPIXELFORMAT); if (ddraw.primsurf->GetPixelFormat(&ddpf) != DD_OK) { goto scre_err; } ZeroMemory(&ddsd, sizeof(ddsd)); ddsd.dwSize = sizeof(ddsd); ddsd.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT; ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN; #ifdef SUPPORT_WAB if(!np2wabwnd.multiwindow && (np2wab.relay&0x3)!=0 && np2wab.realWidth>=640 && np2wab.realHeight>=400){ // 実サイズに width = ddsd.dwWidth = scrnstat.width;//np2wab.realWidth; height = ddsd.dwHeight = scrnstat.height;//np2wab.realHeight; if (scrnmode & SCRNMODE_ROTATE) { ddsd.dwWidth = scrnstat.height; ddsd.dwHeight = scrnstat.width; } ddsd.dwWidth++; // +1しないと駄目らしい }else{ if (!(scrnmode & SCRNMODE_ROTATE)) { ddsd.dwWidth = 640 + 1; ddsd.dwHeight = 480; } else { ddsd.dwWidth = 480; ddsd.dwHeight = 640 + 1; } width = 640; height = 480; } #else if (!(scrnmode & SCRNMODE_ROTATE)) { ddsd.dwWidth = 640 + 1; ddsd.dwHeight = 480; } else { ddsd.dwWidth = 480; ddsd.dwHeight = 640 + 1; } width = 640; height = 480; #endif if (ddraw2->CreateSurface(&ddsd, &ddraw.backsurf, NULL) != DD_OK) { goto scre_err; } #ifdef SUPPORT_WAB if (ddraw2->CreateSurface(&ddsd, &ddraw.wabsurf, NULL) != DD_OK) { goto scre_err; } #endif bitcolor = ddpf.dwRGBBitCount; if (bitcolor == 8) { paletteinit(); } else if (bitcolor == 16) { make16mask(ddpf.dwBBitMask, ddpf.dwRBitMask, ddpf.dwGBitMask); } else if (bitcolor == 24) { } else if (bitcolor == 32) { } else { goto scre_err; } ddraw.extend = 1; } scrnmng.bpp = (UINT8)bitcolor; scrnsurf.bpp = bitcolor; ddraw.scrnmode = scrnmode; ddraw.width = width; ddraw.height = height; ddraw.cliping = 0; renewalclientsize(TRUE); // XXX: スナップ解除等が起こるので暫定TRUE lastscrnmode = scrnmode; // screenupdate = 3; // update! #if defined(SUPPORT_WAB) mt_wabpausedrawing = 0; // MultiThread対策 #endif dd_leave_criticalsection(); return(SUCCESS); scre_err: dd_leave_criticalsection(); scrnmngDD_destroy(); return(FAILURE); } void scrnmngDD_destroy(void) { dd_enter_criticalsection(); if (scrnmng.flag & SCRNFLAG_FULLSCREEN) { np2class_enablemenu(g_hWndMain, (!np2oscfg.wintype)); } #if defined(SUPPORT_DCLOCK) if (ddraw.clocksurf) { ddraw.clocksurf->Release(); ddraw.clocksurf = NULL; } #endif #if defined(SUPPORT_WAB) if (ddraw.wabsurf) { mt_wabpausedrawing = 1; // MultiThread対策 while(mt_wabdrawing) Sleep(10); ddraw.wabsurf->Release(); ddraw.wabsurf = NULL; } #endif if (ddraw.backsurf) { ddraw.backsurf->Release(); ddraw.backsurf = NULL; } if (ddraw.palette) { ddraw.palette->Release(); ddraw.palette = NULL; } if (ddraw.clipper) { ddraw.clipper->Release(); ddraw.clipper = NULL; } if (ddraw.primsurf) { ddraw.primsurf->Release(); ddraw.primsurf = NULL; } if (ddraw.ddraw2) { if (ddraw.scrnmode & SCRNMODE_FULLSCREEN) { ddraw.ddraw2->SetCooperativeLevel(g_hWndMain, DDSCL_NORMAL); } ddraw.ddraw2->Release(); ddraw.ddraw2 = NULL; } if (ddraw.ddraw1) { ddraw.ddraw1->Release(); ddraw.ddraw1 = NULL; } ZeroMemory(&ddraw, sizeof(ddraw)); dd_leave_criticalsection(); } void scrnmngDD_shutdown(void) { if(dd_cs_initialized){ DeleteCriticalSection(&dd_cs); dd_cs_initialized = 0; } } void scrnmngDD_querypalette(void) { dd_enter_criticalsection(); if (ddraw.palette) { ddraw.primsurf->SetPalette(ddraw.palette); } dd_leave_criticalsection(); } RGB16 scrnmngDD_makepal16(RGB32 pal32) { RGB32 pal; pal.d = pal32.d & ddraw.pal16mask.d; return((RGB16)((pal.p.g << ddraw.l16g) + (pal.p.r << ddraw.l16r) + (pal.p.b >> ddraw.r16b))); } void scrnmngDD_fullscrnmenu(int y) { UINT8 menudisp; dd_enter_criticalsection(); if (scrnmng.flag & SCRNFLAG_FULLSCREEN) { menudisp = ((y >= 0) && (y < ddraw.menusize))?1:0; if (ddraw.menudisp != menudisp) { ddraw.menudisp = menudisp; if (menudisp == 1) { np2class_enablemenu(g_hWndMain, TRUE); } else { np2class_enablemenu(g_hWndMain, FALSE); clearoutfullscreen(); } } } dd_leave_criticalsection(); } void scrnmngDD_topwinui(void) { mousemng_disable(MOUSEPROC_WINUI); dd_enter_criticalsection(); if (!ddraw.cliping++) { // ver0.28 if (scrnmng.flag & SCRNFLAG_FULLSCREEN) { ddraw.primsurf->SetClipper(ddraw.clipper); } #ifndef __GNUC__ WINNLSEnableIME(g_hWndMain, TRUE); #endif } dd_leave_criticalsection(); } void scrnmngDD_clearwinui(void) { dd_enter_criticalsection(); if ((ddraw.cliping > 0) && (!(--ddraw.cliping))) { #ifndef __GNUC__ WINNLSEnableIME(g_hWndMain, FALSE); #endif if (scrnmng.flag & SCRNFLAG_FULLSCREEN) { ddraw.primsurf->SetClipper(0); } } if (scrnmng.flag & SCRNFLAG_FULLSCREEN) { np2class_enablemenu(g_hWndMain, FALSE); clearoutfullscreen(); ddraw.menudisp = 0; } else { if (np2oscfg.wintype) { np2class_enablemenu(g_hWndMain, FALSE); InvalidateRect(g_hWndMain, NULL, TRUE); } } mousemng_enable(MOUSEPROC_WINUI); if(scrnmng.forcereset){ scrnmng_destroy(); if (scrnmng_create(g_scrnmode) != SUCCESS) { g_scrnmode &= ~SCRNMODE_FULLSCREEN; if (scrnmng_create(g_scrnmode) != SUCCESS) { dd_leave_criticalsection(); PostQuitMessage(0); return; } } scrnmng.forcereset = 0; } dd_leave_criticalsection(); } void scrnmngDD_setwidth(int posx, int width) { if(scrnstat.multiple < 1) scrnstat.multiple = 8; scrnstat.width = width; renewalclientsize(TRUE); } void scrnmngDD_setextend(int extend) { scrnstat.extend = extend; scrnmng.allflash = TRUE; renewalclientsize(TRUE); } void scrnmngDD_setheight(int posy, int height) { if(scrnstat.multiple < 1) scrnstat.multiple = 8; scrnstat.height = height; renewalclientsize(TRUE); } void scrnmngDD_setsize(int posx, int posy, int width, int height) { if(scrnstat.multiple < 1) scrnstat.multiple = 8; scrnstat.width = width; scrnstat.height = height; renewalclientsize(TRUE); } const SCRNSURF *scrnmngDD_surflock(void) { DDSURFACEDESC destscrn; HRESULT r; ZeroMemory(&destscrn, sizeof(destscrn)); destscrn.dwSize = sizeof(destscrn); if (ddraw.backsurf == NULL) { return(NULL); } dd_enter_criticalsection(); r = ddraw.backsurf->Lock(NULL, &destscrn, DDLOCK_WAIT, NULL); if (r == DDERR_SURFACELOST) { restoresurfaces(); dd_leave_criticalsection(); return(NULL); //r = ddraw.backsurf->Lock(NULL, &destscrn, DDLOCK_WAIT, NULL); } if (r != DD_OK) { // TRACEOUT(("backsurf lock error: %d (%d)", r)); dd_leave_criticalsection(); return(NULL); } if (!(ddraw.scrnmode & SCRNMODE_ROTATE)) { scrnsurf.ptr = (UINT8 *)destscrn.lpSurface; scrnsurf.xalign = scrnsurf.bpp >> 3; scrnsurf.yalign = destscrn.lPitch; } else if (!(ddraw.scrnmode & SCRNMODE_ROTATEDIR)) { scrnsurf.ptr = (UINT8 *)destscrn.lpSurface; scrnsurf.ptr += (scrnsurf.width + scrnsurf.extend - 1) * destscrn.lPitch; scrnsurf.xalign = 0 - destscrn.lPitch; scrnsurf.yalign = scrnsurf.bpp >> 3; } else { scrnsurf.ptr = (UINT8 *)destscrn.lpSurface; scrnsurf.ptr += (scrnsurf.height - 1) * (scrnsurf.bpp >> 3); scrnsurf.xalign = destscrn.lPitch; scrnsurf.yalign = 0 - (scrnsurf.bpp >> 3); } return(&scrnsurf); } void scrnmngDD_surfunlock(const SCRNSURF *surf) { ddraw.backsurf->Unlock(NULL); scrnmngDD_update(); recvideo_update(); dd_leave_criticalsection(); } void scrnmngDD_update(void) { POINT clip; RECT dst; RECT *rect; RECT *scrn; HRESULT r; if(!dd_tryenter_criticalsection()){ req_enter_criticalsection = 1; return; } //dd_enter_criticalsection(); if (scrnmng.palchanged) { scrnmng.palchanged = FALSE; paletteset(); } if (ddraw.backsurf != NULL) { if (ddraw.scrnmode & SCRNMODE_FULLSCREEN) { if (scrnmng.allflash) { scrnmng.allflash = 0; clearoutfullscreen(); } if (GetWindowLongPtr(g_hWndMain, NP2GWLP_HMENU)) { rect = &ddraw.rect; scrn = &ddraw.scrn; } else { rect = &ddraw.rectclip; scrn = &ddraw.scrnclip; } r = ddraw.primsurf->Blt(scrn, ddraw.backsurf, rect, DDBLT_WAIT, NULL); if (r == DDERR_SURFACELOST) { restoresurfaces(); dd_leave_criticalsection(); return; //ddraw.primsurf->Blt(scrn, ddraw.backsurf, rect, // DDBLT_WAIT, NULL); } } else { if (scrnmng.allflash) { scrnmng.allflash = 0; clearoutscreen(); } clip.x = 0; clip.y = 0; ClientToScreen(g_hWndMain, &clip); dst.left = clip.x + ddraw.scrn.left; dst.top = clip.y + ddraw.scrn.top; dst.right = clip.x + ddraw.scrn.right; dst.bottom = clip.y + ddraw.scrn.bottom; r = ddraw.primsurf->Blt(&dst, ddraw.backsurf, &ddraw.rect, DDBLT_WAIT, NULL); if (r == DDERR_SURFACELOST) { restoresurfaces(); dd_leave_criticalsection(); return; //ddraw.primsurf->Blt(&dst, ddraw.backsurf, &ddraw.rect, // DDBLT_WAIT, NULL); } } } dd_leave_criticalsection(); req_enter_criticalsection = 0; } // ---- void scrnmngDD_setmultiple(int multiple) { if (scrnstat.multiple != multiple) { scrnstat.multiple = multiple; renewalclientsize(TRUE); } } int scrnmngDD_getmultiple(void) { return scrnstat.multiple; } // ---- #if defined(SUPPORT_DCLOCK) static const RECT rectclk = {0, 0, DCLOCK_WIDTH, DCLOCK_HEIGHT}; BOOL scrnmngDD_isdispclockclick(const POINT *pt) { if (pt->y >= (ddraw.height - DCLOCK_HEIGHT)) { return(TRUE); } else { return(FALSE); } } void scrnmngDD_dispclock(void) { if (!ddraw.clocksurf) { return; } if (!DispClock::GetInstance()->IsDisplayed()) { return; } const RECT* scrn; if (GetWindowLongPtr(g_hWndMain, NP2GWLP_HMENU)) { scrn = &ddraw.scrn; } else { scrn = &ddraw.scrnclip; } if ((scrn->bottom + DCLOCK_HEIGHT) > ddraw.height) { return; } DispClock::GetInstance()->Make(); dd_enter_criticalsection(); DDSURFACEDESC dest; ZeroMemory(&dest, sizeof(dest)); dest.dwSize = sizeof(dest); if (ddraw.clocksurf->Lock(NULL, &dest, DDLOCK_WAIT, NULL) == DD_OK) { DispClock::GetInstance()->Draw(scrnmng.bpp, dest.lpSurface, dest.lPitch); ddraw.clocksurf->Unlock(NULL); } if (ddraw.primsurf->BltFast(ddraw.width - DCLOCK_WIDTH - 4, ddraw.height - DCLOCK_HEIGHT, ddraw.clocksurf, (RECT *)&rectclk, DDBLTFAST_WAIT) == DDERR_SURFACELOST) { restoresurfaces(); ddraw.clocksurf->Restore(); } DispClock::GetInstance()->CountDown(np2oscfg.DRAW_SKIP); dd_leave_criticalsection(); } #endif // ---- typedef struct { int bx; int by; int cx; int cy; int mul; } SCRNSIZING; static SCRNSIZING scrnsizing; enum { SIZING_ADJUST = 12 }; void scrnmngDD_entersizing(void) { RECT rectwindow; RECT rectclient; int cx; int cy; GetWindowRect(g_hWndMain, &rectwindow); GetClientRect(g_hWndMain, &rectclient); scrnsizing.bx = (np2oscfg.paddingx * 2) + (rectwindow.right - rectwindow.left) - (rectclient.right - rectclient.left); scrnsizing.by = (np2oscfg.paddingy * 2) + (rectwindow.bottom - rectwindow.top) - (rectclient.bottom - rectclient.top); cx = min(scrnstat.width, ddraw.width); cx = (cx + 7) >> 3; cy = min(scrnstat.height, ddraw.height); cy = (cy + 7) >> 3; if (!(ddraw.scrnmode & SCRNMODE_ROTATE)) { scrnsizing.cx = cx; scrnsizing.cy = cy; } else { scrnsizing.cx = cy; scrnsizing.cy = cx; } scrnsizing.mul = scrnstat.multiple; } void scrnmngDD_sizing(UINT side, RECT *rect) { int width; int height; int mul; if ((side != WMSZ_TOP) && (side != WMSZ_BOTTOM)) { width = rect->right - rect->left - scrnsizing.bx + SIZING_ADJUST; width /= scrnsizing.cx; } else { width = 16; } if ((side != WMSZ_LEFT) && (side != WMSZ_RIGHT)) { height = rect->bottom - rect->top - scrnsizing.by + SIZING_ADJUST; height /= scrnsizing.cy; } else { height = 16; } mul = min(width, height); if (mul <= 0) { mul = 1; } else if (mul > 20) { mul = 20; } width = scrnsizing.bx + (scrnsizing.cx * mul); height = scrnsizing.by + (scrnsizing.cy * mul); switch(side) { case WMSZ_LEFT: case WMSZ_TOPLEFT: case WMSZ_BOTTOMLEFT: rect->left = rect->right - width; break; case WMSZ_RIGHT: case WMSZ_TOP: case WMSZ_TOPRIGHT: case WMSZ_BOTTOM: case WMSZ_BOTTOMRIGHT: default: rect->right = rect->left + width; break; } switch(side) { case WMSZ_TOP: case WMSZ_TOPLEFT: case WMSZ_TOPRIGHT: rect->top = rect->bottom - height; break; case WMSZ_LEFT: case WMSZ_RIGHT: case WMSZ_BOTTOM: case WMSZ_BOTTOMLEFT: case WMSZ_BOTTOMRIGHT: default: rect->bottom = rect->top + height; break; } scrnsizing.mul = mul; } void scrnmngDD_exitsizing(void) { scrnmng_setmultiple(scrnsizing.mul); InvalidateRect(g_hWndMain, NULL, TRUE); // ugh } // フルスクリーン解像度調整 void scrnmngDD_updatefsres(void) { #ifdef SUPPORT_WAB RECT rect; int width = scrnstat.width; int height = scrnstat.height; DDBLTFX ddbf = {0}; rect.left = rect.top = 0; rect.right = width; rect.bottom = height; ddbf.dwSize = sizeof(ddbf); ddbf.dwFillColor = 0; if(((FSCRNCFG_fscrnmod & FSCRNMOD_SAMERES) || np2_multithread_Enabled()) && (g_scrnmode & SCRNMODE_FULLSCREEN)){ dd_enter_criticalsection(); ddraw.wabsurf->Blt(NULL, NULL, NULL, DDBLT_WAIT | DDBLT_COLORFILL, &ddbf); ddraw.backsurf->Blt(NULL, NULL, NULL, DDBLT_WAIT | DDBLT_COLORFILL, &ddbf); clearoutscreen(); np2wab.lastWidth = 0; np2wab.lastHeight = 0; dd_leave_criticalsection(); return; } if(scrnstat.width<100 || scrnstat.height<100){ dd_enter_criticalsection(); ddraw.wabsurf->Blt(NULL, NULL, NULL, DDBLT_WAIT | DDBLT_COLORFILL, &ddbf); ddraw.backsurf->Blt(NULL, NULL, NULL, DDBLT_WAIT | DDBLT_COLORFILL, &ddbf); clearoutscreen(); dd_leave_criticalsection(); return; } if(np2wab.lastWidth!=width || np2wab.lastHeight!=height){ dd_enter_criticalsection(); np2wab.lastWidth = width; np2wab.lastHeight = height; if((g_scrnmode & SCRNMODE_FULLSCREEN)!=0){ g_scrnmode = g_scrnmode & ~SCRNMODE_FULLSCREEN; scrnmngDD_destroy(); if (scrnmngDD_create(g_scrnmode | SCRNMODE_FULLSCREEN) == SUCCESS) { g_scrnmode = g_scrnmode | SCRNMODE_FULLSCREEN; } else { if (scrnmngDD_create(g_scrnmode) != SUCCESS) { PostQuitMessage(0); dd_leave_criticalsection(); return; } } }else if(ddraw.width < width || ddraw.height < height){ scrnmngDD_destroy(); if (scrnmngDD_create(g_scrnmode) != SUCCESS) { if (scrnmngDD_create(g_scrnmode | SCRNMODE_FULLSCREEN) != SUCCESS) { // フルスクリーンでリトライ PostQuitMessage(0); dd_leave_criticalsection(); return; } g_scrnmode = g_scrnmode | SCRNMODE_FULLSCREEN; } } clearoutscreen(); ddraw.wabsurf->Blt(NULL, NULL, NULL, DDBLT_WAIT | DDBLT_COLORFILL, &ddbf); ddraw.backsurf->Blt(NULL, NULL, NULL, DDBLT_WAIT | DDBLT_COLORFILL, &ddbf); dd_leave_criticalsection(); } #endif } // ウィンドウアクセラレータ画面転送 void scrnmngDD_blthdc(HDC hdc) { #if defined(SUPPORT_WAB) HRESULT r; HDC hDCDD; mt_wabdrawing = 0; if (np2wabwnd.multiwindow) return; if (mt_wabpausedrawing) return; if (np2wab.wndWidth < 32 || np2wab.wndHeight < 32) return; if (ddraw.wabsurf != NULL) { while(req_enter_criticalsection){ Sleep(1); } dd_enter_criticalsection(); mt_wabdrawing = 1; r = ddraw.wabsurf->GetDC(&hDCDD); if (r == DD_OK){ POINT pt[3]; switch(ddraw.scrnmode & SCRNMODE_ROTATEMASK){ case SCRNMODE_ROTATELEFT: pt[0].x = 0; pt[0].y = scrnstat.width; pt[1].x = 0; pt[1].y = 0; pt[2].x = scrnstat.height; pt[2].y = scrnstat.width; r = PlgBlt(hDCDD, pt, hdc, 0, 0, np2wab.realWidth, np2wab.realHeight, NULL, 0, 0); break; case SCRNMODE_ROTATERIGHT: pt[0].x = scrnstat.height; pt[0].y = 0; pt[1].x = scrnstat.height; pt[1].y = scrnstat.width; pt[2].x = 0; pt[2].y = 0; r = PlgBlt(hDCDD, pt, hdc, 0, 0, np2wab.realWidth, np2wab.realHeight, NULL, 0, 0); break; default: r = BitBlt(hDCDD, 0, 0, scrnstat.width, scrnstat.height, hdc, 0, 0, SRCCOPY); } ddraw.wabsurf->ReleaseDC(hDCDD); } mt_wabdrawing = 0; dd_leave_criticalsection(); } #endif } void scrnmngDD_bltwab() { #if defined(SUPPORT_WAB) RECT *dst; RECT src; RECT dstmp; //DDBLTFX ddfx; HRESULT r; int exmgn = 0; if (np2wabwnd.multiwindow) return; if (ddraw.backsurf != NULL) { if (ddraw.scrnmode & SCRNMODE_FULLSCREEN) { if (GetWindowLongPtr(g_hWndMain, NP2GWLP_HMENU)) { dst = &ddraw.rect; } else { dst = &ddraw.rectclip; } }else{ dst = &ddraw.rect; exmgn = (scrnstat.multiple == 8 ? scrnstat.extend : 0); } src.left = src.top = 0; if (!(ddraw.scrnmode & SCRNMODE_ROTATE)) { src.right = scrnstat.width; src.bottom = scrnstat.height; dstmp = *dst; dstmp.left += exmgn; dstmp.right = dstmp.left + scrnstat.width; }else{ src.right = scrnstat.height; src.bottom = scrnstat.width; dstmp = *dst; dstmp.left += exmgn; dstmp.right = dstmp.left + scrnstat.height; } dd_enter_criticalsection(); r = ddraw.backsurf->Blt(&dstmp, ddraw.wabsurf, &src, DDBLT_WAIT, NULL); if (r == DDERR_SURFACELOST) { restoresurfaces(); } dd_leave_criticalsection(); } #endif } // 描画領域の範囲をクライアント座標で取得 void scrnmngDD_getrect(RECT *lpRect) { if (ddraw.scrnmode & SCRNMODE_FULLSCREEN) { if (GetWindowLongPtr(g_hWndMain, NP2GWLP_HMENU)) { *lpRect = ddraw.scrn; } else { *lpRect = ddraw.scrnclip; } } else { *lpRect = ddraw.scrn; } }
///////////////////////////////////////////////////////////////////////////// // DosEditListDialog.cpp // // Copyright (c) 1992-2020, Robert McNeel & Associates. All rights reserved. // DOSLib is a trademark of Robert McNeel & Associates. // // THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY. // ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF // MERCHANTABILITY ARE HEREBY DISCLAIMED. // #include "StdAfx.h" #include "DosEditListDialog.h" CDosEditListDialog::CDosEditListDialog(CWnd* pParent) : CAcUiDialog(CDosEditListDialog::IDD, pParent) , m_ListBoxExBuddy(IDB_BUDDY) { } void CDosEditListDialog::DoDataExchange(CDataExchange* pDX) { CAcUiDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_LIST, m_List); } BEGIN_MESSAGE_MAP(CDosEditListDialog, CAcUiDialog) ON_WM_NCHITTEST() END_MESSAGE_MAP() BOOL CDosEditListDialog::OnInitDialog() { SetDialogName(L"DOSLib:EditList"); CAcUiDialog::OnInitDialog(); StretchControlX(IDC_BUDDYS, 100); StretchControlXY(IDC_LIST, 100, 100); MoveControlX(IDOK, 100); MoveControlX(IDCANCEL, 100); SetWindowText(m_Title); SetDlgItemText(IDC_BUDDYS, m_Prompt); m_ListBoxExBuddy.SubclassDlgItem(IDC_BUDDYS, this); m_ListBoxExBuddy.SetListBox(&m_List); m_List.SetEditStyle(0); m_List.AllowDrag(FALSE); int i; for (i = 0; i < m_StrArray.GetCount(); i++) m_List.AddString(m_StrArray[i]); m_List.SetCurSel(0); return TRUE; } void CDosEditListDialog::OnOK() { m_StrArray.RemoveAll(); int i; for (i = 0; i < m_List.GetCount(); i++) { CString str; m_List.GetText(i, str); m_StrArray.Add(str); } CAcUiDialog::OnOK(); } LRESULT CDosEditListDialog::OnNcHitTest(CPoint point) { LRESULT hit = CAcUiDialog::OnNcHitTest(point); if (hit == HTCLIENT) return HTCAPTION; return hit; }
// ----------------------------------------------------------------------------------------------------- // Copyright (c) 2006-2021, Knut Reinert & Freie Universität Berlin // Copyright (c) 2016-2021, Knut Reinert & MPI für molekulare Genetik // Copyright (c) 2020-2021, deCODE Genetics // This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License // shipped with this file and also available at: https://github.com/seqan/bio/blob/master/LICENSE.md // ----------------------------------------------------------------------------------------------------- /*!\file * \brief Provides exception types. * \author Hannes Hauswedell <hannes.hauswedell AT decode.is> */ #pragma once #include <ios> #include <stdexcept> #include <bio/platform.hpp> namespace bio { // ---------------------------------------------------------------------------- // file open exceptions // ---------------------------------------------------------------------------- //!\brief Thrown if there is no format that accepts a given file extension. struct unhandled_extension_error : std::invalid_argument { //!\brief Constructor that forwards the exception string. unhandled_extension_error(std::string const & s) : std::invalid_argument{s} {} }; //!\brief Thrown if there is an unspecified filesystem or stream error while opening, e.g. permission problem. struct file_open_error : std::runtime_error { //!\brief Constructor that forwards the exception string. file_open_error(std::string const & s) : std::runtime_error{s} {} }; //!\brief Thrown if there is a parse error, such as reading an unexpected character from an input stream. struct parse_error : std::runtime_error { //!\brief Constructor that forwards the exception string. parse_error(std::string const & s) : std::runtime_error{s} {} }; //!\brief Thrown if there is an io error in low level io operations such as in std::basic_streambuf operations. struct io_error : std::ios_base::failure { //!\brief Constructor that forwards the exception string. explicit io_error(std::string const & s, std::error_code const & ec = std::io_errc::stream) : std::ios_base::failure{s, ec} {} }; // ---------------------------------------------------------------------------- // parse exceptions // ---------------------------------------------------------------------------- //!\brief Thrown if I/O was expecting more input (e.g. a delimiter or a new line), but the end of input was reached. struct unexpected_end_of_input : std::runtime_error { //!\brief Constructor that forwards the exception string. unexpected_end_of_input(std::string const & s) : std::runtime_error{s} {} }; // ---------------------------------------------------------------------------- // write exceptions // ---------------------------------------------------------------------------- //!\brief Thrown if information given to output format didn't match expectations. struct format_error : std::invalid_argument { //!\brief Constructor that forwards the exception string. format_error(std::string const & s) : std::invalid_argument{s} {} }; } // namespace bio
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <QApplication> #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include "guiconstants.h" #include "init.h" #include "util.h" #include "ui_interface.h" #include "paymentserver.h" #include "splashscreen.h" #include <QMessageBox> #if QT_VERSION < 0x050000 #include <QTextCodec> #endif #include <QLocale> #include <QTimer> #include <QTranslator> #include <QLibraryInfo> #ifdef Q_OS_MAC #include "macdockiconhandler.h" #endif #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) #define _BITCOIN_QT_PLUGINS_INCLUDED #define __INSURE__ #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif // Declare meta types used for QMetaObject::invokeMethod Q_DECLARE_METATYPE(bool*) // Need a global reference for the notifications to find the GUI static BitcoinGUI *guiref; static SplashScreen *splashref; static bool ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style) { // Message from network thread if(guiref) { bool modal = (style & CClientUIInterface::MODAL); bool ret = false; // In case of modal message, use blocking connection to wait for user to click a button QMetaObject::invokeMethod(guiref, "message", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(unsigned int, style), Q_ARG(bool*, &ret)); return ret; } else { printf("%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); return false; } } static bool ThreadSafeAskFee(int64 nFeeRequired) { if(!guiref) return false; if(nFeeRequired < CTransaction::nMinTxFee || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } static void InitMessage(const std::string &message) { if(splashref) { splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(55,55,55)); qApp->processEvents(); } printf("init message: %s\n", message.c_str()); } /* Translate string to current locale using Qt. */ static std::string Translate(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } /* Handle runaway exceptions. Shows a message box with the problem and quits the program. */ static void handleRunawayException(std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Paniccoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); exit(1); } #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { // Command-line options take precedence: ParseParameters(argc, argv); #if QT_VERSION < 0x050000 // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); #endif Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); // Register meta types used for QMetaObject::invokeMethod qRegisterMetaType< bool* >(); // Do this early as we don't want to bother initializing if we are just calling IPC // ... but do it after creating app, so QCoreApplication::arguments is initialized: if (PaymentServer::ipcSendCommandLine()) exit(0); PaymentServer* paymentServer = new PaymentServer(&app); // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); // ... then bitcoin.conf: if (!boost::filesystem::is_directory(GetDataDir(false))) { // This message can not be translated, as translation is not initialized yet // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory) QMessageBox::critical(0, "Paniccoin", QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); return 1; } ReadConfigFile(mapArgs, mapMultiArgs); // Application identification (must be set before OptionsModel is initialized, // as it is used to locate QSettings) QApplication::setOrganizationName("Paniccoin"); QApplication::setOrganizationDomain("paniccoin.org"); if(GetBoolArg("-testnet")) // Separate UI settings for testnet QApplication::setApplicationName("Paniccoin-Qt-testnet"); else QApplication::setApplicationName("Paniccoin-Qt"); // ... then GUI settings: OptionsModel optionsModel; // Get desired locale (e.g. "de_DE") from command line or use system locale QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); QString lang = lang_territory; // Convert to "de" only by truncating "_DE" lang.truncate(lang_territory.lastIndexOf('_')); QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) if (translatorBase.load(lang, ":/translations/")) app.installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) if (translator.load(lang_territory, ":/translations/")) app.installTranslator(&translator); // Subscribe to global signals from core uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox); uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); uiInterface.InitMessage.connect(InitMessage); uiInterface.Translate.connect(Translate); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (mapArgs.count("-?") || mapArgs.count("--help")) { GUIUtil::HelpMessageBox help; help.showOrPrint(); return 1; } #ifdef Q_OS_MAC // on mac, also change the icon now because it would look strange to have a testnet splash (green) and a std app icon (orange) if(GetBoolArg("-testnet")) { MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet")); } #endif SplashScreen splash(QPixmap(), 0); if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) { splash.show(); splash.setAutoFillBackground(true); splashref = &splash; } app.processEvents(); app.setQuitOnLastWindowClosed(false); try { #ifndef Q_OS_MAC // Regenerate startup link, to fix links to old versions // OSX: makes no sense on mac and might also scan/mount external (and sleeping) volumes (can take up some secs) if (GUIUtil::GetStartOnSystemStartup()) GUIUtil::SetStartOnSystemStartup(true); #endif boost::thread_group threadGroup; BitcoinGUI window; guiref = &window; QTimer* pollShutdownTimer = new QTimer(guiref); QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown())); pollShutdownTimer->start(200); if(AppInit2(threadGroup)) { { // Put this in a block, so that the Model objects are cleaned up before // calling Shutdown(). optionsModel.Upgrade(); // Must be done after AppInit2 if (splashref) splash.finish(&window); ClientModel clientModel(&optionsModel); WalletModel *walletModel = 0; if(pwalletMain) walletModel = new WalletModel(pwalletMain, &optionsModel); window.setClientModel(&clientModel); if(walletModel) { window.addWallet("~Default", walletModel); window.setCurrentWallet("~Default"); } // If -min option passed, start window minimized. if(GetBoolArg("-min")) { window.showMinimized(); } else { window.show(); } // Now that initialization/startup is done, process any command-line // bitcoin: URIs QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString))); QTimer::singleShot(100, paymentServer, SLOT(uiReady())); app.exec(); window.hide(); window.setClientModel(0); window.removeAllWallets(); guiref = 0; delete walletModel; } // Shutdown the core and its threads, but don't exit Bitcoin-Qt here threadGroup.interrupt_all(); threadGroup.join_all(); Shutdown(); } else { threadGroup.interrupt_all(); threadGroup.join_all(); Shutdown(); return 1; } } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } return 0; } #endif // BITCOIN_QT_TEST
#ifndef MATRIX_MM_HH_ #define MATRIX_MM_HH_ #include <cstdlib> #include <cassert> #include "deepgreen/matrix.hh" namespace deepgreen { /** \brief Naive matrix multiplication (A_mk * B_kn = C_mn) */ template<typename T> auto naive_mm(matrix<T> const& a, matrix<T> const& b) -> matrix<T> { size_t const m = a.rows(), n = b.cols(), k = a.cols(); assert(k == b.rows()); auto c = matrix<T>(m, n); for (size_t row = 0; row < m; ++row) { for (size_t col = 0; col < n; ++col) { c(row, col) = 0.0; for (size_t i = 0; i < k; ++i) { c(row, col) += a(row, i) * b(i, col); } } } return c; } } /* end namespace deepgreen */ #endif
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/browser_sync/profile_sync_components_factory_impl.h" #include <utility> #include "base/debug/dump_without_crashing.h" #include "base/feature_list.h" #include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "components/autofill/core/browser/autofill_wallet_data_type_controller.h" #include "components/autofill/core/browser/webdata/autofill_data_type_controller.h" #include "components/autofill/core/browser/webdata/autofill_profile_data_type_controller.h" #include "components/autofill/core/browser/webdata/autofill_webdata_service.h" #include "components/autofill/core/common/autofill_pref_names.h" #include "components/autofill/core/common/autofill_switches.h" #include "components/browser_sync/browser_sync_switches.h" #include "components/browser_sync/profile_sync_service.h" #include "components/dom_distiller/core/dom_distiller_features.h" #include "components/history/core/browser/history_delete_directives_data_type_controller.h" #include "components/history/core/browser/typed_url_data_type_controller.h" #include "components/password_manager/core/browser/password_store.h" #include "components/password_manager/sync/browser/password_data_type_controller.h" #include "components/prefs/pref_service.h" #include "components/sync/base/report_unrecoverable_error.h" #include "components/sync/device_info/device_info_data_type_controller.h" #include "components/sync/device_info/local_device_info_provider_impl.h" #include "components/sync/driver/data_type_manager_impl.h" #include "components/sync/driver/glue/sync_backend_host.h" #include "components/sync/driver/glue/sync_backend_host_impl.h" #include "components/sync/driver/model_type_controller.h" #include "components/sync/driver/proxy_data_type_controller.h" #include "components/sync/driver/sync_client.h" #include "components/sync/driver/sync_driver_switches.h" #include "components/sync/driver/ui_data_type_controller.h" #include "components/sync/engine/attachments/attachment_downloader.h" #include "components/sync/engine/attachments/attachment_uploader.h" #include "components/sync/model/attachments/attachment_service.h" #include "components/sync_bookmarks/bookmark_change_processor.h" #include "components/sync_bookmarks/bookmark_data_type_controller.h" #include "components/sync_bookmarks/bookmark_model_associator.h" #include "components/sync_sessions/session_data_type_controller.h" #include "google_apis/gaia/oauth2_token_service.h" #include "google_apis/gaia/oauth2_token_service_request.h" #include "net/url_request/url_request_context_getter.h" using bookmarks::BookmarkModel; using sync_bookmarks::BookmarkChangeProcessor; using sync_bookmarks::BookmarkDataTypeController; using sync_bookmarks::BookmarkModelAssociator; using syncer::DataTypeController; using syncer::DataTypeManager; using syncer::DataTypeManagerImpl; using syncer::DataTypeManagerObserver; using syncer::DeviceInfoDataTypeController; using syncer::ProxyDataTypeController; using syncer::UIDataTypeController; using syncer::ModelTypeController; using sync_sessions::SessionDataTypeController; namespace browser_sync { namespace { syncer::ModelTypeSet GetDisabledTypesFromCommandLine( const base::CommandLine& command_line) { syncer::ModelTypeSet disabled_types; std::string disabled_types_str = command_line.GetSwitchValueASCII(switches::kDisableSyncTypes); disabled_types = syncer::ModelTypeSetFromString(disabled_types_str); return disabled_types; } syncer::ModelTypeSet GetEnabledTypesFromCommandLine( const base::CommandLine& command_line) { return syncer::ModelTypeSet(); } } // namespace ProfileSyncComponentsFactoryImpl::ProfileSyncComponentsFactoryImpl( syncer::SyncClient* sync_client, version_info::Channel channel, const std::string& version, bool is_tablet, const base::CommandLine& command_line, const char* history_disabled_pref, const GURL& sync_service_url, const scoped_refptr<base::SingleThreadTaskRunner>& ui_thread, const scoped_refptr<base::SingleThreadTaskRunner>& db_thread, OAuth2TokenService* token_service, net::URLRequestContextGetter* url_request_context_getter, const scoped_refptr<autofill::AutofillWebDataService>& web_data_service, const scoped_refptr<password_manager::PasswordStore>& password_store) : sync_client_(sync_client), channel_(channel), version_(version), is_tablet_(is_tablet), command_line_(command_line), history_disabled_pref_(history_disabled_pref), sync_service_url_(sync_service_url), ui_thread_(ui_thread), db_thread_(db_thread), token_service_(token_service), url_request_context_getter_(url_request_context_getter), web_data_service_(web_data_service), password_store_(password_store), weak_factory_(this) { DCHECK(token_service_); DCHECK(url_request_context_getter_); } ProfileSyncComponentsFactoryImpl::~ProfileSyncComponentsFactoryImpl() {} void ProfileSyncComponentsFactoryImpl::RegisterDataTypes( syncer::SyncService* sync_service, const RegisterDataTypesMethod& register_platform_types_method) { syncer::ModelTypeSet disabled_types = GetDisabledTypesFromCommandLine(command_line_); syncer::ModelTypeSet enabled_types = GetEnabledTypesFromCommandLine(command_line_); RegisterCommonDataTypes(sync_service, disabled_types, enabled_types); if (!register_platform_types_method.is_null()) register_platform_types_method.Run(sync_service, disabled_types, enabled_types); } void ProfileSyncComponentsFactoryImpl::RegisterCommonDataTypes( syncer::SyncService* sync_service, syncer::ModelTypeSet disabled_types, syncer::ModelTypeSet enabled_types) { base::Closure error_callback = base::Bind(&syncer::ReportUnrecoverableError, channel_); // TODO(stanisc): can DEVICE_INFO be one of disabled datatypes? if (base::FeatureList::IsEnabled(switches::kSyncUSSDeviceInfo)) { // Use an error callback that always uploads a stacktrace if it can to help // get USS as stable as possible. sync_service->RegisterDataTypeController( base::MakeUnique<ModelTypeController>( syncer::DEVICE_INFO, base::Bind(&base::debug::DumpWithoutCrashing), sync_client_, base::ThreadTaskRunnerHandle::Get())); } else { sync_service->RegisterDataTypeController( base::MakeUnique<DeviceInfoDataTypeController>( error_callback, sync_client_, sync_service->GetLocalDeviceInfoProvider())); } // Autofill sync is enabled by default. Register unless explicitly // disabled. if (!disabled_types.Has(syncer::AUTOFILL)) { sync_service->RegisterDataTypeController( base::MakeUnique<AutofillDataTypeController>( db_thread_, error_callback, sync_client_, web_data_service_)); } // Autofill profile sync is enabled by default. Register unless explicitly // disabled. if (!disabled_types.Has(syncer::AUTOFILL_PROFILE)) { sync_service->RegisterDataTypeController( base::MakeUnique<AutofillProfileDataTypeController>( db_thread_, error_callback, sync_client_, web_data_service_)); } // Wallet data sync is enabled by default, but behind a syncer experiment // enforced by the datatype controller. Register unless explicitly disabled. bool wallet_disabled = disabled_types.Has(syncer::AUTOFILL_WALLET_DATA); if (!wallet_disabled) { sync_service->RegisterDataTypeController( base::MakeUnique<AutofillWalletDataTypeController>( syncer::AUTOFILL_WALLET_DATA, db_thread_, error_callback, sync_client_, web_data_service_)); } // Wallet metadata sync depends on Wallet data sync. Register if Wallet data // is syncing and metadata sync is not explicitly disabled. if (!wallet_disabled && !disabled_types.Has(syncer::AUTOFILL_WALLET_METADATA)) { sync_service->RegisterDataTypeController( base::MakeUnique<AutofillWalletDataTypeController>( syncer::AUTOFILL_WALLET_METADATA, db_thread_, error_callback, sync_client_, web_data_service_)); } // Bookmark sync is enabled by default. Register unless explicitly // disabled. if (!disabled_types.Has(syncer::BOOKMARKS)) { sync_service->RegisterDataTypeController( base::MakeUnique<BookmarkDataTypeController>(error_callback, sync_client_)); } const bool history_disabled = sync_client_->GetPrefService()->GetBoolean(history_disabled_pref_); // TypedUrl sync is enabled by default. Register unless explicitly disabled, // or if saving history is disabled. if (!disabled_types.Has(syncer::TYPED_URLS) && !history_disabled) { sync_service->RegisterDataTypeController( base::MakeUnique<TypedUrlDataTypeController>( error_callback, sync_client_, history_disabled_pref_)); } // Delete directive sync is enabled by default. Register unless full history // sync is disabled. if (!disabled_types.Has(syncer::HISTORY_DELETE_DIRECTIVES) && !history_disabled) { sync_service->RegisterDataTypeController( base::MakeUnique<HistoryDeleteDirectivesDataTypeController>( error_callback, sync_client_)); } // Session sync is enabled by default. Register unless explicitly disabled. // This is also disabled if the browser history is disabled, because the // tab sync data is added to the web history on the server. if (!disabled_types.Has(syncer::PROXY_TABS) && !history_disabled) { sync_service->RegisterDataTypeController( base::MakeUnique<ProxyDataTypeController>(syncer::PROXY_TABS)); sync_service->RegisterDataTypeController( base::MakeUnique<SessionDataTypeController>( error_callback, sync_client_, sync_service->GetLocalDeviceInfoProvider(), history_disabled_pref_)); } // Favicon sync is enabled by default. Register unless explicitly disabled. if (!disabled_types.Has(syncer::FAVICON_IMAGES) && !disabled_types.Has(syncer::FAVICON_TRACKING) && !history_disabled) { // crbug/384552. We disable error uploading for this data types for now. sync_service->RegisterDataTypeController( base::MakeUnique<UIDataTypeController>(syncer::FAVICON_IMAGES, base::Closure(), sync_client_)); sync_service->RegisterDataTypeController( base::MakeUnique<UIDataTypeController>(syncer::FAVICON_TRACKING, base::Closure(), sync_client_)); } // Password sync is enabled by default. Register unless explicitly // disabled. if (!disabled_types.Has(syncer::PASSWORDS)) { sync_service->RegisterDataTypeController( base::MakeUnique<PasswordDataTypeController>( error_callback, sync_client_, sync_client_->GetPasswordStateChangedCallback(), password_store_)); } if (!disabled_types.Has(syncer::PREFERENCES)) { if (!override_prefs_controller_to_uss_for_test_) { sync_service->RegisterDataTypeController( base::MakeUnique<UIDataTypeController>(syncer::PREFERENCES, error_callback, sync_client_)); } else { sync_service->RegisterDataTypeController( base::MakeUnique<ModelTypeController>( syncer::PREFERENCES, error_callback, sync_client_, base::ThreadTaskRunnerHandle::Get())); } } if (!disabled_types.Has(syncer::PRIORITY_PREFERENCES)) { sync_service->RegisterDataTypeController( base::MakeUnique<UIDataTypeController>(syncer::PRIORITY_PREFERENCES, error_callback, sync_client_)); } // Article sync is disabled by default. Register only if explicitly enabled. if (dom_distiller::IsEnableSyncArticlesSet()) { sync_service->RegisterDataTypeController( base::MakeUnique<UIDataTypeController>(syncer::ARTICLES, error_callback, sync_client_)); } } DataTypeManager* ProfileSyncComponentsFactoryImpl::CreateDataTypeManager( const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>& debug_info_listener, const DataTypeController::TypeMap* controllers, const syncer::DataTypeEncryptionHandler* encryption_handler, syncer::SyncBackendHost* backend, DataTypeManagerObserver* observer) { return new DataTypeManagerImpl(debug_info_listener, controllers, encryption_handler, backend, observer); } syncer::SyncBackendHost* ProfileSyncComponentsFactoryImpl::CreateSyncBackendHost( const std::string& name, invalidation::InvalidationService* invalidator, const base::WeakPtr<syncer::SyncPrefs>& sync_prefs, const base::FilePath& sync_folder) { return new syncer::SyncBackendHostImpl(name, sync_client_, ui_thread_, invalidator, sync_prefs, sync_folder); } std::unique_ptr<syncer::LocalDeviceInfoProvider> ProfileSyncComponentsFactoryImpl::CreateLocalDeviceInfoProvider() { return base::MakeUnique<syncer::LocalDeviceInfoProviderImpl>( channel_, version_, is_tablet_); } class TokenServiceProvider : public OAuth2TokenServiceRequest::TokenServiceProvider { public: TokenServiceProvider( const scoped_refptr<base::SingleThreadTaskRunner>& task_runner, OAuth2TokenService* token_service); // OAuth2TokenServiceRequest::TokenServiceProvider implementation. scoped_refptr<base::SingleThreadTaskRunner> GetTokenServiceTaskRunner() override; OAuth2TokenService* GetTokenService() override; private: ~TokenServiceProvider() override; scoped_refptr<base::SingleThreadTaskRunner> task_runner_; OAuth2TokenService* token_service_; }; TokenServiceProvider::TokenServiceProvider( const scoped_refptr<base::SingleThreadTaskRunner>& task_runner, OAuth2TokenService* token_service) : task_runner_(task_runner), token_service_(token_service) {} TokenServiceProvider::~TokenServiceProvider() {} scoped_refptr<base::SingleThreadTaskRunner> TokenServiceProvider::GetTokenServiceTaskRunner() { return task_runner_; } OAuth2TokenService* TokenServiceProvider::GetTokenService() { return token_service_; } std::unique_ptr<syncer::AttachmentService> ProfileSyncComponentsFactoryImpl::CreateAttachmentService( std::unique_ptr<syncer::AttachmentStoreForSync> attachment_store, const syncer::UserShare& user_share, const std::string& store_birthday, syncer::ModelType model_type, syncer::AttachmentService::Delegate* delegate) { std::unique_ptr<syncer::AttachmentUploader> attachment_uploader; std::unique_ptr<syncer::AttachmentDownloader> attachment_downloader; // Only construct an AttachmentUploader and AttachmentDownload if we have sync // credentials. We may not have sync credentials because there may not be a // signed in sync user. if (!user_share.sync_credentials.account_id.empty() && !user_share.sync_credentials.scope_set.empty()) { scoped_refptr<OAuth2TokenServiceRequest::TokenServiceProvider> token_service_provider( new TokenServiceProvider(ui_thread_, token_service_)); // TODO(maniscalco): Use shared (one per profile) thread-safe instances of // AttachmentUploader and AttachmentDownloader instead of creating a new one // per AttachmentService (bug 369536). attachment_uploader = syncer::AttachmentUploader::Create( sync_service_url_, url_request_context_getter_, user_share.sync_credentials.account_id, user_share.sync_credentials.scope_set, token_service_provider, store_birthday, model_type); token_service_provider = new TokenServiceProvider(ui_thread_, token_service_); attachment_downloader = syncer::AttachmentDownloader::Create( sync_service_url_, url_request_context_getter_, user_share.sync_credentials.account_id, user_share.sync_credentials.scope_set, token_service_provider, store_birthday, model_type); } // It is important that the initial backoff delay is relatively large. For // whatever reason, the server may fail all requests for a short period of // time. When this happens we don't want to overwhelm the server with // requests so we use a large initial backoff. const base::TimeDelta initial_backoff_delay = base::TimeDelta::FromMinutes(30); const base::TimeDelta max_backoff_delay = base::TimeDelta::FromHours(4); return syncer::AttachmentService::Create( std::move(attachment_store), std::move(attachment_uploader), std::move(attachment_downloader), delegate, initial_backoff_delay, max_backoff_delay); } syncer::SyncApiComponentFactory::SyncComponents ProfileSyncComponentsFactoryImpl::CreateBookmarkSyncComponents( syncer::SyncService* sync_service, std::unique_ptr<syncer::DataTypeErrorHandler> error_handler) { BookmarkModel* bookmark_model = sync_service->GetSyncClient()->GetBookmarkModel(); syncer::UserShare* user_share = sync_service->GetUserShare(); // TODO(akalin): We may want to propagate this switch up eventually. #if defined(OS_ANDROID) || defined(OS_IOS) const bool kExpectMobileBookmarksFolder = true; #else const bool kExpectMobileBookmarksFolder = false; #endif BookmarkModelAssociator* model_associator = new BookmarkModelAssociator( bookmark_model, sync_service->GetSyncClient(), user_share, error_handler->Copy(), kExpectMobileBookmarksFolder); BookmarkChangeProcessor* change_processor = new BookmarkChangeProcessor(sync_service->GetSyncClient(), model_associator, std::move(error_handler)); return SyncComponents(model_associator, change_processor); } // static void ProfileSyncComponentsFactoryImpl::OverridePrefsForUssTest(bool use_uss) { override_prefs_controller_to_uss_for_test_ = use_uss; } bool ProfileSyncComponentsFactoryImpl:: override_prefs_controller_to_uss_for_test_ = false; } // namespace browser_sync
#include <limits> #include "Conversion.hpp" #include "Depth.hpp" #include "Serialize.hpp" using namespace std; // Depth 1 is -50 feet (under ground, positive depth). // Depth -1 is 50 feet (above ground, negative depth). int Depth::DEPTH_MULTIPLIER = -50; const string Depth::DEPTH_INFINITE = "inf"; Depth::Depth() : current(0), minimum(0), maximum(0), increment(1), has_max(true) { } Depth::Depth(const int cur, const int min, const int max, const int incr, const bool has_maxi) : current(cur), minimum(min), maximum(max), increment(incr), has_max(has_maxi) { } bool Depth::operator==(const Depth& d) const { bool result = true; result = result && (current == d.current); result = result && (minimum == d.minimum); result = result && (maximum == d.maximum); result = result && (increment == d.increment); result = result && (has_max == d.has_max); return result; } void Depth::set_current(const int new_current) { current = new_current; } int Depth::get_current() const { return current; } void Depth::set_minimum(const int new_minimum) { minimum = new_minimum; } int Depth::get_minimum() const { return minimum; } void Depth::set_maximum(const int new_maximum) { maximum = new_maximum; } int Depth::get_maximum() const { return maximum; } void Depth::set_has_maximum(const bool new_has_maximum) { has_max = new_has_maximum; } bool Depth::has_maximum() const { return has_max; } void Depth::set_increment(const int new_increment) { increment = new_increment; } int Depth::get_increment() const { return increment; } // Return the "next" depth. Depth Depth::lower() const { Depth d(current, minimum, maximum, increment, has_max); if (has_maximum() == false || (current < maximum)) { if (current < numeric_limits<int>::max()) { d.set_current(current + std::abs(increment)); } } return d; } // Return the "previous" depth. Depth Depth::higher() const { Depth d(current, minimum, maximum, increment, has_max); if (has_maximum() == false || (current > minimum)) { if (current > numeric_limits<int>::min()) { d.set_current(current - std::abs(increment)); } } return d; } bool Depth::has_more_levels(const Direction d) const { bool more_levels = false; if (!has_max) { more_levels = true; } else { if (d == Direction::DIRECTION_DOWN) { more_levels = ((current + std::abs(increment)) <= maximum); } else if (d == Direction::DIRECTION_UP) { more_levels = ((current - std::abs(increment)) >= minimum); } } return more_levels; } // Return the depth as a string (for the UI, etc). // // For most cases in game (showing on a map's status line), suppress any // 0-depth values such as the overworld, forests, etc. // e.g., "[-50']", "" (if on overworld, or otherwise at 0') // // For cases such as showing the maximum depth reached in the character dump, // the show_all_depths parameter allows the depth to be shown even when it's // currently 0. string Depth::str(bool show_all_depths) const { string depth_s; // Default, if on plains, forest, etc. if (current != 0 || show_all_depths) { int depth_in_feet = current * DEPTH_MULTIPLIER; depth_s = std::to_string(depth_in_feet); depth_s = "[" + depth_s + "']"; } return depth_s; } bool Depth::serialize(ostream& stream) const { Serialize::write_int(stream, current); Serialize::write_int(stream, minimum); Serialize::write_int(stream, maximum); Serialize::write_int(stream, increment); Serialize::write_bool(stream, has_max); Serialize::write_int(stream, DEPTH_MULTIPLIER); return true; } bool Depth::deserialize(istream& stream) { Serialize::read_int(stream, current); Serialize::read_int(stream, minimum); Serialize::read_int(stream, maximum); Serialize::read_int(stream, increment); Serialize::read_bool(stream, has_max); Serialize::read_int(stream, DEPTH_MULTIPLIER); return true; } ClassIdentifier Depth::internal_class_identifier() const { return ClassIdentifier::CLASS_ID_DEPTH; } #ifdef UNIT_TESTS #include "unit_tests/Depth_test.cpp" #endif
// Copyright (c) 2012-2013 The Bitcoin Core developers // Copyright (c) 2017 The SOMBE developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "pubkey.h" #include "key.h" #include "script/script.h" #include "script/standard.h" #include "uint256.h" #include <vector> #include <boost/foreach.hpp> #include <boost/test/unit_test.hpp> using namespace std; // Helpers: static std::vector<unsigned char> Serialize(const CScript& s) { std::vector<unsigned char> sSerialized(s); return sSerialized; } BOOST_AUTO_TEST_SUITE(sigopcount_tests) BOOST_AUTO_TEST_CASE(GetSigOpCount) { // Test CScript::GetSigOpCount() CScript s1; BOOST_CHECK_EQUAL(s1.GetSigOpCount(false), 0U); BOOST_CHECK_EQUAL(s1.GetSigOpCount(true), 0U); uint160 dummy(0); s1 << OP_1 << ToByteVector(dummy) << ToByteVector(dummy) << OP_2 << OP_CHECKMULTISIG; BOOST_CHECK_EQUAL(s1.GetSigOpCount(true), 2U); s1 << OP_IF << OP_CHECKSIG << OP_ENDIF; BOOST_CHECK_EQUAL(s1.GetSigOpCount(true), 3U); BOOST_CHECK_EQUAL(s1.GetSigOpCount(false), 21U); CScript p2sh = GetScriptForDestination(CScriptID(s1)); CScript scriptSig; scriptSig << OP_0 << Serialize(s1); BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(scriptSig), 3U); std::vector<CPubKey> keys; for (int i = 0; i < 3; i++) { CKey k; k.MakeNewKey(true); keys.push_back(k.GetPubKey()); } CScript s2 = GetScriptForMultisig(1, keys); BOOST_CHECK_EQUAL(s2.GetSigOpCount(true), 3U); BOOST_CHECK_EQUAL(s2.GetSigOpCount(false), 20U); p2sh = GetScriptForDestination(CScriptID(s2)); BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(true), 0U); BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(false), 0U); CScript scriptSig2; scriptSig2 << OP_1 << ToByteVector(dummy) << ToByteVector(dummy) << Serialize(s2); BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(scriptSig2), 3U); } BOOST_AUTO_TEST_SUITE_END()