text
stringlengths
54
60.6k
<commit_before>// Copyright (c) 2009-2014 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 "base58.h" #include "rpcserver.h" #include "init.h" #include "main.h" #include "sync.h" #include "wallet.h" #include <fstream> #include <stdint.h> #include <boost/algorithm/string.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include "json/json_spirit_value.h" using namespace json_spirit; using namespace std; void EnsureWalletIsUnlocked(); std::string static EncodeDumpTime(int64_t nTime) { return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime); } int64_t static DecodeDumpTime(const std::string &str) { static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0); static const std::locale loc(std::locale::classic(), new boost::posix_time::time_input_facet("%Y-%m-%dT%H:%M:%SZ")); std::istringstream iss(str); iss.imbue(loc); boost::posix_time::ptime ptime(boost::date_time::not_a_date_time); iss >> ptime; if (ptime.is_not_a_date_time()) return 0; return (ptime - epoch).total_seconds(); } std::string static EncodeDumpString(const std::string &str) { std::stringstream ret; BOOST_FOREACH(unsigned char c, str) { if (c <= 32 || c >= 128 || c == '%') { ret << '%' << HexStr(&c, &c + 1); } else { ret << c; } } return ret.str(); } std::string DecodeDumpString(const std::string &str) { std::stringstream ret; for (unsigned int pos = 0; pos < str.length(); pos++) { unsigned char c = str[pos]; if (c == '%' && pos+2 < str.length()) { c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) | ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15)); pos += 2; } ret << c; } return ret.str(); } Value importprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importprivkey \"bitcoinprivkey\" ( \"label\" rescan )\n" "\nAdds a private key (as returned by dumpprivkey) to your wallet.\n" "\nArguments:\n" "1. \"bitcoinprivkey\" (string, required) The private key (see dumpprivkey)\n" "2. \"label\" (string, optional) an optional label\n" "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n" "\nExamples:\n" "\nDump a private key\n" + HelpExampleCli("dumpprivkey", "\"myaddress\"") + "\nImport the private key\n" + HelpExampleCli("importprivkey", "\"mykey\"") + "\nImport using a label\n" + HelpExampleCli("importprivkey", "\"mykey\" \"testing\" false") + "\nAs a json rpc call\n" + HelpExampleRpc("importprivkey", "\"mykey\", \"testing\", false") ); EnsureWalletIsUnlocked(); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding"); CKey key = vchSecret.GetKey(); if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range"); CPubKey pubkey = key.GetPubKey(); CKeyID vchAddress = pubkey.GetID(); { LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->MarkDirty(); pwalletMain->SetAddressBook(vchAddress, strLabel, "receive"); // Don't throw error in case a key is already there if (pwalletMain->HaveKey(vchAddress)) return Value::null; pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1; if (!pwalletMain->AddKeyPubKey(key, pubkey)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); // whenever a key is imported, we need to scan the whole chain pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value' if (fRescan) { pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); } } return Value::null; } Value importwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "importwallet \"filename\"\n" "\nImports keys from a wallet dump file (see dumpwallet).\n" "\nArguments:\n" "1. \"filename\" (string, required) The wallet file\n" "\nExamples:\n" "\nDump the wallet\n" + HelpExampleCli("dumpwallet", "\"test\"") + "\nImport the wallet\n" + HelpExampleCli("importwallet", "\"test\"") + "\nImport using the json rpc call\n" + HelpExampleRpc("importwallet", "\"test\"") ); EnsureWalletIsUnlocked(); ifstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); int64_t nTimeBegin = chainActive.Tip()->nTime; bool fGood = true; while (file.good()) { std::string line; std::getline(file, line); if (line.empty() || line[0] == '#') continue; std::vector<std::string> vstr; boost::split(vstr, line, boost::is_any_of(" ")); if (vstr.size() < 2) continue; CBitcoinSecret vchSecret; if (!vchSecret.SetString(vstr[0])) continue; CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); CKeyID keyid = pubkey.GetID(); if (pwalletMain->HaveKey(keyid)) { LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString()); continue; } int64_t nTime = DecodeDumpTime(vstr[1]); std::string strLabel; bool fLabel = true; for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) { if (boost::algorithm::starts_with(vstr[nStr], "#")) break; if (vstr[nStr] == "change=1") fLabel = false; if (vstr[nStr] == "reserve=1") fLabel = false; if (boost::algorithm::starts_with(vstr[nStr], "label=")) { strLabel = DecodeDumpString(vstr[nStr].substr(6)); fLabel = true; } } LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString()); if (!pwalletMain->AddKeyPubKey(key, pubkey)) { fGood = false; continue; } pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime; if (fLabel) pwalletMain->SetAddressBook(keyid, strLabel, "receive"); nTimeBegin = std::min(nTimeBegin, nTime); } file.close(); CBlockIndex *pindex = chainActive.Tip(); while (pindex && pindex->pprev && pindex->nTime > nTimeBegin - 7200) pindex = pindex->pprev; if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey) pwalletMain->nTimeFirstKey = nTimeBegin; LogPrintf("Rescanning last %i blocks\n", chainActive.Height() - pindex->nHeight + 1); pwalletMain->ScanForWalletTransactions(pindex); pwalletMain->MarkDirty(); if (!fGood) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet"); return Value::null; } Value dumpprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey \"bitcoinaddress\"\n" "\nReveals the private key corresponding to 'bitcoinaddress'.\n" "Then the importprivkey can be used with this output\n" "\nArguments:\n" "1. \"bitcoinaddress\" (string, required) The bitcoin address for the private key\n" "\nResult:\n" "\"key\" (string) The private key\n" "\nExamples:\n" + HelpExampleCli("dumpprivkey", "\"myaddress\"") + HelpExampleCli("importprivkey", "\"mykey\"") + HelpExampleRpc("dumpprivkey", "\"myaddress\"") ); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address"); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CKey vchSecret; if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret).ToString(); } Value dumpwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpwallet \"filename\"\n" "\nDumps all wallet keys in a human-readable format.\n" "\nArguments:\n" "1. \"filename\" (string, required) The filename\n" "\nExamples:\n" + HelpExampleCli("dumpwallet", "\"test\"") + HelpExampleRpc("dumpwallet", "\"test\"") ); EnsureWalletIsUnlocked(); ofstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); std::map<CKeyID, int64_t> mapKeyBirth; std::set<CKeyID> setKeyPool; pwalletMain->GetKeyBirthTimes(mapKeyBirth); pwalletMain->GetAllReserveKeys(setKeyPool); // sort time/key pairs std::vector<std::pair<int64_t, CKeyID> > vKeyBirth; for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) { vKeyBirth.push_back(std::make_pair(it->second, it->first)); } mapKeyBirth.clear(); std::sort(vKeyBirth.begin(), vKeyBirth.end()); // produce output file << strprintf("# Wallet dump created by Bitcoin %s (%s)\n", CLIENT_BUILD, CLIENT_DATE); file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime())); file << strprintf("# * Best block at time of backup was %i (%s),\n", chainActive.Height(), chainActive.Tip()->GetBlockHash().ToString()); file << strprintf("# mined on %s\n", EncodeDumpTime(chainActive.Tip()->nTime)); file << "\n"; for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) { const CKeyID &keyid = it->second; std::string strTime = EncodeDumpTime(it->first); std::string strAddr = CBitcoinAddress(keyid).ToString(); CKey key; if (pwalletMain->GetKey(keyid, key)) { if (pwalletMain->mapAddressBook.count(keyid)) { file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, EncodeDumpString(pwalletMain->mapAddressBook[keyid].name), strAddr); } else if (setKeyPool.count(keyid)) { file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr); } else { file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr); } } } file << "\n"; file << "# End of dump\n"; file.close(); return Value::null; } <commit_msg>[Qt] importwallet progress<commit_after>// Copyright (c) 2009-2014 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 "base58.h" #include "rpcserver.h" #include "init.h" #include "main.h" #include "sync.h" #include "wallet.h" #include <fstream> #include <stdint.h> #include <boost/algorithm/string.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include "json/json_spirit_value.h" using namespace json_spirit; using namespace std; void EnsureWalletIsUnlocked(); std::string static EncodeDumpTime(int64_t nTime) { return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime); } int64_t static DecodeDumpTime(const std::string &str) { static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0); static const std::locale loc(std::locale::classic(), new boost::posix_time::time_input_facet("%Y-%m-%dT%H:%M:%SZ")); std::istringstream iss(str); iss.imbue(loc); boost::posix_time::ptime ptime(boost::date_time::not_a_date_time); iss >> ptime; if (ptime.is_not_a_date_time()) return 0; return (ptime - epoch).total_seconds(); } std::string static EncodeDumpString(const std::string &str) { std::stringstream ret; BOOST_FOREACH(unsigned char c, str) { if (c <= 32 || c >= 128 || c == '%') { ret << '%' << HexStr(&c, &c + 1); } else { ret << c; } } return ret.str(); } std::string DecodeDumpString(const std::string &str) { std::stringstream ret; for (unsigned int pos = 0; pos < str.length(); pos++) { unsigned char c = str[pos]; if (c == '%' && pos+2 < str.length()) { c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) | ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15)); pos += 2; } ret << c; } return ret.str(); } Value importprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importprivkey \"bitcoinprivkey\" ( \"label\" rescan )\n" "\nAdds a private key (as returned by dumpprivkey) to your wallet.\n" "\nArguments:\n" "1. \"bitcoinprivkey\" (string, required) The private key (see dumpprivkey)\n" "2. \"label\" (string, optional) an optional label\n" "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n" "\nExamples:\n" "\nDump a private key\n" + HelpExampleCli("dumpprivkey", "\"myaddress\"") + "\nImport the private key\n" + HelpExampleCli("importprivkey", "\"mykey\"") + "\nImport using a label\n" + HelpExampleCli("importprivkey", "\"mykey\" \"testing\" false") + "\nAs a json rpc call\n" + HelpExampleRpc("importprivkey", "\"mykey\", \"testing\", false") ); EnsureWalletIsUnlocked(); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding"); CKey key = vchSecret.GetKey(); if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range"); CPubKey pubkey = key.GetPubKey(); CKeyID vchAddress = pubkey.GetID(); { LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->MarkDirty(); pwalletMain->SetAddressBook(vchAddress, strLabel, "receive"); // Don't throw error in case a key is already there if (pwalletMain->HaveKey(vchAddress)) return Value::null; pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1; if (!pwalletMain->AddKeyPubKey(key, pubkey)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); // whenever a key is imported, we need to scan the whole chain pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value' if (fRescan) { pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); } } return Value::null; } Value importwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "importwallet \"filename\"\n" "\nImports keys from a wallet dump file (see dumpwallet).\n" "\nArguments:\n" "1. \"filename\" (string, required) The wallet file\n" "\nExamples:\n" "\nDump the wallet\n" + HelpExampleCli("dumpwallet", "\"test\"") + "\nImport the wallet\n" + HelpExampleCli("importwallet", "\"test\"") + "\nImport using the json rpc call\n" + HelpExampleRpc("importwallet", "\"test\"") ); EnsureWalletIsUnlocked(); ifstream file; file.open(params[0].get_str().c_str(), std::ios::in | std::ios::ate); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); int64_t nTimeBegin = chainActive.Tip()->nTime; bool fGood = true; int64_t nFilesize = std::max((int64_t)1, (int64_t)file.tellg()); file.seekg(0, file.beg); pwalletMain->ShowProgress(_("Importing..."), 0); // show progress dialog in GUI while (file.good()) { pwalletMain->ShowProgress("", std::max(1, std::min(99, (int)(((double)file.tellg() / (double)nFilesize) * 100)))); std::string line; std::getline(file, line); if (line.empty() || line[0] == '#') continue; std::vector<std::string> vstr; boost::split(vstr, line, boost::is_any_of(" ")); if (vstr.size() < 2) continue; CBitcoinSecret vchSecret; if (!vchSecret.SetString(vstr[0])) continue; CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); CKeyID keyid = pubkey.GetID(); if (pwalletMain->HaveKey(keyid)) { LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString()); continue; } int64_t nTime = DecodeDumpTime(vstr[1]); std::string strLabel; bool fLabel = true; for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) { if (boost::algorithm::starts_with(vstr[nStr], "#")) break; if (vstr[nStr] == "change=1") fLabel = false; if (vstr[nStr] == "reserve=1") fLabel = false; if (boost::algorithm::starts_with(vstr[nStr], "label=")) { strLabel = DecodeDumpString(vstr[nStr].substr(6)); fLabel = true; } } LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString()); if (!pwalletMain->AddKeyPubKey(key, pubkey)) { fGood = false; continue; } pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime; if (fLabel) pwalletMain->SetAddressBook(keyid, strLabel, "receive"); nTimeBegin = std::min(nTimeBegin, nTime); } file.close(); pwalletMain->ShowProgress("", 100); // hide progress dialog in GUI CBlockIndex *pindex = chainActive.Tip(); while (pindex && pindex->pprev && pindex->nTime > nTimeBegin - 7200) pindex = pindex->pprev; if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey) pwalletMain->nTimeFirstKey = nTimeBegin; LogPrintf("Rescanning last %i blocks\n", chainActive.Height() - pindex->nHeight + 1); pwalletMain->ScanForWalletTransactions(pindex); pwalletMain->MarkDirty(); if (!fGood) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet"); return Value::null; } Value dumpprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey \"bitcoinaddress\"\n" "\nReveals the private key corresponding to 'bitcoinaddress'.\n" "Then the importprivkey can be used with this output\n" "\nArguments:\n" "1. \"bitcoinaddress\" (string, required) The bitcoin address for the private key\n" "\nResult:\n" "\"key\" (string) The private key\n" "\nExamples:\n" + HelpExampleCli("dumpprivkey", "\"myaddress\"") + HelpExampleCli("importprivkey", "\"mykey\"") + HelpExampleRpc("dumpprivkey", "\"myaddress\"") ); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address"); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CKey vchSecret; if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret).ToString(); } Value dumpwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpwallet \"filename\"\n" "\nDumps all wallet keys in a human-readable format.\n" "\nArguments:\n" "1. \"filename\" (string, required) The filename\n" "\nExamples:\n" + HelpExampleCli("dumpwallet", "\"test\"") + HelpExampleRpc("dumpwallet", "\"test\"") ); EnsureWalletIsUnlocked(); ofstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); std::map<CKeyID, int64_t> mapKeyBirth; std::set<CKeyID> setKeyPool; pwalletMain->GetKeyBirthTimes(mapKeyBirth); pwalletMain->GetAllReserveKeys(setKeyPool); // sort time/key pairs std::vector<std::pair<int64_t, CKeyID> > vKeyBirth; for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) { vKeyBirth.push_back(std::make_pair(it->second, it->first)); } mapKeyBirth.clear(); std::sort(vKeyBirth.begin(), vKeyBirth.end()); // produce output file << strprintf("# Wallet dump created by Bitcoin %s (%s)\n", CLIENT_BUILD, CLIENT_DATE); file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime())); file << strprintf("# * Best block at time of backup was %i (%s),\n", chainActive.Height(), chainActive.Tip()->GetBlockHash().ToString()); file << strprintf("# mined on %s\n", EncodeDumpTime(chainActive.Tip()->nTime)); file << "\n"; for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) { const CKeyID &keyid = it->second; std::string strTime = EncodeDumpTime(it->first); std::string strAddr = CBitcoinAddress(keyid).ToString(); CKey key; if (pwalletMain->GetKey(keyid, key)) { if (pwalletMain->mapAddressBook.count(keyid)) { file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, EncodeDumpString(pwalletMain->mapAddressBook[keyid].name), strAddr); } else if (setKeyPool.count(keyid)) { file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr); } else { file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr); } } } file << "\n"; file << "# End of dump\n"; file.close(); return Value::null; } <|endoftext|>
<commit_before>#include "SplashScene.h" #include "HelloWorldScene.h" #include "AppMacros.h" #include "GreedyGameSDK.h" USING_NS_CC; CCLabelTTF* pLabel; CCScene* SplashScene::scene() { // 'scene' is an autorelease object CCScene *scene = CCScene::create(); // 'layer' is an autorelease object SplashScene *layer = SplashScene::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } void downloadProgress(float f) { CCLog( "downloadProgress > : %f", f); ostringstream myString; myString << "Loading progress " << f <<"%"; std::string s = myString.str(); pLabel->setString(s.c_str()); } void on_init(int r) { CCLog( "> on_init %d", r); /* * GG_CAMPAIGN_NOT_FOUND, -1 = using no campaign * GG_CAMPAIGN_CACHED, 0 = campaign already cached * GG_CAMPAIGN_FOUND, 1 = new campaign found to Download * GG_CAMPAIGN_DOWNLOADED, 2 = new campaign is Downloaded * GG_ADUNIT_OPENED, 3 = AdUnit Opened * GG_ADUNIT_CLOSED, 4 = AdUnit Closed */ int isBranded = -1; if(r == GG_CAMPAIGN_CACHED || r == GG_CAMPAIGN_DOWNLOADED){ isBranded = 1; }else if(r == GG_CAMPAIGN_NOT_FOUND){ isBranded = 0; } if(isBranded > -1){ greedygame::GreedyGameSDK::fetchAdHead("unit-385"); CCDirector *pDirector = CCDirector::sharedDirector(); CCScene *pScene = HelloWorld::scene(); pDirector->replaceScene(pScene); } if(r == GG_ADUNIT_OPENED){ //Make pause }else if(r == GG_ADUNIT_CLOSED){ //Make unpause } } // on "init" you need to initialize your instance bool SplashScene::init() { //greedygame::GreedyGameSDK::setDebug(true); greedygame::GreedyGameSDK::initialize(&on_init, &downloadProgress); ////////////////////////////// // 1. super init first if ( !CCLayer::init() ) { return false; } CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize(); CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin(); // add "SplashScene" splash screen" CCSprite* pSprite = CCSprite::create("splash.jpg"); pSprite->setPosition(ccp(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); this->addChild(pSprite, 0); pLabel = CCLabelTTF::create("Loading...", "Arial", 48); pLabel->setPosition(ccp(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y - 200)); pLabel->setColor(ccc3(0,0,0)); this->addChild(pLabel, 1); return true; } <commit_msg>Update SplashScene.cpp<commit_after>#include "SplashScene.h" #include "HelloWorldScene.h" #include "AppMacros.h" #include "GreedyGameSDK.h" USING_NS_CC; CCLabelTTF* pLabel; CCScene* SplashScene::scene() { // 'scene' is an autorelease object CCScene *scene = CCScene::create(); // 'layer' is an autorelease object SplashScene *layer = SplashScene::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } void downloadProgress(float f) { CCLog( "downloadProgress > : %f", f); ostringstream myString; myString << "Loading progress " << f <<"%"; std::string s = myString.str(); pLabel->setString(s.c_str()); } void on_init(int r) { CCLog( "> on_init %d", r); /* * GG_CAMPAIGN_NOT_FOUND, -1 = using no campaign * GG_CAMPAIGN_CACHED, 0 = campaign already cached * GG_CAMPAIGN_FOUND, 1 = new campaign found to Download * GG_CAMPAIGN_DOWNLOADED, 2 = new campaign is Downloaded * GG_ADUNIT_OPENED, 3 = AdUnit Opened * GG_ADUNIT_CLOSED, 4 = AdUnit Closed */ int isBranded = -1; if(r == GG_CAMPAIGN_CACHED || r == GG_CAMPAIGN_DOWNLOADED){ isBranded = 1; }else if(r == GG_CAMPAIGN_NOT_FOUND){ isBranded = 0; } if(isBranded > -1){ greedygame::GreedyGameSDK::fetchAdHead("unit-385"); CCDirector *pDirector = CCDirector::sharedDirector(); CCScene *pScene = HelloWorld::scene(); pDirector->replaceScene(pScene); } if(r == GG_ADUNIT_OPENED){ //Make pause }else if(r == GG_ADUNIT_CLOSED){ //Make unpause } } // on "init" you need to initialize your instance bool SplashScene::init() { greedygame::GreedyGameSDK::initialize(&on_init, &downloadProgress); ////////////////////////////// // 1. super init first if ( !CCLayer::init() ) { return false; } CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize(); CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin(); // add "SplashScene" splash screen" CCSprite* pSprite = CCSprite::create("splash.jpg"); pSprite->setPosition(ccp(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); this->addChild(pSprite, 0); pLabel = CCLabelTTF::create("Loading...", "Arial", 48); pLabel->setPosition(ccp(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y - 200)); pLabel->setColor(ccc3(0,0,0)); this->addChild(pLabel, 1); return true; } <|endoftext|>
<commit_before>/* * Jamoma DataspaceLib: DistanceDataspace * Copyright 2007, Nils Peters * * License: This code is licensed under the terms of the GNU LGPL * http://www.gnu.org/licenses/lgpl.html * Based on code by Trond Lossius, 2007 and * Jan Schacher / ICST Zurich 2006 * * */ #include "PositionDataspace.h" Cartesian3DUnit::Cartesian3DUnit() : DataspaceUnit("cart3D") {;} Cartesian3DUnit::~Cartesian3DUnit() {;} void Cartesian3DUnit::convertToNeutral(long inputNumArgs, t_atom *inputAtoms, long *outputNumArgs, double *output) { *outputNumArgs = 3; *(output+0) = atom_getfloat(inputAtoms+0); //x *(output+1) = atom_getfloat(inputAtoms+1); //y *(output+2) = atom_getfloat(inputAtoms+2); //z } void Cartesian3DUnit::convertFromNeutral(long inputNumArgs, double *input, long *outputNumArgs, t_atom **outputAtoms) { *outputNumArgs = 3; atom_setfloat(*outputAtoms+0, *(input+0)); atom_setfloat(*outputAtoms+1, *(input+1)); atom_setfloat(*outputAtoms+2, *(input+2)); } /***********************************************************************************************/ Cartesian2DUnit::Cartesian2DUnit() : DataspaceUnit("cart2D") {;} Cartesian2DUnit::~Cartesian2DUnit() {;} void Cartesian2DUnit::convertToNeutral(long inputNumArgs, t_atom *inputAtoms, long *outputNumArgs, double *output) { *outputNumArgs = 2; *(output+0) = atom_getfloat(inputAtoms+0); //x *(output+1) = atom_getfloat(inputAtoms+1); //y } void Cartesian2DUnit::convertFromNeutral(long inputNumArgs, double *input, long *outputNumArgs, t_atom **outputAtoms) { *outputNumArgs = 2; atom_setfloat(*outputAtoms+0, *(input+0)); atom_setfloat(*outputAtoms+1, *(input+1)); } /***********************************************************************************************/ SphericalUnit::SphericalUnit() : DataspaceUnit("spherical") {;} SphericalUnit::~SphericalUnit() {;} void SphericalUnit::convertToNeutral(long inputNumArgs, t_atom *inputAtoms, long *outputNumArgs, double *output) { //double kDegreesToRadians = kDegreesToRadians; double aa = (90. - atom_getfloat(inputAtoms+0)) * kDegreesToRadians; //a double ee = atom_getfloat(inputAtoms+1) * kDegreesToRadians; //e double dd = atom_getfloat(inputAtoms+2); //d *outputNumArgs = 3; double temp = cos(ee) * dd; *(output+0) = cos(aa) * temp; *(output+1) = sin(aa) * temp; *(output+2) = sin(ee) * dd; } void SphericalUnit::convertFromNeutral(long inputNumArgs, double *input, long *outputNumArgs, t_atom **outputAtoms) { double xx = *(input+0); double yy = *(input+1); double zz = *(input+2); double temp = (xx * xx) + (yy * yy); *outputNumArgs = 3; atom_setfloat(*outputAtoms+0, atan2(xx, yy) * kRadiansToDegrees); atom_setfloat(*outputAtoms+1, atan2(zz, (pow((temp), 0.5))) * kRadiansToDegrees); atom_setfloat(*outputAtoms+2, pow((temp + (zz * zz)), 0.5)); } /***********************************************************************************************/ PolarUnit::PolarUnit() : DataspaceUnit("polar") {;} PolarUnit::~PolarUnit() {;} void PolarUnit::convertToNeutral(long inputNumArgs, t_atom *inputAtoms, long *outputNumArgs, double *output) { *outputNumArgs = 2; double aa = (90. - atom_getfloat(inputAtoms+0)) * kDegreesToRadians; //a double dd = atom_getfloat(inputAtoms+1); //d *(output+0) = cos(aa) * dd; //x *(output+1) = sin(aa) * dd; //y } void PolarUnit::convertFromNeutral(long inputNumArgs, double *input, long *outputNumArgs, t_atom **outputAtoms) { double xx = *(input+0); double yy = *(input+1); *outputNumArgs = 2; atom_setfloat(*outputAtoms+0, atan2(xx, yy) * kRadiansToDegrees); //a atom_setfloat(*outputAtoms+1, pow(((xx * xx) + (yy * yy)), 0.5)); //distance } /***********************************************************************************************/ OpenGlUnit::OpenGlUnit() : DataspaceUnit("openGl") {;} OpenGlUnit::~OpenGlUnit() {;} void OpenGlUnit::convertToNeutral(long inputNumArgs, t_atom *inputAtoms, long *outputNumArgs, double *output) { *outputNumArgs = 3; *(output+0) = atom_getfloat(inputAtoms+0); //x *(output+1) = -1.0 * atom_getfloat(inputAtoms+2); //y *(output+2) = atom_getfloat(inputAtoms+1); //z } void OpenGlUnit::convertFromNeutral(long inputNumArgs, double *input, long *outputNumArgs, t_atom **outputAtoms) { *outputNumArgs = 3; atom_setfloat(*outputAtoms+0, *(input+0));//x atom_setfloat(*outputAtoms+1, *(input+2));//y atom_setfloat(*outputAtoms+2, *(input+1) * -1.0);//z } /***********************************************************************************************/ CylindricalUnit::CylindricalUnit() : DataspaceUnit("cylindrical") {;} CylindricalUnit::~CylindricalUnit() {;} void CylindricalUnit::convertToNeutral(long inputNumArgs, t_atom *inputAtoms, long *outputNumArgs, double *output) { // Cylindrical coordinate System (according to ISO 31-11 http://en.wikipedia.org/wiki/ISO_31-11#Coordinate_systems ) = radius azimut hight *outputNumArgs = 3; double dd = atom_getfloat(inputAtoms+0); //d double aa = (90. - atom_getfloat(inputAtoms+1)) * kDegreesToRadians; //a *(output+0) = cos(aa) * dd; //x *(output+1) = sin(aa) * dd; //y *(output+2) = atom_getfloat(inputAtoms+2); //z } void CylindricalUnit::convertFromNeutral(long inputNumArgs, double *input, long *outputNumArgs, t_atom **outputAtoms) { *outputNumArgs = 3; double xx = *(input+0); double yy = *(input+1); // d a z atom_setfloat(*outputAtoms+0, pow(((xx * xx) + (yy * yy)), 0.5)); //distance atom_setfloat(*outputAtoms+1, atan2(xx, yy) * kRadiansToDegrees); //a atom_setfloat(*outputAtoms+2, *(input+2));//z } /***********************************************************************************************/ PositionDataspace::PositionDataspace() : DataspaceLib("position", "xyz") { // Create one of each kind of unit, and cache them in a hash registerUnit(new Cartesian3DUnit, gensym("cart3D")); registerUnit(new Cartesian3DUnit, gensym("xyz")); registerUnit(new Cartesian2DUnit, gensym("cart2D")); registerUnit(new Cartesian2DUnit, gensym("xy")); registerUnit(new SphericalUnit, gensym("spherical")); registerUnit(new SphericalUnit, gensym("aed")); registerUnit(new PolarUnit, gensym("polar")); registerUnit(new PolarUnit, gensym("ad")); registerUnit(new OpenGlUnit, gensym("openGL")); registerUnit(new CylindricalUnit, gensym("cylindrical")); registerUnit(new CylindricalUnit, gensym("daz")); // Now that the cache is created, we can create a set of default units setInputUnit(neutralUnit); setOutputUnit(neutralUnit); } PositionDataspace::~PositionDataspace() { ; } <commit_msg>improved the code for spherical, polar, and cylindrical coordinates to the neutral Unit<commit_after>/* * Jamoma DataspaceLib: DistanceDataspace * Copyright 2007, Nils Peters * * License: This code is licensed under the terms of the GNU LGPL * http://www.gnu.org/licenses/lgpl.html * Based on code by Trond Lossius, 2007 and * Jan Schacher / ICST Zurich 2006 * * */ #include "PositionDataspace.h" Cartesian3DUnit::Cartesian3DUnit() : DataspaceUnit("cart3D") {;} Cartesian3DUnit::~Cartesian3DUnit() {;} void Cartesian3DUnit::convertToNeutral(long inputNumArgs, t_atom *inputAtoms, long *outputNumArgs, double *output) { *outputNumArgs = 3; *(output+0) = atom_getfloat(inputAtoms+0); //x *(output+1) = atom_getfloat(inputAtoms+1); //y *(output+2) = atom_getfloat(inputAtoms+2); //z } void Cartesian3DUnit::convertFromNeutral(long inputNumArgs, double *input, long *outputNumArgs, t_atom **outputAtoms) { *outputNumArgs = 3; atom_setfloat(*outputAtoms+0, *(input+0)); atom_setfloat(*outputAtoms+1, *(input+1)); atom_setfloat(*outputAtoms+2, *(input+2)); } /***********************************************************************************************/ Cartesian2DUnit::Cartesian2DUnit() : DataspaceUnit("cart2D") {;} Cartesian2DUnit::~Cartesian2DUnit() {;} void Cartesian2DUnit::convertToNeutral(long inputNumArgs, t_atom *inputAtoms, long *outputNumArgs, double *output) { *outputNumArgs = 2; *(output+0) = atom_getfloat(inputAtoms+0); //x *(output+1) = atom_getfloat(inputAtoms+1); //y } void Cartesian2DUnit::convertFromNeutral(long inputNumArgs, double *input, long *outputNumArgs, t_atom **outputAtoms) { *outputNumArgs = 2; atom_setfloat(*outputAtoms+0, *(input+0)); atom_setfloat(*outputAtoms+1, *(input+1)); } /***********************************************************************************************/ SphericalUnit::SphericalUnit() : DataspaceUnit("spherical") {;} SphericalUnit::~SphericalUnit() {;} void SphericalUnit::convertToNeutral(long inputNumArgs, t_atom *inputAtoms, long *outputNumArgs, double *output) { //double kDegreesToRadians = kDegreesToRadians; double aa = (atom_getfloat(inputAtoms+0)) * kDegreesToRadians; //a double ee = atom_getfloat(inputAtoms+1) * kDegreesToRadians; //e double dd = atom_getfloat(inputAtoms+2); //d *outputNumArgs = 3; double temp = cos(ee) * dd; *(output+0) = sin(aa) * temp; *(output+1) = cos(aa) * temp; *(output+2) = sin(ee) * dd; } void SphericalUnit::convertFromNeutral(long inputNumArgs, double *input, long *outputNumArgs, t_atom **outputAtoms) { double xx = *(input+0); double yy = *(input+1); double zz = *(input+2); double temp = (xx * xx) + (yy * yy); *outputNumArgs = 3; atom_setfloat(*outputAtoms+0, atan2(xx, yy) * kRadiansToDegrees); atom_setfloat(*outputAtoms+1, atan2(zz, (pow((temp), 0.5))) * kRadiansToDegrees); atom_setfloat(*outputAtoms+2, pow((temp + (zz * zz)), 0.5)); } /***********************************************************************************************/ PolarUnit::PolarUnit() : DataspaceUnit("polar") {;} PolarUnit::~PolarUnit() {;} void PolarUnit::convertToNeutral(long inputNumArgs, t_atom *inputAtoms, long *outputNumArgs, double *output) { *outputNumArgs = 2; double aa = (atom_getfloat(inputAtoms+0)) * kDegreesToRadians; //a double dd = atom_getfloat(inputAtoms+1); //d *(output+0) = sin(aa) * dd; //x *(output+1) = cos(aa) * dd; //y } void PolarUnit::convertFromNeutral(long inputNumArgs, double *input, long *outputNumArgs, t_atom **outputAtoms) { double xx = *(input+0); double yy = *(input+1); *outputNumArgs = 2; atom_setfloat(*outputAtoms+0, atan2(xx, yy) * kRadiansToDegrees); //a atom_setfloat(*outputAtoms+1, pow(((xx * xx) + (yy * yy)), 0.5)); //distance } /***********************************************************************************************/ OpenGlUnit::OpenGlUnit() : DataspaceUnit("openGl") {;} OpenGlUnit::~OpenGlUnit() {;} void OpenGlUnit::convertToNeutral(long inputNumArgs, t_atom *inputAtoms, long *outputNumArgs, double *output) { *outputNumArgs = 3; *(output+0) = atom_getfloat(inputAtoms+0); //x *(output+1) = -1.0 * atom_getfloat(inputAtoms+2); //y *(output+2) = atom_getfloat(inputAtoms+1); //z } void OpenGlUnit::convertFromNeutral(long inputNumArgs, double *input, long *outputNumArgs, t_atom **outputAtoms) { *outputNumArgs = 3; atom_setfloat(*outputAtoms+0, *(input+0));//x atom_setfloat(*outputAtoms+1, *(input+2));//y atom_setfloat(*outputAtoms+2, *(input+1) * -1.0);//z } /***********************************************************************************************/ CylindricalUnit::CylindricalUnit() : DataspaceUnit("cylindrical") {;} CylindricalUnit::~CylindricalUnit() {;} void CylindricalUnit::convertToNeutral(long inputNumArgs, t_atom *inputAtoms, long *outputNumArgs, double *output) { // Cylindrical coordinate System (according to ISO 31-11 http://en.wikipedia.org/wiki/ISO_31-11#Coordinate_systems ) = radius azimut hight *outputNumArgs = 3; double dd = atom_getfloat(inputAtoms+0); //d double aa = (atom_getfloat(inputAtoms+1)) * kDegreesToRadians; //a *(output+0) = sin(aa) * dd; //x *(output+1) = cos(aa) * dd; //y *(output+2) = atom_getfloat(inputAtoms+2); //z } void CylindricalUnit::convertFromNeutral(long inputNumArgs, double *input, long *outputNumArgs, t_atom **outputAtoms) { *outputNumArgs = 3; double xx = *(input+0); double yy = *(input+1); // d a z atom_setfloat(*outputAtoms+0, pow(((xx * xx) + (yy * yy)), 0.5)); //distance atom_setfloat(*outputAtoms+1, atan2(xx, yy) * kRadiansToDegrees); //a atom_setfloat(*outputAtoms+2, *(input+2));//z } /***********************************************************************************************/ PositionDataspace::PositionDataspace() : DataspaceLib("position", "xyz") { // Create one of each kind of unit, and cache them in a hash registerUnit(new Cartesian3DUnit, gensym("cart3D")); registerUnit(new Cartesian3DUnit, gensym("xyz")); registerUnit(new Cartesian2DUnit, gensym("cart2D")); registerUnit(new Cartesian2DUnit, gensym("xy")); registerUnit(new SphericalUnit, gensym("spherical")); registerUnit(new SphericalUnit, gensym("aed")); registerUnit(new PolarUnit, gensym("polar")); registerUnit(new PolarUnit, gensym("ad")); registerUnit(new OpenGlUnit, gensym("openGL")); registerUnit(new CylindricalUnit, gensym("cylindrical")); registerUnit(new CylindricalUnit, gensym("daz")); // Now that the cache is created, we can create a set of default units setInputUnit(neutralUnit); setOutputUnit(neutralUnit); } PositionDataspace::~PositionDataspace() { ; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkLBFGSBOptimizer.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information. =========================================================================*/ #ifndef _itkLBFGSBOptimizer_txx #define _itkLBFGSBOptimizer_txx #include "itkLBFGSBOptimizer.h" namespace itk { typedef int integer; typedef double doublereal; typedef int logical; // not bool typedef long int ftnlen; extern "C" void s_copy(char*,char*,ftnlen,ftnlen); extern "C" integer s_cmp(char*,char*,ftnlen,ftnlen); extern "C" int setulb_( integer *n, integer *m, const doublereal *x, doublereal *l, doublereal *u, integer *nbd, doublereal *f, doublereal *g, doublereal *factr, doublereal *pgtol, doublereal *wa, integer *iwa, char *task, integer *iprint, char *csave, logical *lsave, integer *isave, doublereal *dsave, ftnlen task_len, ftnlen csave_len ); /** * Constructor */ LBFGSBOptimizer ::LBFGSBOptimizer() { m_LowerBound = BoundValueType(0); m_UpperBound = BoundValueType(0); m_BoundSelection = BoundSelectionType(0); m_CostFunctionConvergenceFactor = 1e+7; m_ProjectedGradientTolerance = 1e-5; m_MaximumNumberOfIterations = 500; m_MaximumNumberOfEvaluations = 500; m_MaximumNumberOfCorrections = 5; m_CurrentIteration = 0; m_Value = 0.0; m_InfinityNormOfProjectedGradient = 0.0; } /** * Destructor */ LBFGSBOptimizer ::~LBFGSBOptimizer() { } /** * PrintSelf */ void LBFGSBOptimizer ::PrintSelf( std::ostream& os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "LowerBound: " << m_LowerBound << std::endl; os << indent << "UpperBound: " << m_UpperBound << std::endl; os << indent << "BoundSelection: " << m_BoundSelection << std::endl; os << indent << "CostFunctionConvergenceFactor: " << m_CostFunctionConvergenceFactor << std::endl; os << indent << "ProjectedGradientTolerance: " << m_ProjectedGradientTolerance << std::endl; os << indent << "MaximumNumberOfIterations: " << m_MaximumNumberOfIterations << std::endl; os << indent << "MaximumNumberOfEvaluations: " << m_MaximumNumberOfEvaluations << std::endl; os << indent << "MaximumNumberOfCorrections: " << m_MaximumNumberOfCorrections << std::endl; os << indent << "CurrentIteration: " << m_CurrentIteration << std::endl; os << indent << "Value: " << m_Value << std::endl; os << indent << "InfinityNormOfProjectedGradient: " << m_InfinityNormOfProjectedGradient << std::endl; } /** * Set lower bound */ void LBFGSBOptimizer ::SetLowerBound( const BoundValueType& value ) { m_LowerBound = value; this->Modified(); } /** * Get lower bound */ const LBFGSBOptimizer ::BoundValueType & LBFGSBOptimizer ::GetLowerBound() { return m_LowerBound; } /** * Set upper bound */ void LBFGSBOptimizer ::SetUpperBound( const BoundValueType& value ) { m_UpperBound = value; this->Modified(); } /** * Get upper bound */ const LBFGSBOptimizer ::BoundValueType & LBFGSBOptimizer ::GetUpperBound() { return m_UpperBound; } /** * Set bound selection array */ void LBFGSBOptimizer ::SetBoundSelection( const BoundSelectionType& value ) { m_BoundSelection = value; this->Modified(); } /** * Get bound selection array */ const LBFGSBOptimizer ::BoundSelectionType & LBFGSBOptimizer ::GetBoundSelection() { return m_BoundSelection; } /** * Start the optimization */ void LBFGSBOptimizer ::StartOptimization( void ) { /** * Check if all the bounds parameters are the same size as the initial parameters. */ unsigned int numberOfParameters = m_CostFunction->GetNumberOfParameters(); if ( this->GetInitialPosition().Size() < numberOfParameters ) { itkExceptionMacro( << "InitialPosition array does not have sufficient number of elements" ); } if ( m_LowerBound.Size() < numberOfParameters ) { itkExceptionMacro( << "LowerBound array does not have sufficient number of elements" ); } if ( m_UpperBound.Size() < numberOfParameters ) { itkExceptionMacro( << "UppperBound array does not have sufficient number of elements" ); } if ( m_BoundSelection.Size() < numberOfParameters ) { itkExceptionMacro( << "BoundSelection array does not have sufficient number of elements" ); } this->SetCurrentPosition( this->GetInitialPosition() ); /** * Allocate memory for gradient and workspaces */ integer n = numberOfParameters; integer m = m_MaximumNumberOfCorrections; Array<double> gradient( n ); // gradient Array<double> wa( (2*m+4)*n + 12*m*m + 12*m ); // double array workspace Array<integer> iwa( 3* n ); // integer array workspace /** String indicating current job */ char task[60]; s_copy( task, "START", (ftnlen)60, (ftnlen)5); /** Control frequency and type of output */ integer iprint = -1; // no output /** Working string of characters */ char csave[60]; /** Logical working array */ Array<logical> lsave(4); /** Integer working array */ Array<integer> isave(44); /** Double working array */ Array<double> dsave(29); // Initialize unsigned int numberOfEvaluations = 0; m_CurrentIteration = 0; this->InvokeEvent( StartEvent() ); // Iteration looop for ( ;; ) { /** Call the L-BFGS-B code */ setulb_(&n, &m, this->GetCurrentPosition().data_block(), (double *)m_LowerBound.data_block(), (double *)m_UpperBound.data_block(), (int *)m_BoundSelection.data_block(), &m_Value, gradient.data_block(), &m_CostFunctionConvergenceFactor, &m_ProjectedGradientTolerance, wa.data_block(), iwa.data_block(), task, &iprint, csave, lsave.data_block(), isave.data_block(), dsave.data_block(), (ftnlen)60, (ftnlen)60 ) ; /** Check return code. * 'FG_*' = request to evaluate f & g for the current x and continue * 'NEW_X' = return with new iterate - continue the iteration w/out evaluation * 'ERROR' = error in input arguments * 'CONVERGENCE' = convergence has been reached */ if ( s_cmp(task, "FG", (ftnlen)2, (ftnlen)2) == 0 ) { m_CostFunction->GetValueAndDerivative( this->GetCurrentPosition(), m_Value, gradient ); numberOfEvaluations++; } else if ( s_cmp( task, "NEW_X", (ftnlen)5, (ftnlen)5) == 0 ) { m_InfinityNormOfProjectedGradient = dsave[12]; this->InvokeEvent( IterationEvent() ); m_CurrentIteration++; } else { // terminate if( s_cmp( task, "CONVERGENCE: NORM OF PROJECTED GRADIENT <= PGTOL", (ftnlen)48, (ftnlen)48) == 0 ) { itkDebugMacro( << "Convergence: gradient tolerance reached." ); break; } if( s_cmp( task, "CONVERGENCE: REL_REDUCTION_OF_F <= FACTR*EPSMCH", (ftnlen)47, (ftnlen)47) == 0 ) { itkDebugMacro( << "Convergence: function tolerance reached." ); break; } if ( s_cmp( task, "ERROR", (ftnlen)5, (ftnlen)5) == 0 ) { itkDebugMacro( << "Error: dodgy input." ); break; } // unknown error itkDebugMacro( << "Unknown error." ); break; } /** Check if we have exceeded the maximum number of iterations */ if ( numberOfEvaluations > m_MaximumNumberOfEvaluations || m_CurrentIteration > m_MaximumNumberOfIterations ) { itkDebugMacro( << "Exceeded maximum number of iterations." ); break; } } this->InvokeEvent( EndEvent() ); } } // end namespace itk #endif <commit_msg>COMP: warnings.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkLBFGSBOptimizer.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information. =========================================================================*/ #ifndef _itkLBFGSBOptimizer_txx #define _itkLBFGSBOptimizer_txx #include "itkLBFGSBOptimizer.h" namespace itk { typedef int integer; typedef double doublereal; typedef int logical; // not bool typedef long int ftnlen; extern "C" void s_copy(char*,const char*,ftnlen,ftnlen); extern "C" integer s_cmp(char*,const char*,ftnlen,ftnlen); extern "C" int setulb_( integer *n, integer *m, const doublereal *x, doublereal *l, doublereal *u, integer *nbd, doublereal *f, doublereal *g, doublereal *factr, doublereal *pgtol, doublereal *wa, integer *iwa, char *task, integer *iprint, char *csave, logical *lsave, integer *isave, doublereal *dsave, ftnlen task_len, ftnlen csave_len ); /** * Constructor */ LBFGSBOptimizer ::LBFGSBOptimizer() { m_LowerBound = BoundValueType(0); m_UpperBound = BoundValueType(0); m_BoundSelection = BoundSelectionType(0); m_CostFunctionConvergenceFactor = 1e+7; m_ProjectedGradientTolerance = 1e-5; m_MaximumNumberOfIterations = 500; m_MaximumNumberOfEvaluations = 500; m_MaximumNumberOfCorrections = 5; m_CurrentIteration = 0; m_Value = 0.0; m_InfinityNormOfProjectedGradient = 0.0; } /** * Destructor */ LBFGSBOptimizer ::~LBFGSBOptimizer() { } /** * PrintSelf */ void LBFGSBOptimizer ::PrintSelf( std::ostream& os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "LowerBound: " << m_LowerBound << std::endl; os << indent << "UpperBound: " << m_UpperBound << std::endl; os << indent << "BoundSelection: " << m_BoundSelection << std::endl; os << indent << "CostFunctionConvergenceFactor: " << m_CostFunctionConvergenceFactor << std::endl; os << indent << "ProjectedGradientTolerance: " << m_ProjectedGradientTolerance << std::endl; os << indent << "MaximumNumberOfIterations: " << m_MaximumNumberOfIterations << std::endl; os << indent << "MaximumNumberOfEvaluations: " << m_MaximumNumberOfEvaluations << std::endl; os << indent << "MaximumNumberOfCorrections: " << m_MaximumNumberOfCorrections << std::endl; os << indent << "CurrentIteration: " << m_CurrentIteration << std::endl; os << indent << "Value: " << m_Value << std::endl; os << indent << "InfinityNormOfProjectedGradient: " << m_InfinityNormOfProjectedGradient << std::endl; } /** * Set lower bound */ void LBFGSBOptimizer ::SetLowerBound( const BoundValueType& value ) { m_LowerBound = value; this->Modified(); } /** * Get lower bound */ const LBFGSBOptimizer ::BoundValueType & LBFGSBOptimizer ::GetLowerBound() { return m_LowerBound; } /** * Set upper bound */ void LBFGSBOptimizer ::SetUpperBound( const BoundValueType& value ) { m_UpperBound = value; this->Modified(); } /** * Get upper bound */ const LBFGSBOptimizer ::BoundValueType & LBFGSBOptimizer ::GetUpperBound() { return m_UpperBound; } /** * Set bound selection array */ void LBFGSBOptimizer ::SetBoundSelection( const BoundSelectionType& value ) { m_BoundSelection = value; this->Modified(); } /** * Get bound selection array */ const LBFGSBOptimizer ::BoundSelectionType & LBFGSBOptimizer ::GetBoundSelection() { return m_BoundSelection; } /** * Start the optimization */ void LBFGSBOptimizer ::StartOptimization( void ) { /** * Check if all the bounds parameters are the same size as the initial parameters. */ unsigned int numberOfParameters = m_CostFunction->GetNumberOfParameters(); if ( this->GetInitialPosition().Size() < numberOfParameters ) { itkExceptionMacro( << "InitialPosition array does not have sufficient number of elements" ); } if ( m_LowerBound.Size() < numberOfParameters ) { itkExceptionMacro( << "LowerBound array does not have sufficient number of elements" ); } if ( m_UpperBound.Size() < numberOfParameters ) { itkExceptionMacro( << "UppperBound array does not have sufficient number of elements" ); } if ( m_BoundSelection.Size() < numberOfParameters ) { itkExceptionMacro( << "BoundSelection array does not have sufficient number of elements" ); } this->SetCurrentPosition( this->GetInitialPosition() ); /** * Allocate memory for gradient and workspaces */ integer n = numberOfParameters; integer m = m_MaximumNumberOfCorrections; Array<double> gradient( n ); // gradient Array<double> wa( (2*m+4)*n + 12*m*m + 12*m ); // double array workspace Array<integer> iwa( 3* n ); // integer array workspace /** String indicating current job */ char task[60]; s_copy( task, "START", (ftnlen)60, (ftnlen)5); /** Control frequency and type of output */ integer iprint = -1; // no output /** Working string of characters */ char csave[60]; /** Logical working array */ Array<logical> lsave(4); /** Integer working array */ Array<integer> isave(44); /** Double working array */ Array<double> dsave(29); // Initialize unsigned int numberOfEvaluations = 0; m_CurrentIteration = 0; this->InvokeEvent( StartEvent() ); // Iteration looop for ( ;; ) { /** Call the L-BFGS-B code */ setulb_(&n, &m, this->GetCurrentPosition().data_block(), (double *)m_LowerBound.data_block(), (double *)m_UpperBound.data_block(), (int *)m_BoundSelection.data_block(), &m_Value, gradient.data_block(), &m_CostFunctionConvergenceFactor, &m_ProjectedGradientTolerance, wa.data_block(), iwa.data_block(), task, &iprint, csave, lsave.data_block(), isave.data_block(), dsave.data_block(), (ftnlen)60, (ftnlen)60 ) ; /** Check return code. * 'FG_*' = request to evaluate f & g for the current x and continue * 'NEW_X' = return with new iterate - continue the iteration w/out evaluation * 'ERROR' = error in input arguments * 'CONVERGENCE' = convergence has been reached */ if ( s_cmp(task, "FG", (ftnlen)2, (ftnlen)2) == 0 ) { m_CostFunction->GetValueAndDerivative( this->GetCurrentPosition(), m_Value, gradient ); numberOfEvaluations++; } else if ( s_cmp( task, "NEW_X", (ftnlen)5, (ftnlen)5) == 0 ) { m_InfinityNormOfProjectedGradient = dsave[12]; this->InvokeEvent( IterationEvent() ); m_CurrentIteration++; } else { // terminate if( s_cmp( task, "CONVERGENCE: NORM OF PROJECTED GRADIENT <= PGTOL", (ftnlen)48, (ftnlen)48) == 0 ) { itkDebugMacro( << "Convergence: gradient tolerance reached." ); break; } if( s_cmp( task, "CONVERGENCE: REL_REDUCTION_OF_F <= FACTR*EPSMCH", (ftnlen)47, (ftnlen)47) == 0 ) { itkDebugMacro( << "Convergence: function tolerance reached." ); break; } if ( s_cmp( task, "ERROR", (ftnlen)5, (ftnlen)5) == 0 ) { itkDebugMacro( << "Error: dodgy input." ); break; } // unknown error itkDebugMacro( << "Unknown error." ); break; } /** Check if we have exceeded the maximum number of iterations */ if ( numberOfEvaluations > m_MaximumNumberOfEvaluations || m_CurrentIteration > m_MaximumNumberOfIterations ) { itkDebugMacro( << "Exceeded maximum number of iterations." ); break; } } this->InvokeEvent( EndEvent() ); } } // end namespace itk #endif <|endoftext|>
<commit_before>/* Copyright (c) 2011, The Mineserver Project 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 The Mineserver Project 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 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. */ #ifdef WIN32 #include <stdlib.h> #include <conio.h> #include <winsock2.h> typedef int socklen_t; #else #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <unistd.h> #endif #include <errno.h> #include <iostream> #include <fstream> #include <deque> #include <vector> #include <ctime> #include <event.h> #include <sys/stat.h> #include <zlib.h> #include "tools.h" #include "logger.h" #include "constants.h" #include "user.h" #include "map.h" #include "chat.h" #include "nbt.h" #include "mineserver.h" #include "packets.h" #include <algorithm> extern int setnonblock(int fd); void client_callback(int fd, short ev, void *arg) { User *user = (User *)arg; /* std::vector<User *>::const_iterator it = std::find (Mineserver::get()->users().begin(), Mineserver::get()->users().end(), user); if(it == Mineserver::get()->users().end()) { Mineserver::get()->logger()->log(LogType::LOG_INFO, "Sockets", "Using dead player!!!"); return; } */ if(ev & EV_READ) { int read = 1; uint8_t *buf = new uint8_t[2048]; read = recv(fd, (char*)buf, 2048, 0); if(read == 0) { Mineserver::get()->logger()->log(LogType::LOG_INFO, "Sockets", "Socket closed properly"); delete user; user = (User *)1; delete[] buf; return; } if(read == SOCKET_ERROR) { Mineserver::get()->logger()->log(LogType::LOG_INFO, "Sockets", "Socket had no data to read"); delete user; user = (User *)2; delete[] buf; return; } user->lastData = time(NULL); user->buffer.addToRead(buf, read); delete[] buf; user->buffer.reset(); while(user->buffer >> (int8_t&)user->action) { //Variable len package if(Mineserver::get()->packetHandler()->packets[user->action].len == PACKET_VARIABLE_LEN) { //Call specific function int (PacketHandler::*function)(User *) = Mineserver::get()->packetHandler()->packets[user->action].function; bool disconnecting = user->action == 0xFF; int curpos = (Mineserver::get()->packetHandler()->*function)(user); if(curpos == PACKET_NEED_MORE_DATA) { user->waitForData = true; event_set(user->GetEvent(), fd, EV_READ, client_callback, user); event_add(user->GetEvent(), NULL); return; } if(disconnecting) // disconnect -- player gone { delete user; user = (User *)4; return; } } else if(Mineserver::get()->packetHandler()->packets[user->action].len == PACKET_DOES_NOT_EXIST) { printf("Unknown action: 0x%x\n", user->action); delete user; user = (User *)3; return; } else { if(!user->buffer.haveData(Mineserver::get()->packetHandler()->packets[user->action].len)) { user->waitForData = true; event_set(user->GetEvent(), fd, EV_READ, client_callback, user); event_add(user->GetEvent(), NULL); return; } //Call specific function int (PacketHandler::*function)(User *) = Mineserver::get()->packetHandler()->packets[user->action].function; (Mineserver::get()->packetHandler()->*function)(user); } } //End while } int writeLen = user->buffer.getWriteLen(); if(writeLen) { int written = send(fd, (char*)user->buffer.getWrite(), writeLen, 0); if(written == SOCKET_ERROR) { #ifdef WIN32 #define ERROR_NUMBER WSAGetLastError() if((errno != WSATRY_AGAIN && errno != WSAEINTR)) #else #define ERROR_NUMBER errno if((errno != EAGAIN && errno != EINTR)) #endif { Mineserver::get()->logger()->log(LogType::LOG_ERROR, "Socket", "Error writing to client, tried to write " + dtos(writeLen) + " bytes, code: " + dtos(ERROR_NUMBER)); delete user; user = (User *)5; return; } else { //user->write_err_count++; } } else { user->buffer.clearWrite(written); //user->write_err_count=0; } if(user->buffer.getWriteLen()) { event_set(user->GetEvent(), fd, EV_WRITE|EV_READ, client_callback, user); event_add(user->GetEvent(), NULL); return; } } event_set(user->GetEvent(), fd, EV_READ, client_callback, user); event_add(user->GetEvent(), NULL); } void accept_callback(int fd, short ev, void *arg) { int client_fd; struct sockaddr_in client_addr; socklen_t client_len = sizeof(client_addr); client_fd = accept(fd, (struct sockaddr *)&client_addr, &client_len); if(client_fd < 0) { LOGLF("Client: accept() failed"); return; } User *client = new User(client_fd, generateEID()); setnonblock(client_fd); event_set(client->GetEvent(), client_fd,EV_WRITE|EV_READ, client_callback, client); event_add(client->GetEvent(), NULL); } <commit_msg>added define for linux<commit_after>/* Copyright (c) 2011, The Mineserver Project 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 The Mineserver Project 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 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. */ #ifdef WIN32 #include <stdlib.h> #include <conio.h> #include <winsock2.h> typedef int socklen_t; #else #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <unistd.h> #endif #include <errno.h> #include <iostream> #include <fstream> #include <deque> #include <vector> #include <ctime> #include <event.h> #include <sys/stat.h> #include <zlib.h> #include "tools.h" #include "logger.h" #include "constants.h" #include "user.h" #include "map.h" #include "chat.h" #include "nbt.h" #include "mineserver.h" #include "packets.h" #include <algorithm> extern int setnonblock(int fd); #ifndef WIN32 #define SOCKET_ERROR -1 #endif void client_callback(int fd, short ev, void *arg) { User *user = (User *)arg; /* std::vector<User *>::const_iterator it = std::find (Mineserver::get()->users().begin(), Mineserver::get()->users().end(), user); if(it == Mineserver::get()->users().end()) { Mineserver::get()->logger()->log(LogType::LOG_INFO, "Sockets", "Using dead player!!!"); return; } */ if(ev & EV_READ) { int read = 1; uint8_t *buf = new uint8_t[2048]; read = recv(fd, (char*)buf, 2048, 0); if(read == 0) { Mineserver::get()->logger()->log(LogType::LOG_INFO, "Sockets", "Socket closed properly"); delete user; user = (User *)1; delete[] buf; return; } if(read == SOCKET_ERROR) { Mineserver::get()->logger()->log(LogType::LOG_INFO, "Sockets", "Socket had no data to read"); delete user; user = (User *)2; delete[] buf; return; } user->lastData = time(NULL); user->buffer.addToRead(buf, read); delete[] buf; user->buffer.reset(); while(user->buffer >> (int8_t&)user->action) { //Variable len package if(Mineserver::get()->packetHandler()->packets[user->action].len == PACKET_VARIABLE_LEN) { //Call specific function int (PacketHandler::*function)(User *) = Mineserver::get()->packetHandler()->packets[user->action].function; bool disconnecting = user->action == 0xFF; int curpos = (Mineserver::get()->packetHandler()->*function)(user); if(curpos == PACKET_NEED_MORE_DATA) { user->waitForData = true; event_set(user->GetEvent(), fd, EV_READ, client_callback, user); event_add(user->GetEvent(), NULL); return; } if(disconnecting) // disconnect -- player gone { delete user; user = (User *)4; return; } } else if(Mineserver::get()->packetHandler()->packets[user->action].len == PACKET_DOES_NOT_EXIST) { printf("Unknown action: 0x%x\n", user->action); delete user; user = (User *)3; return; } else { if(!user->buffer.haveData(Mineserver::get()->packetHandler()->packets[user->action].len)) { user->waitForData = true; event_set(user->GetEvent(), fd, EV_READ, client_callback, user); event_add(user->GetEvent(), NULL); return; } //Call specific function int (PacketHandler::*function)(User *) = Mineserver::get()->packetHandler()->packets[user->action].function; (Mineserver::get()->packetHandler()->*function)(user); } } //End while } int writeLen = user->buffer.getWriteLen(); if(writeLen) { int written = send(fd, (char*)user->buffer.getWrite(), writeLen, 0); if(written == SOCKET_ERROR) { #ifdef WIN32 #define ERROR_NUMBER WSAGetLastError() if((errno != WSATRY_AGAIN && errno != WSAEINTR)) #else #define ERROR_NUMBER errno if((errno != EAGAIN && errno != EINTR)) #endif { Mineserver::get()->logger()->log(LogType::LOG_ERROR, "Socket", "Error writing to client, tried to write " + dtos(writeLen) + " bytes, code: " + dtos(ERROR_NUMBER)); delete user; user = (User *)5; return; } else { //user->write_err_count++; } } else { user->buffer.clearWrite(written); //user->write_err_count=0; } if(user->buffer.getWriteLen()) { event_set(user->GetEvent(), fd, EV_WRITE|EV_READ, client_callback, user); event_add(user->GetEvent(), NULL); return; } } event_set(user->GetEvent(), fd, EV_READ, client_callback, user); event_add(user->GetEvent(), NULL); } void accept_callback(int fd, short ev, void *arg) { int client_fd; struct sockaddr_in client_addr; socklen_t client_len = sizeof(client_addr); client_fd = accept(fd, (struct sockaddr *)&client_addr, &client_len); if(client_fd < 0) { LOGLF("Client: accept() failed"); return; } User *client = new User(client_fd, generateEID()); setnonblock(client_fd); event_set(client->GetEvent(), client_fd,EV_WRITE|EV_READ, client_callback, client); event_add(client->GetEvent(), NULL); } <|endoftext|>
<commit_before>#include <iostream> #include <chrono> #include <thread> #include <string> #include <fstream> #include <sstream> const std::string NETWORK_IF = "eth0"; using namespace std; int main() { while (true) { // Current point in time as reference const auto date = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::system_clock::now().time_since_epoch()).count(); // Steady clock timestamp for robust time-average calculation const auto steady = std::chrono::duration_cast<std::chrono::microseconds>( std::chrono::steady_clock::now().time_since_epoch()).count(); // CPU statistics unsigned long long int cpu_user = 0; unsigned long long int cpu_nice = 0; unsigned long long int cpu_system = 0; unsigned long long int cpu_idle = 0; unsigned long long int cpu_iowait = 0; unsigned long long int cpu_irq = 0; unsigned long long int cpu_softirq = 0; unsigned long long int cpu_steal = 0; unsigned long long int cpu_guest = 0; unsigned long long int cpu_guest_nice = 0; { ifstream in("/proc/stat"); string line; getline(in, line); istringstream l(line); string dump; l >> dump; l >> cpu_user; l >> cpu_nice; l >> cpu_system; l >> cpu_idle; l >> cpu_iowait; l >> cpu_irq; l >> cpu_softirq; l >> cpu_steal; l >> cpu_guest; l >> cpu_guest_nice; } // Memory usage unsigned long long int memory_total = 0; unsigned long long int memory_used = 0; unsigned long long int swap_total = 0; unsigned long long int swap_used = 0; { ifstream in("/proc/meminfo"); unsigned long long int memory_free = 0; unsigned long long int buffers = 0; unsigned long long int cached = 0; unsigned long long int swap_free = 0; for (string line; getline(in, line); ) { istringstream l(line); string type; l >> type; if (type == "MemTotal:") { l >> memory_total; } else if (type == "MemFree:") { l >> memory_free; } else if (type == "Buffers:") { l >> buffers; } else if (type == "Cached:") { l >> cached; } else if (type == "SwapTotal:") { l >> swap_total; } else if (type == "SwapFree:") { l >> swap_free; } } memory_used = memory_total - memory_free - buffers - cached; swap_used = swap_total - swap_free; memory_total *= 1024; memory_used *= 1024; swap_total *= 1024; swap_used *= 1024; } // Bytes received/sent on NETWORK_IF unsigned long long int network_received = 0; unsigned long long int network_sent = 0; { ifstream in("/proc/net/dev"); for (string line; getline(in, line); ) { istringstream l(line); string interface; l >> interface; if (interface == NETWORK_IF + ":") { l >> network_received; for (int i = 0; i < 8; i++) { l >> network_sent; } break; } } } // Print to stdout cout << date << " " << steady << " " << cpu_user << " " << cpu_nice << " " << cpu_system << " " << cpu_idle << " " << cpu_iowait << " " << cpu_irq << " " << cpu_softirq << " " << cpu_steal << " " << cpu_guest << " " << cpu_guest_nice << " " << memory_total << " " << memory_used << " " << swap_total << " " << swap_used << " " << network_received << " " << network_sent << endl; std::this_thread::sleep_for(std::chrono::seconds(1)); } } <commit_msg>Add usage information, add rudimentary command line argument parsing<commit_after>#include <cstdlib> #include <iostream> #include <chrono> #include <thread> #include <string> #include <fstream> #include <sstream> #include <getopt.h> const std::string DEFAULT_NETWORK_INTERFACE = "eth0"; const int DEFAULT_PERIOD = 1; using namespace std; namespace { struct CommandLineArguments { string network_interface = DEFAULT_NETWORK_INTERFACE; int period = DEFAULT_PERIOD; }; } void usage(std::ostream& os = std::cerr) { os << "usage: sss-mon [-f] [-h] [-i INTERFACE] [-p PERIOD]\n" << "\n" << "sss-mon gathers information on the current CPU load, memory usage, \n" << "and network traffic and prints it to stdout. Once started, it runs \n" << "continuously until killed.\n" << "\n" << "optional arguments:\n" << " -f, --field-names Print space-separated list of field names\n" << " and exit.\n" << " -h, --help Show this help message and exit.\n" << " -i, --network-interface INTERFACE\n" << " Gather traffic statistics for the given\n" << " network interface. INTERFACE must be a valid\n" << " interface in '/proc/net/dev' (default: " << DEFAULT_NETWORK_INTERFACE << ").\n" << " -p, --period PERIOD Set sampling period (in seconds). Must be a\n" << " non-negative integer value (default: " << DEFAULT_PERIOD << ").\n" << "\n" << "For each sample, a space-seperated list of the following fields is\n" << "printed to stdout and terminated by a newline character (\\n):\n" << " date Unix timestamp in milliseconds.\n" << " steady A steady timestamp (not necessarily since\n" << " Unix epoch) for robust time-average \n" << " calculations in microseconds.\n" << " cpu_user CPU time spent in user mode.\n" << " cpu_nice CPU time spent in user mode with low \n" << " priority (nice).\n" << " cpu_system CPU time spent in system mode.\n" << " cpu_idle CPU time spent in the idle task.\n" << " cpu_iowait CPU time waiting for I/O to complete.\n" << " cpu_irq CPU time servicing interrupts.\n" << " cpu_softirq CPU time ervicing softirqs.\n" << " cpu_steal CPU stolen time, which is the time spent in\n" << " other operating systems when running in a \n" << " virtualized environment.\n" << " cpu_guest CPU time spent running a virtual CPU for \n" << " guest operating systems under the control of\n" << " the Linux kernel.\n" << " cpu_guest_nice CPU time spent running a niced guest \n" << " (virtual CPU for guest operating systems\n" << " under the control of the Linux kernel).\n" << " memory_total Total usable RAM (in bytes).\n" << " memory_used Memory currently in use (in bytes).\n" << " swap_total Total amount of swap space (in bytes).\n" << " swap_used Swap space currently in use (in bytes).\n" << " network_received Total bytes received (in bytes).\n" << " network_sent Total bytes sent (in bytes).\n" << "\n" << "The recorded information is gathered from the 'proc' filesystem (see\n" << "also 'man proc'). CPU data is from '/proc/stat', memory data is from\n" << "'/proc/meminfo', and network data is from '/proc/net/dev'.\n"; os.flush(); } int main(int argc, char* argv[]) { // Parse command line options CommandLineArguments args; while (true) { // Create structure with long options static struct option long_options[] = { {"field-names", no_argument, nullptr, 'f'}, {"help", no_argument, nullptr, 'h'}, {"network-interface", required_argument, nullptr, 'i'}, {"period", required_argument, nullptr, 'p'}, {nullptr, 0, nullptr, 0} }; // Get next argument const int c = getopt_long(argc, argv, "hl:i:p:", long_options, nullptr); // Break if end of options is reached if (c == -1) { break; } // Parse arguments switch (c) { case 'f': { exit(0); } case 'h': { usage(); exit(0); } case 'i': { args.network_interface = optarg; break; } case 'p': { stringstream ss(optarg); cout << "jo" << endl; ss >> args.period; cout << args.period << endl; cout << "man" << endl; } case '?': { usage(); cout << "?" << endl; exit(2); break; } default: { cerr << "error: unknown error while parsing command line arguments" << endl; exit(1); } } } cout << "Network interface: " << args.network_interface << endl; cout << "Period: " << args.period << endl; return 0; int c, verbose_flag; while (1) { static struct option long_options[] = { /* These options set a flag. */ {"verbose", no_argument, &verbose_flag, 1}, {"brief", no_argument, &verbose_flag, 0}, /* These options don’t set a flag. We distinguish them by their indices. */ {"add", no_argument, 0, 'a'}, {"append", no_argument, 0, 'b'}, {"delete", required_argument, 0, 'd'}, {"create", required_argument, 0, 'c'}, {"file", required_argument, 0, 'f'}, {0, 0, 0, 0} }; /* getopt_long stores the option index here. */ int option_index = 0; c = getopt_long (argc, argv, "abc:d:f:", long_options, &option_index); /* Detect the end of the options. */ if (c == -1) break; switch (c) { case 0: /* If this option set a flag, do nothing else now. */ if (long_options[option_index].flag != 0) break; printf ("option %s", long_options[option_index].name); if (optarg) printf (" with arg %s", optarg); printf ("\n"); break; case 'a': puts ("option -a\n"); break; case 'b': puts ("option -b\n"); break; case 'c': printf ("option -c with value `%s'\n", optarg); break; case 'd': printf ("option -d with value `%s'\n", optarg); break; case 'f': printf ("option -f with value `%s'\n", optarg); break; case '?': /* getopt_long already printed an error message. */ break; default: abort (); } } /* Instead of reporting ‘--verbose’ and ‘--brief’ as they are encountered, we report the final status resulting from them. */ if (verbose_flag) puts ("verbose flag is set"); /* Print any remaining command line arguments (not options). */ if (optind < argc) { printf ("non-option ARGV-elements: "); while (optind < argc) printf ("%s ", argv[optind++]); putchar ('\n'); } return 0; while (true) { // Current point in time as reference const auto date = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::system_clock::now().time_since_epoch()).count(); // Steady clock timestamp for robust time-average calculation const auto steady = std::chrono::duration_cast<std::chrono::microseconds>( std::chrono::steady_clock::now().time_since_epoch()).count(); // CPU statistics unsigned long long int cpu_user = 0; unsigned long long int cpu_nice = 0; unsigned long long int cpu_system = 0; unsigned long long int cpu_idle = 0; unsigned long long int cpu_iowait = 0; unsigned long long int cpu_irq = 0; unsigned long long int cpu_softirq = 0; unsigned long long int cpu_steal = 0; unsigned long long int cpu_guest = 0; unsigned long long int cpu_guest_nice = 0; { ifstream in("/proc/stat"); string line; getline(in, line); istringstream l(line); string dump; l >> dump; l >> cpu_user; l >> cpu_nice; l >> cpu_system; l >> cpu_idle; l >> cpu_iowait; l >> cpu_irq; l >> cpu_softirq; l >> cpu_steal; l >> cpu_guest; l >> cpu_guest_nice; } // Memory usage unsigned long long int memory_total = 0; unsigned long long int memory_used = 0; unsigned long long int swap_total = 0; unsigned long long int swap_used = 0; { ifstream in("/proc/meminfo"); unsigned long long int memory_free = 0; unsigned long long int buffers = 0; unsigned long long int cached = 0; unsigned long long int swap_free = 0; for (string line; getline(in, line); ) { istringstream l(line); string type; l >> type; if (type == "MemTotal:") { l >> memory_total; } else if (type == "MemFree:") { l >> memory_free; } else if (type == "Buffers:") { l >> buffers; } else if (type == "Cached:") { l >> cached; } else if (type == "SwapTotal:") { l >> swap_total; } else if (type == "SwapFree:") { l >> swap_free; } } memory_used = memory_total - memory_free - buffers - cached; swap_used = swap_total - swap_free; memory_total *= 1024; memory_used *= 1024; swap_total *= 1024; swap_used *= 1024; } // Bytes received/sent on network interface unsigned long long int network_received = 0; unsigned long long int network_sent = 0; { ifstream in("/proc/net/dev"); for (string line; getline(in, line); ) { istringstream l(line); string interface; l >> interface; if (interface == DEFAULT_NETWORK_INTERFACE + ":") { l >> network_received; for (int i = 0; i < 8; i++) { l >> network_sent; } break; } } } // Print to stdout cout << date << " " << steady << " " << cpu_user << " " << cpu_nice << " " << cpu_system << " " << cpu_idle << " " << cpu_iowait << " " << cpu_irq << " " << cpu_softirq << " " << cpu_steal << " " << cpu_guest << " " << cpu_guest_nice << " " << memory_total << " " << memory_used << " " << swap_total << " " << swap_used << " " << network_received << " " << network_sent << endl; std::this_thread::sleep_for(std::chrono::seconds(1)); } } <|endoftext|>
<commit_before>/* Start edit with Emacs Aris Bezas */ #include <string> using namespace std; #include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ //ofSetVerticalSync(true); ofSetFrameRate(30); camera.setDistance(400); ofSetCircleResolution(3); cout << "listening for osc messages on port " << 12345 << "\n"; receiver.setup( 12345 ); current_msg_string = 0; lenna.loadImage("lenna.png"); bDrawLenna = false; bShowHelp = true; myFbo.allocate(1440,900); myGlitch.setup(&myFbo); _mapping = new ofxMtlMapping2D(); _mapping->init(ofGetWidth(), ofGetHeight(), "mapping/xml/shapes.xml", "mapping/controls/mapping.xml"); for (int i=0; i<NUM_VIDEOS; i++) { string tempInt; stringstream convert; // stringstream used for the conversion convert << i;//add the value of Number to the characters in the stream tempInt = convert.str(); string tempVideoDir = "video/256g/" + tempInt + ".mp4"; video[i].loadMovie(tempVideoDir); video[i].setVolume(0); videoPlay[i] = false; video[i].play(); cout << "video[" << i << "]:frames: " << video[i].getTotalNumFrames() << ",framerate:" << video[i].getTotalNumFrames()/video[i].getDuration() <<endl; } } //-------------------------------------------------------------- void testApp::update(){ _mapping->update(); ofBackground(0, 0, 0); for ( int i=0; i<NUM_MSG_STRINGS; i++ ) { if ( timers[i] < ofGetElapsedTimef() ) msg_strings[i] = ""; } // check for waiting messages while( receiver.hasWaitingMessages() ) { ofxOscMessage m; receiver.getNextMessage( &m ); if ( m.getAddress() == "/projection" ) { for (int i = 0; i < NUM_PROJECTION; i++) { videoProjection[i] = false; } for (int i = 0; i < NUM_VIDEOS; i++) { videoPlay[i] = false; } videoProjection[0] = true; videoPlay[0] = true; for (int i = 1; i < m.getNumArgs(); i++) { if(m.getArgAsInt32(i) != 0) { videoID[i] = m.getArgAsInt32(i); videoProjection[i] = true; videoPlay[m.getArgAsInt32(i)] = true; } } } if ( m.getAddress() == "state" ) { if(m.getArgAsString(0) == "main") { _mapping->init(ofGetWidth(), ofGetHeight(), "mapping/xml/shapes.xml", "mapping/controls/mapping.xml"); } else { string tempVideoDir = "mapping/xml/state_" + m.getArgAsString(0) + ".xml"; _mapping->init(ofGetWidth(), ofGetHeight(), tempVideoDir, "mapping/controls/mapping.xml"); } } if ( m.getAddress() == "/test" ) { cout << "OK" << endl; } if ( m.getAddress() == "videoPos" ) { video[m.getArgAsInt32(0)].setFrame(m.getArgAsInt32(0)); } if ( m.getAddress() == "/videoSec" ) { video[m.getArgAsInt32(0)].setFrame(m.getArgAsInt32(1)*24);} if ( m.getAddress() == "/videoSpeed" ) { video[m.getArgAsInt32(0)].setSpeed(m.getArgAsInt32(1)); } if ( m.getAddress() == "filter" ) { switch ( m.getArgAsInt32(0) ) { case 0: myGlitch.setFx(OFXPOSTGLITCH_CONVERGENCE , false); myGlitch.setFx(OFXPOSTGLITCH_SHAKER , false); myGlitch.setFx(OFXPOSTGLITCH_CUTSLIDER , false); myGlitch.setFx(OFXPOSTGLITCH_CR_HIGHCONTRAST , false); myGlitch.setFx(OFXPOSTGLITCH_CR_BLUERAISE , false); myGlitch.setFx(OFXPOSTGLITCH_CR_REDRAISE , false); break; case 1: myGlitch.setFx(OFXPOSTGLITCH_CONVERGENCE, true);break; case 2: myGlitch.setFx(OFXPOSTGLITCH_SHAKER, true);break; case 3: myGlitch.setFx(OFXPOSTGLITCH_CUTSLIDER, true);break; case 4: myGlitch.setFx(OFXPOSTGLITCH_CR_HIGHCONTRAST,true);break; case 5: myGlitch.setFx(OFXPOSTGLITCH_CR_BLUERAISE, true);break; case 6: myGlitch.setFx(OFXPOSTGLITCH_CR_REDRAISE, true);break; default: break; } } } for (int i = 0; i < NUM_VIDEOS; i++) { if(videoPlay[i]) {video[i].update();} } } //-------------------------------------------------------------- void testApp::draw(){ _mapping->bind(); myFbo.begin(); myGlitch.generateFx(); ofBackground(0,0,0); ofSetHexColor(0xFFFFFF); if(videoProjection[0]) video[0].draw( 50, 10, 640, 480); if(videoProjection[1]) video[videoID[1]].draw( 50, 500, 256, 144); if(videoProjection[2]) video[videoID[2]].draw( 50, 650, 256, 144); if(videoProjection[3]) video[videoID[3]].draw( 310, 500, 256, 144); if(videoProjection[4]) video[videoID[4]].draw( 310, 650, 256, 144); if(videoProjection[5]) video[videoID[5]].draw( 580, 500, 256, 144); if(videoProjection[6]) video[videoID[6]].draw( 580, 650, 256, 144); if(videoProjection[7]) video[videoID[7]].draw( 850, 50, 256, 144); if(videoProjection[8]) video[videoID[8]].draw( 850, 200, 256, 144); if(videoProjection[9]) video[videoID[9]].draw( 850, 350, 256, 144); if(videoProjection[10]) video[videoID[10]].draw( 850, 500, 256, 144); myFbo.end(); myFbo.draw(0, 0); _mapping->unbind(); _mapping->draw(); } //-------------------------------------------------------------- void testApp::keyPressed(int key){ if (key == '1') myGlitch.setFx(OFXPOSTGLITCH_CONVERGENCE, true); if (key == '2') myGlitch.setFx(OFXPOSTGLITCH_GLOW , true); if (key == '3') myGlitch.setFx(OFXPOSTGLITCH_SHAKER , true); if (key == '4') myGlitch.setFx(OFXPOSTGLITCH_CUTSLIDER , true); if (key == '5') myGlitch.setFx(OFXPOSTGLITCH_TWIST , true); if (key == '6') myGlitch.setFx(OFXPOSTGLITCH_OUTLINE , true); if (key == '7') myGlitch.setFx(OFXPOSTGLITCH_NOISE , true); if (key == '8') myGlitch.setFx(OFXPOSTGLITCH_SLITSCAN , true); if (key == '9') myGlitch.setFx(OFXPOSTGLITCH_SWELL , true); if (key == '0') myGlitch.setFx(OFXPOSTGLITCH_INVERT , true); if (key == 'q') myGlitch.setFx(OFXPOSTGLITCH_CR_HIGHCONTRAST , true); if (key == 'w') myGlitch.setFx(OFXPOSTGLITCH_CR_BLUERAISE , true); if (key == 'e') myGlitch.setFx(OFXPOSTGLITCH_CR_REDRAISE , true); if (key == 'r') myGlitch.setFx(OFXPOSTGLITCH_CR_GREENRAISE , true); if (key == 't') myGlitch.setFx(OFXPOSTGLITCH_CR_BLUEINVERT , true); if (key == 'y') myGlitch.setFx(OFXPOSTGLITCH_CR_REDINVERT , true); if (key == 'u') myGlitch.setFx(OFXPOSTGLITCH_CR_GREENINVERT , true); if (key == 'l') bDrawLenna ^= true; if (key == 'h') bShowHelp ^= true; if(key == 'f' or key == 'F'){ int previousWindowX, previousWindowY; if(ofGetWindowMode() == 0){ ofSetFullscreen(true); ofBackground(0, 0, 0); }else{ ofSetFullscreen(false); ofBackground(0, 0, 0); } } } //-------------------------------------------------------------- void testApp::keyReleased(int key){ if (key == '1') myGlitch.setFx(OFXPOSTGLITCH_CONVERGENCE, false); if (key == '2') myGlitch.setFx(OFXPOSTGLITCH_GLOW , false); if (key == '3') myGlitch.setFx(OFXPOSTGLITCH_SHAKER , false); if (key == '4') myGlitch.setFx(OFXPOSTGLITCH_CUTSLIDER , false); if (key == '5') myGlitch.setFx(OFXPOSTGLITCH_TWIST , false); if (key == '6') myGlitch.setFx(OFXPOSTGLITCH_OUTLINE , false); if (key == '7') myGlitch.setFx(OFXPOSTGLITCH_NOISE , false); if (key == '8') myGlitch.setFx(OFXPOSTGLITCH_SLITSCAN , false); if (key == '9') myGlitch.setFx(OFXPOSTGLITCH_SWELL , false); if (key == '0') myGlitch.setFx(OFXPOSTGLITCH_INVERT , false); if (key == 'q') myGlitch.setFx(OFXPOSTGLITCH_CR_HIGHCONTRAST , false); if (key == 'w') myGlitch.setFx(OFXPOSTGLITCH_CR_BLUERAISE , false); if (key == 'e') myGlitch.setFx(OFXPOSTGLITCH_CR_REDRAISE , false); if (key == 'r') myGlitch.setFx(OFXPOSTGLITCH_CR_GREENRAISE , false); if (key == 't') myGlitch.setFx(OFXPOSTGLITCH_CR_BLUEINVERT , false); if (key == 'y') myGlitch.setFx(OFXPOSTGLITCH_CR_REDINVERT , false); if (key == 'u') myGlitch.setFx(OFXPOSTGLITCH_CR_GREENINVERT , false); if (key == 'p') _mapping->init(ofGetWidth(), ofGetHeight(), "mapping/xml/state1.xml", "mapping/controls/mapping.xml"); if (key == 'o') _mapping->init(ofGetWidth(), ofGetHeight(), "mapping/xml/state2.xml", "mapping/controls/mapping.xml"); } void testApp::mouseMoved(int x, int y ){} void testApp::mouseDragged(int x, int y, int button){} void testApp::mousePressed(int x, int y, int button){} void testApp::mouseReleased(int x, int y, int button){} void testApp::windowResized(int w, int h){} void testApp::gotMessage(ofMessage msg){} void testApp::dragEvent(ofDragInfo dragInfo){ } <commit_msg>Stem Project saved on: Thu Mar 19 18:23:33 GMT 2015<commit_after>/* Start edit with Emacs the project is hosted at https://github.com/igoumeninja/Stem-Cell-Orchestra-Project Aris Bezas */ #include <string> using namespace std; #include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ //ofSetVerticalSync(true); ofSetFrameRate(30); camera.setDistance(400); ofSetCircleResolution(3); cout << "listening for osc messages on port " << 12345 << "\n"; receiver.setup( 12345 ); current_msg_string = 0; lenna.loadImage("lenna.png"); bDrawLenna = false; bShowHelp = true; myFbo.allocate(1440,900); myGlitch.setup(&myFbo); _mapping = new ofxMtlMapping2D(); _mapping->init(ofGetWidth(), ofGetHeight(), "mapping/xml/shapes.xml", "mapping/controls/mapping.xml"); for (int i=0; i<NUM_VIDEOS; i++) { string tempInt; stringstream convert; // stringstream used for the conversion convert << i;//add the value of Number to the characters in the stream tempInt = convert.str(); string tempVideoDir = "video/256g/" + tempInt + ".mp4"; video[i].loadMovie(tempVideoDir); video[i].setVolume(0); videoPlay[i] = false; video[i].play(); cout << "video[" << i << "]:frames: " << video[i].getTotalNumFrames() << ",framerate:" << video[i].getTotalNumFrames()/video[i].getDuration() <<endl; } } //-------------------------------------------------------------- void testApp::update(){ _mapping->update(); ofBackground(0, 0, 0); for ( int i=0; i<NUM_MSG_STRINGS; i++ ) { if ( timers[i] < ofGetElapsedTimef() ) msg_strings[i] = ""; } // check for waiting messages while( receiver.hasWaitingMessages() ) { ofxOscMessage m; receiver.getNextMessage( &m ); if ( m.getAddress() == "/projection" ) { for (int i = 0; i < NUM_PROJECTION; i++) { videoProjection[i] = false; } for (int i = 0; i < NUM_VIDEOS; i++) { videoPlay[i] = false; } videoProjection[0] = true; videoPlay[0] = true; for (int i = 1; i < m.getNumArgs(); i++) { if(m.getArgAsInt32(i) != 0) { videoID[i] = m.getArgAsInt32(i); videoProjection[i] = true; videoPlay[m.getArgAsInt32(i)] = true; } } } if ( m.getAddress() == "state" ) { if(m.getArgAsString(0) == "main") { _mapping->init(ofGetWidth(), ofGetHeight(), "mapping/xml/shapes.xml", "mapping/controls/mapping.xml"); } else { string tempVideoDir = "mapping/xml/state_" + m.getArgAsString(0) + ".xml"; _mapping->init(ofGetWidth(), ofGetHeight(), tempVideoDir, "mapping/controls/mapping.xml"); } } if ( m.getAddress() == "/test" ) { cout << "OK" << endl; } if ( m.getAddress() == "videoPos" ) { video[m.getArgAsInt32(0)].setFrame(m.getArgAsInt32(0)); } if ( m.getAddress() == "/videoSec" ) { video[m.getArgAsInt32(0)].setFrame(m.getArgAsInt32(1)*24);} if ( m.getAddress() == "/videoSpeed" ) { video[m.getArgAsInt32(0)].setSpeed(m.getArgAsInt32(1)); } if ( m.getAddress() == "filter" ) { switch ( m.getArgAsInt32(0) ) { case 0: myGlitch.setFx(OFXPOSTGLITCH_CONVERGENCE , false); myGlitch.setFx(OFXPOSTGLITCH_SHAKER , false); myGlitch.setFx(OFXPOSTGLITCH_CUTSLIDER , false); myGlitch.setFx(OFXPOSTGLITCH_CR_HIGHCONTRAST , false); myGlitch.setFx(OFXPOSTGLITCH_CR_BLUERAISE , false); myGlitch.setFx(OFXPOSTGLITCH_CR_REDRAISE , false); break; case 1: myGlitch.setFx(OFXPOSTGLITCH_CONVERGENCE, true);break; case 2: myGlitch.setFx(OFXPOSTGLITCH_SHAKER, true);break; case 3: myGlitch.setFx(OFXPOSTGLITCH_CUTSLIDER, true);break; case 4: myGlitch.setFx(OFXPOSTGLITCH_CR_HIGHCONTRAST,true);break; case 5: myGlitch.setFx(OFXPOSTGLITCH_CR_BLUERAISE, true);break; case 6: myGlitch.setFx(OFXPOSTGLITCH_CR_REDRAISE, true);break; default: break; } } } for (int i = 0; i < NUM_VIDEOS; i++) { if(videoPlay[i]) {video[i].update();} } } //-------------------------------------------------------------- void testApp::draw(){ _mapping->bind(); myFbo.begin(); myGlitch.generateFx(); ofBackground(0,0,0); ofSetHexColor(0xFFFFFF); if(videoProjection[0]) video[0].draw( 50, 10, 640, 480); if(videoProjection[1]) video[videoID[1]].draw( 50, 500, 256, 144); if(videoProjection[2]) video[videoID[2]].draw( 50, 650, 256, 144); if(videoProjection[3]) video[videoID[3]].draw( 310, 500, 256, 144); if(videoProjection[4]) video[videoID[4]].draw( 310, 650, 256, 144); if(videoProjection[5]) video[videoID[5]].draw( 580, 500, 256, 144); if(videoProjection[6]) video[videoID[6]].draw( 580, 650, 256, 144); if(videoProjection[7]) video[videoID[7]].draw( 850, 50, 256, 144); if(videoProjection[8]) video[videoID[8]].draw( 850, 200, 256, 144); if(videoProjection[9]) video[videoID[9]].draw( 850, 350, 256, 144); if(videoProjection[10]) video[videoID[10]].draw( 850, 500, 256, 144); myFbo.end(); myFbo.draw(0, 0); _mapping->unbind(); _mapping->draw(); } //-------------------------------------------------------------- void testApp::keyPressed(int key){ if (key == '1') myGlitch.setFx(OFXPOSTGLITCH_CONVERGENCE, true); if (key == '2') myGlitch.setFx(OFXPOSTGLITCH_GLOW , true); if (key == '3') myGlitch.setFx(OFXPOSTGLITCH_SHAKER , true); if (key == '4') myGlitch.setFx(OFXPOSTGLITCH_CUTSLIDER , true); if (key == '5') myGlitch.setFx(OFXPOSTGLITCH_TWIST , true); if (key == '6') myGlitch.setFx(OFXPOSTGLITCH_OUTLINE , true); if (key == '7') myGlitch.setFx(OFXPOSTGLITCH_NOISE , true); if (key == '8') myGlitch.setFx(OFXPOSTGLITCH_SLITSCAN , true); if (key == '9') myGlitch.setFx(OFXPOSTGLITCH_SWELL , true); if (key == '0') myGlitch.setFx(OFXPOSTGLITCH_INVERT , true); if (key == 'q') myGlitch.setFx(OFXPOSTGLITCH_CR_HIGHCONTRAST , true); if (key == 'w') myGlitch.setFx(OFXPOSTGLITCH_CR_BLUERAISE , true); if (key == 'e') myGlitch.setFx(OFXPOSTGLITCH_CR_REDRAISE , true); if (key == 'r') myGlitch.setFx(OFXPOSTGLITCH_CR_GREENRAISE , true); if (key == 't') myGlitch.setFx(OFXPOSTGLITCH_CR_BLUEINVERT , true); if (key == 'y') myGlitch.setFx(OFXPOSTGLITCH_CR_REDINVERT , true); if (key == 'u') myGlitch.setFx(OFXPOSTGLITCH_CR_GREENINVERT , true); if (key == 'l') bDrawLenna ^= true; if (key == 'h') bShowHelp ^= true; if(key == 'f' or key == 'F'){ int previousWindowX, previousWindowY; if(ofGetWindowMode() == 0){ ofSetFullscreen(true); ofBackground(0, 0, 0); }else{ ofSetFullscreen(false); ofBackground(0, 0, 0); } } } //-------------------------------------------------------------- void testApp::keyReleased(int key){ if (key == '1') myGlitch.setFx(OFXPOSTGLITCH_CONVERGENCE, false); if (key == '2') myGlitch.setFx(OFXPOSTGLITCH_GLOW , false); if (key == '3') myGlitch.setFx(OFXPOSTGLITCH_SHAKER , false); if (key == '4') myGlitch.setFx(OFXPOSTGLITCH_CUTSLIDER , false); if (key == '5') myGlitch.setFx(OFXPOSTGLITCH_TWIST , false); if (key == '6') myGlitch.setFx(OFXPOSTGLITCH_OUTLINE , false); if (key == '7') myGlitch.setFx(OFXPOSTGLITCH_NOISE , false); if (key == '8') myGlitch.setFx(OFXPOSTGLITCH_SLITSCAN , false); if (key == '9') myGlitch.setFx(OFXPOSTGLITCH_SWELL , false); if (key == '0') myGlitch.setFx(OFXPOSTGLITCH_INVERT , false); if (key == 'q') myGlitch.setFx(OFXPOSTGLITCH_CR_HIGHCONTRAST , false); if (key == 'w') myGlitch.setFx(OFXPOSTGLITCH_CR_BLUERAISE , false); if (key == 'e') myGlitch.setFx(OFXPOSTGLITCH_CR_REDRAISE , false); if (key == 'r') myGlitch.setFx(OFXPOSTGLITCH_CR_GREENRAISE , false); if (key == 't') myGlitch.setFx(OFXPOSTGLITCH_CR_BLUEINVERT , false); if (key == 'y') myGlitch.setFx(OFXPOSTGLITCH_CR_REDINVERT , false); if (key == 'u') myGlitch.setFx(OFXPOSTGLITCH_CR_GREENINVERT , false); if (key == 'p') _mapping->init(ofGetWidth(), ofGetHeight(), "mapping/xml/state1.xml", "mapping/controls/mapping.xml"); if (key == 'o') _mapping->init(ofGetWidth(), ofGetHeight(), "mapping/xml/state2.xml", "mapping/controls/mapping.xml"); } void testApp::mouseMoved(int x, int y ){} void testApp::mouseDragged(int x, int y, int button){} void testApp::mousePressed(int x, int y, int button){} void testApp::mouseReleased(int x, int y, int button){} void testApp::windowResized(int w, int h){} void testApp::gotMessage(ofMessage msg){} void testApp::dragEvent(ofDragInfo dragInfo){ } <|endoftext|>
<commit_before>#include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ ofBackground(0,0,0); ofSetBackgroundAuto(false); isFullScreen = false; ofSetFrameRate(30); masterCounter = 0; direction = 1; //count up // OSC STUFF receiver.setup(PORT); current_msg_string = 0; mainMix = 0; } //-------------------------------------------------------------- void testApp::update(){ // hide old messages for(int i = 0; i < NUM_MSG_STRINGS; i++){ if(timers[i] < ofGetElapsedTimef()){ msg_strings[i] = ""; } } // check for waiting messages while(receiver.hasWaitingMessages()){ // get the next message ofxOscMessage m; receiver.getNextMessage(&m); // check for mouse moved message if(m.getAddress() == "/main/mix"){ // both the arguments are int32's mainMix = m.getArgAsFloat(0); ofLogNotice("mainMix: "+ofToString(m.getArgAsFloat(0))); } // check for mouse button message else{ // unrecognized message: display on the bottom of the screen string msg_string; msg_string = m.getAddress(); msg_string += ": "; for(int i = 0; i < m.getNumArgs(); i++){ // get the argument type msg_string += m.getArgTypeName(i); msg_string += ":"; // display the argument - make sure we get the right type if(m.getArgType(i) == OFXOSC_TYPE_INT32){ msg_string += ofToString(m.getArgAsInt32(i)); } else if(m.getArgType(i) == OFXOSC_TYPE_FLOAT){ msg_string += ofToString(m.getArgAsFloat(i)); } else if(m.getArgType(i) == OFXOSC_TYPE_STRING){ msg_string += m.getArgAsString(i); } else{ msg_string += "unknown"; } } // add to the list of strings to display msg_strings[current_msg_string] = msg_string; timers[current_msg_string] = ofGetElapsedTimef() + 5.0f; current_msg_string = (current_msg_string + 1) % NUM_MSG_STRINGS; // clear the next line msg_strings[current_msg_string] = ""; } } // FUN STUFF masterCounter+=direction; if (masterCounter > 2000) { direction = -1; } if (masterCounter < -2000) { direction = 1; } } //-------------------------------------------------------------- void testApp::draw(){ //normalize mouse (within the window space... float daMouseX = float(mouseX)/float(ofGetWidth()); float daMouseY = float(mouseY)/ofGetHeight(); // ofLogNotice(ofToString(daMouseX)); //Abstract line stuff for (int i = 0; i < ofGetWidth(); i++) { int r = daMouseX*sin(masterCounter)/4; int g = i/4; int b = daMouseX*daMouseY*i/4; // line start and destination int xStart = i; int yStart = ofGetHeight()/2; int xDest = i*sin(i)*mouseY; int yDest = i*cos(i)*masterCounter; //shake the signal r += r*mainMix; ofSetColor(r, g, b); //Replace this with pixel colors from feed ofLine(xStart, yStart, xDest, yDest); } } //-------------------------------------------------------------- void testApp::keyPressed(int key){ if (key == 'f' || 'F') { isFullScreen = !isFullScreen; ofSetFullscreen(isFullScreen); } } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo){ } <commit_msg>shaking the signal<commit_after>#include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ ofBackground(0,0,0); ofSetBackgroundAuto(false); isFullScreen = false; ofSetFrameRate(30); masterCounter = 0; direction = 1; //count up // OSC STUFF receiver.setup(PORT); current_msg_string = 0; mainMix = 0; } //-------------------------------------------------------------- void testApp::update(){ // hide old messages for(int i = 0; i < NUM_MSG_STRINGS; i++){ if(timers[i] < ofGetElapsedTimef()){ msg_strings[i] = ""; } } // check for waiting messages while(receiver.hasWaitingMessages()){ // get the next message ofxOscMessage m; receiver.getNextMessage(&m); // check for mouse moved message if(m.getAddress() == "/main/mix"){ // both the arguments are int32's mainMix = m.getArgAsFloat(0); ofLogNotice("mainMix: "+ofToString(m.getArgAsFloat(0))); } // check for mouse button message else{ // unrecognized message: display on the bottom of the screen string msg_string; msg_string = m.getAddress(); msg_string += ": "; for(int i = 0; i < m.getNumArgs(); i++){ // get the argument type msg_string += m.getArgTypeName(i); msg_string += ":"; // display the argument - make sure we get the right type if(m.getArgType(i) == OFXOSC_TYPE_INT32){ msg_string += ofToString(m.getArgAsInt32(i)); } else if(m.getArgType(i) == OFXOSC_TYPE_FLOAT){ msg_string += ofToString(m.getArgAsFloat(i)); } else if(m.getArgType(i) == OFXOSC_TYPE_STRING){ msg_string += m.getArgAsString(i); } else{ msg_string += "unknown"; } } // add to the list of strings to display msg_strings[current_msg_string] = msg_string; timers[current_msg_string] = ofGetElapsedTimef() + 5.0f; current_msg_string = (current_msg_string + 1) % NUM_MSG_STRINGS; // clear the next line msg_strings[current_msg_string] = ""; } } // FUN STUFF masterCounter+=direction; if (masterCounter > 2000) { direction = -1; } if (masterCounter < -2000) { direction = 1; } } //-------------------------------------------------------------- void testApp::draw(){ //normalize mouse (within the window space... float daMouseX = float(mouseX)/float(ofGetWidth()); float daMouseY = float(mouseY)/ofGetHeight(); // ofLogNotice(ofToString(daMouseX)); //Abstract line stuff for (int i = 0; i < ofGetWidth(); i++) { // set the color for each line int r = daMouseX*sin(masterCounter)/4; int g = i/4; int b = daMouseX*daMouseY*i/4; // line start and destination int xStart = i; int yStart = ofGetHeight()/2; int xDest = i*sin(i)*mouseY; int yDest = i*cos(i)*masterCounter; //shake the signal if (masterCounter%2 == 0) { yStart += mainMix*30; } else { yStart -= mainMix*30; ofLogNotice("!!!!!"); } xDest += xDest*mainMix; yDest += yDest*mainMix; ofSetColor(r, g, b); //Replace this with pixel colors from feed ofLine(xStart, yStart, xDest, yDest); } } //-------------------------------------------------------------- void testApp::keyPressed(int key){ if (key == 'f' || 'F') { isFullScreen = !isFullScreen; ofSetFullscreen(isFullScreen); } } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo){ } <|endoftext|>
<commit_before>/* This file is part of Zanshin Todo. Copyright 2008 Kevin Ottens <[email protected]> Copyright 2008, 2009 Mario Bensi <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "librarymodel.h" #include <KIcon> #include <KLocale> LibraryModel::LibraryModel(QObject *parent) : QAbstractProxyModel(parent), m_inboxToken(1), m_libraryToken(2), m_tokenShift(m_libraryToken+1), m_type(Projects) { } LibraryModel::~LibraryModel() { } LibraryModel::LibraryType LibraryModel::type() const { return m_type; } void LibraryModel::setType(LibraryType type) { m_type = type; } QModelIndex LibraryModel::index(int row, int column, const QModelIndex &parent) const { if (column!=0) return QModelIndex(); if (parent==QModelIndex()) { switch (row) { case 0: return createIndex(row, column, (void*)m_inboxToken); case 1: return createIndex(row, column, (void*)m_libraryToken); default: return QModelIndex(); } } return mapFromSource(sourceModel()->index(row, column, mapToSource(parent))); } QModelIndex LibraryModel::parent(const QModelIndex &index) const { if (index.column()!=0 || !index.isValid() || isInbox(index) || isLibraryRoot(index)) { return QModelIndex(); } return mapFromSource(sourceModel()->parent(mapToSource(index))); } int LibraryModel::rowCount(const QModelIndex &parent) const { if (parent==QModelIndex()) { return 2; } if (parent.column()!=0) return -1; if (isInbox(parent)) { return 0; } if (isLibraryRoot(parent)) { return sourceModel()->rowCount(); } return sourceModel()->rowCount(mapToSource(parent)); } int LibraryModel::columnCount(const QModelIndex &/*parent*/) const { return 1; } QStringList LibraryModel::mimeTypes() const { return sourceModel()->mimeTypes(); } Qt::DropActions LibraryModel::supportedDropActions() const { return sourceModel()->supportedDropActions(); } Qt::ItemFlags LibraryModel::flags(const QModelIndex &index) const { if (isInbox(index) || isLibraryRoot(index)) { return Qt::ItemIsEnabled|Qt::ItemIsSelectable; } return QAbstractProxyModel::flags(index); } QMimeData *LibraryModel::mimeData(const QModelIndexList &indexes) const { QModelIndexList sourceIndexes; foreach (const QModelIndex &proxyIndex, indexes) { sourceIndexes << mapToSource(proxyIndex); } return sourceModel()->mimeData(sourceIndexes); } bool LibraryModel::dropMimeData(const QMimeData *mimeData, Qt::DropAction action, int row, int column, const QModelIndex &parent) { QModelIndex sourceParent = mapToSource(parent); return sourceModel()->dropMimeData(mimeData, action, row, column, sourceParent); } QVariant LibraryModel::data(const QModelIndex &index, int role) const { if (index.column()!=0 || !index.isValid()) return QVariant(); if (isInbox(index)) { switch (role) { case Qt::DisplayRole: switch (m_type) { case Contexts: return i18n("No Context"); default: return i18n("Inbox"); } case Qt::DecorationRole: return KIcon("mail-folder-inbox"); default: return QVariant(); } } if (isLibraryRoot(index)) { switch (role) { case Qt::DisplayRole: switch (m_type) { case Contexts: return i18n("Contexts"); default: return i18n("Library"); } case Qt::DecorationRole: return KIcon("document-multiple"); default: return QVariant(); } } return QAbstractProxyModel::data(index, role); } QVariant LibraryModel::headerData(int section, Qt::Orientation orientation, int role) const { return sourceModel()->headerData(section, orientation, role); } bool LibraryModel::isInbox(const QModelIndex &index) const { return index.internalId()==m_inboxToken; } bool LibraryModel::isLibraryRoot(const QModelIndex &index) const { return index.internalId()==m_libraryToken; } QModelIndex LibraryModel::mapToSource(const QModelIndex &proxyIndex) const { if (proxyIndex.column()!=0 || isInbox(proxyIndex) || isLibraryRoot(proxyIndex)) { return QModelIndex(); } return m_sourceIndexesList[proxyIndex.internalId()-m_tokenShift]; } QModelIndex LibraryModel::mapFromSource(const QModelIndex &sourceIndex) const { if (!sourceIndex.isValid()) { return index(1, 0); // Index of the library item } else { qint64 indexOf = m_sourceIndexesList.indexOf(sourceIndex); if (indexOf==-1) { indexOf = m_sourceIndexesList.size(); m_sourceIndexesList << sourceIndex; } return createIndex(sourceIndex.row(), sourceIndex.column(), (void*)(indexOf+m_tokenShift)); } } void LibraryModel::setSourceModel(QAbstractItemModel *source) { if (sourceModel()) { disconnect(sourceModel()); } QAbstractProxyModel::setSourceModel(source); connect(sourceModel(), SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(onSourceDataChanged(const QModelIndex&, const QModelIndex&))); connect(sourceModel(), SIGNAL(rowsAboutToBeInserted(const QModelIndex&, int, int)), this, SLOT(onSourceRowsAboutToBeInserted(const QModelIndex&, int, int))); connect(sourceModel(), SIGNAL(rowsInserted(const QModelIndex&, int, int)), this, SLOT(onSourceRowsInserted(const QModelIndex&, int, int))); connect(sourceModel(), SIGNAL(rowsAboutToBeRemoved(const QModelIndex&, int, int)), this, SLOT(onSourceRowsAboutToBeRemoved(const QModelIndex&, int, int))); connect(sourceModel(), SIGNAL(rowsRemoved(const QModelIndex&, int, int)), this, SLOT(onSourceRowsRemoved(const QModelIndex&, int, int))); connect(sourceModel(), SIGNAL(layoutAboutToBeChanged()), this, SIGNAL(layoutAboutToBeChanged())); connect(sourceModel(), SIGNAL(layoutChanged()), this, SLOT(onSourceLayoutChanged())); } void LibraryModel::onSourceDataChanged(const QModelIndex &begin, const QModelIndex &end) { emit dataChanged(mapFromSource(begin), mapFromSource(end)); } void LibraryModel::onSourceRowsAboutToBeInserted(const QModelIndex &sourceIndex, int begin, int end) { m_sourceIndexesList << sourceIndex; beginInsertRows(mapFromSource(sourceIndex), begin, end); } void LibraryModel::onSourceRowsInserted(const QModelIndex &sourceIndex, int begin, int end) { for (int i=begin; i<=end; i++) { QModelIndex child = sourceModel()->index(i, 0, sourceIndex); m_sourceIndexesList << child; } endInsertRows(); } void LibraryModel::onSourceRowsAboutToBeRemoved(const QModelIndex &sourceIndex, int begin, int end) { beginRemoveRows(mapFromSource(sourceIndex), begin, end); for (int i=begin; i<=end; i++) { QModelIndex child = sourceModel()->index(i, 0, sourceIndex); m_sourceIndexesList.removeAll(child); } } void LibraryModel::onSourceRowsRemoved(const QModelIndex &/*sourceIndex*/, int /*begin*/, int /*end*/) { endRemoveRows(); } void LibraryModel::onSourceLayoutChanged() { m_sourceIndexesList.clear(); emit layoutChanged(); } <commit_msg>Be extra paranoid when mapping an index to source.<commit_after>/* This file is part of Zanshin Todo. Copyright 2008 Kevin Ottens <[email protected]> Copyright 2008, 2009 Mario Bensi <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "librarymodel.h" #include <KIcon> #include <KLocale> LibraryModel::LibraryModel(QObject *parent) : QAbstractProxyModel(parent), m_inboxToken(1), m_libraryToken(2), m_tokenShift(m_libraryToken+1), m_type(Projects) { } LibraryModel::~LibraryModel() { } LibraryModel::LibraryType LibraryModel::type() const { return m_type; } void LibraryModel::setType(LibraryType type) { m_type = type; } QModelIndex LibraryModel::index(int row, int column, const QModelIndex &parent) const { if (column!=0) return QModelIndex(); if (parent==QModelIndex()) { switch (row) { case 0: return createIndex(row, column, (void*)m_inboxToken); case 1: return createIndex(row, column, (void*)m_libraryToken); default: return QModelIndex(); } } return mapFromSource(sourceModel()->index(row, column, mapToSource(parent))); } QModelIndex LibraryModel::parent(const QModelIndex &index) const { if (index.column()!=0 || !index.isValid() || isInbox(index) || isLibraryRoot(index)) { return QModelIndex(); } return mapFromSource(sourceModel()->parent(mapToSource(index))); } int LibraryModel::rowCount(const QModelIndex &parent) const { if (parent==QModelIndex()) { return 2; } if (parent.column()!=0) return -1; if (isInbox(parent)) { return 0; } if (isLibraryRoot(parent)) { return sourceModel()->rowCount(); } return sourceModel()->rowCount(mapToSource(parent)); } int LibraryModel::columnCount(const QModelIndex &/*parent*/) const { return 1; } QStringList LibraryModel::mimeTypes() const { return sourceModel()->mimeTypes(); } Qt::DropActions LibraryModel::supportedDropActions() const { return sourceModel()->supportedDropActions(); } Qt::ItemFlags LibraryModel::flags(const QModelIndex &index) const { if (isInbox(index) || isLibraryRoot(index)) { return Qt::ItemIsEnabled|Qt::ItemIsSelectable; } return QAbstractProxyModel::flags(index); } QMimeData *LibraryModel::mimeData(const QModelIndexList &indexes) const { QModelIndexList sourceIndexes; foreach (const QModelIndex &proxyIndex, indexes) { sourceIndexes << mapToSource(proxyIndex); } return sourceModel()->mimeData(sourceIndexes); } bool LibraryModel::dropMimeData(const QMimeData *mimeData, Qt::DropAction action, int row, int column, const QModelIndex &parent) { QModelIndex sourceParent = mapToSource(parent); return sourceModel()->dropMimeData(mimeData, action, row, column, sourceParent); } QVariant LibraryModel::data(const QModelIndex &index, int role) const { if (index.column()!=0 || !index.isValid()) return QVariant(); if (isInbox(index)) { switch (role) { case Qt::DisplayRole: switch (m_type) { case Contexts: return i18n("No Context"); default: return i18n("Inbox"); } case Qt::DecorationRole: return KIcon("mail-folder-inbox"); default: return QVariant(); } } if (isLibraryRoot(index)) { switch (role) { case Qt::DisplayRole: switch (m_type) { case Contexts: return i18n("Contexts"); default: return i18n("Library"); } case Qt::DecorationRole: return KIcon("document-multiple"); default: return QVariant(); } } return QAbstractProxyModel::data(index, role); } QVariant LibraryModel::headerData(int section, Qt::Orientation orientation, int role) const { return sourceModel()->headerData(section, orientation, role); } bool LibraryModel::isInbox(const QModelIndex &index) const { return index.internalId()==m_inboxToken; } bool LibraryModel::isLibraryRoot(const QModelIndex &index) const { return index.internalId()==m_libraryToken; } QModelIndex LibraryModel::mapToSource(const QModelIndex &proxyIndex) const { if (proxyIndex.column()!=0 || isInbox(proxyIndex) || isLibraryRoot(proxyIndex)) { return QModelIndex(); } int pos = proxyIndex.internalId()-m_tokenShift; if (pos>=m_sourceIndexesList.size()) { return QModelIndex(); } return m_sourceIndexesList[pos]; } QModelIndex LibraryModel::mapFromSource(const QModelIndex &sourceIndex) const { if (!sourceIndex.isValid()) { return index(1, 0); // Index of the library item } else { qint64 indexOf = m_sourceIndexesList.indexOf(sourceIndex); if (indexOf==-1) { indexOf = m_sourceIndexesList.size(); m_sourceIndexesList << sourceIndex; } return createIndex(sourceIndex.row(), sourceIndex.column(), (void*)(indexOf+m_tokenShift)); } } void LibraryModel::setSourceModel(QAbstractItemModel *source) { if (sourceModel()) { disconnect(sourceModel()); } QAbstractProxyModel::setSourceModel(source); connect(sourceModel(), SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(onSourceDataChanged(const QModelIndex&, const QModelIndex&))); connect(sourceModel(), SIGNAL(rowsAboutToBeInserted(const QModelIndex&, int, int)), this, SLOT(onSourceRowsAboutToBeInserted(const QModelIndex&, int, int))); connect(sourceModel(), SIGNAL(rowsInserted(const QModelIndex&, int, int)), this, SLOT(onSourceRowsInserted(const QModelIndex&, int, int))); connect(sourceModel(), SIGNAL(rowsAboutToBeRemoved(const QModelIndex&, int, int)), this, SLOT(onSourceRowsAboutToBeRemoved(const QModelIndex&, int, int))); connect(sourceModel(), SIGNAL(rowsRemoved(const QModelIndex&, int, int)), this, SLOT(onSourceRowsRemoved(const QModelIndex&, int, int))); connect(sourceModel(), SIGNAL(layoutAboutToBeChanged()), this, SIGNAL(layoutAboutToBeChanged())); connect(sourceModel(), SIGNAL(layoutChanged()), this, SLOT(onSourceLayoutChanged())); } void LibraryModel::onSourceDataChanged(const QModelIndex &begin, const QModelIndex &end) { emit dataChanged(mapFromSource(begin), mapFromSource(end)); } void LibraryModel::onSourceRowsAboutToBeInserted(const QModelIndex &sourceIndex, int begin, int end) { m_sourceIndexesList << sourceIndex; beginInsertRows(mapFromSource(sourceIndex), begin, end); } void LibraryModel::onSourceRowsInserted(const QModelIndex &sourceIndex, int begin, int end) { for (int i=begin; i<=end; i++) { QModelIndex child = sourceModel()->index(i, 0, sourceIndex); m_sourceIndexesList << child; } endInsertRows(); } void LibraryModel::onSourceRowsAboutToBeRemoved(const QModelIndex &sourceIndex, int begin, int end) { beginRemoveRows(mapFromSource(sourceIndex), begin, end); for (int i=begin; i<=end; i++) { QModelIndex child = sourceModel()->index(i, 0, sourceIndex); m_sourceIndexesList.removeAll(child); } } void LibraryModel::onSourceRowsRemoved(const QModelIndex &/*sourceIndex*/, int /*begin*/, int /*end*/) { endRemoveRows(); } void LibraryModel::onSourceLayoutChanged() { m_sourceIndexesList.clear(); emit layoutChanged(); } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Pavel Vainerman. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, version 2.1. * * 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 * Lesser General Lesser Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // ----------------------------------------------------------------------------------------- /*! \todo Добавить проверку на предельный номер id */ // ----------------------------------------------------------------------------------------- #include "ObjectIndex.h" #include "ORepHelpers.h" #include "Configuration.h" // ----------------------------------------------------------------------------------------- using namespace uniset; // ----------------------------------------------------------------------------------------- //const std::string ObjectIndex::sepName = "@"; //const std::string ObjectIndex::sepNode = ":"; // ----------------------------------------------------------------------------------------- std::string ObjectIndex::getNameById( const ObjectId id ) const noexcept { return getMapName(id); } // ----------------------------------------------------------------------------------------- std::string ObjectIndex::getNodeName(const ObjectId id) const noexcept { return getNameById(id); } // ----------------------------------------------------------------------------------------- ObjectId ObjectIndex::getNodeId(const std::__cxx11::string& name) const noexcept { return getIdByName(name); } // ----------------------------------------------------------------------------------------- std::string ObjectIndex::getBaseName( const std::string& fname ) noexcept { std::string::size_type pos = fname.rfind('/'); try { if( pos != std::string::npos ) return fname.substr(pos + 1); } catch(...) {} return fname; } // ----------------------------------------------------------------------------------------- void ObjectIndex::initLocalNode( const ObjectId nodeid ) noexcept { nmLocalNode = getMapName(nodeid); } // ----------------------------------------------------------------------------------------- <commit_msg>__cxx11::string --> std::string<commit_after>/* * Copyright (c) 2015 Pavel Vainerman. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, version 2.1. * * 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 * Lesser General Lesser Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // ----------------------------------------------------------------------------------------- /*! \todo Добавить проверку на предельный номер id */ // ----------------------------------------------------------------------------------------- #include "ObjectIndex.h" #include "ORepHelpers.h" #include "Configuration.h" // ----------------------------------------------------------------------------------------- using namespace uniset; // ----------------------------------------------------------------------------------------- //const std::string ObjectIndex::sepName = "@"; //const std::string ObjectIndex::sepNode = ":"; // ----------------------------------------------------------------------------------------- std::string ObjectIndex::getNameById( const ObjectId id ) const noexcept { return getMapName(id); } // ----------------------------------------------------------------------------------------- std::string ObjectIndex::getNodeName(const ObjectId id) const noexcept { return getNameById(id); } // ----------------------------------------------------------------------------------------- ObjectId ObjectIndex::getNodeId(const std::string& name) const noexcept { return getIdByName(name); } // ----------------------------------------------------------------------------------------- std::string ObjectIndex::getBaseName( const std::string& fname ) noexcept { std::string::size_type pos = fname.rfind('/'); try { if( pos != std::string::npos ) return fname.substr(pos + 1); } catch(...) {} return fname; } // ----------------------------------------------------------------------------------------- void ObjectIndex::initLocalNode( const ObjectId nodeid ) noexcept { nmLocalNode = getMapName(nodeid); } // ----------------------------------------------------------------------------------------- <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // FILE: ThorlabsDCStage.cpp // PROJECT: Micro-Manager // SUBSYSTEM: DeviceAdapters //----------------------------------------------------------------------------- // DESCRIPTION: Thorlabs device adapters: TDC001 Controller (version 0.0) // // COPYRIGHT: Emilio J. Gualda,2012 // // LICENSE: This file is distributed under the BSD license. // // This file 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. // // IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. // // AUTHOR: Emilio J. Gualda, IGC, 2012 // #ifdef WIN32 #include <windows.h> #define snprintf _snprintf #endif #include "ThorlabsDCStage.h" #include "APTAPI.h" #include <cstdio> #include <string> #include <math.h> #include <sstream> #include <string.h> const char* g_ThorlabsDCStageDeviceName = "ThorlabsDCStage"; const char* g_PositionProp = "Position"; const char* g_Keyword_Position = "Set position (microns)"; const char* g_Keyword_Velocity = "Velocity (mm/s)"; const char* g_Keyword_Home="Go Home"; const char* g_NumberUnitsProp = "Number of Units"; const char* g_SerialNumberProp = "Serial Number"; const char* g_MaxVelProp = "Maximum Velocity"; const char* g_MaxAccnProp = "Maximum Acceleration"; const char* g_StepSizeProp = "Step Size"; using namespace std; /////////////////////////////////////////////////////////////////////////////// // Exported MMDevice API /////////////////////////////////////////////////////////////////////////////// MODULE_API void InitializeModuleData() { AddAvailableDeviceName(g_ThorlabsDCStageDeviceName, "Thorlabs DC Stage"); } MODULE_API MM::Device* CreateDevice(const char* deviceName) { if (deviceName == 0) return 0; if (strcmp(deviceName, g_ThorlabsDCStageDeviceName) == 0) { ThorlabsDCStage* s = new ThorlabsDCStage(); return s; } return 0; } MODULE_API void DeleteDevice(MM::Device* pDevice) { delete pDevice; } /////////////////////////////////////////////////////////////////////////////// // PiezoZStage class /////////////////////////////////////////////////////////////////////////////// ThorlabsDCStage::ThorlabsDCStage() : port_("Undefined"), stepSizeUm_(0.1), initialized_(false), answerTimeoutMs_(1000), maxTravelUm_(50000.0), curPosUm_(0.0), Homed_(false), HomeInProgress_(false), plNumUnits(-1) { InitializeDefaultErrorMessages(); // set device specific error messages SetErrorText(ERR_PORT_CHANGE_FORBIDDEN, "Serial port can't be changed at run-time." " Use configuration utility or modify configuration file manually."); SetErrorText(ERR_UNRECOGNIZED_ANSWER, "Invalid response from the device hola=0"); SetErrorText(ERR_UNSPECIFIED_ERROR, "Unspecified error occured."); SetErrorText(ERR_RESPONSE_TIMEOUT, "Device timed-out: no response received withing expected time interval."); SetErrorText(ERR_BUSY, "Device busy."); SetErrorText(ERR_STAGE_NOT_ZEROED, "Zero sequence still in progress.\n" "Wait for few more seconds before trying again." "Zero sequence executes only once per power cycle"); // create pre-initialization properties // ------------------------------------ // Name CreateProperty(MM::g_Keyword_Name, g_ThorlabsDCStageDeviceName, MM::String, true); // Description CreateProperty(MM::g_Keyword_Description, "Thorlabs DC Stage", MM::String, true); // Port /* CPropertyAction* pAct = new CPropertyAction (this, &ThorlabsDCStage::OnPort); CreateProperty(MM::g_Keyword_Port, "Undefined", MM::String, false, pAct, true);*/ } ThorlabsDCStage::~ThorlabsDCStage() { Shutdown(); } void ThorlabsDCStage::GetName(char* Name) const { CDeviceUtils::CopyLimitedString(Name, g_ThorlabsDCStageDeviceName); } int ThorlabsDCStage::Initialize() { int ret(DEVICE_OK); register int i; hola_=APTInit(); //Initialize variuos data structures, initialise USB bus and other start funcions printf("initialize: %i\n",hola_); hola_=GetNumHWUnitsEx(HWTYPE_TDC001,&plNumUnits); i = 0; hola_=GetHWSerialNumEx(HWTYPE_TDC001,i,plSerialNum+i); InitHWDevice(plSerialNum[i]); MOT_GetVelParamLimits(plSerialNum[i], pfMaxAccn+i, pfMaxVel+i); if (ret != DEVICE_OK) return ret; // READ ONLY PROPERTIES //Number of Units CreateProperty(g_NumberUnitsProp,CDeviceUtils::ConvertToString(plNumUnits),MM::String,true); //Serial Number CreateProperty(g_SerialNumberProp,CDeviceUtils::ConvertToString(plSerialNum[i]),MM::String,true); CreateProperty(g_MaxVelProp,CDeviceUtils::ConvertToString(pfMaxVel),MM::String,true); CreateProperty(g_MaxAccnProp,CDeviceUtils::ConvertToString(pfMaxAccn),MM::String,true); //Action Properties //Change position CPropertyAction* pAct = new CPropertyAction (this, &ThorlabsDCStage::OnPosition); CPropertyAction* pAct2 = new CPropertyAction (this, &ThorlabsDCStage::OnVelocity); CPropertyAction* pAct3 = new CPropertyAction (this, &ThorlabsDCStage::OnHome); CreateProperty(g_Keyword_Position, "0.0", MM::Float, false, pAct); SetPropertyLimits(g_Keyword_Position, 0.0, maxTravelUm_); CreateProperty(g_Keyword_Velocity, CDeviceUtils::ConvertToString(pfMaxVel), MM::Float, false, pAct2); CreateProperty(g_Keyword_Home, "0.0", MM::Float, false, pAct3); SetPropertyLimits(g_Keyword_Home, 0.0, 1.0); ret = UpdateStatus(); if (ret != DEVICE_OK) return ret; initialized_ = true; return DEVICE_OK; } int ThorlabsDCStage::Shutdown() { if (initialized_) { initialized_ = false; hola_=APTCleanUp(); } return DEVICE_OK; } bool ThorlabsDCStage::Busy() { // never busy because all commands block return false; } int ThorlabsDCStage::GetPositionUm(double& posUm) { register int i; i=0; MOT_GetPosition(plSerialNum[i], pfPosition + i); posUm=pfPosition[i]*1000; curPosUm_=(float)posUm; return DEVICE_OK; } int ThorlabsDCStage::SetPositionUm(double posUm) { register int i; i=0; newPosition[i]=(float)posUm/1000; MOT_MoveAbsoluteEx(plSerialNum[i], newPosition[i], 1); curPosUm_=newPosition[i]*1000; OnStagePositionChanged(curPosUm_); return DEVICE_OK; } int ThorlabsDCStage::SetOrigin() { return DEVICE_UNSUPPORTED_COMMAND; } int ThorlabsDCStage::SetPositionSteps(long steps) { steps=(long)0.1; return DEVICE_OK; } int ThorlabsDCStage::GetPositionSteps(long& steps) { stepSizeUm_=steps; return DEVICE_OK; } int ThorlabsDCStage::GetLimits(double& min, double& max) { min; max; return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // private methods /////////////////////////////////////////////////////////////////////////////// /** * Send Home command to the stage * If stage was already Homed, this command has no effect. * If not, then the zero sequence will be initiated. */ int ThorlabsDCStage::SetHome(double home) { if (!IsHomed() && !HomeInProgress_) { register int i; i=0; if (home!=0){ hola_=MOT_MoveHome(plSerialNum[i], 1); Homed_=true; } HomeInProgress_ = true; } return DEVICE_OK; } /** * Check if the stage is already zeroed or not. */ bool ThorlabsDCStage::IsHomed() { if (Homed_) return true; return Homed_; } int ThorlabsDCStage::IsHomed2(double& home) { if (Homed_) home=1; return DEVICE_OK; } int ThorlabsDCStage::GetVelParam(double& vel) { register int i; i=0; MOT_GetVelParams(plSerialNum[i], pfMinVel, pfAccn, pfMaxVel); vel=(double) pfMaxVel[i]; return DEVICE_OK; } int ThorlabsDCStage::SetVelParam(double vel) { register int i; i=0; newVel[i]=(float)vel; MOT_SetVelParams(plSerialNum[i], 0.0f, pfAccn[i], static_cast<float>(vel)); return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // Action handlers /////////////////////////////////////////////////////////////////////////////// /*int ThorlabsDCStage::OnPort(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(port_.c_str()); } else if (eAct == MM::AfterSet) { if (initialized_) { // revert pProp->Set(port_.c_str()); return ERR_PORT_CHANGE_FORBIDDEN; } pProp->Get(port_); } return DEVICE_OK; }*/ int ThorlabsDCStage::OnPosition(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { double pos; int ret = GetPositionUm(pos); if (ret != DEVICE_OK) return ret; pProp->Set(pos); } else if (eAct == MM::AfterSet) { double pos; pProp->Get(pos); int ret = SetPositionUm(pos); if (ret != DEVICE_OK) return ret; } return DEVICE_OK; } int ThorlabsDCStage::OnVelocity(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { double vel; int ret = GetVelParam(vel); if (ret != DEVICE_OK) return ret; pProp->Set(vel); } else if (eAct == MM::AfterSet) { double vel; pProp->Get(vel); int ret = SetVelParam(vel); if (ret != DEVICE_OK) return ret; } return DEVICE_OK; } int ThorlabsDCStage::OnHome(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { double home; int ret = IsHomed2(home); if (ret != DEVICE_OK) return ret; pProp->Set(home); } else if (eAct == MM::AfterSet) { double home; pProp->Get(home); int ret = SetHome(home); if (ret != DEVICE_OK) return ret; } return DEVICE_OK; }<commit_msg>ThorlabsDCStage: Fix invalid initial values for properties.<commit_after>/////////////////////////////////////////////////////////////////////////////// // FILE: ThorlabsDCStage.cpp // PROJECT: Micro-Manager // SUBSYSTEM: DeviceAdapters //----------------------------------------------------------------------------- // DESCRIPTION: Thorlabs device adapters: TDC001 Controller (version 0.0) // // COPYRIGHT: Emilio J. Gualda,2012 // // LICENSE: This file is distributed under the BSD license. // // This file 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. // // IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. // // AUTHOR: Emilio J. Gualda, IGC, 2012 // #ifdef WIN32 #include <windows.h> #define snprintf _snprintf #endif #include "ThorlabsDCStage.h" #include "APTAPI.h" #include <cstdio> #include <string> #include <math.h> #include <sstream> #include <string.h> const char* g_ThorlabsDCStageDeviceName = "ThorlabsDCStage"; const char* g_PositionProp = "Position"; const char* g_Keyword_Position = "Set position (microns)"; const char* g_Keyword_Velocity = "Velocity (mm/s)"; const char* g_Keyword_Home="Go Home"; const char* g_NumberUnitsProp = "Number of Units"; const char* g_SerialNumberProp = "Serial Number"; const char* g_MaxVelProp = "Maximum Velocity"; const char* g_MaxAccnProp = "Maximum Acceleration"; const char* g_StepSizeProp = "Step Size"; using namespace std; /////////////////////////////////////////////////////////////////////////////// // Exported MMDevice API /////////////////////////////////////////////////////////////////////////////// MODULE_API void InitializeModuleData() { AddAvailableDeviceName(g_ThorlabsDCStageDeviceName, "Thorlabs DC Stage"); } MODULE_API MM::Device* CreateDevice(const char* deviceName) { if (deviceName == 0) return 0; if (strcmp(deviceName, g_ThorlabsDCStageDeviceName) == 0) { ThorlabsDCStage* s = new ThorlabsDCStage(); return s; } return 0; } MODULE_API void DeleteDevice(MM::Device* pDevice) { delete pDevice; } /////////////////////////////////////////////////////////////////////////////// // PiezoZStage class /////////////////////////////////////////////////////////////////////////////// ThorlabsDCStage::ThorlabsDCStage() : port_("Undefined"), stepSizeUm_(0.1), initialized_(false), answerTimeoutMs_(1000), maxTravelUm_(50000.0), curPosUm_(0.0), Homed_(false), HomeInProgress_(false), plNumUnits(-1) { InitializeDefaultErrorMessages(); // set device specific error messages SetErrorText(ERR_PORT_CHANGE_FORBIDDEN, "Serial port can't be changed at run-time." " Use configuration utility or modify configuration file manually."); SetErrorText(ERR_UNRECOGNIZED_ANSWER, "Invalid response from the device hola=0"); SetErrorText(ERR_UNSPECIFIED_ERROR, "Unspecified error occured."); SetErrorText(ERR_RESPONSE_TIMEOUT, "Device timed-out: no response received withing expected time interval."); SetErrorText(ERR_BUSY, "Device busy."); SetErrorText(ERR_STAGE_NOT_ZEROED, "Zero sequence still in progress.\n" "Wait for few more seconds before trying again." "Zero sequence executes only once per power cycle"); // create pre-initialization properties // ------------------------------------ // Name CreateProperty(MM::g_Keyword_Name, g_ThorlabsDCStageDeviceName, MM::String, true); // Description CreateProperty(MM::g_Keyword_Description, "Thorlabs DC Stage", MM::String, true); // Port /* CPropertyAction* pAct = new CPropertyAction (this, &ThorlabsDCStage::OnPort); CreateProperty(MM::g_Keyword_Port, "Undefined", MM::String, false, pAct, true);*/ } ThorlabsDCStage::~ThorlabsDCStage() { Shutdown(); } void ThorlabsDCStage::GetName(char* Name) const { CDeviceUtils::CopyLimitedString(Name, g_ThorlabsDCStageDeviceName); } int ThorlabsDCStage::Initialize() { int ret(DEVICE_OK); register int i; hola_=APTInit(); //Initialize variuos data structures, initialise USB bus and other start funcions printf("initialize: %i\n",hola_); hola_=GetNumHWUnitsEx(HWTYPE_TDC001,&plNumUnits); i = 0; hola_=GetHWSerialNumEx(HWTYPE_TDC001,i,plSerialNum+i); InitHWDevice(plSerialNum[i]); MOT_GetVelParamLimits(plSerialNum[i], pfMaxAccn+i, pfMaxVel+i); if (ret != DEVICE_OK) return ret; // READ ONLY PROPERTIES //Number of Units CreateProperty(g_NumberUnitsProp,CDeviceUtils::ConvertToString(plNumUnits),MM::String,true); //Serial Number CreateProperty(g_SerialNumberProp,CDeviceUtils::ConvertToString(plSerialNum[i]),MM::String,true); CreateProperty(g_MaxVelProp,CDeviceUtils::ConvertToString(pfMaxVel[i]),MM::String,true); CreateProperty(g_MaxAccnProp,CDeviceUtils::ConvertToString(pfMaxAccn[i]),MM::String,true); //Action Properties //Change position CPropertyAction* pAct = new CPropertyAction (this, &ThorlabsDCStage::OnPosition); CPropertyAction* pAct2 = new CPropertyAction (this, &ThorlabsDCStage::OnVelocity); CPropertyAction* pAct3 = new CPropertyAction (this, &ThorlabsDCStage::OnHome); CreateProperty(g_Keyword_Position, "0.0", MM::Float, false, pAct); SetPropertyLimits(g_Keyword_Position, 0.0, maxTravelUm_); CreateProperty(g_Keyword_Velocity, CDeviceUtils::ConvertToString(pfMaxVel[i]), MM::Float, false, pAct2); CreateProperty(g_Keyword_Home, "0.0", MM::Float, false, pAct3); SetPropertyLimits(g_Keyword_Home, 0.0, 1.0); ret = UpdateStatus(); if (ret != DEVICE_OK) return ret; initialized_ = true; return DEVICE_OK; } int ThorlabsDCStage::Shutdown() { if (initialized_) { initialized_ = false; hola_=APTCleanUp(); } return DEVICE_OK; } bool ThorlabsDCStage::Busy() { // never busy because all commands block return false; } int ThorlabsDCStage::GetPositionUm(double& posUm) { register int i; i=0; MOT_GetPosition(plSerialNum[i], pfPosition + i); posUm=pfPosition[i]*1000; curPosUm_=(float)posUm; return DEVICE_OK; } int ThorlabsDCStage::SetPositionUm(double posUm) { register int i; i=0; newPosition[i]=(float)posUm/1000; MOT_MoveAbsoluteEx(plSerialNum[i], newPosition[i], 1); curPosUm_=newPosition[i]*1000; OnStagePositionChanged(curPosUm_); return DEVICE_OK; } int ThorlabsDCStage::SetOrigin() { return DEVICE_UNSUPPORTED_COMMAND; } int ThorlabsDCStage::SetPositionSteps(long steps) { steps=(long)0.1; return DEVICE_OK; } int ThorlabsDCStage::GetPositionSteps(long& steps) { stepSizeUm_=steps; return DEVICE_OK; } int ThorlabsDCStage::GetLimits(double& min, double& max) { min; max; return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // private methods /////////////////////////////////////////////////////////////////////////////// /** * Send Home command to the stage * If stage was already Homed, this command has no effect. * If not, then the zero sequence will be initiated. */ int ThorlabsDCStage::SetHome(double home) { if (!IsHomed() && !HomeInProgress_) { register int i; i=0; if (home!=0){ hola_=MOT_MoveHome(plSerialNum[i], 1); Homed_=true; } HomeInProgress_ = true; } return DEVICE_OK; } /** * Check if the stage is already zeroed or not. */ bool ThorlabsDCStage::IsHomed() { if (Homed_) return true; return Homed_; } int ThorlabsDCStage::IsHomed2(double& home) { if (Homed_) home=1; return DEVICE_OK; } int ThorlabsDCStage::GetVelParam(double& vel) { register int i; i=0; MOT_GetVelParams(plSerialNum[i], pfMinVel, pfAccn, pfMaxVel); vel=(double) pfMaxVel[i]; return DEVICE_OK; } int ThorlabsDCStage::SetVelParam(double vel) { register int i; i=0; newVel[i]=(float)vel; MOT_SetVelParams(plSerialNum[i], 0.0f, pfAccn[i], static_cast<float>(vel)); return DEVICE_OK; } /////////////////////////////////////////////////////////////////////////////// // Action handlers /////////////////////////////////////////////////////////////////////////////// /*int ThorlabsDCStage::OnPort(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { pProp->Set(port_.c_str()); } else if (eAct == MM::AfterSet) { if (initialized_) { // revert pProp->Set(port_.c_str()); return ERR_PORT_CHANGE_FORBIDDEN; } pProp->Get(port_); } return DEVICE_OK; }*/ int ThorlabsDCStage::OnPosition(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { double pos; int ret = GetPositionUm(pos); if (ret != DEVICE_OK) return ret; pProp->Set(pos); } else if (eAct == MM::AfterSet) { double pos; pProp->Get(pos); int ret = SetPositionUm(pos); if (ret != DEVICE_OK) return ret; } return DEVICE_OK; } int ThorlabsDCStage::OnVelocity(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { double vel; int ret = GetVelParam(vel); if (ret != DEVICE_OK) return ret; pProp->Set(vel); } else if (eAct == MM::AfterSet) { double vel; pProp->Get(vel); int ret = SetVelParam(vel); if (ret != DEVICE_OK) return ret; } return DEVICE_OK; } int ThorlabsDCStage::OnHome(MM::PropertyBase* pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { double home; int ret = IsHomed2(home); if (ret != DEVICE_OK) return ret; pProp->Set(home); } else if (eAct == MM::AfterSet) { double home; pProp->Get(home); int ret = SetHome(home); if (ret != DEVICE_OK) return ret; } return DEVICE_OK; }<|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2017 ScyllaDB. */ #pragma once #include <tuple> #include <utility> namespace seastar { /// \cond internal namespace internal { template<typename Tuple> Tuple untuple(Tuple t) { return std::move(t); } template<typename T> T untuple(std::tuple<T> t) { return std::get<0>(std::move(t)); } template<typename Tuple, typename Function, size_t... I> void tuple_for_each_helper(Tuple&& t, Function&& f, std::index_sequence<I...>&&) { auto ignore_me = { (f(std::get<I>(std::forward<Tuple>(t))), 1)... }; (void)ignore_me; } template<typename Tuple, typename MapFunction, size_t... I> auto tuple_map_helper(Tuple&& t, MapFunction&& f, std::index_sequence<I...>&&) { return std::make_tuple(f(std::get<I>(std::forward<Tuple>(t)))...); } template<size_t I, typename IndexSequence> struct prepend; template<size_t I, size_t... Is> struct prepend<I, std::index_sequence<Is...>> { using type = std::index_sequence<I, Is...>; }; template<template<typename> class Filter, typename Tuple, typename IndexSequence> struct tuple_filter; template<template<typename> class Filter, typename T, typename... Ts, size_t I, size_t... Is> struct tuple_filter<Filter, std::tuple<T, Ts...>, std::index_sequence<I, Is...>> { using tail = typename tuple_filter<Filter, std::tuple<Ts...>, std::index_sequence<Is...>>::type; using type = std::conditional_t<Filter<T>::value, typename prepend<I, tail>::type, tail>; }; template<template<typename> class Filter> struct tuple_filter<Filter, std::tuple<>, std::index_sequence<>> { using type = std::index_sequence<>; }; template<typename Tuple, size_t... I> auto tuple_filter_helper(Tuple&& t, std::index_sequence<I...>&&) { return std::make_tuple(std::get<I>(std::forward<Tuple>(t))...); } } /// \endcond /// \addtogroup utilities /// @{ /// Filters elements in tuple by their type /// /// Returns a tuple containing only those elements which type `T` caused /// expression `FilterClass<T>::value` to be true. /// /// \tparam FilterClass class template having an element value set to true for elements that /// should be present in the result /// \param t tuple to filter /// \return a tuple contaning elements which type passed the test template<template<typename> class FilterClass, typename... Elements> auto tuple_filter_by_type(const std::tuple<Elements...>& t) { using sequence = typename internal::tuple_filter<FilterClass, std::tuple<Elements...>, std::index_sequence_for<Elements...>>::type; return internal::tuple_filter_helper(t, sequence()); } template<template<typename> class FilterClass, typename... Elements> auto tuple_filter_by_type(std::tuple<Elements...>&& t) { using sequence = typename internal::tuple_filter<FilterClass, std::tuple<Elements...>, std::index_sequence_for<Elements...>>::type; return internal::tuple_filter_helper(std::move(t), sequence()); } /// Applies function to all elements in tuple /// /// Applies given function to all elements in the tuple and returns a tuple /// of results. /// /// \param t original tuple /// \param f function to apply /// \return tuple of results returned by f for each element in t template<typename Function, typename... Elements> auto tuple_map(const std::tuple<Elements...>& t, Function&& f) { return internal::tuple_map_helper(t, std::forward<Function>(f), std::index_sequence_for<Elements...>()); } template<typename Function, typename... Elements> auto tuple_map(std::tuple<Elements...>&& t, Function&& f) { return internal::tuple_map_helper(std::move(t), std::forward<Function>(f), std::index_sequence_for<Elements...>()); } /// Iterate over all elements in tuple /// /// Iterates over given tuple and calls the specified function for each of /// it elements. /// /// \param t a tuple to iterate over /// \param f function to call for each tuple element template<typename Function, typename... Elements> void tuple_for_each(const std::tuple<Elements...>& t, Function&& f) { return internal::tuple_for_each_helper(t, std::forward<Function>(f), std::index_sequence_for<Elements...>()); } template<typename Function, typename... Elements> void tuple_for_each(std::tuple<Elements...>& t, Function&& f) { return internal::tuple_for_each_helper(t, std::forward<Function>(f), std::index_sequence_for<Elements...>()); } template<typename Function, typename... Elements> void tuple_for_each(std::tuple<Elements...>&& t, Function&& f) { return internal::tuple_for_each_helper(std::move(t), std::forward<Function>(f), std::index_sequence_for<Elements...>()); } /// @} } <commit_msg>util: add tuple_map_types<><commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2017 ScyllaDB. */ #pragma once #include <tuple> #include <utility> namespace seastar { /// \cond internal namespace internal { template<typename Tuple> Tuple untuple(Tuple t) { return std::move(t); } template<typename T> T untuple(std::tuple<T> t) { return std::get<0>(std::move(t)); } template<typename Tuple, typename Function, size_t... I> void tuple_for_each_helper(Tuple&& t, Function&& f, std::index_sequence<I...>&&) { auto ignore_me = { (f(std::get<I>(std::forward<Tuple>(t))), 1)... }; (void)ignore_me; } template<typename Tuple, typename MapFunction, size_t... I> auto tuple_map_helper(Tuple&& t, MapFunction&& f, std::index_sequence<I...>&&) { return std::make_tuple(f(std::get<I>(std::forward<Tuple>(t)))...); } template<size_t I, typename IndexSequence> struct prepend; template<size_t I, size_t... Is> struct prepend<I, std::index_sequence<Is...>> { using type = std::index_sequence<I, Is...>; }; template<template<typename> class Filter, typename Tuple, typename IndexSequence> struct tuple_filter; template<template<typename> class Filter, typename T, typename... Ts, size_t I, size_t... Is> struct tuple_filter<Filter, std::tuple<T, Ts...>, std::index_sequence<I, Is...>> { using tail = typename tuple_filter<Filter, std::tuple<Ts...>, std::index_sequence<Is...>>::type; using type = std::conditional_t<Filter<T>::value, typename prepend<I, tail>::type, tail>; }; template<template<typename> class Filter> struct tuple_filter<Filter, std::tuple<>, std::index_sequence<>> { using type = std::index_sequence<>; }; template<typename Tuple, size_t... I> auto tuple_filter_helper(Tuple&& t, std::index_sequence<I...>&&) { return std::make_tuple(std::get<I>(std::forward<Tuple>(t))...); } } /// \endcond /// \addtogroup utilities /// @{ /// Applies type transformation to all types in tuple /// /// Member type `type` is set to a tuple type which is a result of applying /// transformation `MapClass<T>::type` to each element `T` of the input tuple /// type. /// /// \tparam MapClass class template defining type transformation /// \tparam Tuple input tuple type template<template<typename> class MapClass, typename Tuple> struct tuple_map_types; /// @} template<template<typename> class MapClass, typename... Elements> struct tuple_map_types<MapClass, std::tuple<Elements...>> { using type = std::tuple<typename MapClass<Elements>::type...>; }; /// \addtogroup utilities /// @{ /// Filters elements in tuple by their type /// /// Returns a tuple containing only those elements which type `T` caused /// expression `FilterClass<T>::value` to be true. /// /// \tparam FilterClass class template having an element value set to true for elements that /// should be present in the result /// \param t tuple to filter /// \return a tuple contaning elements which type passed the test template<template<typename> class FilterClass, typename... Elements> auto tuple_filter_by_type(const std::tuple<Elements...>& t) { using sequence = typename internal::tuple_filter<FilterClass, std::tuple<Elements...>, std::index_sequence_for<Elements...>>::type; return internal::tuple_filter_helper(t, sequence()); } template<template<typename> class FilterClass, typename... Elements> auto tuple_filter_by_type(std::tuple<Elements...>&& t) { using sequence = typename internal::tuple_filter<FilterClass, std::tuple<Elements...>, std::index_sequence_for<Elements...>>::type; return internal::tuple_filter_helper(std::move(t), sequence()); } /// Applies function to all elements in tuple /// /// Applies given function to all elements in the tuple and returns a tuple /// of results. /// /// \param t original tuple /// \param f function to apply /// \return tuple of results returned by f for each element in t template<typename Function, typename... Elements> auto tuple_map(const std::tuple<Elements...>& t, Function&& f) { return internal::tuple_map_helper(t, std::forward<Function>(f), std::index_sequence_for<Elements...>()); } template<typename Function, typename... Elements> auto tuple_map(std::tuple<Elements...>&& t, Function&& f) { return internal::tuple_map_helper(std::move(t), std::forward<Function>(f), std::index_sequence_for<Elements...>()); } /// Iterate over all elements in tuple /// /// Iterates over given tuple and calls the specified function for each of /// it elements. /// /// \param t a tuple to iterate over /// \param f function to call for each tuple element template<typename Function, typename... Elements> void tuple_for_each(const std::tuple<Elements...>& t, Function&& f) { return internal::tuple_for_each_helper(t, std::forward<Function>(f), std::index_sequence_for<Elements...>()); } template<typename Function, typename... Elements> void tuple_for_each(std::tuple<Elements...>& t, Function&& f) { return internal::tuple_for_each_helper(t, std::forward<Function>(f), std::index_sequence_for<Elements...>()); } template<typename Function, typename... Elements> void tuple_for_each(std::tuple<Elements...>&& t, Function&& f) { return internal::tuple_for_each_helper(std::move(t), std::forward<Function>(f), std::index_sequence_for<Elements...>()); } /// @} } <|endoftext|>
<commit_before>// // flags.cc // tbd // // Created by administrator on 7/10/17. // Copyright © 2017 inoahdev. All rights reserved. // #include <cstdio> #include <cstdlib> #include <cerrno> #include <cstring> #include "flags.h" flags::flags(long length) : length_(length) { if (length > bit_size()) { size_t size = length * bit_size(); flags_.ptr = calloc(1, size); if (!flags_.ptr) { fprintf(stderr, "Failed to allocate data of size (%ld), failing with error (%s)\n", size, strerror(errno)); exit(1); } } } flags::~flags() { if (length_ > bit_size()) { free(flags_.ptr); } } void flags::cast(long index, bool result) noexcept { if (length_ > bit_size()) { auto ptr = (unsigned int *)flags_.ptr; const auto bit_size = this->bit_size(); // 16 const auto bits_length = bit_size * length_; // 32 auto index_from_back = (bits_length - 1) - index; // 13 if (index_from_back > bit_size) { do { index_from_back -= 8; ptr++; } while (index_from_back > bit_size); } else { index = bit_size - index; } if (result) { *ptr |= 1 << index; } else { *ptr &= ~(1 << index); } } else { auto flags = flags_.flags; if (result) { flags |= 1 << index; } else { flags &= ~(1 << index); } flags_.flags = flags; } } bool flags::at_index(long index) const noexcept { if (length_ > bit_size()) { auto ptr = (unsigned int *)flags_.ptr; const auto bit_size = this->bit_size(); // 16 const auto bits_length = bit_size * length_; // 32 auto index_from_back = (bits_length - 1) - index; // 13 if (index_from_back > bit_size) { do { index_from_back -= 8; ptr++; } while (index_from_back > bit_size); } else { index = bit_size - index; } return (*ptr & 1 << index) ? true : false; } else { const auto flags = flags_.flags; return (flags & 1 << index) ? true : false; } } bool flags::operator==(const flags &flags) const noexcept { if (length_ != flags.length_) { return false; } if (length_ > bit_size()) { return memcmp(flags_.ptr, flags_.ptr, length_); } else { return flags_.flags == flags.flags_.flags; } } <commit_msg>Remove old debug comments<commit_after>// // flags.cc // tbd // // Created by administrator on 7/10/17. // Copyright © 2017 inoahdev. All rights reserved. // #include <cstdio> #include <cstdlib> #include <cerrno> #include <cstring> #include "flags.h" flags::flags(long length) : length_(length) { if (length > bit_size()) { size_t size = length * bit_size(); flags_.ptr = calloc(1, size); if (!flags_.ptr) { fprintf(stderr, "Failed to allocate data of size (%ld), failing with error (%s)\n", size, strerror(errno)); exit(1); } } } flags::~flags() { if (length_ > bit_size()) { free(flags_.ptr); } } void flags::cast(long index, bool result) noexcept { if (length_ > bit_size()) { auto ptr = (unsigned int *)flags_.ptr; const auto bit_size = this->bit_size(); const auto bits_length = bit_size * length_; auto index_from_back = (bits_length - 1) - index; if (index_from_back > bit_size) { do { index_from_back -= 8; ptr++; } while (index_from_back > bit_size); } else { index = bit_size - index; } if (result) { *ptr |= 1 << index; } else { *ptr &= ~(1 << index); } } else { auto flags = flags_.flags; if (result) { flags |= 1 << index; } else { flags &= ~(1 << index); } flags_.flags = flags; } } bool flags::at_index(long index) const noexcept { if (length_ > bit_size()) { auto ptr = (unsigned int *)flags_.ptr; const auto bit_size = this->bit_size(); const auto bits_length = bit_size * length_; auto index_from_back = (bits_length - 1) - index; if (index_from_back > bit_size) { do { index_from_back -= 8; ptr++; } while (index_from_back > bit_size); } else { index = bit_size - index; } return (*ptr & 1 << index) ? true : false; } else { const auto flags = flags_.flags; return (flags & 1 << index) ? true : false; } } bool flags::operator==(const flags &flags) const noexcept { if (length_ != flags.length_) { return false; } if (length_ > bit_size()) { return memcmp(flags_.ptr, flags_.ptr, length_); } else { return flags_.flags == flags.flags_.flags; } } <|endoftext|>
<commit_before>#include <algorithm> #include <cstdlib> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> using std::atof; using std::count; using std::cout; using std::cerr; using std::endl; using std::getline; using std::string; using std::stringstream; using std::ifstream; using cv::filter2D; using cv::imread; using cv::Mat; using cv::namedWindow; using cv::Rect; using cv::waitKey; namespace { /* Set operators to a kernel row from a string \param row a kernel row. \param line a string \param size a kernel size */ void setOperator(Mat row, const string& line, uint64_t size) { stringstream line_stream(line); for(uint64_t i = 0; i < size; ++i) { if(line_stream.good() && !line_stream.eof()) { string op; getline(line_stream, op, ','); row.at<double>(i) = static_cast<double>(atof(op.c_str())); } else { break; } } }; /*! Get a kernel matrix from a csv file. \param filename csv file name \return a kernel matrix */ cv::Mat getKernel(const std::string& filename) { ifstream stream; stream.open(filename); if(stream.good()) { string line; getline(stream, line); uint64_t size = count(line.begin(), line.end(), ',') + 1; Mat kernel(size, size, cv::DataType<double>::type); if(kernel.data == NULL) { return Mat::zeros(1, 1, CV_8S); } setOperator(kernel.row(0), line, size); for(uint64_t i = 1; i < size; ++i) { if(stream.good() && !stream.eof()) { getline(stream, line); setOperator(kernel.row(i), line, size); } else { break; } } return kernel; } else { return Mat::zeros(1, 1, CV_8S); } } /*! Get a filtered matrix. \param src an original matrix. \param kernel a kernel. \return a fitered matrix. */ cv::Mat filter(const cv::Mat& src, const cv::Mat& kernel) { Mat filtered; src.copyTo(filtered); filter2D(src, filtered, src.depth(), kernel, cv::Point(0, 0)); return filtered; } /*! Show an original image and a filtered image on GUI. \param original an original image matrix. \param filtered a filtered image matrix. \return always EXIT_SUCCESS */ int showImage(const cv::Mat& original, const cv::Mat& filtered) { Mat output = Mat::zeros( original.size().height, original.size().width * 2, original.type() ); original.copyTo(Mat(output, Rect(0, 0, original.cols, original.rows))); filtered.copyTo( Mat(output, Rect(original.cols, 0, original.cols, original.rows)) ); string window_name("linear_filter"); namedWindow(window_name, CV_WINDOW_AUTOSIZE); imshow(window_name, output); waitKey(0); return EXIT_SUCCESS; } /*! Show an empty window to show error messages on title. When an empty window was closed, show error messages on an console. \param window_name error messages \return always EXIT_FAILURE */ int showErrorWindow(const std::string& window_name) { namedWindow(window_name, CV_WINDOW_AUTOSIZE); waitKey(0); cerr << window_name << endl; return EXIT_FAILURE; } /* Get image file name from program options. \param agrc argc \param argv argv \return image file name */ std::string getImageFilename(int argc, char** argv) { return (argc == 2)? string("input.jpg"): string(argv[1]); } /*! Get kernel file name from program options. \param argc argc \param argv argv \return kernel file name */ std::string getKernelFilename(int argc, char** argv) { return (argc == 2)? string(argv[1]): string(argv[2]); } } // namespace int main(int argc, char** argv) { if(argc == 2 || argc == 3) { Mat original = imread( ::getImageFilename(argc, argv), CV_LOAD_IMAGE_GRAYSCALE ); exit( (original.data != NULL)? ::showImage( original, ::filter(original, ::getKernel(::getKernelFilename(argc, argv))) ): ::showErrorWindow(string("Could not open or find the image")) ); } else { exit( ::showErrorWindow(string("Usage: linear_filter image_file filter_csv")) ); } return 0; } <commit_msg>一部の関数はエラー時に空の画像(NULLが格納されているcv::Mat)を返すように変更。<commit_after>#include <algorithm> #include <cstdlib> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> using std::atof; using std::count; using std::cout; using std::cerr; using std::endl; using std::getline; using std::string; using std::stringstream; using std::ifstream; using cv::filter2D; using cv::imread; using cv::Mat; using cv::namedWindow; using cv::Rect; using cv::waitKey; namespace { /* Set operators to a kernel row from a string. \param row a kernel row. \param line a string \param size a kernel size */ void setOperator(Mat row, const string& line, uint64_t size) { stringstream line_stream(line); for(uint64_t i = 0; i < size; ++i) { if(line_stream.good() && !line_stream.eof()) { string op; getline(line_stream, op, ','); // Set an operator parameter. row.at<double>(i) = static_cast<double>(atof(op.c_str())); } else { break; } } }; /*! Get a kernel matrix from a csv file. \param filename csv file name \return a kernel matrix. If had some error, return empty matrix. */ cv::Mat getKernel(const std::string& filename) { ifstream stream; stream.open(filename); if(stream.good()) { string line; getline(stream, line); // Get filter size. uint64_t size = count(line.begin(), line.end(), ',') + 1; // Allocate a kernel matrix. Mat kernel = Mat::zeros(size, size, cv::DataType<double>::type); if(kernel.data == NULL) { return Mat(); } else { setOperator(kernel.row(0), line, size); for(uint64_t i = 1; i < size; ++i) { if(stream.good() && !stream.eof()) { getline(stream, line); setOperator(kernel.row(i), line, size); } else { break; } } return kernel; } } else { return Mat(); } } /*! Get a filtered matrix. \param src an original matrix. \param kernel a kernel. \return a fitered matrix. If an input matrix was empty, return an empty matrix. */ cv::Mat filter(const cv::Mat& src, const cv::Mat& kernel) { if(src.data != NULL && kernel.data != NULL) { Mat filtered; src.copyTo(filtered); filter2D(src, filtered, src.depth(), kernel, cv::Point(0, 0)); return filtered; } else { return Mat(); } } /*! Show an empty window to show error messages on title. When an empty window was closed, show error messages on an console. \param window_name error messages \return always EXIT_FAILURE */ int showErrorWindow(const std::string& error_message) { namedWindow(error_message, CV_WINDOW_AUTOSIZE); waitKey(0); cerr << error_message << endl; return EXIT_FAILURE; } /*! Show an original image and a filtered image on GUI. \param original an original image matrix. \param filtered a filtered image matrix. \return always EXIT_SUCCESS */ int showImageWindow(const cv::Mat& original, const cv::Mat& filtered) { Mat output = Mat::zeros( original.size().height, original.size().width * 2, original.type() ); // Combine an original image and a filtered image. original.copyTo(Mat(output, Rect(0, 0, original.cols, original.rows))); filtered.copyTo( Mat(output, Rect(original.cols, 0, original.cols, original.rows)) ); string window_name("linear_filter"); namedWindow(window_name, CV_WINDOW_AUTOSIZE); imshow(window_name, output); waitKey(0); return EXIT_SUCCESS; } int showWindow(const cv::Mat& original, const cv::Mat& filtered) { if(original.data == NULL) { return showErrorWindow(string("failed to open the image.")); } else if(filtered.data == NULL) { return showErrorWindow(string("failed to filter the image.")); } else { return showImageWindow(original, filtered); } } //int showImageWindow( /* Get image file name from program options. \param agrc argc \param argv argv \return image file name */ std::string getImageFilename(int argc, char** argv) { return (argc == 2)? string("input.jpg"): string(argv[1]); } /*! Get kernel file name from program options. \param argc argc \param argv argv \return kernel file name */ std::string getKernelFilename(int argc, char** argv) { return (argc == 2)? string(argv[1]): string(argv[2]); } } // namespace int main(int argc, char** argv) { if(argc == 2 || argc == 3) { Mat original = imread( ::getImageFilename(argc, argv), CV_LOAD_IMAGE_GRAYSCALE ); exit( ::showWindow( original, ::filter(original, ::getKernel(::getKernelFilename(argc, argv))) ) ); } else { exit( ::showErrorWindow(string("Usage: linear_filter image_file filter_csv")) ); } return 0; } <|endoftext|>
<commit_before>// // // MIT License // // Copyright (c) 2020 Stellacore Corporation. // // 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. // // /*! \file \brief This file contains unit test for geo::si */ #include "libgeo/si.h" #include "libdat/info.h" #include "libdat/validity.h" #include "libio/sprintf.h" #include "libio/stream.h" #include <iostream> #include <sstream> #include <string> namespace { //! Check for common functions std::string geo_si_test0 () { std::ostringstream oss; /* geo::si const aNull(dat::nullValue<geo::si>()); if (dat::isValid(aNull)) { oss << "Failure of null value test" << std::endl; oss << "infoString: " << dat::infoString(aNull) << std::endl; } */ return oss.str(); } //! Check demonstrate Thales' type test std::string geo_si_test1 () { std::ostringstream oss; constexpr double staH{ 50. }; // station height constexpr double range{ 1000. }; // horizontal distance to target ga::Vector const base{ ga::zero }; constexpr double sigRay{ 2. }; constexpr double sigSea{ 1. }; ga::Vector const raySta{ base + staH * ga::e3 }; ga::Vector const expPnt{ base -range * ga::e1 }; // measurement observations geo::Ray const ray{ geo::Ray::fromToward(raySta, expPnt) }; geo::Plane const sea(base, ga::E12); /* io::out() << dat::infoString(base, "base") << std::endl; io::out() << dat::infoString(raySta, "raySta") << std::endl; io::out() << dat::infoString(expPnt, "expPnt") << std::endl; io::out() << dat::infoString(ray, "ray") << std::endl; io::out() << dat::infoString(sea, "sea") << std::endl; */ // collect observations of same classifications std::vector<geo::si::WRay> const wrays{ {(1./sigRay), ray} }; std::vector<geo::si::WPlane> const wplanes{ {(1./sigSea), sea} }; // create observation system geo::si::PointSystem system{}; system.addWeightedRays(wrays); system.addWeightedPlanes(wplanes); // compute intersection of collections geo::si::PointSoln const pntSoln{ system.pointSolution() }; // check point solution ga::Vector const & gotPnt = pntSoln.theLoc; bool okay{ true }; double const tol{ staH * range * math::eps }; if (! gotPnt.nearlyEquals(expPnt, tol)) { ga::Vector const difPnt{ gotPnt - expPnt }; double const difMag{ ga::magnitude(difPnt) }; oss << "Failure of ray/sea pointSolution.theLoc test" << std::endl; oss << dat::infoString(expPnt, "expPnt") << std::endl; oss << dat::infoString(gotPnt, "gotPnt") << std::endl; oss << dat::infoString(difPnt, "difPnt") << " difMag: " << io::sprintf("%12.5e", difMag) << std::endl; okay = false; } // check uncertainty // (no prediction possible; single plane and one ray has exact soln) constexpr bool show{ false }; if ((! okay) || show) { io::out() << "==== test data ====>" << std::endl; io::out() << dat::infoString(sea, "sea") << std::endl; io::out() << dat::infoString(ray, "ray") << std::endl; io::out() << dat::infoString(pntSoln, "pntSoln") << std::endl; io::out() << "<=== test data" << std::endl; } return oss.str(); } //! Check two ray intersection std::string geo_si_test2 () { std::ostringstream oss; ga::Vector const sta1{ 1., -1., 0. }; ga::Vector const sta2{ 1., 1., 0. }; ga::Vector const expPnt{ 0., 0., 0. }; double const sig0{ 8. }; std::array<double, 3u> const expSigs{ sig0, sig0, .5*sig0 }; // big->sml // measurement observations geo::Ray const ray1{ geo::Ray::fromToward(sta1, expPnt) }; geo::Ray const ray2{ geo::Ray::fromToward(sta2, expPnt) }; double const sig1{ sig0 }; double const sig2{ sig0 }; // collect observations of same classifications std::vector<geo::si::WRay> const wrays { { (1./sig1), ray1 } , { (1./sig2), ray2 } }; // compute intersection of collections geo::si::PointSystem system{}; system.addWeightedRays(wrays); // io::out() << "\n\n"; // io::out() << dat::infoString(system, "system") << std::endl; geo::si::PointSoln const pntSoln{ system.pointSolution() }; // io::out() << dat::infoString(pntSoln, "pntSoln") << std::endl; // check point location ga::Vector const & gotPnt = pntSoln.theLoc; bool okay{ true }; if (! gotPnt.nearlyEquals(expPnt)) { oss << "Failure of ray/ray pointSolution.theLoc test" << std::endl; oss << dat::infoString(expPnt, "expPnt") << std::endl; oss << dat::infoString(gotPnt, "gotPnt") << std::endl; okay = false; } // check uncertainty ellipsoid geo::si::SemiAxis const gotSig0{ pntSoln.kthLargestSemiAxis(0) }; geo::si::SemiAxis const gotSig1{ pntSoln.kthLargestSemiAxis(1) }; geo::si::SemiAxis const gotSig2{ pntSoln.kthLargestSemiAxis(2) }; std::array<double, 3u> const gotSigs { gotSig0.theMag, gotSig1.theMag, gotSig2.theMag }; if (! dat::nearlyEquals(gotSigs, expSigs)) { oss << "Failure of aposterior sigma estimate test" << std::endl; oss << dat::infoString(expSigs, "expSigs") << std::endl; oss << dat::infoString(gotSigs, "gotSigs") << std::endl; } constexpr bool show{ false }; if ((! okay) || show) { io::out() << "==== test data ====>" << std::endl; io::out() << dat::infoString(ray1, "ray1") << std::endl; io::out() << dat::infoString(ray2, "ray2") << std::endl; io::out() << dat::infoString(pntSoln, "pntSoln") << std::endl; io::out() << "<=== test data" << std::endl; } return oss.str(); } } //! Unit test for geo::si int main ( int const /*argc*/ , char const * const * /*argv*/ ) { std::ostringstream oss; // run tests oss << geo_si_test0(); oss << geo_si_test1(); oss << geo_si_test2(); // check/report results std::string const errMessages(oss.str()); if (! errMessages.empty()) { io::err() << errMessages << std::endl; return 1; } return 0; } <commit_msg>usi.cpp added output to test data reporting (when enabled)<commit_after>// // // MIT License // // Copyright (c) 2020 Stellacore Corporation. // // 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. // // /*! \file \brief This file contains unit test for geo::si */ #include "libgeo/si.h" #include "libdat/info.h" #include "libdat/validity.h" #include "libio/sprintf.h" #include "libio/stream.h" #include <iostream> #include <sstream> #include <string> namespace { //! Check for common functions std::string geo_si_test0 () { std::ostringstream oss; /* geo::si const aNull(dat::nullValue<geo::si>()); if (dat::isValid(aNull)) { oss << "Failure of null value test" << std::endl; oss << "infoString: " << dat::infoString(aNull) << std::endl; } */ return oss.str(); } //! Check demonstrate Thales' type test std::string geo_si_test1 () { std::ostringstream oss; constexpr double staH{ 50. }; // station height constexpr double range{ 1000. }; // horizontal distance to target ga::Vector const base{ 0., 300., 10. }; constexpr double sigRay{ 2. }; constexpr double sigSea{ 1. }; ga::Vector const raySta{ base + staH * ga::e3 }; ga::Vector const expPnt{ base -range * ga::e1 }; // measurement observations geo::Ray const ray{ geo::Ray::fromToward(raySta, expPnt) }; geo::Plane const sea(base, ga::E12); /* io::out() << dat::infoString(base, "base") << std::endl; io::out() << dat::infoString(raySta, "raySta") << std::endl; io::out() << dat::infoString(expPnt, "expPnt") << std::endl; io::out() << dat::infoString(ray, "ray") << std::endl; io::out() << dat::infoString(sea, "sea") << std::endl; */ // collect observations of same classifications std::vector<geo::si::WRay> const wrays{ {(1./sigRay), ray} }; std::vector<geo::si::WPlane> const wplanes{ {(1./sigSea), sea} }; // create observation system geo::si::PointSystem system{}; system.addWeightedRays(wrays); system.addWeightedPlanes(wplanes); // compute intersection of collections geo::si::PointSoln const pntSoln{ system.pointSolution() }; // check point solution ga::Vector const & gotPnt = pntSoln.theLoc; bool okay{ true }; double const tol{ staH * range * math::eps }; if (! gotPnt.nearlyEquals(expPnt, tol)) { ga::Vector const difPnt{ gotPnt - expPnt }; double const difMag{ ga::magnitude(difPnt) }; oss << "Failure of ray/sea pointSolution.theLoc test" << std::endl; oss << dat::infoString(expPnt, "expPnt") << std::endl; oss << dat::infoString(gotPnt, "gotPnt") << std::endl; oss << dat::infoString(difPnt, "difPnt") << " difMag: " << io::sprintf("%12.5e", difMag) << std::endl; okay = false; } // check uncertainty // (no prediction possible; single plane and one ray has exact soln) constexpr bool show{ false }; if ((! okay) || show) { io::out() << "==== test data ====>" << std::endl; io::out() << dat::infoString(base, "base") << std::endl; io::out() << dat::infoString(raySta, "raySta") << std::endl; io::out() << dat::infoString(sea, "sea") << std::endl; io::out() << dat::infoString(ray, "ray") << std::endl; io::out() << dat::infoString(pntSoln, "pntSoln") << std::endl; io::out() << "<=== test data" << std::endl; } return oss.str(); } //! Check two ray intersection std::string geo_si_test2 () { std::ostringstream oss; ga::Vector const sta1{ 1., -1., 0. }; ga::Vector const sta2{ 1., 1., 0. }; ga::Vector const expPnt{ 0., 0., 0. }; double const sig0{ 8. }; std::array<double, 3u> const expSigs{ sig0, sig0, .5*sig0 }; // big->sml // measurement observations geo::Ray const ray1{ geo::Ray::fromToward(sta1, expPnt) }; geo::Ray const ray2{ geo::Ray::fromToward(sta2, expPnt) }; double const sig1{ sig0 }; double const sig2{ sig0 }; // collect observations of same classifications std::vector<geo::si::WRay> const wrays { { (1./sig1), ray1 } , { (1./sig2), ray2 } }; // compute intersection of collections geo::si::PointSystem system{}; system.addWeightedRays(wrays); // io::out() << "\n\n"; // io::out() << dat::infoString(system, "system") << std::endl; geo::si::PointSoln const pntSoln{ system.pointSolution() }; // io::out() << dat::infoString(pntSoln, "pntSoln") << std::endl; // check point location ga::Vector const & gotPnt = pntSoln.theLoc; bool okay{ true }; if (! gotPnt.nearlyEquals(expPnt)) { oss << "Failure of ray/ray pointSolution.theLoc test" << std::endl; oss << dat::infoString(expPnt, "expPnt") << std::endl; oss << dat::infoString(gotPnt, "gotPnt") << std::endl; okay = false; } // check uncertainty ellipsoid geo::si::SemiAxis const gotSig0{ pntSoln.kthLargestSemiAxis(0) }; geo::si::SemiAxis const gotSig1{ pntSoln.kthLargestSemiAxis(1) }; geo::si::SemiAxis const gotSig2{ pntSoln.kthLargestSemiAxis(2) }; std::array<double, 3u> const gotSigs { gotSig0.theMag, gotSig1.theMag, gotSig2.theMag }; if (! dat::nearlyEquals(gotSigs, expSigs)) { oss << "Failure of aposterior sigma estimate test" << std::endl; oss << dat::infoString(expSigs, "expSigs") << std::endl; oss << dat::infoString(gotSigs, "gotSigs") << std::endl; } constexpr bool show{ false }; if ((! okay) || show) { io::out() << "==== test data ====>" << std::endl; io::out() << dat::infoString(ray1, "ray1") << std::endl; io::out() << dat::infoString(ray2, "ray2") << std::endl; io::out() << dat::infoString(pntSoln, "pntSoln") << std::endl; io::out() << "<=== test data" << std::endl; } return oss.str(); } } //! Unit test for geo::si int main ( int const /*argc*/ , char const * const * /*argv*/ ) { std::ostringstream oss; // run tests oss << geo_si_test0(); oss << geo_si_test1(); oss << geo_si_test2(); // check/report results std::string const errMessages(oss.str()); if (! errMessages.empty()) { io::err() << errMessages << std::endl; return 1; } return 0; } <|endoftext|>
<commit_before>/* TimeManager.cpp * * Kubo Ryosuke */ #include "search/time/TimeManager.hpp" #include "search/Searcher.hpp" namespace { using namespace sunfish; PV::SizeType getPvStability(const PV& pv, const PV& pv2) { PV::SizeType pvStability = 0; for (; pvStability < pv.size() && pvStability < pv2.size(); pvStability++) { if (pv.getMove(pvStability) != pv2.getMove(pvStability)) { break; } } return pvStability; } } // namespace namespace sunfish { TimeManager::TimeManager() : previous2_(new History), previous_(new History), current_(new History) { } void TimeManager::clearGame() { } void TimeManager::clearPosition(SearchConfig::TimeType optimumTimeMs, SearchConfig::TimeType maximumTimeMs) { optimumTimeMs_ = optimumTimeMs; maximumTimeMs_ = maximumTimeMs; shouldInterrupt_ = false; previous2_->depth = 0; previous_->depth = 0; current_->depth = 0; } void TimeManager::update(uint32_t elapsedMs, int depth, Score score, const PV& pv, int moveCount, int maxMoveCount) { if (current_->depth != 0 && current_->depth != depth) { *previous2_ = *previous_; *previous_ = *current_; } current_->depth = depth; current_->score = score; current_->pv = pv; // if 90% of maximumTimeMs is already used if (maximumTimeMs_ != SearchConfig::InfinityTime && elapsedMs * 100 >= maximumTimeMs_ * 90) { shouldInterrupt_ = true; LOG(info) << "TimeManager: interrupt(90% of MAX)"; return; } if (previous2_->depth == 0 || previous_->depth == 0) { // do nothing return; } if (optimumTimeMs_ == SearchConfig::InfinityTime) { // do nothing return; } Score scoreDiff = current_->score - previous_->score; PV::SizeType pvStability = getPvStability(current_->pv, previous_->pv); PV::SizeType pvStability2 = getPvStability(current_->pv, previous2_->pv); // 10% of optimumTimeMs_ if (elapsedMs * 100 >= optimumTimeMs_ * 10 && depth >= Searcher::Depth1Ply * 12 && scoreDiff < 128 && scoreDiff > -32) { if ((pvStability >= 10 || pvStability2 >= 11) && (moveCount >= 20 || moveCount >= maxMoveCount)) { shouldInterrupt_ = true; LOG(info) << "TimeManager: interrupt(10% of OPTIM, L" << __LINE__ << ")"; return; } if (pvStability >= 7 && pvStability2 >= 7) { shouldInterrupt_ = true; LOG(info) << "TimeManager: interrupt(10% of OPTIM, L" << __LINE__ << ")"; return; } } // 50% of optimumTimeMs_ if (elapsedMs * 100 >= optimumTimeMs_ * 70 && depth >= Searcher::Depth1Ply * 12 && scoreDiff < 256 && scoreDiff > -64) { if ((pvStability >= 6 || pvStability2 >= 7) && (moveCount >= 8 || moveCount >= maxMoveCount)) { shouldInterrupt_ = true; LOG(info) << "TimeManager: interrupt(50% of OPTIM, L" << __LINE__ << ")"; return; } if (pvStability >= 3 && pvStability2 >= 3) { shouldInterrupt_ = true; LOG(info) << "TimeManager: interrupt(50% of OPTIM, L" << __LINE__ << ")"; return; } } // 100% of optimumTimeMs_ if (elapsedMs >= optimumTimeMs_ && depth >= Searcher::Depth1Ply * 12 && scoreDiff < 512 && scoreDiff > -128) { if ((pvStability >= 4 || pvStability2 >= 5) && (moveCount >= 3 || moveCount >= maxMoveCount)) { shouldInterrupt_ = true; LOG(info) << "TimeManager: interrupt(100% of OPTIM, L" << __LINE__ << ")"; return; } if (pvStability >= 2 && pvStability2 >= 2) { shouldInterrupt_ = true; LOG(info) << "TimeManager: interrupt(100% of OPTIM, L" << __LINE__ << ")"; return; } } // 200% of optimumTimeMs_ if (elapsedMs * 100 >= optimumTimeMs_ * 200 && depth >= Searcher::Depth1Ply * 12 && scoreDiff < 1024 && scoreDiff > -256) { if ((pvStability >= 3 || pvStability2 >= 3) && (moveCount >= 3 || moveCount >= maxMoveCount)) { shouldInterrupt_ = true; LOG(info) << "TimeManager: interrupt(200% of OPTIM, L" << __LINE__ << ")"; return; } if (pvStability >= 2 || pvStability2 >= 2) { shouldInterrupt_ = true; LOG(info) << "TimeManager: interrupt(200% of OPTIM, L" << __LINE__ << ")"; return; } } // 400% of optimumTimeMs_ if (elapsedMs * 100 >= optimumTimeMs_ * 400 && depth >= Searcher::Depth1Ply * 12 && scoreDiff < 2048 && scoreDiff > -512) { if ((pvStability >= 2 || pvStability2 >= 2) && (moveCount >= 2 || moveCount >= maxMoveCount)) { shouldInterrupt_ = true; LOG(info) << "TimeManager: interrupt(400% of OPTIM, L" << __LINE__ << ")"; return; } if (pvStability >= 2 && pvStability2 >= 2) { shouldInterrupt_ = true; LOG(info) << "TimeManager: interrupt(400% of OPTIM, L" << __LINE__ << ")"; return; } } } } // namespace sunfish <commit_msg>Modify TimeManager to use 97% of maximumTimeMs<commit_after>/* TimeManager.cpp * * Kubo Ryosuke */ #include "search/time/TimeManager.hpp" #include "search/Searcher.hpp" namespace { using namespace sunfish; PV::SizeType getPvStability(const PV& pv, const PV& pv2) { PV::SizeType pvStability = 0; for (; pvStability < pv.size() && pvStability < pv2.size(); pvStability++) { if (pv.getMove(pvStability) != pv2.getMove(pvStability)) { break; } } return pvStability; } } // namespace namespace sunfish { TimeManager::TimeManager() : previous2_(new History), previous_(new History), current_(new History) { } void TimeManager::clearGame() { } void TimeManager::clearPosition(SearchConfig::TimeType optimumTimeMs, SearchConfig::TimeType maximumTimeMs) { optimumTimeMs_ = optimumTimeMs; maximumTimeMs_ = maximumTimeMs; shouldInterrupt_ = false; previous2_->depth = 0; previous_->depth = 0; current_->depth = 0; } void TimeManager::update(uint32_t elapsedMs, int depth, Score score, const PV& pv, int moveCount, int maxMoveCount) { if (current_->depth != 0 && current_->depth != depth) { *previous2_ = *previous_; *previous_ = *current_; } current_->depth = depth; current_->score = score; current_->pv = pv; // if 97% of maximumTimeMs is already used if (maximumTimeMs_ != SearchConfig::InfinityTime && elapsedMs * 100 >= maximumTimeMs_ * 97) { shouldInterrupt_ = true; LOG(info) << "TimeManager: interrupt(97% of MAX)"; return; } if (previous2_->depth == 0 || previous_->depth == 0) { // do nothing return; } if (optimumTimeMs_ == SearchConfig::InfinityTime) { // do nothing return; } Score scoreDiff = current_->score - previous_->score; PV::SizeType pvStability = getPvStability(current_->pv, previous_->pv); PV::SizeType pvStability2 = getPvStability(current_->pv, previous2_->pv); // 10% of optimumTimeMs_ if (elapsedMs * 100 >= optimumTimeMs_ * 10 && depth >= Searcher::Depth1Ply * 12 && scoreDiff < 128 && scoreDiff > -32) { if ((pvStability >= 10 || pvStability2 >= 11) && (moveCount >= 20 || moveCount >= maxMoveCount)) { shouldInterrupt_ = true; LOG(info) << "TimeManager: interrupt(10% of OPTIM, L" << __LINE__ << ")"; return; } if (pvStability >= 7 && pvStability2 >= 7) { shouldInterrupt_ = true; LOG(info) << "TimeManager: interrupt(10% of OPTIM, L" << __LINE__ << ")"; return; } } // 50% of optimumTimeMs_ if (elapsedMs * 100 >= optimumTimeMs_ * 70 && depth >= Searcher::Depth1Ply * 12 && scoreDiff < 256 && scoreDiff > -64) { if ((pvStability >= 6 || pvStability2 >= 7) && (moveCount >= 8 || moveCount >= maxMoveCount)) { shouldInterrupt_ = true; LOG(info) << "TimeManager: interrupt(50% of OPTIM, L" << __LINE__ << ")"; return; } if (pvStability >= 3 && pvStability2 >= 3) { shouldInterrupt_ = true; LOG(info) << "TimeManager: interrupt(50% of OPTIM, L" << __LINE__ << ")"; return; } } // 100% of optimumTimeMs_ if (elapsedMs >= optimumTimeMs_ && depth >= Searcher::Depth1Ply * 12 && scoreDiff < 512 && scoreDiff > -128) { if ((pvStability >= 4 || pvStability2 >= 5) && (moveCount >= 3 || moveCount >= maxMoveCount)) { shouldInterrupt_ = true; LOG(info) << "TimeManager: interrupt(100% of OPTIM, L" << __LINE__ << ")"; return; } if (pvStability >= 2 && pvStability2 >= 2) { shouldInterrupt_ = true; LOG(info) << "TimeManager: interrupt(100% of OPTIM, L" << __LINE__ << ")"; return; } } // 200% of optimumTimeMs_ if (elapsedMs * 100 >= optimumTimeMs_ * 200 && depth >= Searcher::Depth1Ply * 12 && scoreDiff < 1024 && scoreDiff > -256) { if ((pvStability >= 3 || pvStability2 >= 3) && (moveCount >= 3 || moveCount >= maxMoveCount)) { shouldInterrupt_ = true; LOG(info) << "TimeManager: interrupt(200% of OPTIM, L" << __LINE__ << ")"; return; } if (pvStability >= 2 || pvStability2 >= 2) { shouldInterrupt_ = true; LOG(info) << "TimeManager: interrupt(200% of OPTIM, L" << __LINE__ << ")"; return; } } // 400% of optimumTimeMs_ if (elapsedMs * 100 >= optimumTimeMs_ * 400 && depth >= Searcher::Depth1Ply * 12 && scoreDiff < 2048 && scoreDiff > -512) { if ((pvStability >= 2 || pvStability2 >= 2) && (moveCount >= 2 || moveCount >= maxMoveCount)) { shouldInterrupt_ = true; LOG(info) << "TimeManager: interrupt(400% of OPTIM, L" << __LINE__ << ")"; return; } if (pvStability >= 2 && pvStability2 >= 2) { shouldInterrupt_ = true; LOG(info) << "TimeManager: interrupt(400% of OPTIM, L" << __LINE__ << ")"; return; } } } } // namespace sunfish <|endoftext|>
<commit_before>// https://github.com/KubaO/stackoverflown/tree/master/questions/multisocket-22726075 #include <QtNetwork> class EchoServer : public QTcpServer { QStack<QTcpSocket*> m_pool; void incomingConnection(qintptr descr) Q_DECL_OVERRIDE { auto newSocket = m_pool.isEmpty(); auto s = newSocket ? new QTcpSocket(this) : m_pool.pop(); if (newSocket) { QObject::connect(s, &QTcpSocket::readyRead, s, [s]{ s->write(s->readAll()); }); QObject::connect(s, &QTcpSocket::disconnected, this, [this, s]{ m_pool.push(s); }); } s->setSocketDescriptor(descr, QTcpSocket::ConnectedState); } public: ~EchoServer() { qDebug() << "pool size:" << m_pool.size(); } }; void setupEchoClient(QTcpSocket & sock) { static const char kByteCount[] = "byteCount"; QObject::connect(&sock, &QTcpSocket::connected, [&sock]{ auto byteCount = 64 + qrand() % 65536; sock.setProperty(kByteCount, byteCount); sock.write(QByteArray(byteCount, '\x2A')); }); QObject::connect(&sock, &QTcpSocket::readyRead, [&sock]{ auto byteCount = sock.property(kByteCount).toInt(); if (byteCount) { auto read = sock.read(sock.bytesAvailable()).size(); byteCount -= read; } if (byteCount <= 0) sock.disconnectFromHost(); sock.setProperty(kByteCount, byteCount); }); } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QHostAddress addr("127.0.0.1"); quint16 port = 5050; EchoServer server; if (! server.listen(addr, port)) qFatal("can't listen"); QTcpSocket clientSocket; setupEchoClient(clientSocket); auto connectsLeft = 20; auto connector = [&clientSocket, &addr, port, &connectsLeft]{ if (connectsLeft--) { qDebug() << "connecting" << connectsLeft; clientSocket.connectToHost(addr, port); } else qApp->quit(); }; // reconnect upon disconnection QObject::connect(&clientSocket, &QTcpSocket::disconnected, connector); // initiate first connection connector(); return a.exec(); } <commit_msg>Make pool fill more explicit.<commit_after>// https://github.com/KubaO/stackoverflown/tree/master/questions/multisocket-22726075 #include <QtNetwork> class EchoServer : public QTcpServer { QStack<QTcpSocket*> m_pool; void incomingConnection(qintptr descr) Q_DECL_OVERRIDE { if (m_pool.isEmpty()) { auto s = new QTcpSocket(this); QObject::connect(s, &QTcpSocket::readyRead, s, [s]{ s->write(s->readAll()); }); QObject::connect(s, &QTcpSocket::disconnected, this, [this, s]{ m_pool.push(s); }); m_pool.push(s); } m_pool.pop()->setSocketDescriptor(descr, QTcpSocket::ConnectedState); } public: ~EchoServer() { qDebug() << "pool size:" << m_pool.size(); } }; void setupEchoClient(QTcpSocket & sock) { static const char kByteCount[] = "byteCount"; QObject::connect(&sock, &QTcpSocket::connected, [&sock]{ auto byteCount = 64 + qrand() % 65536; sock.setProperty(kByteCount, byteCount); sock.write(QByteArray(byteCount, '\x2A')); }); QObject::connect(&sock, &QTcpSocket::readyRead, [&sock]{ auto byteCount = sock.property(kByteCount).toInt(); if (byteCount) { auto read = sock.read(sock.bytesAvailable()).size(); byteCount -= read; } if (byteCount <= 0) sock.disconnectFromHost(); sock.setProperty(kByteCount, byteCount); }); } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QHostAddress addr("127.0.0.1"); quint16 port = 5050; EchoServer server; if (! server.listen(addr, port)) qFatal("can't listen"); QTcpSocket clientSocket; setupEchoClient(clientSocket); auto connectsLeft = 20; auto connector = [&clientSocket, &addr, port, &connectsLeft]{ if (connectsLeft--) { qDebug() << "connecting" << connectsLeft; clientSocket.connectToHost(addr, port); } else qApp->quit(); }; // reconnect upon disconnection QObject::connect(&clientSocket, &QTcpSocket::disconnected, connector); // initiate first connection connector(); return a.exec(); } <|endoftext|>
<commit_before>// (c) Facebook, Inc. and its affiliates. Confidential and proprietary. #include <quic/common/TransportKnobs.h> #include <folly/portability/GTest.h> using namespace ::testing; namespace quic { namespace test { struct QuicKnobsParsingTestFixture { std::string serializedKnobs; bool expectError; TransportKnobParams expectParams; }; void run(const QuicKnobsParsingTestFixture& fixture) { auto result = parseTransportKnobs(fixture.serializedKnobs); if (fixture.expectError) { EXPECT_FALSE(result.hasValue()); } else { EXPECT_EQ(result->size(), fixture.expectParams.size()); for (size_t i = 0; i < result->size(); i++) { auto& actualKnob = (*result)[i]; auto& expectKnob = fixture.expectParams[i]; EXPECT_EQ(actualKnob.id, expectKnob.id) << "Knob " << i; EXPECT_EQ(actualKnob.val, expectKnob.val) << "Knob " << i; } } } TEST(QuicKnobsParsingTest, Simple) { QuicKnobsParsingTestFixture fixture = { "{ \"0\": 1," " \"1\": 5," " \"19\": 6," " \"2\": 3" " }", false, {{0, 1}, {1, 5}, {2, 3}, {19, 6}}}; run(fixture); } TEST(QuicKnobsParsingTest, ObjectValue) { QuicKnobsParsingTestFixture fixture = { "{ \"1\": " " {" " \"0\" : 1" " }" "}", true, {}}; run(fixture); } TEST(QuicKnobsParsingTest, InvalidJson) { QuicKnobsParsingTestFixture fixture = { "{\"0\": " " \"1\": " " {" " \"0\" : 1" " }" "}", true, {}}; run(fixture); } TEST(QuicKnobsParsingTest, Characters) { QuicKnobsParsingTestFixture fixture = {"{ \"o\" : 1 }", true, {}}; run(fixture); } TEST(QuicKnobsParsingTest, NegativeNumbers) { QuicKnobsParsingTestFixture fixture = {"{ \"1\" : -1 }", true, {}}; run(fixture); } TEST(QuicKnobsParsingTest, StringValue) { QuicKnobsParsingTestFixture fixture = {"{ \"1\" : \"1\" }", true, {}}; run(fixture); } TEST(QuicKnobsParsingTest, NonStringKey) { QuicKnobsParsingTestFixture fixture = {"{ 1 : 1 }", true, {}}; run(fixture); } TEST(QuicKnobsParsingTest, DoubleKey) { QuicKnobsParsingTestFixture fixture = {"{ \"3.14\" : 1 }", true, {}}; run(fixture); } TEST(QuicKnobsParsingTest, DoubleValue) { QuicKnobsParsingTestFixture fixture = {"{ \"10\" : 0.1 }", true, {}}; run(fixture); } } // namespace test } // namespace quic <commit_msg>Update copyright on new file<commit_after>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ #include <quic/common/TransportKnobs.h> #include <folly/portability/GTest.h> using namespace ::testing; namespace quic { namespace test { struct QuicKnobsParsingTestFixture { std::string serializedKnobs; bool expectError; TransportKnobParams expectParams; }; void run(const QuicKnobsParsingTestFixture& fixture) { auto result = parseTransportKnobs(fixture.serializedKnobs); if (fixture.expectError) { EXPECT_FALSE(result.hasValue()); } else { EXPECT_EQ(result->size(), fixture.expectParams.size()); for (size_t i = 0; i < result->size(); i++) { auto& actualKnob = (*result)[i]; auto& expectKnob = fixture.expectParams[i]; EXPECT_EQ(actualKnob.id, expectKnob.id) << "Knob " << i; EXPECT_EQ(actualKnob.val, expectKnob.val) << "Knob " << i; } } } TEST(QuicKnobsParsingTest, Simple) { QuicKnobsParsingTestFixture fixture = { "{ \"0\": 1," " \"1\": 5," " \"19\": 6," " \"2\": 3" " }", false, {{0, 1}, {1, 5}, {2, 3}, {19, 6}}}; run(fixture); } TEST(QuicKnobsParsingTest, ObjectValue) { QuicKnobsParsingTestFixture fixture = { "{ \"1\": " " {" " \"0\" : 1" " }" "}", true, {}}; run(fixture); } TEST(QuicKnobsParsingTest, InvalidJson) { QuicKnobsParsingTestFixture fixture = { "{\"0\": " " \"1\": " " {" " \"0\" : 1" " }" "}", true, {}}; run(fixture); } TEST(QuicKnobsParsingTest, Characters) { QuicKnobsParsingTestFixture fixture = {"{ \"o\" : 1 }", true, {}}; run(fixture); } TEST(QuicKnobsParsingTest, NegativeNumbers) { QuicKnobsParsingTestFixture fixture = {"{ \"1\" : -1 }", true, {}}; run(fixture); } TEST(QuicKnobsParsingTest, StringValue) { QuicKnobsParsingTestFixture fixture = {"{ \"1\" : \"1\" }", true, {}}; run(fixture); } TEST(QuicKnobsParsingTest, NonStringKey) { QuicKnobsParsingTestFixture fixture = {"{ 1 : 1 }", true, {}}; run(fixture); } TEST(QuicKnobsParsingTest, DoubleKey) { QuicKnobsParsingTestFixture fixture = {"{ \"3.14\" : 1 }", true, {}}; run(fixture); } TEST(QuicKnobsParsingTest, DoubleValue) { QuicKnobsParsingTestFixture fixture = {"{ \"10\" : 0.1 }", true, {}}; run(fixture); } } // namespace test } // namespace quic <|endoftext|>
<commit_before>#include "contest.h" #include <simlib/debug.h> #include <simlib/logger.h> #include <simlib/time.h> using std::string; using std::vector; string Contest::submissionStatusDescription(const string& status) { if (status == "ok") return "Initial tests: OK"; if (status == "error") return "Initial tests: Error"; if (status == "c_error") return "Compilation failed"; if (status == "judge_error") return "Judge error"; if (status == "waiting") return "Pending"; return "Unknown"; } Contest::RoundPath* Contest::getRoundPath(const string& round_id) { std::unique_ptr<RoundPath> r_path(new RoundPath(round_id)); try { DB::Statement stmt = db_conn.prepare( "SELECT id, parent, problem_id, name, owner, is_public, visible, " "show_ranking, begins, ends, full_results " "FROM rounds " "WHERE id=? OR id=(SELECT parent FROM rounds WHERE id=?) OR " "id=(SELECT grandparent FROM rounds WHERE id=?)"); stmt.setString(1, round_id); stmt.setString(2, round_id); stmt.setString(3, round_id); DB::Result res = stmt.executeQuery(); auto copyDataTo = [&](std::unique_ptr<Round>& r) { r.reset(new Round); r->id = res[1]; r->parent = res[2]; r->problem_id = res[3]; r->name = res[4]; r->owner = res[5]; r->is_public = res.getBool(6); r->visible = res.getBool(7); r->show_ranking = res.getBool(8); r->begins = res[9]; r->ends = res[10]; r->full_results = res[11]; }; int rows = res.rowCount(); // If round does not exist if (rows == 0) { error404(); return nullptr; } r_path->type = (rows == 1 ? CONTEST : (rows == 2 ? ROUND : PROBLEM)); while (res.next()) { if (res.isNull(2)) copyDataTo(r_path->contest); else if (res.isNull(3)) // problem_id IS NULL copyDataTo(r_path->round); else copyDataTo(r_path->problem); } // Check rounds hierarchy if (!r_path->contest || (rows > 1 && !r_path->round) || (rows > 2 && !r_path->problem)) { THROW("Database error: corrupted hierarchy of rounds (id: ", round_id, ")"); } // Check access r_path->admin_access = isAdmin(*r_path); // TODO: get data in above query! if (!r_path->admin_access) { if (!r_path->contest->is_public) { // Check access to contest if (!Session::open()) { redirect(concat("/login", req->target)); return nullptr; } stmt = db_conn.prepare("SELECT user_id " "FROM users_to_contests WHERE user_id=? AND contest_id=?"); stmt.setString(1, Session::user_id); stmt.setString(2, r_path->contest->id); res = stmt.executeQuery(); if (!res.next()) { // User is not assigned to this contest error403(); return nullptr; } } // Check access to round - check if round has begun // If begin time is not null and round has not begun, then error 403 if (r_path->type != CONTEST && r_path->round->begins.size() && date("%Y-%m-%d %H:%M:%S") < r_path->round->begins) { error403(); return nullptr; } } } catch (const std::exception& e) { ERRLOG_CAUGHT(e); error500(); return nullptr; } return r_path.release(); } Template::TemplateEnder Contest::contestTemplate(const StringView& title, const StringView& styles, const StringView& scripts) { auto ender = baseTemplate(title, concat(".body{margin-left:190px}", styles), scripts); append("<ul class=\"menu\">\n"); // Aliases string &round_id = rpath->round_id; bool &admin_access = rpath->admin_access; if (admin_access) { append( "<a href=\"/c/add\">Add contest</a>\n" "<span>CONTEST ADMINISTRATION</span>\n"); // Adding append("<a href=\"/c/", rpath->contest->id, "/add\">Add round</a>\n"); if (rpath->type >= ROUND) append("<a href=\"/c/", rpath->round->id, "/add\">" "Add problem</a>\n"); // Editing append("<a href=\"/c/", rpath->contest->id, "/edit\">" "Edit contest</a>\n"); if (rpath->type >= ROUND) append("<a href=\"/c/", rpath->round->id, "/edit\">" "Edit round</a>\n"); if (rpath->type == PROBLEM) append("<a href=\"/c/", round_id, "/edit\">Edit problem</a>\n"); append("<hr/>" "<a href=\"/c/", rpath->contest->id, "\">Contest dashboard</a>\n" "<a href=\"/c/", rpath->contest->id, "/problems\">Problems</a>\n" "<a href=\"/c/", rpath->contest->id, "/files\">Files</a>\n" "<a href=\"/c/", round_id, "/submit\">Submit a solution</a>\n" "<a href=\"/c/", rpath->contest->id, "/submissions\">" "Submissions</a>\n" "<a href=\"/c/", round_id, "/submissions\">" "Local submissions</a>\n" "<a href=\"/c/", rpath->contest->id, "/ranking\">Ranking</a>\n" "<span>OBSERVER MENU</span>\n"); } append("<a href=\"/c/", rpath->contest->id, (admin_access ? "/n" : ""), "\">Contest dashboard</a>\n" "<a href=\"/c/", rpath->contest->id, (admin_access ? "/n" : ""), "/problems\">Problems</a>\n" "<a href=\"/c/", rpath->contest->id, (admin_access ? "/n" : ""), "/files\">Files</a>\n"); string current_date = date("%Y-%m-%d %H:%M:%S"); Round *round = rpath->round.get(); if (rpath->type == CONTEST || ( (round->begins.empty() || round->begins <= current_date) && (round->ends.empty() || current_date < round->ends))) { append("<a href=\"/c/", round_id, (admin_access ? "/n" : ""), "/submit\">Submit a solution</a>\n"); } append("<a href=\"/c/", rpath->contest->id, (admin_access ? "/n" : ""), "/submissions\">Submissions</a>\n"); append("<a href=\"/c/", round_id, (admin_access ? "/n" : ""), "/submissions\">Local submissions</a>\n"); if (rpath->contest->show_ranking) append("<a href=\"/c/", rpath->contest->id, (admin_access ? "/n" : ""), "/ranking\">Ranking</a>\n"); append("</ul>"); return ender; } bool Contest::isAdmin(const RoundPath& r_path) { // If is not logged in, he cannot be admin if (!Session::open()) return false; // User is the owner of the contest if (r_path.contest->owner == Session::user_id) return true; try { // Check if user has more privileges than the owner DB::Statement stmt = db_conn.prepare( "SELECT type FROM users WHERE id=?"); stmt.setString(1, r_path.contest->owner); DB::Result res = stmt.executeQuery(); int owner_type = UTYPE_ADMIN; if (res.next()) owner_type = res.getUInt(1); return owner_type > Session::user_type; // TODO: give SIM root privileges to admins' contests (in contest list // in handle() also) } catch (const std::exception& e) { ERRLOG_CAUGHT(e); } return false; } void Contest::printRoundPath(const StringView& page, bool force_normal) { append("<div class=\"round-path\"><a href=\"/c/", rpath->contest->id, (force_normal ? "/n/" : "/"), page, "\">", htmlSpecialChars(rpath->contest->name), "</a>"); if (rpath->type != CONTEST) { append(" -> <a href=\"/c/", rpath->round->id, (force_normal ? "/n/" : "/"), page, "\">", htmlSpecialChars(rpath->round->name), "</a>"); if (rpath->type == PROBLEM) append(" -> <a href=\"/c/", rpath->problem->id, (force_normal ? "/n/" : "/"), page, "\">", htmlSpecialChars(rpath->problem->name), "</a>"); } append("</div>\n"); } void Contest::printRoundView(bool link_to_problem_statement, bool admin_view) { try { if (rpath->type == CONTEST) { // Select subrounds DB::Statement stmt = db_conn.prepare(admin_view ? "SELECT id, name, item, visible, begins, ends, " "full_results FROM rounds WHERE parent=? ORDER BY item" : "SELECT id, name, item, visible, begins, ends, full_results " "FROM rounds WHERE parent=? AND " "(visible IS TRUE OR begins IS NULL OR begins<=?) " "ORDER BY item"); stmt.setString(1, rpath->contest->id); if (!admin_view) stmt.setString(2, date("%Y-%m-%d %H:%M:%S")); // current date struct SubroundExtended { string id, name, item, begins, ends, full_results; bool visible; }; DB::Result res = stmt.executeQuery(); vector<SubroundExtended> subrounds; // For performance subrounds.reserve(res.rowCount()); // Collect results while (res.next()) { subrounds.emplace_back(); subrounds.back().id = res[1]; subrounds.back().name = res[2]; subrounds.back().item = res[3]; subrounds.back().visible = res.getBool(4); subrounds.back().begins = res[5]; subrounds.back().ends = res[6]; subrounds.back().full_results = res[7]; } // Select problems stmt = db_conn.prepare("SELECT id, parent, name FROM rounds " "WHERE grandparent=? ORDER BY item"); stmt.setString(1, rpath->contest->id); res = stmt.executeQuery(); std::map<string, vector<Problem> > problems; // (round_id, problems) // Fill with all subrounds for (auto&& sr : subrounds) problems[sr.id]; // Collect results while (res.next()) { // Get reference to proper vector<Problem> auto it = problems.find(res[2]); // If problem parent is not visible or database error if (it == problems.end()) continue; // Ignore vector<Problem>& prob = it->second; prob.emplace_back(); prob.back().id = res[1]; prob.back().parent = res[2]; prob.back().name = res[3]; } // Construct "table" append("<div class=\"round-view\">\n" "<a href=\"/c/", rpath->contest->id, "\"", ">", htmlSpecialChars(rpath->contest->name), "</a>\n" "<div>\n"); // For each subround list all problems for (auto&& sr : subrounds) { // Round append("<div>\n" "<a href=\"/c/", sr.id, "\">", htmlSpecialChars(sr.name), "</a>\n"); // List problems vector<Problem>& prob = problems[sr.id]; for (auto&& pro : prob) { append("<a href=\"/c/", pro.id); if (link_to_problem_statement) append("/statement"); append("\">", htmlSpecialChars(pro.name), "</a>\n"); } append("</div>\n"); } append("</div>\n" "</div>\n"); } else if (rpath->type == ROUND) { // Construct "table" append("<div class=\"round-view\">\n" "<a href=\"/c/", rpath->contest->id, "\"", ">", htmlSpecialChars(rpath->contest->name), "</a>\n" "<div>\n"); // Round append("<div>\n" "<a href=\"/c/", rpath->round->id, "\">", htmlSpecialChars(rpath->round->name), "</a>\n"); // Select problems DB::Statement stmt = db_conn.prepare("SELECT id, name " "FROM rounds WHERE parent=? ORDER BY item"); stmt.setString(1, rpath->round->id); // List problems DB::Result res = stmt.executeQuery(); while (res.next()) { append("<a href=\"/c/", res[1]); if (link_to_problem_statement) append("/statement"); append("\">", htmlSpecialChars(res[2]), "</a>\n"); } append("</div>\n" "</div>\n" "</div>\n"); } else { // rpath->type == PROBLEM // Construct "table" append("<div class=\"round-view\">\n" "<a href=\"/c/", rpath->contest->id, "\"", ">", htmlSpecialChars(rpath->contest->name), "</a>\n" "<div>\n"); // Round append("<div>\n" "<a href=\"/c/", rpath->round->id, "\">", htmlSpecialChars(rpath->round->name), "</a>\n" "<a href=\"/c/", rpath->problem->id); if (link_to_problem_statement) append("/statement"); append("\">", htmlSpecialChars(rpath->problem->name), "</a>\n" "</div>\n" "</div>\n" "</div>\n"); } } catch (const std::exception& e) { ERRLOG_CAUGHT(e); } } <commit_msg>Gave Sim root permissions to administer admins' contests<commit_after>#include "contest.h" #include <simlib/debug.h> #include <simlib/logger.h> #include <simlib/time.h> using std::string; using std::vector; string Contest::submissionStatusDescription(const string& status) { if (status == "ok") return "Initial tests: OK"; if (status == "error") return "Initial tests: Error"; if (status == "c_error") return "Compilation failed"; if (status == "judge_error") return "Judge error"; if (status == "waiting") return "Pending"; return "Unknown"; } Contest::RoundPath* Contest::getRoundPath(const string& round_id) { std::unique_ptr<RoundPath> r_path(new RoundPath(round_id)); try { DB::Statement stmt = db_conn.prepare( "SELECT id, parent, problem_id, name, owner, is_public, visible, " "show_ranking, begins, ends, full_results " "FROM rounds " "WHERE id=? OR id=(SELECT parent FROM rounds WHERE id=?) OR " "id=(SELECT grandparent FROM rounds WHERE id=?)"); stmt.setString(1, round_id); stmt.setString(2, round_id); stmt.setString(3, round_id); DB::Result res = stmt.executeQuery(); auto copyDataTo = [&](std::unique_ptr<Round>& r) { r.reset(new Round); r->id = res[1]; r->parent = res[2]; r->problem_id = res[3]; r->name = res[4]; r->owner = res[5]; r->is_public = res.getBool(6); r->visible = res.getBool(7); r->show_ranking = res.getBool(8); r->begins = res[9]; r->ends = res[10]; r->full_results = res[11]; }; int rows = res.rowCount(); // If round does not exist if (rows == 0) { error404(); return nullptr; } r_path->type = (rows == 1 ? CONTEST : (rows == 2 ? ROUND : PROBLEM)); while (res.next()) { if (res.isNull(2)) copyDataTo(r_path->contest); else if (res.isNull(3)) // problem_id IS NULL copyDataTo(r_path->round); else copyDataTo(r_path->problem); } // Check rounds hierarchy if (!r_path->contest || (rows > 1 && !r_path->round) || (rows > 2 && !r_path->problem)) { THROW("Database error: corrupted hierarchy of rounds (id: ", round_id, ")"); } // Check access r_path->admin_access = isAdmin(*r_path); // TODO: get data in above query! if (!r_path->admin_access) { if (!r_path->contest->is_public) { // Check access to contest if (!Session::open()) { redirect(concat("/login", req->target)); return nullptr; } stmt = db_conn.prepare("SELECT user_id " "FROM users_to_contests WHERE user_id=? AND contest_id=?"); stmt.setString(1, Session::user_id); stmt.setString(2, r_path->contest->id); res = stmt.executeQuery(); if (!res.next()) { // User is not assigned to this contest error403(); return nullptr; } } // Check access to round - check if round has begun // If begin time is not null and round has not begun, then error 403 if (r_path->type != CONTEST && r_path->round->begins.size() && date("%Y-%m-%d %H:%M:%S") < r_path->round->begins) { error403(); return nullptr; } } } catch (const std::exception& e) { ERRLOG_CAUGHT(e); error500(); return nullptr; } return r_path.release(); } Template::TemplateEnder Contest::contestTemplate(const StringView& title, const StringView& styles, const StringView& scripts) { auto ender = baseTemplate(title, concat(".body{margin-left:190px}", styles), scripts); append("<ul class=\"menu\">\n"); // Aliases string &round_id = rpath->round_id; bool &admin_access = rpath->admin_access; if (admin_access) { append( "<a href=\"/c/add\">Add contest</a>\n" "<span>CONTEST ADMINISTRATION</span>\n"); // Adding append("<a href=\"/c/", rpath->contest->id, "/add\">Add round</a>\n"); if (rpath->type >= ROUND) append("<a href=\"/c/", rpath->round->id, "/add\">" "Add problem</a>\n"); // Editing append("<a href=\"/c/", rpath->contest->id, "/edit\">" "Edit contest</a>\n"); if (rpath->type >= ROUND) append("<a href=\"/c/", rpath->round->id, "/edit\">" "Edit round</a>\n"); if (rpath->type == PROBLEM) append("<a href=\"/c/", round_id, "/edit\">Edit problem</a>\n"); append("<hr/>" "<a href=\"/c/", rpath->contest->id, "\">Contest dashboard</a>\n" "<a href=\"/c/", rpath->contest->id, "/problems\">Problems</a>\n" "<a href=\"/c/", rpath->contest->id, "/files\">Files</a>\n" "<a href=\"/c/", round_id, "/submit\">Submit a solution</a>\n" "<a href=\"/c/", rpath->contest->id, "/submissions\">" "Submissions</a>\n" "<a href=\"/c/", round_id, "/submissions\">" "Local submissions</a>\n" "<a href=\"/c/", rpath->contest->id, "/ranking\">Ranking</a>\n" "<span>OBSERVER MENU</span>\n"); } append("<a href=\"/c/", rpath->contest->id, (admin_access ? "/n" : ""), "\">Contest dashboard</a>\n" "<a href=\"/c/", rpath->contest->id, (admin_access ? "/n" : ""), "/problems\">Problems</a>\n" "<a href=\"/c/", rpath->contest->id, (admin_access ? "/n" : ""), "/files\">Files</a>\n"); string current_date = date("%Y-%m-%d %H:%M:%S"); Round *round = rpath->round.get(); if (rpath->type == CONTEST || ( (round->begins.empty() || round->begins <= current_date) && (round->ends.empty() || current_date < round->ends))) { append("<a href=\"/c/", round_id, (admin_access ? "/n" : ""), "/submit\">Submit a solution</a>\n"); } append("<a href=\"/c/", rpath->contest->id, (admin_access ? "/n" : ""), "/submissions\">Submissions</a>\n"); append("<a href=\"/c/", round_id, (admin_access ? "/n" : ""), "/submissions\">Local submissions</a>\n"); if (rpath->contest->show_ranking) append("<a href=\"/c/", rpath->contest->id, (admin_access ? "/n" : ""), "/ranking\">Ranking</a>\n"); append("</ul>"); return ender; } bool Contest::isAdmin(const RoundPath& r_path) { // If is not logged in, he cannot be admin if (!Session::open()) return false; // User is the owner of the contest or is the Sim root if (r_path.contest->owner == Session::user_id || Session::user_id == "1") return true; try { // Check if user has more privileges than the owner DB::Statement stmt = db_conn.prepare( "SELECT type FROM users WHERE id=?"); stmt.setString(1, r_path.contest->owner); DB::Result res = stmt.executeQuery(); int owner_type = UTYPE_ADMIN; if (res.next()) owner_type = res.getUInt(1); return owner_type > Session::user_type; // TODO: give SIM root privileges to admins' contests (in contest list // in handle() also) } catch (const std::exception& e) { ERRLOG_CAUGHT(e); } return false; } void Contest::printRoundPath(const StringView& page, bool force_normal) { append("<div class=\"round-path\"><a href=\"/c/", rpath->contest->id, (force_normal ? "/n/" : "/"), page, "\">", htmlSpecialChars(rpath->contest->name), "</a>"); if (rpath->type != CONTEST) { append(" -> <a href=\"/c/", rpath->round->id, (force_normal ? "/n/" : "/"), page, "\">", htmlSpecialChars(rpath->round->name), "</a>"); if (rpath->type == PROBLEM) append(" -> <a href=\"/c/", rpath->problem->id, (force_normal ? "/n/" : "/"), page, "\">", htmlSpecialChars(rpath->problem->name), "</a>"); } append("</div>\n"); } void Contest::printRoundView(bool link_to_problem_statement, bool admin_view) { try { if (rpath->type == CONTEST) { // Select subrounds DB::Statement stmt = db_conn.prepare(admin_view ? "SELECT id, name, item, visible, begins, ends, " "full_results FROM rounds WHERE parent=? ORDER BY item" : "SELECT id, name, item, visible, begins, ends, full_results " "FROM rounds WHERE parent=? AND " "(visible IS TRUE OR begins IS NULL OR begins<=?) " "ORDER BY item"); stmt.setString(1, rpath->contest->id); if (!admin_view) stmt.setString(2, date("%Y-%m-%d %H:%M:%S")); // current date struct SubroundExtended { string id, name, item, begins, ends, full_results; bool visible; }; DB::Result res = stmt.executeQuery(); vector<SubroundExtended> subrounds; // For performance subrounds.reserve(res.rowCount()); // Collect results while (res.next()) { subrounds.emplace_back(); subrounds.back().id = res[1]; subrounds.back().name = res[2]; subrounds.back().item = res[3]; subrounds.back().visible = res.getBool(4); subrounds.back().begins = res[5]; subrounds.back().ends = res[6]; subrounds.back().full_results = res[7]; } // Select problems stmt = db_conn.prepare("SELECT id, parent, name FROM rounds " "WHERE grandparent=? ORDER BY item"); stmt.setString(1, rpath->contest->id); res = stmt.executeQuery(); std::map<string, vector<Problem> > problems; // (round_id, problems) // Fill with all subrounds for (auto&& sr : subrounds) problems[sr.id]; // Collect results while (res.next()) { // Get reference to proper vector<Problem> auto it = problems.find(res[2]); // If problem parent is not visible or database error if (it == problems.end()) continue; // Ignore vector<Problem>& prob = it->second; prob.emplace_back(); prob.back().id = res[1]; prob.back().parent = res[2]; prob.back().name = res[3]; } // Construct "table" append("<div class=\"round-view\">\n" "<a href=\"/c/", rpath->contest->id, "\"", ">", htmlSpecialChars(rpath->contest->name), "</a>\n" "<div>\n"); // For each subround list all problems for (auto&& sr : subrounds) { // Round append("<div>\n" "<a href=\"/c/", sr.id, "\">", htmlSpecialChars(sr.name), "</a>\n"); // List problems vector<Problem>& prob = problems[sr.id]; for (auto&& pro : prob) { append("<a href=\"/c/", pro.id); if (link_to_problem_statement) append("/statement"); append("\">", htmlSpecialChars(pro.name), "</a>\n"); } append("</div>\n"); } append("</div>\n" "</div>\n"); } else if (rpath->type == ROUND) { // Construct "table" append("<div class=\"round-view\">\n" "<a href=\"/c/", rpath->contest->id, "\"", ">", htmlSpecialChars(rpath->contest->name), "</a>\n" "<div>\n"); // Round append("<div>\n" "<a href=\"/c/", rpath->round->id, "\">", htmlSpecialChars(rpath->round->name), "</a>\n"); // Select problems DB::Statement stmt = db_conn.prepare("SELECT id, name " "FROM rounds WHERE parent=? ORDER BY item"); stmt.setString(1, rpath->round->id); // List problems DB::Result res = stmt.executeQuery(); while (res.next()) { append("<a href=\"/c/", res[1]); if (link_to_problem_statement) append("/statement"); append("\">", htmlSpecialChars(res[2]), "</a>\n"); } append("</div>\n" "</div>\n" "</div>\n"); } else { // rpath->type == PROBLEM // Construct "table" append("<div class=\"round-view\">\n" "<a href=\"/c/", rpath->contest->id, "\"", ">", htmlSpecialChars(rpath->contest->name), "</a>\n" "<div>\n"); // Round append("<div>\n" "<a href=\"/c/", rpath->round->id, "\">", htmlSpecialChars(rpath->round->name), "</a>\n" "<a href=\"/c/", rpath->problem->id); if (link_to_problem_statement) append("/statement"); append("\">", htmlSpecialChars(rpath->problem->name), "</a>\n" "</div>\n" "</div>\n" "</div>\n"); } } catch (const std::exception& e) { ERRLOG_CAUGHT(e); } } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #if !defined(XMLPARSERLIAISON_HEADER_GUARD_1357924680) #define XMLPARSERLIAISON_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <XMLSupport/XMLSupportDefinitions.hpp> #include <XalanDOM/XalanDOMString.hpp> #include <PlatformSupport/Resettable.hpp> class DocumentHandler; class EntityResolver; class ErrorHandler; class ExecutionContext; class FormatterListener; class InputSource; class XalanAttr; class XalanDocument; class XalanElement; class XALAN_XMLSUPPORT_EXPORT XMLParserLiaison : public Resettable { public: XMLParserLiaison(); virtual ~XMLParserLiaison(); // These interfaces are inherited from Resettable... virtual void reset() = 0; // These interfaces are new to XMLParserLiaison virtual ExecutionContext* getExecutionContext() const = 0; virtual void setExecutionContext(ExecutionContext& theContext) = 0; /** * Parse the text pointed at by the reader as XML, and return a DOM * Document interface. It is recommended that you pass in some sort of * recognizable name, such as the filename or URI, with which the reader * can be recognized if the parse fails. * * The liaison owns the XalanDocument instance, and will delete it when * when asked (see DestroyDocument()), or when the liaison is reset, or * goes out of scope. * * @param reader stream that should hold valid XML * @param identifier used for diagnostic purposes only, some sort of * identification for error reporting, default an empty * string * @return DOM document created */ virtual XalanDocument* parseXMLStream( const InputSource& inputSource, const XalanDOMString& identifier = XalanDOMString()) = 0; /** * Parse the text pointed at by the reader as XML. It is recommended that * you pass in some sort of recognizable name, such as the filename or URI, * with which the reader can be recognized if the parse fails. * * @param inputSource input source that should hold valid XML * @param handler instance of a DocumentHandler * @param identifier used for diagnostic purposes only, some sort of * identification for error reporting, default an * empty string */ virtual void parseXMLStream( const InputSource& inputSource, DocumentHandler& handler, const XalanDOMString& identifier = XalanDOMString()) = 0; /** * Create an empty DOM Document. Mainly used for creating an * output document. * * The liaison owns the XalanDocument instance, and will delete it when * when asked (see DestroyDocument()), or when the liaison is reset, or * goes out of scope. * * @return DOM document created */ virtual XalanDocument* createDocument() = 0; /** * Get a factory object required to create nodes in the result tree. * * The liaison owns the XalanDocument instance, and will delete it when * when asked (see DestroyDocument()), or when the liaison is reset, or * goes out of scope. * * @return A XalanDocument instance. */ virtual XalanDocument* createDOMFactory() = 0; /** * Destroy the supplied XalanDocument instance. It must be an instance that * was created by a previous call to createDocument() or getDOMFactory(). * * @param theDocument The XalanDocument instance to destroy. */ virtual void destroyDocument(XalanDocument* theDocument) = 0; /** * Get a unique number for identifying the document. The number need * only be unique to the parser liaison instance. * * @return The unique number */ virtual unsigned long getDocumentNumber() = 0; /** * Get the amount to indent when indent-result="yes". * * @deprecated * * @return number of characters to indent */ virtual int getIndent() const = 0; /** * Set the amount to indent when indent-result="yes". * * @deprecated * * @param i number of characters to indent */ virtual void setIndent(int i) = 0; /** * Get whether or not validation will be performed. Validation is off by * default. * * @return true to perform validation */ virtual bool getUseValidation() const = 0; /** * If set to true, validation will be performed. Validation is off by * default. * * @param b true to perform validation */ virtual void setUseValidation(bool b) = 0; /** * Return a string suitable for telling the user what parser is being used. * * @return string describing parser */ virtual const XalanDOMString getParserDescription() const = 0; /** * This method returns the installed entity resolver. * * @return The pointer to the installed entity resolver object. */ virtual EntityResolver* getEntityResolver() const = 0; /** * This method installs the user specified entity resolver on the * parser. It allows applications to trap and redirect calls to * external entities. * * @param handler A pointer to the entity resolver to be called * when the parser comes across references to * entities in the XML file. */ virtual void setEntityResolver(EntityResolver* resolver) = 0; /** * This method returns the installed error handler. * * @return The pointer to the installed error handler object. */ virtual ErrorHandler* getErrorHandler() const = 0; /** * This method installs the user-specified error handler. * * @param handler A pointer to the error handler to be called upon error. */ virtual void setErrorHandler(ErrorHandler* handler) = 0; private: // Not implemented XMLParserLiaison(const XMLParserLiaison&); XMLParserLiaison& operator=(const XMLParserLiaison&); }; #endif // XMLPARSERLIAISON_HEADER_GUARD_1357924680 <commit_msg>Renamed member function for clarity.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #if !defined(XMLPARSERLIAISON_HEADER_GUARD_1357924680) #define XMLPARSERLIAISON_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <XMLSupport/XMLSupportDefinitions.hpp> #include <XalanDOM/XalanDOMString.hpp> #include <PlatformSupport/Resettable.hpp> class DocumentHandler; class EntityResolver; class ErrorHandler; class ExecutionContext; class FormatterListener; class InputSource; class XalanAttr; class XalanDocument; class XalanElement; class XALAN_XMLSUPPORT_EXPORT XMLParserLiaison : public Resettable { public: typedef unsigned long DocumentNumberType; XMLParserLiaison(); virtual ~XMLParserLiaison(); // These interfaces are inherited from Resettable... virtual void reset() = 0; // These interfaces are new to XMLParserLiaison virtual ExecutionContext* getExecutionContext() const = 0; virtual void setExecutionContext(ExecutionContext& theContext) = 0; /** * Parse the text pointed at by the reader as XML, and return a DOM * Document interface. It is recommended that you pass in some sort of * recognizable name, such as the filename or URI, with which the reader * can be recognized if the parse fails. * * The liaison owns the XalanDocument instance, and will delete it when * when asked (see DestroyDocument()), or when the liaison is reset, or * goes out of scope. * * @param reader stream that should hold valid XML * @param identifier used for diagnostic purposes only, some sort of * identification for error reporting, default an empty * string * @return DOM document created */ virtual XalanDocument* parseXMLStream( const InputSource& inputSource, const XalanDOMString& identifier = XalanDOMString()) = 0; /** * Parse the text pointed at by the reader as XML. It is recommended that * you pass in some sort of recognizable name, such as the filename or URI, * with which the reader can be recognized if the parse fails. * * @param inputSource input source that should hold valid XML * @param handler instance of a DocumentHandler * @param identifier used for diagnostic purposes only, some sort of * identification for error reporting, default an * empty string */ virtual void parseXMLStream( const InputSource& inputSource, DocumentHandler& handler, const XalanDOMString& identifier = XalanDOMString()) = 0; /** * Create an empty DOM Document. Mainly used for creating an * output document. * * The liaison owns the XalanDocument instance, and will delete it when * when asked (see DestroyDocument()), or when the liaison is reset, or * goes out of scope. * * @return DOM document created */ virtual XalanDocument* createDocument() = 0; /** * Get a factory object required to create nodes in the result tree. * * The liaison owns the XalanDocument instance, and will delete it when * when asked (see DestroyDocument()), or when the liaison is reset, or * goes out of scope. * * @return A XalanDocument instance. */ virtual XalanDocument* createDOMFactory() = 0; /** * Destroy the supplied XalanDocument instance. It must be an instance that * was created by a previous call to createDocument() or getDOMFactory(). * * @param theDocument The XalanDocument instance to destroy. */ virtual void destroyDocument(XalanDocument* theDocument) = 0; /** * Get a unique number for identifying the document. The number need * only be unique to the parser liaison instance. * * @return The unique number */ virtual DocumentNumberType getNextDocumentNumber() = 0; /** * Get the amount to indent when indent-result="yes". * * @deprecated * * @return number of characters to indent */ virtual int getIndent() const = 0; /** * Set the amount to indent when indent-result="yes". * * @deprecated * * @param i number of characters to indent */ virtual void setIndent(int i) = 0; /** * Get whether or not validation will be performed. Validation is off by * default. * * @return true to perform validation */ virtual bool getUseValidation() const = 0; /** * If set to true, validation will be performed. Validation is off by * default. * * @param b true to perform validation */ virtual void setUseValidation(bool b) = 0; /** * Return a string suitable for telling the user what parser is being used. * * @return string describing parser */ virtual const XalanDOMString getParserDescription() const = 0; /** * This method returns the installed entity resolver. * * @return The pointer to the installed entity resolver object. */ virtual EntityResolver* getEntityResolver() const = 0; /** * This method installs the user specified entity resolver on the * parser. It allows applications to trap and redirect calls to * external entities. * * @param handler A pointer to the entity resolver to be called * when the parser comes across references to * entities in the XML file. */ virtual void setEntityResolver(EntityResolver* resolver) = 0; /** * This method returns the installed error handler. * * @return The pointer to the installed error handler object. */ virtual ErrorHandler* getErrorHandler() const = 0; /** * This method installs the user-specified error handler. * * @param handler A pointer to the error handler to be called upon error. */ virtual void setErrorHandler(ErrorHandler* handler) = 0; private: // Not implemented XMLParserLiaison(const XMLParserLiaison&); XMLParserLiaison& operator=(const XMLParserLiaison&); }; #endif // XMLPARSERLIAISON_HEADER_GUARD_1357924680 <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sallayout.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2007-12-12 13:19:53 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SV_SALLAYOUT_HXX #define _SV_SALLAYOUT_HXX #ifndef _SV_GEN_HXX #include <tools/gen.hxx> #endif #include <vector> namespace basegfx { class B2DPolyPolygon; typedef std::vector<B2DPolyPolygon> B2DPolyPolygonVector; } #ifndef _TOOLS_LANG_HXX typedef unsigned short LanguageType; #endif #include <vector> #include <list> #ifndef _VCL_DLLAPI_H #include <vcl/dllapi.h> #endif // for typedef sal_UCS4 #include <vcl/vclenum.hxx> class SalGraphics; class ImplFontData; #define MAX_FALLBACK 16 // ---------------- // - LayoutOption - // ---------------- #define SAL_LAYOUT_BIDI_RTL 0x0001 #define SAL_LAYOUT_BIDI_STRONG 0x0002 #define SAL_LAYOUT_RIGHT_ALIGN 0x0004 #define SAL_LAYOUT_KERNING_PAIRS 0x0010 #define SAL_LAYOUT_KERNING_ASIAN 0x0020 #define SAL_LAYOUT_VERTICAL 0x0040 #define SAL_LAYOUT_COMPLEX_DISABLED 0x0100 #define SAL_LAYOUT_ENABLE_LIGATURES 0x0200 #define SAL_LAYOUT_SUBSTITUTE_DIGITS 0x0400 #define SAL_LAYOUT_KASHIDA_JUSTIFICATON 0x0800 #define SAL_LAYOUT_DISABLE_GLYPH_PROCESSING 0x1000 #define SAL_LAYOUT_FOR_FALLBACK 0x2000 // ----------------- // used for managing runs e.g. for BiDi, glyph and script fallback class VCL_DLLPUBLIC ImplLayoutRuns { private: int mnRunIndex; std::vector<int> maRuns; public: ImplLayoutRuns() { mnRunIndex = 0; maRuns.reserve(8); } void Clear() { maRuns.clear(); } bool AddPos( int nCharPos, bool bRTL ); bool AddRun( int nMinRunPos, int nEndRunPos, bool bRTL ); bool IsEmpty() const { return maRuns.empty(); } void ResetPos() { mnRunIndex = 0; } void NextRun() { mnRunIndex += 2; } bool GetRun( int* nMinRunPos, int* nEndRunPos, bool* bRTL ) const; bool GetNextPos( int* nCharPos, bool* bRTL ); bool PosIsInRun( int nCharPos ) const; bool PosIsInAnyRun( int nCharPos ) const; }; // ----------------- class ImplLayoutArgs { public: // string related inputs int mnFlags; int mnLength; int mnMinCharPos; int mnEndCharPos; const xub_Unicode* mpStr; // positioning related inputs const sal_Int32* mpDXArray; // in pixel units long mnLayoutWidth; // in pixel units int mnOrientation; // in 0-3600 system // data for bidi and glyph+script fallback ImplLayoutRuns maRuns; ImplLayoutRuns maReruns; public: ImplLayoutArgs( const xub_Unicode* pStr, int nLength, int nMinCharPos, int nEndCharPos, int nFlags ); void SetLayoutWidth( long nWidth ) { mnLayoutWidth = nWidth; } void SetDXArray( const sal_Int32* pDXArray ) { mpDXArray = pDXArray; } void SetOrientation( int nOrientation ) { mnOrientation = nOrientation; } void ResetPos() { maRuns.ResetPos(); } bool GetNextPos( int* nCharPos, bool* bRTL ) { return maRuns.GetNextPos( nCharPos, bRTL ); } bool GetNextRun( int* nMinRunPos, int* nEndRunPos, bool* bRTL ); bool NeedFallback( int nCharPos, bool bRTL ) { return maReruns.AddPos( nCharPos, bRTL ); } bool NeedFallback( int nMinRunPos, int nEndRunPos, bool bRTL ) { return maReruns.AddRun( nMinRunPos, nEndRunPos, bRTL ); } // methods used by BiDi and glyph fallback bool NeedFallback() const { return !maReruns.IsEmpty(); } bool PrepareFallback(); protected: void AddRun( int nMinCharPos, int nEndCharPos, bool bRTL ); }; // helper functions often used with ImplLayoutArgs int GetVerticalFlags( sal_UCS4 ); sal_UCS4 GetVerticalChar( sal_UCS4 ); // #i80090# GetMirroredChar also needed outside vcl, moved to svapp.hxx // VCL_DLLPUBLIC sal_UCS4 GetMirroredChar( sal_UCS4 ); sal_UCS4 GetLocalizedChar( sal_UCS4, LanguageType ); VCL_DLLPUBLIC const char* GetAutofallback( sal_UCS4 ) ; // ------------- // - SalLayout - // ------------- // Glyph Flags #define GF_NONE 0x00000000 #define GF_FLAGMASK 0xFF800000 #define GF_IDXMASK ~GF_FLAGMASK #define GF_ISCHAR 0x00800000 #define GF_ROTL 0x01000000 // caution !!! #define GF_VERT 0x02000000 // GF_VERT is only for windows implementation // (win/source/gdi/salgdi3.cxx, win/source/gdi/winlayout.cxx) // don't use this elsewhere !!! #define GF_ROTR 0x03000000 #define GF_ROTMASK 0x03000000 #define GF_UNHINTED 0x04000000 #define GF_GSUB 0x08000000 #define GF_FONTMASK 0xF0000000 #define GF_FONTSHIFT 28 #define GF_DROPPED 0xFFFFFFFF // all positions/widths are in font units // one exception: drawposition is in pixel units class VCL_DLLPUBLIC SalLayout { public: // used by upper layers Point& DrawBase() { return maDrawBase; } Point& DrawOffset() { return maDrawOffset; } Point GetDrawPosition( const Point& rRelative = Point(0,0) ) const; virtual bool LayoutText( ImplLayoutArgs& ) = 0; // first step of layouting virtual void AdjustLayout( ImplLayoutArgs& ); // adjusting after fallback etc. virtual void InitFont() const {} virtual void DrawText( SalGraphics& ) const = 0; int GetUnitsPerPixel() const { return mnUnitsPerPixel; } int GetOrientation() const { return mnOrientation; } // methods using string indexing virtual int GetTextBreak( long nMaxWidth, long nCharExtra=0, int nFactor=1 ) const = 0; virtual long FillDXArray( sal_Int32* pDXArray ) const = 0; virtual long GetTextWidth() const { return FillDXArray( NULL ); } virtual void GetCaretPositions( int nArraySize, sal_Int32* pCaretXArray ) const = 0; // methods using glyph indexing virtual int GetNextGlyphs( int nLen, sal_Int32* pGlyphIdxAry, Point& rPos, int&, sal_Int32* pGlyphAdvAry = NULL, int* pCharPosAry = NULL ) const = 0; virtual bool GetOutline( SalGraphics&, ::basegfx::B2DPolyPolygonVector& ) const; virtual bool GetBoundRect( SalGraphics&, Rectangle& ) const; virtual bool IsSpacingGlyph( long nGlyphIndex ) const; // reference counting void Reference() const; void Release() const; // used by glyph+font+script fallback virtual void MoveGlyph( int nStart, long nNewXPos ) = 0; virtual void DropGlyph( int nStart ) = 0; virtual void Simplify( bool bIsBase ) = 0; protected: // used by layout engines SalLayout(); virtual ~SalLayout(); // used by layout layers void SetUnitsPerPixel( int n ) { mnUnitsPerPixel = n; } void SetOrientation( int nOrientation ) // in 0-3600 system { mnOrientation = nOrientation; } static int CalcAsianKerning( sal_UCS4, bool bLeft, bool bVertical ); private: // enforce proper copy semantic SAL_DLLPRIVATE SalLayout( const SalLayout& ); SAL_DLLPRIVATE SalLayout& operator=( const SalLayout& ); protected: int mnMinCharPos; int mnEndCharPos; int mnLayoutFlags; int mnUnitsPerPixel; int mnOrientation; mutable int mnRefCount; mutable Point maDrawOffset; Point maDrawBase; }; // ------------------ // - MultiSalLayout - // ------------------ class VCL_DLLPUBLIC MultiSalLayout : public SalLayout { public: virtual void DrawText( SalGraphics& ) const; virtual int GetTextBreak( long nMaxWidth, long nCharExtra, int nFactor ) const; virtual long FillDXArray( sal_Int32* pDXArray ) const; virtual void GetCaretPositions( int nArraySize, sal_Int32* pCaretXArray ) const; virtual int GetNextGlyphs( int nLen, sal_Int32* pGlyphIdxAry, Point& rPos, int&, sal_Int32* pGlyphAdvAry, int* pCharPosAry ) const; virtual bool GetOutline( SalGraphics&, ::basegfx::B2DPolyPolygonVector& ) const; virtual bool GetBoundRect( SalGraphics&, Rectangle& ) const; // used only by OutputDevice::ImplLayout, TODO: make friend MultiSalLayout( SalLayout& rBaseLayout ); // transfer ownership virtual bool AddFallback( SalLayout& rFallback, // transfer ownership ImplLayoutRuns& rRuns, ImplFontData* pFallbackFont ); virtual bool LayoutText( ImplLayoutArgs& ); virtual void AdjustLayout( ImplLayoutArgs& ); virtual void InitFont() const; ImplFontData* GetFallbackFontData( int nFallbackLevel ) const { return mpFallbackFonts[ nFallbackLevel ]; } void SetInComplete(bool bInComplete = true); protected: virtual ~MultiSalLayout(); private: // dummy implementations virtual void MoveGlyph( int, long ) {} virtual void DropGlyph( int ) {} virtual void Simplify( bool ) {} // enforce proper copy semantic SAL_DLLPRIVATE MultiSalLayout( const MultiSalLayout& ); SAL_DLLPRIVATE MultiSalLayout& operator=( const MultiSalLayout& ); private: SalLayout* mpLayouts[ MAX_FALLBACK ]; ImplFontData* mpFallbackFonts[ MAX_FALLBACK ]; ImplLayoutRuns maFallbackRuns[ MAX_FALLBACK ]; int mnLevel; bool mbInComplete; }; // -------------------- // - GenericSalLayout - // -------------------- struct GlyphItem { int mnFlags; int mnCharPos; // index in string int mnOrigWidth; // original glyph width int mnNewWidth; // width after adjustments long mnGlyphIndex; Point maLinearPos; // absolute position of non rotated string public: GlyphItem() {} GlyphItem( int nCharPos, long nGlyphIndex, const Point& rLinearPos, long nFlags, int nOrigWidth ) : mnFlags(nFlags), mnCharPos(nCharPos), mnOrigWidth(nOrigWidth), mnNewWidth(nOrigWidth), mnGlyphIndex(nGlyphIndex), maLinearPos(rLinearPos) {} enum{ FALLBACK_MASK=0xFF, IS_IN_CLUSTER=0x100, IS_RTL_GLYPH=0x200 }; bool IsClusterStart() const { return !(mnFlags & IS_IN_CLUSTER); } bool IsRTLGlyph() const { return ((mnFlags & IS_RTL_GLYPH) != 0); } }; // --------------- typedef std::list<GlyphItem> GlyphList; typedef std::vector<GlyphItem> GlyphVector; // --------------- class VCL_DLLPUBLIC GenericSalLayout : public SalLayout { public: // used by layout engines void AppendGlyph( const GlyphItem& ); virtual void AdjustLayout( ImplLayoutArgs& ); virtual void ApplyDXArray( ImplLayoutArgs& ); virtual void Justify( long nNewWidth ); void KashidaJustify( long nIndex, int nWidth ); void ApplyAsianKerning( const sal_Unicode*, int nLength ); void SortGlyphItems(); // used by upper layers virtual long GetTextWidth() const; virtual long FillDXArray( sal_Int32* pDXArray ) const; virtual int GetTextBreak( long nMaxWidth, long nCharExtra, int nFactor ) const; virtual void GetCaretPositions( int nArraySize, sal_Int32* pCaretXArray ) const; // used by display layers virtual int GetNextGlyphs( int nLen, sal_Int32* pGlyphIdxAry, Point& rPos, int&, sal_Int32* pGlyphAdvAry = NULL, int* pCharPosAry = NULL ) const; protected: GenericSalLayout(); virtual ~GenericSalLayout(); // for glyph+font+script fallback virtual void MoveGlyph( int nStart, long nNewXPos ); virtual void DropGlyph( int nStart ); virtual void Simplify( bool bIsBase ); bool GetCharWidths( sal_Int32* pCharWidths ) const; private: GlyphItem* mpGlyphItems; // TODO: change to GlyphList int mnGlyphCount; int mnGlyphCapacity; mutable Point maBasePoint; // enforce proper copy semantic SAL_DLLPRIVATE GenericSalLayout( const GenericSalLayout& ); SAL_DLLPRIVATE GenericSalLayout& operator=( const GenericSalLayout& ); }; #undef SalGraphics #endif // _SV_SALLAYOUT_HXX <commit_msg>INTEGRATION: CWS pdffix02 (1.4.38); FILE MERGED 2008/01/25 12:44:57 hdu 1.4.38.2: #i85554# improve const correctness for PDF exports glyph fallback fonts 2008/01/17 16:25:35 hdu 1.4.38.1: #i83121# improve usability for glyph fallback methods<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sallayout.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: kz $ $Date: 2008-03-31 13:23:54 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SV_SALLAYOUT_HXX #define _SV_SALLAYOUT_HXX #ifndef _SV_GEN_HXX #include <tools/gen.hxx> #endif #include <vector> namespace basegfx { class B2DPolyPolygon; typedef std::vector<B2DPolyPolygon> B2DPolyPolygonVector; } #ifndef _TOOLS_LANG_HXX typedef unsigned short LanguageType; #endif #include <vector> #include <list> #ifndef _VCL_DLLAPI_H #include <vcl/dllapi.h> #endif // for typedef sal_UCS4 #include <vcl/vclenum.hxx> class SalGraphics; class ImplFontData; #define MAX_FALLBACK 16 // ---------------- // - LayoutOption - // ---------------- #define SAL_LAYOUT_BIDI_RTL 0x0001 #define SAL_LAYOUT_BIDI_STRONG 0x0002 #define SAL_LAYOUT_RIGHT_ALIGN 0x0004 #define SAL_LAYOUT_KERNING_PAIRS 0x0010 #define SAL_LAYOUT_KERNING_ASIAN 0x0020 #define SAL_LAYOUT_VERTICAL 0x0040 #define SAL_LAYOUT_COMPLEX_DISABLED 0x0100 #define SAL_LAYOUT_ENABLE_LIGATURES 0x0200 #define SAL_LAYOUT_SUBSTITUTE_DIGITS 0x0400 #define SAL_LAYOUT_KASHIDA_JUSTIFICATON 0x0800 #define SAL_LAYOUT_DISABLE_GLYPH_PROCESSING 0x1000 #define SAL_LAYOUT_FOR_FALLBACK 0x2000 // ----------------- // used for managing runs e.g. for BiDi, glyph and script fallback class VCL_DLLPUBLIC ImplLayoutRuns { private: int mnRunIndex; std::vector<int> maRuns; public: ImplLayoutRuns() { mnRunIndex = 0; maRuns.reserve(8); } void Clear() { maRuns.clear(); } bool AddPos( int nCharPos, bool bRTL ); bool AddRun( int nMinRunPos, int nEndRunPos, bool bRTL ); bool IsEmpty() const { return maRuns.empty(); } void ResetPos() { mnRunIndex = 0; } void NextRun() { mnRunIndex += 2; } bool GetRun( int* nMinRunPos, int* nEndRunPos, bool* bRTL ) const; bool GetNextPos( int* nCharPos, bool* bRTL ); bool PosIsInRun( int nCharPos ) const; bool PosIsInAnyRun( int nCharPos ) const; }; // ----------------- class ImplLayoutArgs { public: // string related inputs int mnFlags; int mnLength; int mnMinCharPos; int mnEndCharPos; const xub_Unicode* mpStr; // positioning related inputs const sal_Int32* mpDXArray; // in pixel units long mnLayoutWidth; // in pixel units int mnOrientation; // in 0-3600 system // data for bidi and glyph+script fallback ImplLayoutRuns maRuns; ImplLayoutRuns maReruns; public: ImplLayoutArgs( const xub_Unicode* pStr, int nLength, int nMinCharPos, int nEndCharPos, int nFlags ); void SetLayoutWidth( long nWidth ) { mnLayoutWidth = nWidth; } void SetDXArray( const sal_Int32* pDXArray ) { mpDXArray = pDXArray; } void SetOrientation( int nOrientation ) { mnOrientation = nOrientation; } void ResetPos() { maRuns.ResetPos(); } bool GetNextPos( int* nCharPos, bool* bRTL ) { return maRuns.GetNextPos( nCharPos, bRTL ); } bool GetNextRun( int* nMinRunPos, int* nEndRunPos, bool* bRTL ); bool NeedFallback( int nCharPos, bool bRTL ) { return maReruns.AddPos( nCharPos, bRTL ); } bool NeedFallback( int nMinRunPos, int nEndRunPos, bool bRTL ) { return maReruns.AddRun( nMinRunPos, nEndRunPos, bRTL ); } // methods used by BiDi and glyph fallback bool NeedFallback() const { return !maReruns.IsEmpty(); } bool PrepareFallback(); protected: void AddRun( int nMinCharPos, int nEndCharPos, bool bRTL ); }; // helper functions often used with ImplLayoutArgs int GetVerticalFlags( sal_UCS4 ); sal_UCS4 GetVerticalChar( sal_UCS4 ); // #i80090# GetMirroredChar also needed outside vcl, moved to svapp.hxx // VCL_DLLPUBLIC sal_UCS4 GetMirroredChar( sal_UCS4 ); sal_UCS4 GetLocalizedChar( sal_UCS4, LanguageType ); VCL_DLLPUBLIC const char* GetAutofallback( sal_UCS4 ) ; // ------------- // - SalLayout - // ------------- typedef sal_uInt32 sal_GlyphId; // Glyph Flags #define GF_NONE 0x00000000 #define GF_FLAGMASK 0xFF800000 #define GF_IDXMASK ~GF_FLAGMASK #define GF_ISCHAR 0x00800000 #define GF_ROTL 0x01000000 // caution !!! #define GF_VERT 0x02000000 // GF_VERT is only for windows implementation // (win/source/gdi/salgdi3.cxx, win/source/gdi/winlayout.cxx) // don't use this elsewhere !!! #define GF_ROTR 0x03000000 #define GF_ROTMASK 0x03000000 #define GF_UNHINTED 0x04000000 #define GF_GSUB 0x08000000 #define GF_FONTMASK 0xF0000000 #define GF_FONTSHIFT 28 #define GF_DROPPED 0xFFFFFFFF // all positions/widths are in font units // one exception: drawposition is in pixel units class VCL_DLLPUBLIC SalLayout { public: // used by upper layers Point& DrawBase() { return maDrawBase; } Point& DrawOffset() { return maDrawOffset; } Point GetDrawPosition( const Point& rRelative = Point(0,0) ) const; virtual bool LayoutText( ImplLayoutArgs& ) = 0; // first step of layouting virtual void AdjustLayout( ImplLayoutArgs& ); // adjusting after fallback etc. virtual void InitFont() const {} virtual void DrawText( SalGraphics& ) const = 0; int GetUnitsPerPixel() const { return mnUnitsPerPixel; } int GetOrientation() const { return mnOrientation; } virtual const ImplFontData* GetFallbackFontData( sal_GlyphId ) const; // methods using string indexing virtual int GetTextBreak( long nMaxWidth, long nCharExtra=0, int nFactor=1 ) const = 0; virtual long FillDXArray( sal_Int32* pDXArray ) const = 0; virtual long GetTextWidth() const { return FillDXArray( NULL ); } virtual void GetCaretPositions( int nArraySize, sal_Int32* pCaretXArray ) const = 0; // methods using glyph indexing virtual int GetNextGlyphs( int nLen, sal_GlyphId* pGlyphIdAry, Point& rPos, int&, sal_Int32* pGlyphAdvAry = NULL, int* pCharPosAry = NULL ) const = 0; virtual bool GetOutline( SalGraphics&, ::basegfx::B2DPolyPolygonVector& ) const; virtual bool GetBoundRect( SalGraphics&, Rectangle& ) const; virtual bool IsSpacingGlyph( sal_GlyphId ) const; // reference counting void Reference() const; void Release() const; // used by glyph+font+script fallback virtual void MoveGlyph( int nStart, long nNewXPos ) = 0; virtual void DropGlyph( int nStart ) = 0; virtual void Simplify( bool bIsBase ) = 0; protected: // used by layout engines SalLayout(); virtual ~SalLayout(); // used by layout layers void SetUnitsPerPixel( int n ) { mnUnitsPerPixel = n; } void SetOrientation( int nOrientation ) // in 0-3600 system { mnOrientation = nOrientation; } static int CalcAsianKerning( sal_UCS4, bool bLeft, bool bVertical ); private: // enforce proper copy semantic SAL_DLLPRIVATE SalLayout( const SalLayout& ); SAL_DLLPRIVATE SalLayout& operator=( const SalLayout& ); protected: int mnMinCharPos; int mnEndCharPos; int mnLayoutFlags; int mnUnitsPerPixel; int mnOrientation; mutable int mnRefCount; mutable Point maDrawOffset; Point maDrawBase; }; // ------------------ // - MultiSalLayout - // ------------------ class VCL_DLLPUBLIC MultiSalLayout : public SalLayout { public: virtual void DrawText( SalGraphics& ) const; virtual int GetTextBreak( long nMaxWidth, long nCharExtra, int nFactor ) const; virtual long FillDXArray( sal_Int32* pDXArray ) const; virtual void GetCaretPositions( int nArraySize, sal_Int32* pCaretXArray ) const; virtual int GetNextGlyphs( int nLen, sal_GlyphId* pGlyphIdxAry, Point& rPos, int&, sal_Int32* pGlyphAdvAry, int* pCharPosAry ) const; virtual bool GetOutline( SalGraphics&, ::basegfx::B2DPolyPolygonVector& ) const; virtual bool GetBoundRect( SalGraphics&, Rectangle& ) const; // used only by OutputDevice::ImplLayout, TODO: make friend MultiSalLayout( SalLayout& rBaseLayout ); // transfer ownership virtual bool AddFallback( SalLayout& rFallback, // transfer ownership ImplLayoutRuns&, const ImplFontData* pFallbackFont ); virtual bool LayoutText( ImplLayoutArgs& ); virtual void AdjustLayout( ImplLayoutArgs& ); virtual void InitFont() const; virtual const ImplFontData* GetFallbackFontData( sal_GlyphId ) const; void SetInComplete(bool bInComplete = true); protected: virtual ~MultiSalLayout(); private: // dummy implementations virtual void MoveGlyph( int, long ) {} virtual void DropGlyph( int ) {} virtual void Simplify( bool ) {} // enforce proper copy semantic SAL_DLLPRIVATE MultiSalLayout( const MultiSalLayout& ); SAL_DLLPRIVATE MultiSalLayout& operator=( const MultiSalLayout& ); private: SalLayout* mpLayouts[ MAX_FALLBACK ]; const ImplFontData* mpFallbackFonts[ MAX_FALLBACK ]; ImplLayoutRuns maFallbackRuns[ MAX_FALLBACK ]; int mnLevel; bool mbInComplete; }; // -------------------- // - GenericSalLayout - // -------------------- struct GlyphItem { int mnFlags; int mnCharPos; // index in string int mnOrigWidth; // original glyph width int mnNewWidth; // width after adjustments sal_GlyphId mnGlyphIndex; Point maLinearPos; // absolute position of non rotated string public: GlyphItem() {} GlyphItem( int nCharPos, sal_GlyphId nGlyphIndex, const Point& rLinearPos, long nFlags, int nOrigWidth ) : mnFlags(nFlags), mnCharPos(nCharPos), mnOrigWidth(nOrigWidth), mnNewWidth(nOrigWidth), mnGlyphIndex(nGlyphIndex), maLinearPos(rLinearPos) {} enum{ FALLBACK_MASK=0xFF, IS_IN_CLUSTER=0x100, IS_RTL_GLYPH=0x200 }; bool IsClusterStart() const { return !(mnFlags & IS_IN_CLUSTER); } bool IsRTLGlyph() const { return ((mnFlags & IS_RTL_GLYPH) != 0); } }; // --------------- typedef std::list<GlyphItem> GlyphList; typedef std::vector<GlyphItem> GlyphVector; // --------------- class VCL_DLLPUBLIC GenericSalLayout : public SalLayout { public: // used by layout engines void AppendGlyph( const GlyphItem& ); virtual void AdjustLayout( ImplLayoutArgs& ); virtual void ApplyDXArray( ImplLayoutArgs& ); virtual void Justify( long nNewWidth ); void KashidaJustify( long nIndex, int nWidth ); void ApplyAsianKerning( const sal_Unicode*, int nLength ); void SortGlyphItems(); // used by upper layers virtual long GetTextWidth() const; virtual long FillDXArray( sal_Int32* pDXArray ) const; virtual int GetTextBreak( long nMaxWidth, long nCharExtra, int nFactor ) const; virtual void GetCaretPositions( int nArraySize, sal_Int32* pCaretXArray ) const; // used by display layers virtual int GetNextGlyphs( int nLen, sal_GlyphId* pGlyphIdxAry, Point& rPos, int&, sal_Int32* pGlyphAdvAry = NULL, int* pCharPosAry = NULL ) const; protected: GenericSalLayout(); virtual ~GenericSalLayout(); // for glyph+font+script fallback virtual void MoveGlyph( int nStart, long nNewXPos ); virtual void DropGlyph( int nStart ); virtual void Simplify( bool bIsBase ); bool GetCharWidths( sal_Int32* pCharWidths ) const; private: GlyphItem* mpGlyphItems; // TODO: change to GlyphList int mnGlyphCount; int mnGlyphCapacity; mutable Point maBasePoint; // enforce proper copy semantic SAL_DLLPRIVATE GenericSalLayout( const GenericSalLayout& ); SAL_DLLPRIVATE GenericSalLayout& operator=( const GenericSalLayout& ); }; #undef SalGraphics #endif // _SV_SALLAYOUT_HXX <|endoftext|>
<commit_before>#include "xcfun_internal.h" // Compute the xc potential(s). This is simple for lda and more complicated for // GGA's. For metaGAA's that depend on tau this is a non-local problem and // cannot be solved by xcfun. Laplacian dependent metaGGA's could be implemented.. // Another option is to evaluate the divergence directly in cartesian coordinates, // but one have to find a way to do this without introducing the gradient components // explicitly (for niceness) void xc_potential(xc_functional fun, const double *density, double *e_xc, double *v_xc) { if (fun->mode == XC_VARS_AB) { if (fun->type == XC_LDA) { double out[3]; xc_eval(fun,1,density,out); e_xc[0] = out[0]; v_xc[0] = out[1]; v_xc[1] = out[2]; } // Expecting lap_a and lap_b as element 5 and 6 of density // Using that v_xc = dE/dn - div dE/dgradn // When deriving the expressions it helps to have the operator // (g_a).nabla act on the basic variables (and the same for g_b). else if (fun->type == XC_GGA) { const int gaa = 2, gab = 3, gbb = 4, lapa = 5, lapb = 6; double out[21]; xc_eval(fun,2,density,out); e_xc[0] = out[XC_D00000]; v_xc[0] = out[XC_D10000]; v_xc[0] -= 2*density[lapa]*out[XC_D00100] + density[lapb]*out[XC_D00010]; v_xc[0] -= 2*(out[XC_D10100]*density[gaa] + out[XC_D01100]*density[gab] + out[XC_D00200]*(2*density[lapa]*density[gaa]) + out[XC_D00110]*(density[lapa]*density[gab] + density[lapb]*density[gaa]) + out[XC_D00101]*(2*density[lapb]*density[gab]) ); v_xc[0] -= (out[XC_D10010]*density[gab] + out[XC_D01010]*density[gbb] + out[XC_D00110]*(2*density[lapa]*density[gab]) + out[XC_D00020]*(density[lapb]*density[gab] + density[lapa]*density[gbb]) + out[XC_D00011]*(2*density[lapb]*density[gbb])); v_xc[1] = out[XC_D01000]; v_xc[1] -= 2*density[lapb]*out[XC_D00001] + density[lapa]*out[XC_D00010]; v_xc[1] -= 2*(out[XC_D01001]*density[gbb] + out[XC_D10001]*density[gab] + out[XC_D00002]*(2*density[lapb]*density[gbb]) + out[XC_D00011]*(density[lapb]*density[gab] + density[lapa]*density[gbb]) + out[XC_D00101]*(2*density[lapa]*density[gab]) ); v_xc[1] -= (out[XC_D01010]*density[gab] + out[XC_D10010]*density[gaa] + out[XC_D00011]*(2*density[lapb]*density[gab]) + out[XC_D00020]*(density[lapa]*density[gab] + density[lapb]*density[gaa]) + out[XC_D00110]*(2*density[lapa]*density[gaa])); } else { xcint_die("xc_potential() not implemented for metaGGA's",fun->type); } } else { xcint_die("xc_potential() only implemented for AB mode",fun->mode); } } <commit_msg>Remove old potential code, it was just kept for reference anyway.<commit_after><|endoftext|>
<commit_before>/* Copyright (c) 2013-2016 Jeffrey Pfau * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "ObjView.h" #include "GBAApp.h" #include <QFontDatabase> #include <QTimer> #include <mgba/internal/gba/gba.h> #ifdef M_CORE_GB #include <mgba/internal/gb/gb.h> #include <mgba/internal/gb/io.h> #endif using namespace QGBA; ObjView::ObjView(GameController* controller, QWidget* parent) : AssetView(controller, parent) , m_controller(controller) , m_tileStatus{} , m_objId(0) , m_objInfo{} { m_ui.setupUi(this); m_ui.tile->setController(controller); const QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont); m_ui.x->setFont(font); m_ui.y->setFont(font); m_ui.w->setFont(font); m_ui.h->setFont(font); m_ui.address->setFont(font); m_ui.priority->setFont(font); m_ui.palette->setFont(font); m_ui.transform->setFont(font); m_ui.mode->setFont(font); connect(m_ui.tiles, SIGNAL(indexPressed(int)), this, SLOT(translateIndex(int))); connect(m_ui.objId, SIGNAL(valueChanged(int)), this, SLOT(selectObj(int))); connect(m_ui.magnification, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [this]() { updateTiles(true); }); } void ObjView::selectObj(int obj) { m_objId = obj; updateTiles(true); } void ObjView::translateIndex(int index) { unsigned x = index % m_objInfo.width; unsigned y = index / m_objInfo.width; m_ui.tile->selectIndex(x + y * m_objInfo.stride + m_tileOffset); } #ifdef M_CORE_GBA void ObjView::updateTilesGBA(bool force) { const GBA* gba = static_cast<const GBA*>(m_controller->thread()->core->board); const GBAObj* obj = &gba->video.oam.obj[m_objId]; unsigned shape = GBAObjAttributesAGetShape(obj->a); unsigned size = GBAObjAttributesBGetSize(obj->b); unsigned width = GBAVideoObjSizes[shape * 4 + size][0]; unsigned height = GBAVideoObjSizes[shape * 4 + size][1]; unsigned tile = GBAObjAttributesCGetTile(obj->c); ObjInfo newInfo{ tile, width / 8, height / 8, width / 8 }; m_ui.tiles->setTileCount(width * height / 64); m_ui.tiles->setMinimumSize(QSize(width, height) * m_ui.magnification->value()); m_ui.tiles->resize(QSize(width, height) * m_ui.magnification->value()); unsigned palette = GBAObjAttributesCGetPalette(obj->c); GBARegisterDISPCNT dispcnt = gba->memory.io[0]; // FIXME: Register name can't be imported due to namespacing issues if (!GBARegisterDISPCNTIsObjCharacterMapping(dispcnt)) { newInfo.stride = 0x20 >> (GBAObjAttributesAGet256Color(obj->a)); }; if (newInfo != m_objInfo) { force = true; } m_objInfo = newInfo; int i = 0; if (GBAObjAttributesAIs256Color(obj->a)) { m_ui.palette->setText("256-color"); mTileCacheSetPalette(m_tileCache.get(), 1); m_ui.tile->setPalette(0); m_ui.tile->setPaletteSet(1, 1024, 1536); tile /= 2; unsigned t = tile + i; for (int y = 0; y < height / 8; ++y) { for (int x = 0; x < width / 8; ++x, ++i, ++t) { const uint16_t* data = mTileCacheGetTileIfDirty(m_tileCache.get(), &m_tileStatus[32 * t], t + 1024, 1); if (data) { m_ui.tiles->setTile(i, data); } else if (force) { m_ui.tiles->setTile(i, mTileCacheGetTile(m_tileCache.get(), t + 1024, 1)); } } t += newInfo.stride - width / 8; } tile += 1024; } else { m_ui.palette->setText(QString::number(palette)); mTileCacheSetPalette(m_tileCache.get(), 0); m_ui.tile->setPalette(palette); m_ui.tile->setPaletteSet(0, 2048, 3072); unsigned t = tile + i; for (int y = 0; y < height / 8; ++y) { for (int x = 0; x < width / 8; ++x, ++i, ++t) { const uint16_t* data = mTileCacheGetTileIfDirty(m_tileCache.get(), &m_tileStatus[32 * t], t + 2048, palette + 16); if (data) { m_ui.tiles->setTile(i, data); } else if (force) { m_ui.tiles->setTile(i, mTileCacheGetTile(m_tileCache.get(), t + 2048, palette + 16)); } } t += newInfo.stride - width / 8; } tile += 2048; } m_tileOffset = tile; m_ui.x->setText(QString::number(GBAObjAttributesBGetX(obj->b))); m_ui.y->setText(QString::number(GBAObjAttributesAGetY(obj->a))); m_ui.w->setText(QString::number(width)); m_ui.h->setText(QString::number(height)); m_ui.address->setText(tr("0x%0").arg(BASE_OAM + m_objId * sizeof(*obj), 8, 16, QChar('0'))); m_ui.priority->setText(QString::number(GBAObjAttributesCGetPriority(obj->c))); m_ui.flippedH->setChecked(GBAObjAttributesBIsHFlip(obj->b)); m_ui.flippedV->setChecked(GBAObjAttributesBIsVFlip(obj->b)); m_ui.enabled->setChecked(!GBAObjAttributesAIsDisable(obj->a) || GBAObjAttributesAIsTransformed(obj->a)); m_ui.doubleSize->setChecked(GBAObjAttributesAIsDoubleSize(obj->a) && GBAObjAttributesAIsTransformed(obj->a)); m_ui.mosaic->setChecked(GBAObjAttributesAIsMosaic(obj->a)); if (GBAObjAttributesAIsTransformed(obj->a)) { m_ui.transform->setText(QString::number(GBAObjAttributesBGetMatIndex(obj->b))); } else { m_ui.transform->setText(tr("Off")); } switch (GBAObjAttributesAGetMode(obj->a)) { case OBJ_MODE_NORMAL: m_ui.mode->setText(tr("Normal")); break; case OBJ_MODE_SEMITRANSPARENT: m_ui.mode->setText(tr("Trans")); break; case OBJ_MODE_OBJWIN: m_ui.mode->setText(tr("OBJWIN")); break; default: m_ui.mode->setText(tr("Invalid")); break; } } #endif #ifdef M_CORE_GB void ObjView::updateTilesGB(bool force) { const GB* gb = static_cast<const GB*>(m_controller->thread()->core->board); const GBObj* obj = &gb->video.oam.obj[m_objId]; unsigned width = 8; unsigned height = 8; GBRegisterLCDC lcdc = gb->memory.io[REG_LCDC]; if (GBRegisterLCDCIsObjSize(lcdc)) { height = 16; } unsigned tile = obj->tile; ObjInfo newInfo{ tile, 1, height / 8, 1 }; if (newInfo != m_objInfo) { force = true; } m_objInfo = newInfo; m_ui.tiles->setTileCount(width * height / 64); m_ui.tiles->setMinimumSize(QSize(width, height) * m_ui.magnification->value()); m_ui.tiles->resize(QSize(width, height) * m_ui.magnification->value()); int palette = 0; if (gb->model >= GB_MODEL_CGB) { if (GBObjAttributesIsBank(obj->attr)) { tile += 512; } palette = GBObjAttributesGetCGBPalette(obj->attr); } else { palette = GBObjAttributesGetPalette(obj->attr); } int i = 0; m_ui.palette->setText(QString::number(palette)); mTileCacheSetPalette(m_tileCache.get(), 0); m_ui.tile->setPalette(palette + 8); m_ui.tile->setPaletteSet(0, 512, 1024); for (int y = 0; y < height / 8; ++y, ++i) { unsigned t = tile + i; const uint16_t* data = mTileCacheGetTileIfDirty(m_tileCache.get(), &m_tileStatus[16 * t], t, palette + 8); if (data) { m_ui.tiles->setTile(i, data); } else if (force) { m_ui.tiles->setTile(i, mTileCacheGetTile(m_tileCache.get(), t, palette + 8)); } } m_tileOffset = tile; m_ui.x->setText(QString::number(obj->x)); m_ui.y->setText(QString::number(obj->y)); m_ui.w->setText(QString::number(width)); m_ui.h->setText(QString::number(height)); m_ui.address->setText(tr("0x%0").arg(GB_BASE_OAM + m_objId * sizeof(*obj), 4, 16, QChar('0'))); m_ui.priority->setText(QString::number(GBObjAttributesGetPriority(obj->attr))); m_ui.flippedH->setChecked(GBObjAttributesIsXFlip(obj->attr)); m_ui.flippedV->setChecked(GBObjAttributesIsYFlip(obj->attr)); m_ui.enabled->setChecked(obj->y != 0 && obj->y < 160); m_ui.doubleSize->setChecked(false); m_ui.mosaic->setChecked(false); m_ui.transform->setText(tr("N/A")); m_ui.mode->setText(tr("N/A")); } #endif bool ObjView::ObjInfo::operator!=(const ObjInfo& other) { return other.tile != tile || other.width != width || other.height != height || other.stride != stride; } <commit_msg>Qt: Clean up ObjView<commit_after>/* Copyright (c) 2013-2016 Jeffrey Pfau * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "ObjView.h" #include "GBAApp.h" #include <QFontDatabase> #include <QTimer> #include <mgba/internal/gba/gba.h> #ifdef M_CORE_GB #include <mgba/internal/gb/gb.h> #include <mgba/internal/gb/io.h> #endif using namespace QGBA; ObjView::ObjView(GameController* controller, QWidget* parent) : AssetView(controller, parent) , m_controller(controller) , m_tileStatus{} , m_objId(0) , m_objInfo{} { m_ui.setupUi(this); m_ui.tile->setController(controller); const QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont); m_ui.x->setFont(font); m_ui.y->setFont(font); m_ui.w->setFont(font); m_ui.h->setFont(font); m_ui.address->setFont(font); m_ui.priority->setFont(font); m_ui.palette->setFont(font); m_ui.transform->setFont(font); m_ui.mode->setFont(font); connect(m_ui.tiles, SIGNAL(indexPressed(int)), this, SLOT(translateIndex(int))); connect(m_ui.objId, SIGNAL(valueChanged(int)), this, SLOT(selectObj(int))); connect(m_ui.magnification, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [this]() { updateTiles(true); }); } void ObjView::selectObj(int obj) { m_objId = obj; updateTiles(true); } void ObjView::translateIndex(int index) { unsigned x = index % m_objInfo.width; unsigned y = index / m_objInfo.width; m_ui.tile->selectIndex(x + y * m_objInfo.stride + m_tileOffset); } #ifdef M_CORE_GBA void ObjView::updateTilesGBA(bool force) { const GBA* gba = static_cast<const GBA*>(m_controller->thread()->core->board); const GBAObj* obj = &gba->video.oam.obj[m_objId]; unsigned shape = GBAObjAttributesAGetShape(obj->a); unsigned size = GBAObjAttributesBGetSize(obj->b); unsigned width = GBAVideoObjSizes[shape * 4 + size][0]; unsigned height = GBAVideoObjSizes[shape * 4 + size][1]; unsigned tile = GBAObjAttributesCGetTile(obj->c); m_ui.tiles->setTileCount(width * height / 64); m_ui.tiles->setMinimumSize(QSize(width, height) * m_ui.magnification->value()); m_ui.tiles->resize(QSize(width, height) * m_ui.magnification->value()); unsigned palette = GBAObjAttributesCGetPalette(obj->c); unsigned tileBase = tile; if (GBAObjAttributesAIs256Color(obj->a)) { m_ui.palette->setText("256-color"); mTileCacheSetPalette(m_tileCache.get(), 1); m_ui.tile->setPalette(0); m_ui.tile->setPaletteSet(1, 1024, 1536); palette = 1; tile = tile / 2 + 1024; } else { m_ui.palette->setText(QString::number(palette)); mTileCacheSetPalette(m_tileCache.get(), 0); m_ui.tile->setPalette(palette); m_ui.tile->setPaletteSet(0, 2048, 3072); palette += 16; tile += 2048; } ObjInfo newInfo{ tile, width / 8, height / 8, width / 8 }; if (newInfo != m_objInfo) { force = true; } m_objInfo = newInfo; m_tileOffset = tile; GBARegisterDISPCNT dispcnt = gba->memory.io[0]; // FIXME: Register name can't be imported due to namespacing issues if (!GBARegisterDISPCNTIsObjCharacterMapping(dispcnt)) { newInfo.stride = 0x20 >> (GBAObjAttributesAGet256Color(obj->a)); }; int i = 0; for (int y = 0; y < height / 8; ++y) { for (int x = 0; x < width / 8; ++x, ++i, ++tile, ++tileBase) { const uint16_t* data = mTileCacheGetTileIfDirty(m_tileCache.get(), &m_tileStatus[32 * tileBase], tile, palette); if (data) { m_ui.tiles->setTile(i, data); } else if (force) { m_ui.tiles->setTile(i, mTileCacheGetTile(m_tileCache.get(), tile, palette)); } } tile += newInfo.stride - width / 8; tileBase += newInfo.stride - width / 8; } m_ui.x->setText(QString::number(GBAObjAttributesBGetX(obj->b))); m_ui.y->setText(QString::number(GBAObjAttributesAGetY(obj->a))); m_ui.w->setText(QString::number(width)); m_ui.h->setText(QString::number(height)); m_ui.address->setText(tr("0x%0").arg(BASE_OAM + m_objId * sizeof(*obj), 8, 16, QChar('0'))); m_ui.priority->setText(QString::number(GBAObjAttributesCGetPriority(obj->c))); m_ui.flippedH->setChecked(GBAObjAttributesBIsHFlip(obj->b)); m_ui.flippedV->setChecked(GBAObjAttributesBIsVFlip(obj->b)); m_ui.enabled->setChecked(!GBAObjAttributesAIsDisable(obj->a) || GBAObjAttributesAIsTransformed(obj->a)); m_ui.doubleSize->setChecked(GBAObjAttributesAIsDoubleSize(obj->a) && GBAObjAttributesAIsTransformed(obj->a)); m_ui.mosaic->setChecked(GBAObjAttributesAIsMosaic(obj->a)); if (GBAObjAttributesAIsTransformed(obj->a)) { m_ui.transform->setText(QString::number(GBAObjAttributesBGetMatIndex(obj->b))); } else { m_ui.transform->setText(tr("Off")); } switch (GBAObjAttributesAGetMode(obj->a)) { case OBJ_MODE_NORMAL: m_ui.mode->setText(tr("Normal")); break; case OBJ_MODE_SEMITRANSPARENT: m_ui.mode->setText(tr("Trans")); break; case OBJ_MODE_OBJWIN: m_ui.mode->setText(tr("OBJWIN")); break; default: m_ui.mode->setText(tr("Invalid")); break; } } #endif #ifdef M_CORE_GB void ObjView::updateTilesGB(bool force) { const GB* gb = static_cast<const GB*>(m_controller->thread()->core->board); const GBObj* obj = &gb->video.oam.obj[m_objId]; unsigned width = 8; unsigned height = 8; GBRegisterLCDC lcdc = gb->memory.io[REG_LCDC]; if (GBRegisterLCDCIsObjSize(lcdc)) { height = 16; } unsigned tile = obj->tile; m_ui.tiles->setTileCount(width * height / 64); m_ui.tiles->setMinimumSize(QSize(width, height) * m_ui.magnification->value()); m_ui.tiles->resize(QSize(width, height) * m_ui.magnification->value()); int palette = 0; if (gb->model >= GB_MODEL_CGB) { if (GBObjAttributesIsBank(obj->attr)) { tile += 512; } palette = GBObjAttributesGetCGBPalette(obj->attr); } else { palette = GBObjAttributesGetPalette(obj->attr); } ObjInfo newInfo{ tile, 1, height / 8, 1 }; if (newInfo != m_objInfo) { force = true; } m_objInfo = newInfo; m_tileOffset = tile; int i = 0; m_ui.palette->setText(QString::number(palette)); palette += 8; mTileCacheSetPalette(m_tileCache.get(), 0); m_ui.tile->setPalette(palette); m_ui.tile->setPaletteSet(0, 512, 1024); for (int y = 0; y < height / 8; ++y, ++i) { unsigned t = tile + i; const uint16_t* data = mTileCacheGetTileIfDirty(m_tileCache.get(), &m_tileStatus[16 * t], t, palette); if (data) { m_ui.tiles->setTile(i, data); } else if (force) { m_ui.tiles->setTile(i, mTileCacheGetTile(m_tileCache.get(), t, palette)); } } m_ui.x->setText(QString::number(obj->x)); m_ui.y->setText(QString::number(obj->y)); m_ui.w->setText(QString::number(width)); m_ui.h->setText(QString::number(height)); m_ui.address->setText(tr("0x%0").arg(GB_BASE_OAM + m_objId * sizeof(*obj), 4, 16, QChar('0'))); m_ui.priority->setText(QString::number(GBObjAttributesGetPriority(obj->attr))); m_ui.flippedH->setChecked(GBObjAttributesIsXFlip(obj->attr)); m_ui.flippedV->setChecked(GBObjAttributesIsYFlip(obj->attr)); m_ui.enabled->setChecked(obj->y != 0 && obj->y < 160); m_ui.doubleSize->setChecked(false); m_ui.mosaic->setChecked(false); m_ui.transform->setText(tr("N/A")); m_ui.mode->setText(tr("N/A")); } #endif bool ObjView::ObjInfo::operator!=(const ObjInfo& other) { return other.tile != tile || other.width != width || other.height != height || other.stride != stride; } <|endoftext|>
<commit_before> /* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrSoftwarePathRenderer.h" #include "GrPaint.h" #include "SkPaint.h" #include "GrRenderTarget.h" #include "GrContext.h" #include "SkDraw.h" #include "SkRasterClip.h" #include "GrGpu.h" //////////////////////////////////////////////////////////////////////////////// bool GrSoftwarePathRenderer::canDrawPath(const SkPath& path, GrPathFill fill, const GrDrawTarget* target, bool antiAlias) const { if (!antiAlias || NULL == fContext) { // TODO: We could allow the SW path to also handle non-AA paths but // this would mean that GrDefaultPathRenderer would never be called // (since it appears after the SW renderer in the path renderer // chain). Some testing would need to be done r.e. performance // and consistency of the resulting images before removing // the "!antiAlias" clause from the above test return false; } return true; } namespace { //////////////////////////////////////////////////////////////////////////////// SkPath::FillType gr_fill_to_sk_fill(GrPathFill fill) { switch (fill) { case kWinding_GrPathFill: return SkPath::kWinding_FillType; case kEvenOdd_GrPathFill: return SkPath::kEvenOdd_FillType; case kInverseWinding_GrPathFill: return SkPath::kInverseWinding_FillType; case kInverseEvenOdd_GrPathFill: return SkPath::kInverseEvenOdd_FillType; default: GrCrash("Unexpected fill."); return SkPath::kWinding_FillType; } } //////////////////////////////////////////////////////////////////////////////// // gets device coord bounds of path (not considering the fill) and clip. The // path bounds will be a subset of the clip bounds. returns false if // path bounds would be empty. bool get_path_and_clip_bounds(const GrDrawTarget* target, const SkPath& path, const GrVec* translate, GrIRect* pathBounds, GrIRect* clipBounds) { // compute bounds as intersection of rt size, clip, and path const GrRenderTarget* rt = target->getDrawState().getRenderTarget(); if (NULL == rt) { return false; } *pathBounds = GrIRect::MakeWH(rt->width(), rt->height()); const GrClip& clip = target->getClip(); if (clip.hasConservativeBounds()) { clip.getConservativeBounds().roundOut(clipBounds); if (!pathBounds->intersect(*clipBounds)) { return false; } } else { // pathBounds is currently the rt extent, set clip bounds to that rect. *clipBounds = *pathBounds; } GrRect pathSBounds = path.getBounds(); if (!pathSBounds.isEmpty()) { if (NULL != translate) { pathSBounds.offset(*translate); } target->getDrawState().getViewMatrix().mapRect(&pathSBounds, pathSBounds); GrIRect pathIBounds; pathSBounds.roundOut(&pathIBounds); if (!pathBounds->intersect(pathIBounds)) { // set the correct path bounds, as this would be used later. *pathBounds = pathIBounds; return false; } } else { *pathBounds = GrIRect::EmptyIRect(); return false; } return true; } /* * Convert a boolean operation into a transfer mode code */ SkXfermode::Mode op_to_mode(SkRegion::Op op) { static const SkXfermode::Mode modeMap[] = { SkXfermode::kDstOut_Mode, // kDifference_Op SkXfermode::kMultiply_Mode, // kIntersect_Op SkXfermode::kSrcOver_Mode, // kUnion_Op SkXfermode::kXor_Mode, // kXOR_Op SkXfermode::kClear_Mode, // kReverseDifference_Op SkXfermode::kSrc_Mode, // kReplace_Op }; return modeMap[op]; } } /** * Draw a single rect element of the clip stack into the accumulation bitmap */ void GrSWMaskHelper::draw(const GrRect& clientRect, SkRegion::Op op, bool antiAlias, GrColor color) { SkPaint paint; SkXfermode* mode = SkXfermode::Create(op_to_mode(op)); paint.setXfermode(mode); paint.setAntiAlias(antiAlias); paint.setColor(color); fDraw.drawRect(clientRect, paint); SkSafeUnref(mode); } /** * Draw a single path element of the clip stack into the accumulation bitmap */ void GrSWMaskHelper::draw(const SkPath& clientPath, SkRegion::Op op, GrPathFill fill, bool antiAlias, GrColor color) { SkPaint paint; SkPath tmpPath; const SkPath* pathToDraw = &clientPath; if (kHairLine_GrPathFill == fill) { paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(SK_Scalar1); } else { paint.setStyle(SkPaint::kFill_Style); SkPath::FillType skfill = gr_fill_to_sk_fill(fill); if (skfill != pathToDraw->getFillType()) { tmpPath = *pathToDraw; tmpPath.setFillType(skfill); pathToDraw = &tmpPath; } } SkXfermode* mode = SkXfermode::Create(op_to_mode(op)); paint.setXfermode(mode); paint.setAntiAlias(antiAlias); paint.setColor(color); fDraw.drawPath(*pathToDraw, paint); SkSafeUnref(mode); } bool GrSWMaskHelper::init(const GrIRect& pathDevBounds, const GrPoint* translate, bool useMatrix) { if (useMatrix) { fMatrix = fContext->getMatrix(); } else { fMatrix.setIdentity(); } if (NULL != translate) { fMatrix.postTranslate(translate->fX, translate->fY); } fMatrix.postTranslate(-pathDevBounds.fLeft * SK_Scalar1, -pathDevBounds.fTop * SK_Scalar1); GrIRect bounds = GrIRect::MakeWH(pathDevBounds.width(), pathDevBounds.height()); fBM.setConfig(SkBitmap::kA8_Config, bounds.fRight, bounds.fBottom); if (!fBM.allocPixels()) { return false; } sk_bzero(fBM.getPixels(), fBM.getSafeSize()); sk_bzero(&fDraw, sizeof(fDraw)); fRasterClip.setRect(bounds); fDraw.fRC = &fRasterClip; fDraw.fClip = &fRasterClip.bwRgn(); fDraw.fMatrix = &fMatrix; fDraw.fBitmap = &fBM; return true; } /** * Get a texture (from the texture cache) of the correct size & format */ bool GrSWMaskHelper::getTexture(GrAutoScratchTexture* tex) { GrTextureDesc desc; desc.fWidth = fBM.width(); desc.fHeight = fBM.height(); desc.fConfig = kAlpha_8_GrPixelConfig; tex->set(fContext, desc); GrTexture* texture = tex->texture(); if (NULL == texture) { return false; } return true; } /** * Move the result of the software mask generation back to the gpu */ void GrSWMaskHelper::toTexture(GrTexture *texture, bool clearToWhite) { SkAutoLockPixels alp(fBM); // The destination texture is almost always larger than "fBM". Clear // it appropriately so we don't get mask artifacts outside of the path's // bounding box // "texture" needs to be installed as the render target for the clear // and the texture upload but cannot remain the render target upon // returned. Callers typically use it as a texture and it would then // be both source and dest. GrDrawState::AutoRenderTargetRestore artr(fContext->getGpu()->drawState(), texture->asRenderTarget()); if (clearToWhite) { fContext->getGpu()->clear(NULL, SK_ColorWHITE); } else { fContext->getGpu()->clear(NULL, 0x00000000); } texture->writePixels(0, 0, fBM.width(), fBM.height(), kAlpha_8_GrPixelConfig, fBM.getPixels(), fBM.rowBytes()); } namespace { //////////////////////////////////////////////////////////////////////////////// /** * sw rasterizes path to A8 mask using the context's matrix and uploads to a * scratch texture. */ bool sw_draw_path_to_mask_texture(const SkPath& clientPath, const GrIRect& pathDevBounds, GrPathFill fill, GrContext* context, const GrPoint* translate, GrAutoScratchTexture* tex, bool antiAlias) { GrSWMaskHelper helper(context); if (!helper.init(pathDevBounds, translate, true)) { return false; } helper.draw(clientPath, SkRegion::kReplace_Op, fill, antiAlias, SK_ColorWHITE); if (!helper.getTexture(tex)) { return false; } helper.toTexture(tex->texture(), false); return true; } //////////////////////////////////////////////////////////////////////////////// void draw_around_inv_path(GrDrawTarget* target, GrDrawState::StageMask stageMask, const GrIRect& clipBounds, const GrIRect& pathBounds) { GrDrawTarget::AutoDeviceCoordDraw adcd(target, stageMask); GrRect rect; if (clipBounds.fTop < pathBounds.fTop) { rect.iset(clipBounds.fLeft, clipBounds.fTop, clipBounds.fRight, pathBounds.fTop); target->drawSimpleRect(rect, NULL, stageMask); } if (clipBounds.fLeft < pathBounds.fLeft) { rect.iset(clipBounds.fLeft, pathBounds.fTop, pathBounds.fLeft, pathBounds.fBottom); target->drawSimpleRect(rect, NULL, stageMask); } if (clipBounds.fRight > pathBounds.fRight) { rect.iset(pathBounds.fRight, pathBounds.fTop, clipBounds.fRight, pathBounds.fBottom); target->drawSimpleRect(rect, NULL, stageMask); } if (clipBounds.fBottom > pathBounds.fBottom) { rect.iset(clipBounds.fLeft, pathBounds.fBottom, clipBounds.fRight, clipBounds.fBottom); target->drawSimpleRect(rect, NULL, stageMask); } } } //////////////////////////////////////////////////////////////////////////////// // return true on success; false on failure bool GrSoftwarePathRenderer::onDrawPath(const SkPath& path, GrPathFill fill, const GrVec* translate, GrDrawTarget* target, GrDrawState::StageMask stageMask, bool antiAlias) { if (NULL == fContext) { return false; } GrAutoScratchTexture ast; GrIRect pathBounds, clipBounds; if (!get_path_and_clip_bounds(target, path, translate, &pathBounds, &clipBounds)) { if (GrIsFillInverted(fill)) { draw_around_inv_path(target, stageMask, clipBounds, pathBounds); } return true; } if (sw_draw_path_to_mask_texture(path, pathBounds, fill, fContext, translate, &ast, antiAlias)) { SkAutoTUnref<GrTexture> texture(ast.detach()); GrAssert(NULL != texture); GrDrawTarget::AutoDeviceCoordDraw adcd(target, stageMask); enum { // the SW path renderer shares this stage with glyph // rendering (kGlyphMaskStage in GrBatchedTextContext) kPathMaskStage = GrPaint::kTotalStages, }; GrAssert(NULL == target->drawState()->getTexture(kPathMaskStage)); target->drawState()->setTexture(kPathMaskStage, texture); target->drawState()->sampler(kPathMaskStage)->reset(); GrScalar w = GrIntToScalar(pathBounds.width()); GrScalar h = GrIntToScalar(pathBounds.height()); GrRect maskRect = GrRect::MakeWH(w / texture->width(), h / texture->height()); const GrRect* srcRects[GrDrawState::kNumStages] = {NULL}; srcRects[kPathMaskStage] = &maskRect; stageMask |= 1 << kPathMaskStage; GrRect dstRect = GrRect::MakeLTRB( SK_Scalar1* pathBounds.fLeft, SK_Scalar1* pathBounds.fTop, SK_Scalar1* pathBounds.fRight, SK_Scalar1* pathBounds.fBottom); target->drawRect(dstRect, NULL, stageMask, srcRects, NULL); target->drawState()->setTexture(kPathMaskStage, NULL); if (GrIsFillInverted(fill)) { draw_around_inv_path(target, stageMask, clipBounds, pathBounds); } return true; } return false; } <commit_msg>Reverting r4319<commit_after> /* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrSoftwarePathRenderer.h" #include "GrPaint.h" #include "SkPaint.h" #include "GrRenderTarget.h" #include "GrContext.h" #include "SkDraw.h" #include "SkRasterClip.h" #include "GrGpu.h" //////////////////////////////////////////////////////////////////////////////// bool GrSoftwarePathRenderer::canDrawPath(const SkPath& path, GrPathFill fill, const GrDrawTarget* target, bool antiAlias) const { if (!antiAlias || NULL == fContext) { // TODO: We could allow the SW path to also handle non-AA paths but // this would mean that GrDefaultPathRenderer would never be called // (since it appears after the SW renderer in the path renderer // chain). Some testing would need to be done r.e. performance // and consistency of the resulting images before removing // the "!antiAlias" clause from the above test return false; } return true; } namespace { //////////////////////////////////////////////////////////////////////////////// SkPath::FillType gr_fill_to_sk_fill(GrPathFill fill) { switch (fill) { case kWinding_GrPathFill: return SkPath::kWinding_FillType; case kEvenOdd_GrPathFill: return SkPath::kEvenOdd_FillType; case kInverseWinding_GrPathFill: return SkPath::kInverseWinding_FillType; case kInverseEvenOdd_GrPathFill: return SkPath::kInverseEvenOdd_FillType; default: GrCrash("Unexpected fill."); return SkPath::kWinding_FillType; } } //////////////////////////////////////////////////////////////////////////////// // gets device coord bounds of path (not considering the fill) and clip. The // path bounds will be a subset of the clip bounds. returns false if // path bounds would be empty. bool get_path_and_clip_bounds(const GrDrawTarget* target, const SkPath& path, const GrVec* translate, GrIRect* pathBounds, GrIRect* clipBounds) { // compute bounds as intersection of rt size, clip, and path const GrRenderTarget* rt = target->getDrawState().getRenderTarget(); if (NULL == rt) { return false; } *pathBounds = GrIRect::MakeWH(rt->width(), rt->height()); const GrClip& clip = target->getClip(); if (clip.hasConservativeBounds()) { clip.getConservativeBounds().roundOut(clipBounds); if (!pathBounds->intersect(*clipBounds)) { return false; } } else { // pathBounds is currently the rt extent, set clip bounds to that rect. *clipBounds = *pathBounds; } GrRect pathSBounds = path.getBounds(); if (!pathSBounds.isEmpty()) { if (NULL != translate) { pathSBounds.offset(*translate); } target->getDrawState().getViewMatrix().mapRect(&pathSBounds, pathSBounds); GrIRect pathIBounds; pathSBounds.roundOut(&pathIBounds); if (!pathBounds->intersect(pathIBounds)) { // set the correct path bounds, as this would be used later. *pathBounds = pathIBounds; return false; } } else { *pathBounds = GrIRect::EmptyIRect(); return false; } return true; } /* * Convert a boolean operation into a transfer mode code */ SkXfermode::Mode op_to_mode(SkRegion::Op op) { static const SkXfermode::Mode modeMap[] = { SkXfermode::kDstOut_Mode, // kDifference_Op SkXfermode::kMultiply_Mode, // kIntersect_Op SkXfermode::kSrcOver_Mode, // kUnion_Op SkXfermode::kXor_Mode, // kXOR_Op SkXfermode::kClear_Mode, // kReverseDifference_Op SkXfermode::kSrc_Mode, // kReplace_Op }; return modeMap[op]; } } /** * Draw a single rect element of the clip stack into the accumulation bitmap */ void GrSWMaskHelper::draw(const GrRect& clientRect, SkRegion::Op op, bool antiAlias, GrColor color) { SkPaint paint; SkXfermode* mode = SkXfermode::Create(op_to_mode(op)); paint.setXfermode(mode); paint.setAntiAlias(antiAlias); paint.setColor(color); fDraw.drawRect(clientRect, paint); SkSafeUnref(mode); } /** * Draw a single path element of the clip stack into the accumulation bitmap */ void GrSWMaskHelper::draw(const SkPath& clientPath, SkRegion::Op op, GrPathFill fill, bool antiAlias, GrColor color) { SkPaint paint; SkPath tmpPath; const SkPath* pathToDraw = &clientPath; if (kHairLine_GrPathFill == fill) { paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(SK_Scalar1); } else { paint.setStyle(SkPaint::kFill_Style); SkPath::FillType skfill = gr_fill_to_sk_fill(fill); if (skfill != pathToDraw->getFillType()) { tmpPath = *pathToDraw; tmpPath.setFillType(skfill); pathToDraw = &tmpPath; } } SkXfermode* mode = SkXfermode::Create(op_to_mode(op)); paint.setXfermode(mode); paint.setAntiAlias(antiAlias); paint.setColor(color); fDraw.drawPath(*pathToDraw, paint); SkSafeUnref(mode); } bool GrSWMaskHelper::init(const GrIRect& pathDevBounds, const GrPoint* translate, bool useMatrix) { if (useMatrix) { fMatrix = fContext->getMatrix(); } else { fMatrix.setIdentity(); } if (NULL != translate) { fMatrix.postTranslate(translate->fX, translate->fY); } fMatrix.postTranslate(-pathDevBounds.fLeft * SK_Scalar1, -pathDevBounds.fTop * SK_Scalar1); GrIRect bounds = GrIRect::MakeWH(pathDevBounds.width(), pathDevBounds.height()); fBM.setConfig(SkBitmap::kA8_Config, bounds.fRight, bounds.fBottom); if (!fBM.allocPixels()) { return false; } sk_bzero(fBM.getPixels(), fBM.getSafeSize()); sk_bzero(&fDraw, sizeof(fDraw)); fRasterClip.setRect(bounds); fDraw.fRC = &fRasterClip; fDraw.fClip = &fRasterClip.bwRgn(); fDraw.fMatrix = &fMatrix; fDraw.fBitmap = &fBM; return true; } /** * Get a texture (from the texture cache) of the correct size & format */ bool GrSWMaskHelper::getTexture(GrAutoScratchTexture* tex) { GrTextureDesc desc; desc.fWidth = fBM.width(); desc.fHeight = fBM.height(); desc.fConfig = kAlpha_8_GrPixelConfig; tex->set(fContext, desc); GrTexture* texture = tex->texture(); if (NULL == texture) { return false; } return true; } /** * Move the result of the software mask generation back to the gpu */ void GrSWMaskHelper::toTexture(GrTexture *texture, bool clearToWhite) { SkAutoLockPixels alp(fBM); // The destination texture is almost always larger than "fBM". Clear // it appropriately so we don't get mask artifacts outside of the path's // bounding box // "texture" needs to be installed as the render target for the clear // and the texture upload but cannot remain the render target upon // returned. Callers typically use it as a texture and it would then // be both source and dest. GrDrawState::AutoRenderTargetRestore artr(fContext->getGpu()->drawState(), texture->asRenderTarget()); if (clearToWhite) { fContext->getGpu()->clear(NULL, SK_ColorWHITE); } else { fContext->getGpu()->clear(NULL, 0x00000000); } texture->writePixels(0, 0, fBM.width(), fBM.height(), kAlpha_8_GrPixelConfig, fBM.getPixels(), fBM.rowBytes()); } namespace { //////////////////////////////////////////////////////////////////////////////// /** * sw rasterizes path to A8 mask using the context's matrix and uploads to a * scratch texture. */ bool sw_draw_path_to_mask_texture(const SkPath& clientPath, const GrIRect& pathDevBounds, GrPathFill fill, GrContext* context, const GrPoint* translate, GrAutoScratchTexture* tex, bool antiAlias) { GrSWMaskHelper helper(context); if (!helper.init(pathDevBounds, translate, true)) { return false; } helper.draw(clientPath, SkRegion::kReplace_Op, fill, antiAlias, SK_ColorWHITE); if (!helper.getTexture(tex)) { return false; } helper.toTexture(tex->texture(), false); return true; } //////////////////////////////////////////////////////////////////////////////// void draw_around_inv_path(GrDrawTarget* target, GrDrawState::StageMask stageMask, const GrIRect& clipBounds, const GrIRect& pathBounds) { GrDrawTarget::AutoDeviceCoordDraw adcd(target, stageMask); GrRect rect; if (clipBounds.fTop < pathBounds.fTop) { rect.iset(clipBounds.fLeft, clipBounds.fTop, clipBounds.fRight, pathBounds.fTop); target->drawSimpleRect(rect, NULL, stageMask); } if (clipBounds.fLeft < pathBounds.fLeft) { rect.iset(clipBounds.fLeft, pathBounds.fTop, pathBounds.fLeft, pathBounds.fBottom); target->drawSimpleRect(rect, NULL, stageMask); } if (clipBounds.fRight > pathBounds.fRight) { rect.iset(pathBounds.fRight, pathBounds.fTop, clipBounds.fRight, pathBounds.fBottom); target->drawSimpleRect(rect, NULL, stageMask); } if (clipBounds.fBottom > pathBounds.fBottom) { rect.iset(clipBounds.fLeft, pathBounds.fBottom, clipBounds.fRight, clipBounds.fBottom); target->drawSimpleRect(rect, NULL, stageMask); } } } //////////////////////////////////////////////////////////////////////////////// // return true on success; false on failure bool GrSoftwarePathRenderer::onDrawPath(const SkPath& path, GrPathFill fill, const GrVec* translate, GrDrawTarget* target, GrDrawState::StageMask stageMask, bool antiAlias) { if (NULL == fContext) { return false; } GrAutoScratchTexture ast; GrIRect pathBounds, clipBounds; if (!get_path_and_clip_bounds(target, path, translate, &pathBounds, &clipBounds)) { if (GrIsFillInverted(fill)) { draw_around_inv_path(target, stageMask, clipBounds, pathBounds); } return true; } if (sw_draw_path_to_mask_texture(path, pathBounds, fill, fContext, translate, &ast, antiAlias)) { #if 1 GrTexture* texture = ast.texture(); #else SkAutoTUnref<GrTexture> texture(ast.detach()); #endif GrAssert(NULL != texture); GrDrawTarget::AutoDeviceCoordDraw adcd(target, stageMask); enum { // the SW path renderer shares this stage with glyph // rendering (kGlyphMaskStage in GrBatchedTextContext) kPathMaskStage = GrPaint::kTotalStages, }; GrAssert(NULL == target->drawState()->getTexture(kPathMaskStage)); target->drawState()->setTexture(kPathMaskStage, texture); target->drawState()->sampler(kPathMaskStage)->reset(); GrScalar w = GrIntToScalar(pathBounds.width()); GrScalar h = GrIntToScalar(pathBounds.height()); GrRect maskRect = GrRect::MakeWH(w / texture->width(), h / texture->height()); const GrRect* srcRects[GrDrawState::kNumStages] = {NULL}; srcRects[kPathMaskStage] = &maskRect; stageMask |= 1 << kPathMaskStage; GrRect dstRect = GrRect::MakeLTRB( SK_Scalar1* pathBounds.fLeft, SK_Scalar1* pathBounds.fTop, SK_Scalar1* pathBounds.fRight, SK_Scalar1* pathBounds.fBottom); target->drawRect(dstRect, NULL, stageMask, srcRects, NULL); target->drawState()->setTexture(kPathMaskStage, NULL); if (GrIsFillInverted(fill)) { draw_around_inv_path(target, stageMask, clipBounds, pathBounds); } return true; } return false; } <|endoftext|>
<commit_before>#ifndef STAN_IO_STAN_CSV_READER_HPP #define STAN_IO_STAN_CSV_READER_HPP #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <Eigen/Dense> #include <istream> #include <iostream> #include <sstream> #include <string> namespace stan { namespace io { // FIXME: should consolidate with the options from // the command line in stan::lang struct stan_csv_metadata { int stan_version_major; int stan_version_minor; int stan_version_patch; std::string model; std::string data; std::string init; size_t chain_id; size_t seed; bool random_seed; size_t num_samples; size_t num_warmup; bool save_warmup; size_t thin; bool append_samples; std::string algorithm; std::string engine; int max_depth; stan_csv_metadata() : stan_version_major(0), stan_version_minor(0), stan_version_patch(0), model(""), data(""), init(""), chain_id(1), seed(0), random_seed(false), num_samples(0), num_warmup(0), save_warmup(false), thin(0), append_samples(false), algorithm(""), engine(""), max_depth(10) {} }; struct stan_csv_adaptation { double step_size; Eigen::MatrixXd metric; stan_csv_adaptation() : step_size(0), metric(0, 0) {} }; struct stan_csv_timing { double warmup; double sampling; stan_csv_timing() : warmup(0), sampling(0) {} }; struct stan_csv { stan_csv_metadata metadata; Eigen::Matrix<std::string, Eigen::Dynamic, 1> header; stan_csv_adaptation adaptation; Eigen::MatrixXd samples; stan_csv_timing timing; }; /** * Reads from a Stan output csv file. */ class stan_csv_reader { public: stan_csv_reader() {} ~stan_csv_reader() {} static bool read_metadata(std::istream& in, stan_csv_metadata& metadata, std::ostream* out) { std::stringstream ss; std::string line; if (in.peek() != '#') return false; while (in.peek() == '#') { std::getline(in, line); ss << line << '\n'; } ss.seekg(std::ios_base::beg); char comment; std::string lhs; std::string name; std::string value; while (ss.good()) { ss >> comment; std::getline(ss, lhs); size_t equal = lhs.find("="); if (equal != std::string::npos) { name = lhs.substr(0, equal); boost::trim(name); value = lhs.substr(equal + 1, lhs.size()); boost::trim(value); boost::replace_first(value, " (Default)", ""); } else { if (lhs.compare(" data") == 0) { ss >> comment; std::getline(ss, lhs); size_t equal = lhs.find("="); if (equal != std::string::npos) { name = lhs.substr(0, equal); boost::trim(name); value = lhs.substr(equal + 2, lhs.size()); boost::replace_first(value, " (Default)", ""); } if (name.compare("file") == 0) metadata.data = value; continue; } } if (name.compare("stan_version_major") == 0) { metadata.stan_version_major = boost::lexical_cast<int>(value); } else if (name.compare("stan_version_minor") == 0) { metadata.stan_version_minor = boost::lexical_cast<int>(value); } else if (name.compare("stan_version_patch") == 0) { metadata.stan_version_patch = boost::lexical_cast<int>(value); } else if (name.compare("model") == 0) { metadata.model = value; } else if (name.compare("num_samples") == 0) { metadata.num_samples = boost::lexical_cast<int>(value); } else if (name.compare("num_warmup") == 0) { metadata.num_warmup = boost::lexical_cast<int>(value); } else if (name.compare("save_warmup") == 0) { metadata.save_warmup = boost::lexical_cast<bool>(value); } else if (name.compare("thin") == 0) { metadata.thin = boost::lexical_cast<int>(value); } else if (name.compare("chain_id") == 0) { metadata.chain_id = boost::lexical_cast<int>(value); } else if (name.compare("init") == 0) { metadata.init = value; boost::trim(metadata.init); } else if (name.compare("seed") == 0) { metadata.seed = boost::lexical_cast<unsigned int>(value); metadata.random_seed = false; } else if (name.compare("append_samples") == 0) { metadata.append_samples = boost::lexical_cast<bool>(value); } else if (name.compare("algorithm") == 0) { metadata.algorithm = value; } else if (name.compare("engine") == 0) { metadata.engine = value; } else if (name.compare("max_depth") == 0) { metadata.max_depth = boost::lexical_cast<int>(value); } } if (ss.good() == true) return false; return true; } // read_metadata static bool read_header(std::istream& in, Eigen::Matrix<std::string, Eigen::Dynamic, 1>& header, std::ostream* out) { std::string line; if (in.peek() != 'l') return false; std::getline(in, line); std::stringstream ss(line); header.resize(std::count(line.begin(), line.end(), ',') + 1); int idx = 0; while (ss.good()) { std::string token; std::getline(ss, token, ','); boost::trim(token); int pos = token.find('.'); if (pos > 0) { token.replace(pos, 1, "["); std::replace(token.begin(), token.end(), '.', ','); token += "]"; } header(idx++) = token; } return true; } static bool read_adaptation(std::istream& in, stan_csv_adaptation& adaptation, std::ostream* out) { std::stringstream ss; std::string line; int lines = 0; if (in.peek() != '#' || in.good() == false) return false; while (in.peek() == '#') { std::getline(in, line); ss << line << std::endl; lines++; } ss.seekg(std::ios_base::beg); if (lines < 4) return false; char comment; // Buffer for comment indicator, # // Skip first two lines std::getline(ss, line); // Stepsize std::getline(ss, line, '='); boost::trim(line); ss >> adaptation.step_size; // Metric parameters std::getline(ss, line); std::getline(ss, line); std::getline(ss, line); int rows = lines - 3; int cols = std::count(line.begin(), line.end(), ',') + 1; adaptation.metric.resize(rows, cols); for (int row = 0; row < rows; row++) { std::stringstream line_ss; line_ss.str(line); line_ss >> comment; for (int col = 0; col < cols; col++) { std::string token; std::getline(line_ss, token, ','); boost::trim(token); adaptation.metric(row, col) = boost::lexical_cast<double>(token); } std::getline(ss, line); // Read in next line } if (ss.good()) return false; else return true; } static bool read_samples(std::istream& in, Eigen::MatrixXd& samples, stan_csv_timing& timing, std::ostream* out) { std::stringstream ss; std::string line; int rows = 0; int cols = -1; if (in.peek() == '#' || in.good() == false) return false; while (in.good()) { bool comment_line = (in.peek() == '#'); bool empty_line = (in.peek() == '\n'); std::getline(in, line); if (empty_line) continue; if (!line.length()) break; if (comment_line) { if (line.find("(Warm-up)") != std::string::npos) { int left = 17; int right = line.find(" seconds"); timing.warmup += boost::lexical_cast<double>(line.substr(left, right - left)); } else if (line.find("(Sampling)") != std::string::npos) { int left = 17; int right = line.find(" seconds"); timing.sampling += boost::lexical_cast<double>(line.substr(left, right - left)); } } else { ss << line << '\n'; int current_cols = std::count(line.begin(), line.end(), ',') + 1; if (cols == -1) { cols = current_cols; } else if (cols != current_cols) { if (out) *out << "Error: expected " << cols << " columns, but found " << current_cols << " instead for row " << rows + 1 << std::endl; return false; } rows++; } in.peek(); } ss.seekg(std::ios_base::beg); if (rows > 0) { samples.resize(rows, cols); for (int row = 0; row < rows; row++) { std::getline(ss, line); std::stringstream ls(line); for (int col = 0; col < cols; col++) { std::getline(ls, line, ','); boost::trim(line); samples(row, col) = boost::lexical_cast<double>(line); } } } return true; } /** * Parses the file. * * @param[in] in input stream to parse * @param[out] out output stream to send messages */ static stan_csv parse(std::istream& in, std::ostream* out) { stan_csv data; if (!read_metadata(in, data.metadata, out)) { if (out) *out << "Warning: non-fatal error reading metadata" << std::endl; } if (!read_header(in, data.header, out)) { if (out) *out << "Error: error reading header" << std::endl; throw std::invalid_argument ("Error with header of input file in parse"); } if (!read_adaptation(in, data.adaptation, out)) { if (out) *out << "Warning: non-fatal error reading adapation data" << std::endl; } data.timing.warmup = 0; data.timing.sampling = 0; if (!read_samples(in, data.samples, data.timing, out)) { if (out) *out << "Warning: non-fatal error reading samples" << std::endl; } return data; } }; } // io } // stan #endif <commit_msg>Change unwanted tabs to spaces<commit_after>#ifndef STAN_IO_STAN_CSV_READER_HPP #define STAN_IO_STAN_CSV_READER_HPP #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <Eigen/Dense> #include <istream> #include <iostream> #include <sstream> #include <string> namespace stan { namespace io { // FIXME: should consolidate with the options from // the command line in stan::lang struct stan_csv_metadata { int stan_version_major; int stan_version_minor; int stan_version_patch; std::string model; std::string data; std::string init; size_t chain_id; size_t seed; bool random_seed; size_t num_samples; size_t num_warmup; bool save_warmup; size_t thin; bool append_samples; std::string algorithm; std::string engine; int max_depth; stan_csv_metadata() : stan_version_major(0), stan_version_minor(0), stan_version_patch(0), model(""), data(""), init(""), chain_id(1), seed(0), random_seed(false), num_samples(0), num_warmup(0), save_warmup(false), thin(0), append_samples(false), algorithm(""), engine(""), max_depth(10) {} }; struct stan_csv_adaptation { double step_size; Eigen::MatrixXd metric; stan_csv_adaptation() : step_size(0), metric(0, 0) {} }; struct stan_csv_timing { double warmup; double sampling; stan_csv_timing() : warmup(0), sampling(0) {} }; struct stan_csv { stan_csv_metadata metadata; Eigen::Matrix<std::string, Eigen::Dynamic, 1> header; stan_csv_adaptation adaptation; Eigen::MatrixXd samples; stan_csv_timing timing; }; /** * Reads from a Stan output csv file. */ class stan_csv_reader { public: stan_csv_reader() {} ~stan_csv_reader() {} static bool read_metadata(std::istream& in, stan_csv_metadata& metadata, std::ostream* out) { std::stringstream ss; std::string line; if (in.peek() != '#') return false; while (in.peek() == '#') { std::getline(in, line); ss << line << '\n'; } ss.seekg(std::ios_base::beg); char comment; std::string lhs; std::string name; std::string value; while (ss.good()) { ss >> comment; std::getline(ss, lhs); size_t equal = lhs.find("="); if (equal != std::string::npos) { name = lhs.substr(0, equal); boost::trim(name); value = lhs.substr(equal + 1, lhs.size()); boost::trim(value); boost::replace_first(value, " (Default)", ""); } else { if (lhs.compare(" data") == 0) { ss >> comment; std::getline(ss, lhs); size_t equal = lhs.find("="); if (equal != std::string::npos) { name = lhs.substr(0, equal); boost::trim(name); value = lhs.substr(equal + 2, lhs.size()); boost::replace_first(value, " (Default)", ""); } if (name.compare("file") == 0) metadata.data = value; continue; } } if (name.compare("stan_version_major") == 0) { metadata.stan_version_major = boost::lexical_cast<int>(value); } else if (name.compare("stan_version_minor") == 0) { metadata.stan_version_minor = boost::lexical_cast<int>(value); } else if (name.compare("stan_version_patch") == 0) { metadata.stan_version_patch = boost::lexical_cast<int>(value); } else if (name.compare("model") == 0) { metadata.model = value; } else if (name.compare("num_samples") == 0) { metadata.num_samples = boost::lexical_cast<int>(value); } else if (name.compare("num_warmup") == 0) { metadata.num_warmup = boost::lexical_cast<int>(value); } else if (name.compare("save_warmup") == 0) { metadata.save_warmup = boost::lexical_cast<bool>(value); } else if (name.compare("thin") == 0) { metadata.thin = boost::lexical_cast<int>(value); } else if (name.compare("chain_id") == 0) { metadata.chain_id = boost::lexical_cast<int>(value); } else if (name.compare("init") == 0) { metadata.init = value; boost::trim(metadata.init); } else if (name.compare("seed") == 0) { metadata.seed = boost::lexical_cast<unsigned int>(value); metadata.random_seed = false; } else if (name.compare("append_samples") == 0) { metadata.append_samples = boost::lexical_cast<bool>(value); } else if (name.compare("algorithm") == 0) { metadata.algorithm = value; } else if (name.compare("engine") == 0) { metadata.engine = value; } else if (name.compare("max_depth") == 0) { metadata.max_depth = boost::lexical_cast<int>(value); } } if (ss.good() == true) return false; return true; } // read_metadata static bool read_header(std::istream& in, Eigen::Matrix<std::string, Eigen::Dynamic, 1>& header, std::ostream* out) { std::string line; if (in.peek() != 'l') return false; std::getline(in, line); std::stringstream ss(line); header.resize(std::count(line.begin(), line.end(), ',') + 1); int idx = 0; while (ss.good()) { std::string token; std::getline(ss, token, ','); boost::trim(token); int pos = token.find('.'); if (pos > 0) { token.replace(pos, 1, "["); std::replace(token.begin(), token.end(), '.', ','); token += "]"; } header(idx++) = token; } return true; } static bool read_adaptation(std::istream& in, stan_csv_adaptation& adaptation, std::ostream* out) { std::stringstream ss; std::string line; int lines = 0; if (in.peek() != '#' || in.good() == false) return false; while (in.peek() == '#') { std::getline(in, line); ss << line << std::endl; lines++; } ss.seekg(std::ios_base::beg); if (lines < 4) return false; char comment; // Buffer for comment indicator, # // Skip first two lines std::getline(ss, line); // Stepsize std::getline(ss, line, '='); boost::trim(line); ss >> adaptation.step_size; // Metric parameters std::getline(ss, line); std::getline(ss, line); std::getline(ss, line); int rows = lines - 3; int cols = std::count(line.begin(), line.end(), ',') + 1; adaptation.metric.resize(rows, cols); for (int row = 0; row < rows; row++) { std::stringstream line_ss; line_ss.str(line); line_ss >> comment; for (int col = 0; col < cols; col++) { std::string token; std::getline(line_ss, token, ','); boost::trim(token); adaptation.metric(row, col) = boost::lexical_cast<double>(token); } std::getline(ss, line); // Read in next line } if (ss.good()) return false; else return true; } static bool read_samples(std::istream& in, Eigen::MatrixXd& samples, stan_csv_timing& timing, std::ostream* out) { std::stringstream ss; std::string line; int rows = 0; int cols = -1; if (in.peek() == '#' || in.good() == false) return false; while (in.good()) { bool comment_line = (in.peek() == '#'); bool empty_line = (in.peek() == '\n'); std::getline(in, line); if (empty_line) continue; if (!line.length()) break; if (comment_line) { if (line.find("(Warm-up)") != std::string::npos) { int left = 17; int right = line.find(" seconds"); timing.warmup += boost::lexical_cast<double>(line.substr(left, right - left)); } else if (line.find("(Sampling)") != std::string::npos) { int left = 17; int right = line.find(" seconds"); timing.sampling += boost::lexical_cast<double>(line.substr(left, right - left)); } } else { ss << line << '\n'; int current_cols = std::count(line.begin(), line.end(), ',') + 1; if (cols == -1) { cols = current_cols; } else if (cols != current_cols) { if (out) *out << "Error: expected " << cols << " columns, but found " << current_cols << " instead for row " << rows + 1 << std::endl; return false; } rows++; } in.peek(); } ss.seekg(std::ios_base::beg); if (rows > 0) { samples.resize(rows, cols); for (int row = 0; row < rows; row++) { std::getline(ss, line); std::stringstream ls(line); for (int col = 0; col < cols; col++) { std::getline(ls, line, ','); boost::trim(line); samples(row, col) = boost::lexical_cast<double>(line); } } } return true; } /** * Parses the file. * * @param[in] in input stream to parse * @param[out] out output stream to send messages */ static stan_csv parse(std::istream& in, std::ostream* out) { stan_csv data; if (!read_metadata(in, data.metadata, out)) { if (out) *out << "Warning: non-fatal error reading metadata" << std::endl; } if (!read_header(in, data.header, out)) { if (out) *out << "Error: error reading header" << std::endl; throw std::invalid_argument ("Error with header of input file in parse"); } if (!read_adaptation(in, data.adaptation, out)) { if (out) *out << "Warning: non-fatal error reading adapation data" << std::endl; } data.timing.warmup = 0; data.timing.sampling = 0; if (!read_samples(in, data.samples, data.timing, out)) { if (out) *out << "Warning: non-fatal error reading samples" << std::endl; } return data; } }; } // io } // stan #endif <|endoftext|>
<commit_before>/* * File: ShaderProgram.cpp * Author: Ale Strooisma * * Created on June 8, 2015, 5:04 PM */ #include <string> #include <vector> #include <fstream> #include <sstream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include "ShaderProgram.hpp" #include "exceptions.hpp" using namespace std; string getName(int shaderType) { if (shaderType == GL_VERTEX_SHADER) { return "vertex"; } if (shaderType == GL_GEOMETRY_SHADER) { return "geometry"; } if (shaderType == GL_FRAGMENT_SHADER) { return "fragment"; } return "<unknown type>"; } string loadShader(string fname) { // Open the file ifstream file(filename); if (!file.is_open()) { throw IOException("Cannot read file \"" + filename + "\": " + strerror(errno) + "."); } // Load file into buffer stringstream buffer; buffer << file.rdbuf(); if (file.bad()) { throw IOException("Error while reading file \"" + filename + "\": " + strerror(errno) + "."); } // Return buffer contents return buffer.str(); } int createShader(int shaderType, string filename) { // Create the actual shader int shader = glCreateShader(shaderType); string shaderSource = loadShader(filename); const char *c_str = shaderSource.c_str(); glShaderSource(shader, 1, &c_str, NULL); glCompileShader(shader); // Error handling int status; glGetShaderiv(shader, GL_COMPILE_STATUS, &status); if (status == GL_FALSE) { int logLength; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLength); char log[logLength]; glGetShaderInfoLog(shader, logLength, &logLength, log); string msg = string("Failure in compiling ") + getName(shaderType) + " shader. " + "Error log:\n" + log; throw ShaderException(msg); } // Return the shader upon success return shader; } ShaderProgram::ShaderProgram(string vertexShader, string fragmentShader) : ShaderProgram(vertexShader, "", fragmentShader) { } ShaderProgram::ShaderProgram(string vertexShader, string fragmentShader, vector<string>* attributes) : ShaderProgram(vertexShader, "", fragmentShader, attributes) { } ShaderProgram::ShaderProgram(string vertexShader, string geometryShader, string fragmentShader) : ShaderProgram(vertexShader, geometryShader, fragmentShader, nullptr) { } ShaderProgram::ShaderProgram(string vertexShader, string geometryShader, string fragmentShader, vector<string>* attributes) { // Create the shaders int vs = createShader(GL_VERTEX_SHADER, vertexShader); int gs = -1; if (geometryShader.compare("")) { createShader(GL_GEOMETRY_SHADER, geometryShader); } int fs = createShader(GL_FRAGMENT_SHADER, fragmentShader); // Create the program program = glCreateProgram(); // Attach the shaders glAttachShader(program, vs); if (gs != -1) { glAttachShader(program, gs); } glAttachShader(program, fs); // Bind the shader attributes if (attributes != nullptr) { for (int i = 0; i < attributes->size(); i++) { glBindAttribLocation(program, i, attributes->at(i).c_str()); } } // Link the Program glLinkProgram(program); // Error handling int status; glGetProgramiv(program, GL_LINK_STATUS, &status); if (status == GL_FALSE) { int logLength; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &logLength); char log[logLength]; glGetProgramInfoLog(program, logLength, &logLength, log); string msg = string("Failure in linking program. Error log:\n") + log; throw ShaderException(msg); } // Clean up glDetachShader(program, vs); if (gs != -1) { glDetachShader(program, gs); } glDetachShader(program, fs); glDeleteShader(vs); if (gs != -1) { glDeleteShader(gs); } glDeleteShader(fs); } ShaderProgram::~ShaderProgram() { glDeleteProgram(program); } GLuint ShaderProgram::getProgram() { return program; } GLint ShaderProgram::getUniformLocation(string name) { return glGetUniformLocation(program, name.c_str()); } GLuint ShaderProgram::getUniformBlockIndex(string name) { return glGetUniformBlockIndex(program, name.c_str()); }<commit_msg>Had not tested last changes - fixed errors.<commit_after>/* * File: ShaderProgram.cpp * Author: Ale Strooisma * * Created on June 8, 2015, 5:04 PM */ #include <string> #include <vector> #include <fstream> #include <sstream> #include <errno.h> #include <cstring> #include <GL/glew.h> #include <GLFW/glfw3.h> #include "ShaderProgram.hpp" #include "exceptions.hpp" using namespace std; string getName(int shaderType) { if (shaderType == GL_VERTEX_SHADER) { return "vertex"; } if (shaderType == GL_GEOMETRY_SHADER) { return "geometry"; } if (shaderType == GL_FRAGMENT_SHADER) { return "fragment"; } return "<unknown type>"; } string loadShader(string filename) { // Open the file ifstream file(filename); if (!file.is_open()) { throw IOException("Cannot read file \"" + filename + "\": " + strerror(errno) + "."); } // Load file into buffer stringstream buffer; buffer << file.rdbuf(); if (file.bad()) { throw IOException("Error while reading file \"" + filename + "\": " + strerror(errno) + "."); } // Return buffer contents return buffer.str(); } int createShader(int shaderType, string filename) { // Create the actual shader int shader = glCreateShader(shaderType); string shaderSource = loadShader(filename); const char *c_str = shaderSource.c_str(); glShaderSource(shader, 1, &c_str, NULL); glCompileShader(shader); // Error handling int status; glGetShaderiv(shader, GL_COMPILE_STATUS, &status); if (status == GL_FALSE) { int logLength; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLength); char log[logLength]; glGetShaderInfoLog(shader, logLength, &logLength, log); string msg = string("Failure in compiling ") + getName(shaderType) + " shader. " + "Error log:\n" + log; throw ShaderException(msg); } // Return the shader upon success return shader; } ShaderProgram::ShaderProgram(string vertexShader, string fragmentShader) : ShaderProgram(vertexShader, "", fragmentShader) { } ShaderProgram::ShaderProgram(string vertexShader, string fragmentShader, vector<string>* attributes) : ShaderProgram(vertexShader, "", fragmentShader, attributes) { } ShaderProgram::ShaderProgram(string vertexShader, string geometryShader, string fragmentShader) : ShaderProgram(vertexShader, geometryShader, fragmentShader, nullptr) { } ShaderProgram::ShaderProgram(string vertexShader, string geometryShader, string fragmentShader, vector<string>* attributes) { // Create the shaders int vs = createShader(GL_VERTEX_SHADER, vertexShader); int gs = -1; if (geometryShader.compare("")) { createShader(GL_GEOMETRY_SHADER, geometryShader); } int fs = createShader(GL_FRAGMENT_SHADER, fragmentShader); // Create the program program = glCreateProgram(); // Attach the shaders glAttachShader(program, vs); if (gs != -1) { glAttachShader(program, gs); } glAttachShader(program, fs); // Bind the shader attributes if (attributes != nullptr) { for (int i = 0; i < attributes->size(); i++) { glBindAttribLocation(program, i, attributes->at(i).c_str()); } } // Link the Program glLinkProgram(program); // Error handling int status; glGetProgramiv(program, GL_LINK_STATUS, &status); if (status == GL_FALSE) { int logLength; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &logLength); char log[logLength]; glGetProgramInfoLog(program, logLength, &logLength, log); string msg = string("Failure in linking program. Error log:\n") + log; throw ShaderException(msg); } // Clean up glDetachShader(program, vs); if (gs != -1) { glDetachShader(program, gs); } glDetachShader(program, fs); glDeleteShader(vs); if (gs != -1) { glDeleteShader(gs); } glDeleteShader(fs); } ShaderProgram::~ShaderProgram() { glDeleteProgram(program); } GLuint ShaderProgram::getProgram() { return program; } GLint ShaderProgram::getUniformLocation(string name) { return glGetUniformLocation(program, name.c_str()); } GLuint ShaderProgram::getUniformBlockIndex(string name) { return glGetUniformBlockIndex(program, name.c_str()); }<|endoftext|>
<commit_before> void logging_setup(); void logging_loop(FILE *logging_file); void logging_setup() { p_sensor.MS5803Init(); gps_ser.baud(9600); mkdir("/sd/test_dir", 0777); FILE *fp = fopen("/sd/test_dir/test_file.txt", "a"); if(fp == NULL) { error("Could not open file for write\n"); return -1; } else { //Now write in one line of data into the new file! update_data(); log_data(fp); fclose(fp); } mkdir("/sd/data", 0777); logging_file = fopen("/sd/data/logging.txt", "a"); } void logging_loop(FILE *logging_file) { update_data(); log_data(logging_file); } void internalStateLoop(); void internalStateSetup(); void internalStateSetup() { //TMP102.h temperature ranges from -40 to 125 C controller.setInputLimits(-40.0, 125.0); controller.setOutputLimits(0.0, 1.0); controller.setBias(0.3); // Try experimenting with the bias! controller.setMode(AUTO_MODE); controller.setSetPoint(DESIRED_INTERNAL_TEMP); W.Start(WATCH_DOG_RATE); } void internalStateLoop() { //Pet the watchdog W.Pet(); controller.setProcessValue(CURR_TEMP); //We won't actually read from the TMP 102.h, we'll use the most recent internal temp variable (global). // Set the new output. heater = controller.compute(); printf("What should the output be? %f\n", controller.compute()); //printf("Was reset by watchdog? %s\n", W.WasResetByWatchdog() ? "true" : "false"); // Now check for termination conditions // 1. If the GPS lat,lon exceed the permitted bounds, cut down. // 2. If you receive an iridum command telling you to end the flight, cut down. // 3. If you've not received an Iridium command in a while (5 hrs), cut down. } <commit_msg>GOing to experiment with logging_code<commit_after>/* ############################### mbed nucleo l152re sd and gps test using tinygps v13 and sdfilesystem libraries. last change: 10/12/2015 status: - gps working - sd logging functional ############################### */ #include "mbed.h" #include <string> #include "SDFileSystem.h" #include "TinyGPS.h" #include "TMP102.h" #include "MS5803.h" #include "PID.h" #include "Watchdog.h" #include "ScheduleEvent.h" //LOGGING GLOBAL VARS static float internal_temp = 0.0; static float external_temp = 0.0; static float pressure = 0.0; static float power = 0.0; static float latitude = 0.0; static float longitude = 0.0; static float altitude = 0.0; static unsigned long precision = 0; static char date[32]; static unsigned long encoded_chars = 0; static unsigned short good_sentences = 0; static unsigned short failed_checksums = 0; static FILE *logging_file = NULL; //INTERNAL GLOBAL VARS #define WATCH_DOG_RATE 500.0 #define PID_RATE 120.0 #define DESIRED_INTERNAL_TEMP 20.0 #define CURR_TEMP 23.0 Watchdog W = Watchdog(); //LOGGING PINS MS5803 p_sensor(D14, D15,ms5803_addrCL); TMP102 temperature(D14, D15, 0x90); //A0 pin is connected to ground Serial gps_ser(D8,D2); //serial to gps, 9600 baud. D8 <-> TX , D2 <-> RX SDFileSystem sd(SPI_MOSI, SPI_MISO, SPI_SCK, SPI_CS, "sd"); // the pinout on the mbed Cool Components workshop board / mosi, miso, sclk, cs TinyGPS gps; AnalogIn ain(A0); //Reads the power //INTERNAL PINS PID controller(1.0, 0.0, 0.0, PID_RATE); PwmOut heater(PB_10); //LOGGING FUNCS int logging_setup(); void logging_loop(FILE *logging_file); int update_data(); void log_data(FILE *fp); //INTERNAL FUNCS void internalStateLoop(); void internalStateSetup(); int main() { printf("Doing Logging Setup!\n"); int error = logging_setup(); if (error) return -1; printf("Now beginning the logging loop!\n"); while (true) { logging_loop(logging_file); } fclose(logging_file); return 0; } void log_data(FILE *fp) { char data_buffer[200]; sprintf(data_buffer,"%s %.6f %.6f %.6f %lu %.6f %.6f %.6f %.6f %lu %hu %hu\n", date,latitude,longitude,altitude,precision,internal_temp,external_temp,pressure,power, encoded_chars,good_sentences,failed_checksums); fprintf(fp,data_buffer); printf(data_buffer); } int update_lat_long() { unsigned long age; gps.f_get_position(&latitude, &longitude, &age); //Updates longitude and latitude if (age == TinyGPS::GPS_INVALID_AGE) { latitude = -500.0; //These are sentinel values for lat long; if GPS can't track them longitude = -500.0; return -1; } else { return 0; } } int update_datetime() { unsigned long age; int year; byte month, day, hour, minute, second, hundredths; gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age); if (age == TinyGPS::GPS_INVALID_AGE) { sprintf(date,"1000 BC"); return -1; } else { sprintf(date,"%02d/%02d/%02d %02d:%02d:%02d",month, day, year, hour, minute, second); return 0; } } bool gps_readable() { bool new_data = false; for (unsigned long start = time(NULL); time(NULL) - start < 0.5;) { while (gps_ser.readable()) { char c = gps_ser.getc(); //printf("%c",c); if (gps.encode(c)) new_data = true; } } return new_data; } void place_dummy_gps_values() { latitude = -1000.0; longitude = -1000.0; altitude = -1000.0; precision = -1000; sprintf(date,"20000 BC"); encoded_chars = -1; good_sentences = -1; failed_checksums = -1; } int update_data() { p_sensor.Barometer_MS5803(); //Gathers data from external temp/pressure sensor //Updates temperatures, pressure, and power pressure = p_sensor.MS5803_Pressure(); external_temp = p_sensor.MS5803_Temperature(); internal_temp = temperature.read(); power = ain.read(); //Data gathered from GPS bool gps_ready = gps_readable(); int max_gps_requests = 4; int gps_counter = 0; while (!gps_ready && gps_counter < max_gps_requests) { gps_ready = gps_readable(); gps_counter++; //printf("Waiting!\n"); } if (gps_ready) { update_lat_long(); altitude = gps.f_altitude(); precision = gps.hdop(); gps.stats(&encoded_chars, &good_sentences, &failed_checksums); update_datetime(); } else { place_dummy_gps_values(); } return 0; //Data update was a success! } int logging_setup() { p_sensor.MS5803Init(); gps_ser.baud(9600); mkdir("/sd/test_dir", 0777); wait(1.0); FILE *fp = fopen("/sd/test_dir/test_file2.txt", "a"); wait(1.0); if(fp == NULL) { error("Could not open test file for write\n"); return 1; } else { //Now write in one line of data into the new file! update_data(); log_data(fp); fclose(fp); } mkdir("/sd/data", 0777); wait(1.0); logging_file = fopen("/sd/data/logging2.txt", "a"); wait(1.0); if(logging_file == NULL) { error("Could not open log file for write\n"); return 1; } return 0; } void logging_loop(FILE *log_file) { update_data(); log_data(log_file); } void internalStateSetup() { //TMP102.h temperature ranges from -40 to 125 C controller.setInputLimits(-40.0, 125.0); controller.setOutputLimits(0.0, 1.0); controller.setBias(0.3); // Try experimenting with the bias! controller.setMode(AUTO_MODE); controller.setSetPoint(DESIRED_INTERNAL_TEMP); W.Start(WATCH_DOG_RATE); } void internalStateLoop() { //Pet the watchdog W.Pet(); controller.setProcessValue(CURR_TEMP); //We won't actually read from the TMP 102.h, we'll use the most recent internal temp variable (global). // Set the new output. heater = controller.compute(); printf("What should the output be? %f\n", controller.compute()); //printf("Was reset by watchdog? %s\n", W.WasResetByWatchdog() ? "true" : "false"); // Now check for termination conditions // 1. If the GPS lat,lon exceed the permitted bounds, cut down. // 2. If you receive an iridum command telling you to end the flight, cut down. // 3. If you've not received an Iridium command in a while (5 hrs), cut down. } <|endoftext|>
<commit_before>#include <SPI.h> #define PACKET_BODY_LENGTH 2 bool transmitMany = false; int bytesSent = 0; int CHIPSELECT = 16; int incomingByte = 0; int numError = 0; uint16_t echo[PACKET_BODY_LENGTH] = {0x0, 0xbbbb}; uint16_t stat[PACKET_BODY_LENGTH] = {0x1, 0xaaaa}; uint16_t idle_[PACKET_BODY_LENGTH] = {0x2, 0xcccc}; uint16_t shutdown_[PACKET_BODY_LENGTH] = {0x3, 0xdddd}; uint16_t enterImu[PACKET_BODY_LENGTH] = {0x4, 0xcccc}; uint16_t getImuData[PACKET_BODY_LENGTH] = {0x5, 0xeeee}; void rando(); SPISettings settingsA(6250000, MSBFIRST, SPI_MODE0); void setup() { Serial.begin(115200); pinMode(0, INPUT); SPI.begin(); pinMode(CHIPSELECT, OUTPUT); SPI.beginTransaction(settingsA); delay(1000); digitalWrite(CHIPSELECT, HIGH); //rando(); Serial.println("hey\n"); } void transmitH(uint16_t *buf, bool verbos); uint16_t send16(uint16_t to_send, bool verbos) { uint16_t dat = SPI.transfer16(to_send); if (verbos) { Serial.printf("Sent: %x, received: %x\n", to_send, dat); } return dat; } void transmit(uint16_t *buf) { if (transmitMany) { transmitMany = false; for (int i = 0; i < 30000; i++) { transmitH(buf, false); } Serial.println("Done"); } else { transmitH(buf, true); } } void transmitH(uint16_t *buf, bool verbos) { digitalWrite(CHIPSELECT, HIGH); digitalWrite(CHIPSELECT, LOW); delayMicroseconds(80); send16(0x1234, verbos); uint16_t checksum = 0; for (int i = 0; i < PACKET_BODY_LENGTH; i++) { send16(buf[i], verbos); checksum += buf[i]; } send16(checksum, verbos); send16(0x4321, verbos); int numIters = 30; if (buf == getImuData) { numIters = 310; } uint16_t received; for (int i = 0; i < numIters; i++) { received = send16(0xffff, verbos); if (received == 0x1234) { break; } } if (received != 0x1234) { Serial.println("bad"); numError++; } uint16_t len = send16(0xffff, verbos); uint16_t reponseNumber = send16(0xffff, verbos); for (int i = 0; i < len - 2; i++) { send16(0xffff, verbos); } if(verbos) { Serial.println("---------------------------------"); } delayMicroseconds(80); digitalWrite(CHIPSELECT, HIGH); } void transmitCrappy(uint16_t *buf) { digitalWrite(CHIPSELECT, HIGH); digitalWrite(CHIPSELECT, LOW); delay(1); send16(0x1233, true); uint16_t checksum = 0; for (int i = 0; i < PACKET_BODY_LENGTH; i++) { send16(buf[i], true); checksum += buf[i]; } send16(checksum, true); send16(0x4321, true); for (int i = 0; i < 30; i++) { send16(0xffff, true); } Serial.println("---------------------------------"); delay(1); digitalWrite(CHIPSELECT, HIGH); } void rando() { Serial.println("begin random"); int i = 0; while (Serial.available() <= 0) { int nextCommand = random(3); if (nextCommand == 0) { transmitH(echo, false); } else if (nextCommand == 1) { transmitH(stat, false); } else if (nextCommand == 2) { transmitH(idle_, false); } else { return; }/*else if (nextCommand == 3) { } transmitH(shutdown_, false); }*/ i++; } Serial.printf("end random, send %d packets\n", i); } void loop() { // send data only when you receive data: if (Serial.available() > 0) { // read the incoming byte: incomingByte = Serial.read(); if (incomingByte == '\n') { } else if (incomingByte == '1') { transmit(echo); } else if (incomingByte == '2') { transmit(stat); } else if (incomingByte == '3') { transmit(idle_); } else if (incomingByte == '4') { transmit(enterImu); } else if (incomingByte == '5') { transmit(getImuData); } else if (incomingByte == '6') { transmitCrappy(echo); } else if (incomingByte == 'r') { while (Serial.available() > 0) { Serial.read(); } rando(); } else if (incomingByte == 'm') { transmitMany = true; } } } <commit_msg>Stricter buffer times<commit_after>#include <SPI.h> #define PACKET_BODY_LENGTH 2 bool transmitMany = false; int bytesSent = 0; int CHIPSELECT = 16; int incomingByte = 0; int numError = 0; uint16_t echo[PACKET_BODY_LENGTH] = {0x0, 0xbbbb}; uint16_t stat[PACKET_BODY_LENGTH] = {0x1, 0xaaaa}; uint16_t idle_[PACKET_BODY_LENGTH] = {0x2, 0xcccc}; uint16_t shutdown_[PACKET_BODY_LENGTH] = {0x3, 0xdddd}; uint16_t enterImu[PACKET_BODY_LENGTH] = {0x4, 0xcccc}; uint16_t getImuData[PACKET_BODY_LENGTH] = {0x5, 0xeeee}; void rando(); SPISettings settingsA(6250000, MSBFIRST, SPI_MODE0); void setup() { Serial.begin(115200); pinMode(0, INPUT); SPI.begin(); pinMode(CHIPSELECT, OUTPUT); SPI.beginTransaction(settingsA); delay(1000); digitalWrite(CHIPSELECT, HIGH); //rando(); Serial.println("hey\n"); } void transmitH(uint16_t *buf, bool verbos); uint16_t send16(uint16_t to_send, bool verbos) { uint16_t dat = SPI.transfer16(to_send); if (verbos) { Serial.printf("Sent: %x, received: %x\n", to_send, dat); } return dat; } void transmit(uint16_t *buf) { if (transmitMany) { transmitMany = false; for (int i = 0; i < 30000; i++) { transmitH(buf, false); } Serial.println("Done"); } else { transmitH(buf, true); } } void transmitH(uint16_t *buf, bool verbos) { digitalWrite(CHIPSELECT, HIGH); digitalWrite(CHIPSELECT, LOW); delayMicroseconds(20); send16(0x1234, verbos); uint16_t checksum = 0; for (int i = 0; i < PACKET_BODY_LENGTH; i++) { send16(buf[i], verbos); checksum += buf[i]; } send16(checksum, verbos); send16(0x4321, verbos); int numIters = 30; if (buf == getImuData) { numIters = 310; } uint16_t received; for (int i = 0; i < numIters; i++) { received = send16(0xffff, verbos); if (received == 0x1234) { break; } } if (received != 0x1234) { Serial.println("bad"); numError++; } uint16_t len = send16(0xffff, verbos); uint16_t reponseNumber = send16(0xffff, verbos); for (int i = 0; i < len - 2; i++) { send16(0xffff, verbos); } if(verbos) { Serial.println("---------------------------------"); } delayMicroseconds(20); digitalWrite(CHIPSELECT, HIGH); } void transmitCrappy(uint16_t *buf) { digitalWrite(CHIPSELECT, HIGH); digitalWrite(CHIPSELECT, LOW); delay(1); send16(0x1233, true); uint16_t checksum = 0; for (int i = 0; i < PACKET_BODY_LENGTH; i++) { send16(buf[i], true); checksum += buf[i]; } send16(checksum, true); send16(0x4321, true); for (int i = 0; i < 30; i++) { send16(0xffff, true); } Serial.println("---------------------------------"); delay(1); digitalWrite(CHIPSELECT, HIGH); } void rando() { Serial.println("begin random"); int i = 0; while (Serial.available() <= 0) { int nextCommand = random(3); if (nextCommand == 0) { transmitH(echo, false); } else if (nextCommand == 1) { transmitH(stat, false); } else if (nextCommand == 2) { transmitH(idle_, false); } else { return; }/*else if (nextCommand == 3) { } transmitH(shutdown_, false); }*/ i++; } Serial.printf("end random, send %d packets\n", i); } void loop() { // send data only when you receive data: if (Serial.available() > 0) { // read the incoming byte: incomingByte = Serial.read(); if (incomingByte == '\n') { } else if (incomingByte == '1') { transmit(echo); } else if (incomingByte == '2') { transmit(stat); } else if (incomingByte == '3') { transmit(idle_); } else if (incomingByte == '4') { transmit(enterImu); } else if (incomingByte == '5') { transmit(getImuData); } else if (incomingByte == '6') { transmitCrappy(echo); } else if (incomingByte == 'r') { while (Serial.available() > 0) { Serial.read(); } rando(); } else if (incomingByte == 'm') { transmitMany = true; } } } <|endoftext|>
<commit_before>// @(#)root/thread:$Id$ // Author: Danilo Piparo, CERN 11/2/2016 /************************************************************************* * Copyright (C) 1995-2016, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_TThreadedObject #define ROOT_TThreadedObject #include "TList.h" #include "TError.h" #include <functional> #include <map> #include <memory> #include <mutex> #include <string> #include <thread> #include <vector> #include "ROOT/TSpinMutex.hxx" #include "TROOT.h" class TH1; namespace ROOT { namespace Internal { namespace TThreadedObjectUtils { /// Get the unique index identifying a TThreadedObject. inline unsigned GetTThreadedObjectIndex() { static unsigned fgTThreadedObjectIndex = 0; return fgTThreadedObjectIndex++; } template<typename T, bool ISHISTO = std::is_base_of<TH1,T>::value> struct Detacher{ static T* Detach(T* obj) { return obj; } }; template<typename T> struct Detacher<T, true>{ static T* Detach(T* obj) { obj->SetDirectory(nullptr); obj->ResetBit(kMustCleanup); return obj; } }; /// Return a copy of the object or a "Clone" if the copy constructor is not implemented. template<class T, bool isCopyConstructible = std::is_copy_constructible<T>::value> struct Cloner { static T *Clone(const T *obj, TDirectory* d = nullptr) { T* clone; if (d){ TDirectory::TContext ctxt(d); clone = new T(*obj); } else { clone = new T(*obj); } return Detacher<T>::Detach(clone); } }; template<class T> struct Cloner<T, false> { static T *Clone(const T *obj, TDirectory* d = nullptr) { T* clone; if (d){ TDirectory::TContext ctxt(d); clone = (T*)obj->Clone(); } else { clone = (T*)obj->Clone(); } return clone; } }; template<class T, bool ISHISTO = std::is_base_of<TH1,T>::value> struct DirCreator{ static std::vector<TDirectory*> Create(unsigned maxSlots) { std::string dirName = "__TThreaded_dir_"; dirName += std::to_string(ROOT::Internal::TThreadedObjectUtils::GetTThreadedObjectIndex()) + "_"; std::vector<TDirectory*> dirs; dirs.reserve(maxSlots); for (unsigned i=0; i< maxSlots;++i) { auto dir = gROOT->mkdir((dirName+std::to_string(i)).c_str()); dirs.emplace_back(dir); } return dirs; } }; template<class T> struct DirCreator<T, true>{ static std::vector<TDirectory*> Create(unsigned maxSlots) { std::vector<TDirectory*> dirs(maxSlots, nullptr); return dirs; } }; } // End of namespace TThreadedObjectUtils } // End of namespace Internals namespace TThreadedObjectUtils { template<class T> using MergeFunctionType = std::function<void(std::shared_ptr<T>, std::vector<std::shared_ptr<T>>&)>; /// Merge TObjects template<class T> void MergeTObjects(std::shared_ptr<T> target, std::vector<std::shared_ptr<T>> &objs) { if (!target) return; TList objTList; // Cannot do better than this for (auto obj : objs) { if (obj && obj != target) objTList.Add(obj.get()); } target->Merge(&objTList); } } // end of namespace TThreadedObjectUtils /** * \class ROOT::TThreadedObject * \brief A wrapper to make object instances thread private, lazily. * \tparam T Class of the object to be made thread private (e.g. TH1F) * \ingroup Multicore * * A wrapper which makes objects thread private. The methods of the underlying * object can be invoked via the the arrow operator. The object is created in * a specific thread lazily, i.e. upon invocation of one of its methods. * The correct object pointer from within a particular thread can be accessed * with the overloaded arrow operator or with the Get method. * In case an elaborate thread management is in place, e.g. in presence of * stream of operations or "processing slots", it is also possible to * manually select the correct object pointer explicitly. */ template<class T> class TThreadedObject { public: static unsigned fgMaxSlots; ///< The maximum number of processing slots (distinct threads) which the instances can manage TThreadedObject(const TThreadedObject&) = delete; /// Construct the TThreaded object and the "model" of the thread private /// objects. /// \tparam ARGS Arguments of the constructor of T template<class ...ARGS> TThreadedObject(ARGS&&... args): fObjPointers(fgMaxSlots, nullptr) { fDirectories = Internal::TThreadedObjectUtils::DirCreator<T>::Create(fgMaxSlots); TDirectory::TContext ctxt(fDirectories[0]); fModel.reset(Internal::TThreadedObjectUtils::Detacher<T>::Detach(new T(std::forward<ARGS>(args)...))); } /// Access a particular processing slot. This /// method is *thread-unsafe*: it cannot be invoked from two different /// threads with the same argument. std::shared_ptr<T> GetAtSlot(unsigned i) { if ( i >= fObjPointers.size()) { Warning("TThreadedObject::GetAtSlot", "Maximum number of slots reached."); return nullptr; } auto objPointer = fObjPointers[i]; if (!objPointer) { objPointer.reset(Internal::TThreadedObjectUtils::Cloner<T>::Clone(fModel.get(), fDirectories[i])); fObjPointers[i] = objPointer; } return objPointer; } /// Set the value of a particular slot. void SetAtSlot(unsigned i, std::shared_ptr<T> v) { fObjPointers[i] = v; } /// Access a particular slot which corresponds to a single thread. /// This is in general faster than the GetAtSlot method but it is /// responsibility of the caller to make sure that an object is /// initialised for the particular slot. std::shared_ptr<T> GetAtSlotUnchecked(unsigned i) const { return fObjPointers[i]; } /// Access the pointer corresponding to the current slot. This method is /// not adequate for being called inside tight loops as it implies a /// lookup in a mapping between the threadIDs and the slot indices. /// A good practice consists in copying the pointer onto the stack and /// proceed with the loop as shown in this work item (psudo-code) which /// will be sent to different threads: /// ~~~{.cpp} /// auto workItem = [](){ /// auto objPtr = tthreadedObject.Get(); /// for (auto i : ROOT::TSeqI(1000)) { /// // tthreadedObject->FastMethod(i); // don't do this! Inefficient! /// objPtr->FastMethod(i); /// } /// } /// ~~~ std::shared_ptr<T> Get() { return GetAtSlot(GetThisSlotNumber()); } /// Access the wrapped object and allow to call its methods. T *operator->() { return Get().get(); } /// Merge all the thread private objects. Can be called once: it does not /// create any new object but destroys the present bookkeping collapsing /// all objects into the one at slot 0. std::shared_ptr<T> Merge(TThreadedObjectUtils::MergeFunctionType<T> mergeFunction = TThreadedObjectUtils::MergeTObjects<T>) { // We do not return if we already merged. if (fIsMerged) { Warning("TThreadedObject::Merge", "This object was already merged. Returning the previous result."); return fObjPointers[0]; } mergeFunction(fObjPointers[0], fObjPointers); fIsMerged = true; return fObjPointers[0]; } /// Merge all the thread private objects. Can be called many times. It /// does create a new instance of class T to represent the "Sum" object. /// This method is not thread safe: correct or acceptable behaviours /// depend on the nature of T and of the merging function. std::unique_ptr<T> SnapshotMerge(TThreadedObjectUtils::MergeFunctionType<T> mergeFunction = TThreadedObjectUtils::MergeTObjects<T>) { if (fIsMerged) { Warning("TThreadedObject::SnapshotMerge", "This object was already merged. Returning the previous result."); return std::unique_ptr<T>(Internal::TThreadedObjectUtils::Cloner<T>::Clone(fObjPointers[0].get())); } auto targetPtr = Internal::TThreadedObjectUtils::Cloner<T>::Clone(fModel.get()); std::shared_ptr<T> targetPtrShared(targetPtr, [](T *) {}); mergeFunction(targetPtrShared, fObjPointers); return std::unique_ptr<T>(targetPtr); } private: std::unique_ptr<T> fModel; ///< Use to store a "model" of the object std::vector<std::shared_ptr<T>> fObjPointers; ///< A pointer per thread is kept. std::vector<TDirectory*> fDirectories; ///< A TDirectory per thread is kept. std::map<std::thread::id, unsigned> fThrIDSlotMap; ///< A mapping between the thread IDs and the slots unsigned fCurrMaxSlotIndex = 0; ///< The maximum slot index bool fIsMerged = false; ///< Remember if the objects have been merged already ROOT::TSpinMutex fThrIDSlotMutex; ///< Mutex to protect the ID-slot map access /// Get the slot number for this threadID. unsigned GetThisSlotNumber() { const auto thisThreadID = std::this_thread::get_id(); unsigned thisIndex; { std::lock_guard<ROOT::TSpinMutex> lg(fThrIDSlotMutex); auto thisSlotNumIt = fThrIDSlotMap.find(thisThreadID); if (thisSlotNumIt != fThrIDSlotMap.end()) return thisSlotNumIt->second; thisIndex = fCurrMaxSlotIndex++; fThrIDSlotMap[thisThreadID] = thisIndex; } return thisIndex; } }; template<class T> unsigned TThreadedObject<T>::fgMaxSlots = 64; } // End ROOT namespace #include <sstream> //////////////////////////////////////////////////////////////////////////////// /// Print a TThreadedObject at the prompt: namespace cling { template<class T> std::string printValue(ROOT::TThreadedObject<T> *val) { auto model = ((std::unique_ptr<T>*)(val))->get(); std::ostringstream ret; ret << "A wrapper to make object instances thread private, lazily. " << "The model which is replicated is " << printValue(model); return ret.str(); } } #endif <commit_msg>[IMT] Add TThreadedObject::GetAtSlotRaw<commit_after>// @(#)root/thread:$Id$ // Author: Danilo Piparo, CERN 11/2/2016 /************************************************************************* * Copyright (C) 1995-2016, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_TThreadedObject #define ROOT_TThreadedObject #include "TList.h" #include "TError.h" #include <functional> #include <map> #include <memory> #include <mutex> #include <string> #include <thread> #include <vector> #include "ROOT/TSpinMutex.hxx" #include "TROOT.h" class TH1; namespace ROOT { namespace Internal { namespace TThreadedObjectUtils { /// Get the unique index identifying a TThreadedObject. inline unsigned GetTThreadedObjectIndex() { static unsigned fgTThreadedObjectIndex = 0; return fgTThreadedObjectIndex++; } template<typename T, bool ISHISTO = std::is_base_of<TH1,T>::value> struct Detacher{ static T* Detach(T* obj) { return obj; } }; template<typename T> struct Detacher<T, true>{ static T* Detach(T* obj) { obj->SetDirectory(nullptr); obj->ResetBit(kMustCleanup); return obj; } }; /// Return a copy of the object or a "Clone" if the copy constructor is not implemented. template<class T, bool isCopyConstructible = std::is_copy_constructible<T>::value> struct Cloner { static T *Clone(const T *obj, TDirectory* d = nullptr) { T* clone; if (d){ TDirectory::TContext ctxt(d); clone = new T(*obj); } else { clone = new T(*obj); } return Detacher<T>::Detach(clone); } }; template<class T> struct Cloner<T, false> { static T *Clone(const T *obj, TDirectory* d = nullptr) { T* clone; if (d){ TDirectory::TContext ctxt(d); clone = (T*)obj->Clone(); } else { clone = (T*)obj->Clone(); } return clone; } }; template<class T, bool ISHISTO = std::is_base_of<TH1,T>::value> struct DirCreator{ static std::vector<TDirectory*> Create(unsigned maxSlots) { std::string dirName = "__TThreaded_dir_"; dirName += std::to_string(ROOT::Internal::TThreadedObjectUtils::GetTThreadedObjectIndex()) + "_"; std::vector<TDirectory*> dirs; dirs.reserve(maxSlots); for (unsigned i=0; i< maxSlots;++i) { auto dir = gROOT->mkdir((dirName+std::to_string(i)).c_str()); dirs.emplace_back(dir); } return dirs; } }; template<class T> struct DirCreator<T, true>{ static std::vector<TDirectory*> Create(unsigned maxSlots) { std::vector<TDirectory*> dirs(maxSlots, nullptr); return dirs; } }; } // End of namespace TThreadedObjectUtils } // End of namespace Internals namespace TThreadedObjectUtils { template<class T> using MergeFunctionType = std::function<void(std::shared_ptr<T>, std::vector<std::shared_ptr<T>>&)>; /// Merge TObjects template<class T> void MergeTObjects(std::shared_ptr<T> target, std::vector<std::shared_ptr<T>> &objs) { if (!target) return; TList objTList; // Cannot do better than this for (auto obj : objs) { if (obj && obj != target) objTList.Add(obj.get()); } target->Merge(&objTList); } } // end of namespace TThreadedObjectUtils /** * \class ROOT::TThreadedObject * \brief A wrapper to make object instances thread private, lazily. * \tparam T Class of the object to be made thread private (e.g. TH1F) * \ingroup Multicore * * A wrapper which makes objects thread private. The methods of the underlying * object can be invoked via the the arrow operator. The object is created in * a specific thread lazily, i.e. upon invocation of one of its methods. * The correct object pointer from within a particular thread can be accessed * with the overloaded arrow operator or with the Get method. * In case an elaborate thread management is in place, e.g. in presence of * stream of operations or "processing slots", it is also possible to * manually select the correct object pointer explicitly. */ template<class T> class TThreadedObject { public: static unsigned fgMaxSlots; ///< The maximum number of processing slots (distinct threads) which the instances can manage TThreadedObject(const TThreadedObject&) = delete; /// Construct the TThreaded object and the "model" of the thread private /// objects. /// \tparam ARGS Arguments of the constructor of T template<class ...ARGS> TThreadedObject(ARGS&&... args): fObjPointers(fgMaxSlots, nullptr) { fDirectories = Internal::TThreadedObjectUtils::DirCreator<T>::Create(fgMaxSlots); TDirectory::TContext ctxt(fDirectories[0]); fModel.reset(Internal::TThreadedObjectUtils::Detacher<T>::Detach(new T(std::forward<ARGS>(args)...))); } /// Access a particular processing slot. This /// method is *thread-unsafe*: it cannot be invoked from two different /// threads with the same argument. std::shared_ptr<T> GetAtSlot(unsigned i) { if ( i >= fObjPointers.size()) { Warning("TThreadedObject::GetAtSlot", "Maximum number of slots reached."); return nullptr; } auto objPointer = fObjPointers[i]; if (!objPointer) { objPointer.reset(Internal::TThreadedObjectUtils::Cloner<T>::Clone(fModel.get(), fDirectories[i])); fObjPointers[i] = objPointer; } return objPointer; } /// Set the value of a particular slot. void SetAtSlot(unsigned i, std::shared_ptr<T> v) { fObjPointers[i] = v; } /// Access a particular slot which corresponds to a single thread. /// This is in general faster than the GetAtSlot method but it is /// responsibility of the caller to make sure that an object is /// initialised for the particular slot. std::shared_ptr<T> GetAtSlotUnchecked(unsigned i) const { return fObjPointers[i]; } /// Access a particular slot which corresponds to a single thread. /// This overload is faster than the GetAtSlotUnchecked method but /// the caller is responsible to make sure that an object is /// initialised for the particular slot and that the returned pointer /// will not outlive the TThreadedObject that returned it. T* GetAtSlotRaw(unsigned i) const { return fObjPointers[i].get(); } /// Access the pointer corresponding to the current slot. This method is /// not adequate for being called inside tight loops as it implies a /// lookup in a mapping between the threadIDs and the slot indices. /// A good practice consists in copying the pointer onto the stack and /// proceed with the loop as shown in this work item (psudo-code) which /// will be sent to different threads: /// ~~~{.cpp} /// auto workItem = [](){ /// auto objPtr = tthreadedObject.Get(); /// for (auto i : ROOT::TSeqI(1000)) { /// // tthreadedObject->FastMethod(i); // don't do this! Inefficient! /// objPtr->FastMethod(i); /// } /// } /// ~~~ std::shared_ptr<T> Get() { return GetAtSlot(GetThisSlotNumber()); } /// Access the wrapped object and allow to call its methods. T *operator->() { return Get().get(); } /// Merge all the thread private objects. Can be called once: it does not /// create any new object but destroys the present bookkeping collapsing /// all objects into the one at slot 0. std::shared_ptr<T> Merge(TThreadedObjectUtils::MergeFunctionType<T> mergeFunction = TThreadedObjectUtils::MergeTObjects<T>) { // We do not return if we already merged. if (fIsMerged) { Warning("TThreadedObject::Merge", "This object was already merged. Returning the previous result."); return fObjPointers[0]; } mergeFunction(fObjPointers[0], fObjPointers); fIsMerged = true; return fObjPointers[0]; } /// Merge all the thread private objects. Can be called many times. It /// does create a new instance of class T to represent the "Sum" object. /// This method is not thread safe: correct or acceptable behaviours /// depend on the nature of T and of the merging function. std::unique_ptr<T> SnapshotMerge(TThreadedObjectUtils::MergeFunctionType<T> mergeFunction = TThreadedObjectUtils::MergeTObjects<T>) { if (fIsMerged) { Warning("TThreadedObject::SnapshotMerge", "This object was already merged. Returning the previous result."); return std::unique_ptr<T>(Internal::TThreadedObjectUtils::Cloner<T>::Clone(fObjPointers[0].get())); } auto targetPtr = Internal::TThreadedObjectUtils::Cloner<T>::Clone(fModel.get()); std::shared_ptr<T> targetPtrShared(targetPtr, [](T *) {}); mergeFunction(targetPtrShared, fObjPointers); return std::unique_ptr<T>(targetPtr); } private: std::unique_ptr<T> fModel; ///< Use to store a "model" of the object std::vector<std::shared_ptr<T>> fObjPointers; ///< A pointer per thread is kept. std::vector<TDirectory*> fDirectories; ///< A TDirectory per thread is kept. std::map<std::thread::id, unsigned> fThrIDSlotMap; ///< A mapping between the thread IDs and the slots unsigned fCurrMaxSlotIndex = 0; ///< The maximum slot index bool fIsMerged = false; ///< Remember if the objects have been merged already ROOT::TSpinMutex fThrIDSlotMutex; ///< Mutex to protect the ID-slot map access /// Get the slot number for this threadID. unsigned GetThisSlotNumber() { const auto thisThreadID = std::this_thread::get_id(); unsigned thisIndex; { std::lock_guard<ROOT::TSpinMutex> lg(fThrIDSlotMutex); auto thisSlotNumIt = fThrIDSlotMap.find(thisThreadID); if (thisSlotNumIt != fThrIDSlotMap.end()) return thisSlotNumIt->second; thisIndex = fCurrMaxSlotIndex++; fThrIDSlotMap[thisThreadID] = thisIndex; } return thisIndex; } }; template<class T> unsigned TThreadedObject<T>::fgMaxSlots = 64; } // End ROOT namespace #include <sstream> //////////////////////////////////////////////////////////////////////////////// /// Print a TThreadedObject at the prompt: namespace cling { template<class T> std::string printValue(ROOT::TThreadedObject<T> *val) { auto model = ((std::unique_ptr<T>*)(val))->get(); std::ostringstream ret; ret << "A wrapper to make object instances thread private, lazily. " << "The model which is replicated is " << printValue(model); return ret.str(); } } #endif <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: TestMapVectorsAsRGBColors.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 "vtkImageData.h" #include "vtkPointData.h" #include "vtkImageMapper.h" #include "vtkActor2D.h" #include "vtkRenderWindow.h" #include "vtkRenderer.h" #include "vtkLookupTable.h" #include "vtkUnsignedCharArray.h" #include "vtkSmartPointer.h" #include "vtkTestUtilities.h" #include "vtkRegressionTestImage.h" #include <math.h> int TestMapVectorsAsRGBColors(int argc, char *argv[]) { // Cases to check: // 1, 2, 3, 4 components to 1, 2, 3, 4, components // with scaling and without scaling // with alpha and without alpha // so 64 tests in total // on an 8x8 grid // Make the four sets of test scalars vtkSmartPointer<vtkUnsignedCharArray> inputs[4]; for (int ncomp = 1; ncomp <= 4; ncomp++) { inputs[ncomp-1] = vtkSmartPointer<vtkUnsignedCharArray>::New(); vtkUnsignedCharArray *arr = inputs[ncomp-1].GetPointer(); arr->SetNumberOfComponents(ncomp); arr->SetNumberOfTuples(6400); // luminance conversion factors static float a = 0.30; static float b = 0.59; static float c = 0.11; static float d = 0.50; static int f = 85; unsigned char cval[4]; vtkIdType i = 0; for (int j = 0; j < 16; j++) { for (int jj = 0; jj < 5; jj++) { for (int k = 0; k < 16; k++) { cval[0] = ((k >> 2) & 3)*f; cval[1] = (k & 3)*f; cval[2] = ((j >> 2) & 3)*f; cval[3] = (j & 3)*f; float l = cval[0]*a + cval[1]*b + cval[2]*c + d; unsigned char lc = static_cast<unsigned char>(l); cval[0] = (ncomp > 2 ? cval[0] : lc); cval[1] = (ncomp > 2 ? cval[1] : cval[3]); for (int kk = 0; kk < 5; kk++) { arr->SetTupleValue(i++, cval); } } } } } vtkSmartPointer<vtkLookupTable> table = vtkSmartPointer<vtkLookupTable>::New(); table->SetVectorModeToRGBColors(); vtkSmartPointer<vtkLookupTable> table2 = vtkSmartPointer<vtkLookupTable>::New(); vtkSmartPointer<vtkRenderWindow> renWin = vtkSmartPointer<vtkRenderWindow>::New(); renWin->SetSize(640, 640); // Make the 64 sets of output scalars vtkSmartPointer<vtkUnsignedCharArray> outputs[64]; for (int i = 0; i < 64; i++) { int j = (i & 7); int k = ((i >> 3) & 7); double alpha = 0.5*(2 - (j & 1)); double range[2]; range[0] = 63.75*(k & 1); range[1] = 255.0 - 63.75*(k & 1); int inputc = ((j >> 1) & 3) + 1; int outputc = ((k >> 1) & 3) + 1; table->SetRange(range); table->SetAlpha(alpha); outputs[i] = vtkSmartPointer<vtkUnsignedCharArray>::New(); outputs[i]->SetNumberOfComponents(outputc); outputs[i]->SetNumberOfTuples(0); // test mapping with a count of zero vtkUnsignedCharArray *tmparray = table2->MapScalars(outputs[i], VTK_COLOR_MODE_DEFAULT, outputc); tmparray->Delete(); table->MapVectorsThroughTable( inputs[inputc-1]->GetPointer(0), outputs[i]->WritePointer(0, 6400), VTK_UNSIGNED_CHAR, 0, inputc, outputc); // now the real thing outputs[i]->SetNumberOfTuples(6400); table->MapVectorsThroughTable( inputs[inputc-1]->GetPointer(0), outputs[i]->WritePointer(0, 6400), VTK_UNSIGNED_CHAR, 6400, inputc, outputc); vtkSmartPointer<vtkImageData> image = vtkSmartPointer<vtkImageData>::New(); image->SetDimensions(80, 80, 1); image->SetScalarTypeToUnsignedChar(); vtkUnsignedCharArray *colors = table2->MapScalars(outputs[i], VTK_COLOR_MODE_DEFAULT, outputc); image->GetPointData()->SetScalars(colors); colors->Delete(); int pos[2]; pos[0] = j*80; pos[1] = k*80; vtkSmartPointer<vtkImageMapper> mapper = vtkSmartPointer<vtkImageMapper>::New(); mapper->SetColorWindow(255.0); mapper->SetColorLevel(127.5); mapper->SetInput(image); vtkSmartPointer<vtkActor2D> actor = vtkSmartPointer<vtkActor2D>::New(); actor->SetMapper(mapper); vtkSmartPointer<vtkRenderer> ren = vtkSmartPointer<vtkRenderer>::New(); ren->AddViewProp(actor); ren->SetViewport(pos[0]/640.0, pos[1]/640.0, (pos[0] + 80)/640.0, (pos[1] + 80)/640.0); renWin->AddRenderer(ren); } renWin->Render(); int retVal = vtkRegressionTestImage(renWin); return !retVal; } <commit_msg>Add interaction to test<commit_after>/*========================================================================= Program: Visualization Toolkit Module: TestMapVectorsAsRGBColors.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 "vtkImageData.h" #include "vtkRenderWindowInteractor.h" #include "vtkPointData.h" #include "vtkImageMapper.h" #include "vtkActor2D.h" #include "vtkRenderWindow.h" #include "vtkRenderer.h" #include "vtkLookupTable.h" #include "vtkUnsignedCharArray.h" #include "vtkSmartPointer.h" #include "vtkTestUtilities.h" #include "vtkRegressionTestImage.h" #include <math.h> int TestMapVectorsAsRGBColors(int argc, char *argv[]) { // Cases to check: // 1, 2, 3, 4 components to 1, 2, 3, 4, components // with scaling and without scaling // with alpha and without alpha // so 64 tests in total // on an 8x8 grid // Make the four sets of test scalars vtkSmartPointer<vtkUnsignedCharArray> inputs[4]; for (int ncomp = 1; ncomp <= 4; ncomp++) { inputs[ncomp-1] = vtkSmartPointer<vtkUnsignedCharArray>::New(); vtkUnsignedCharArray *arr = inputs[ncomp-1].GetPointer(); arr->SetNumberOfComponents(ncomp); arr->SetNumberOfTuples(6400); // luminance conversion factors static float a = 0.30; static float b = 0.59; static float c = 0.11; static float d = 0.50; static int f = 85; unsigned char cval[4]; vtkIdType i = 0; for (int j = 0; j < 16; j++) { for (int jj = 0; jj < 5; jj++) { for (int k = 0; k < 16; k++) { cval[0] = ((k >> 2) & 3)*f; cval[1] = (k & 3)*f; cval[2] = ((j >> 2) & 3)*f; cval[3] = (j & 3)*f; float l = cval[0]*a + cval[1]*b + cval[2]*c + d; unsigned char lc = static_cast<unsigned char>(l); cval[0] = (ncomp > 2 ? cval[0] : lc); cval[1] = (ncomp > 2 ? cval[1] : cval[3]); for (int kk = 0; kk < 5; kk++) { arr->SetTupleValue(i++, cval); } } } } } vtkSmartPointer<vtkLookupTable> table = vtkSmartPointer<vtkLookupTable>::New(); table->SetVectorModeToRGBColors(); vtkSmartPointer<vtkLookupTable> table2 = vtkSmartPointer<vtkLookupTable>::New(); vtkSmartPointer<vtkRenderWindow> renWin = vtkSmartPointer<vtkRenderWindow>::New(); vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkSmartPointer<vtkRenderWindowInteractor>::New(); iren->SetRenderWindow(renWin); renWin->SetSize(640, 640); // Make the 64 sets of output scalars vtkSmartPointer<vtkUnsignedCharArray> outputs[64]; for (int i = 0; i < 64; i++) { int j = (i & 7); int k = ((i >> 3) & 7); double alpha = 0.5*(2 - (j & 1)); double range[2]; range[0] = 63.75*(k & 1); range[1] = 255.0 - 63.75*(k & 1); int inputc = ((j >> 1) & 3) + 1; int outputc = ((k >> 1) & 3) + 1; table->SetRange(range); table->SetAlpha(alpha); outputs[i] = vtkSmartPointer<vtkUnsignedCharArray>::New(); outputs[i]->SetNumberOfComponents(outputc); outputs[i]->SetNumberOfTuples(0); // test mapping with a count of zero vtkUnsignedCharArray *tmparray = table2->MapScalars(outputs[i], VTK_COLOR_MODE_DEFAULT, outputc); tmparray->Delete(); table->MapVectorsThroughTable( inputs[inputc-1]->GetPointer(0), outputs[i]->WritePointer(0, 6400), VTK_UNSIGNED_CHAR, 0, inputc, outputc); // now the real thing outputs[i]->SetNumberOfTuples(6400); table->MapVectorsThroughTable( inputs[inputc-1]->GetPointer(0), outputs[i]->WritePointer(0, 6400), VTK_UNSIGNED_CHAR, 6400, inputc, outputc); vtkSmartPointer<vtkImageData> image = vtkSmartPointer<vtkImageData>::New(); image->SetDimensions(80, 80, 1); image->SetScalarTypeToUnsignedChar(); vtkUnsignedCharArray *colors = table2->MapScalars(outputs[i], VTK_COLOR_MODE_DEFAULT, outputc); image->GetPointData()->SetScalars(colors); colors->Delete(); int pos[2]; pos[0] = j*80; pos[1] = k*80; vtkSmartPointer<vtkImageMapper> mapper = vtkSmartPointer<vtkImageMapper>::New(); mapper->SetColorWindow(255.0); mapper->SetColorLevel(127.5); mapper->SetInput(image); vtkSmartPointer<vtkActor2D> actor = vtkSmartPointer<vtkActor2D>::New(); actor->SetMapper(mapper); vtkSmartPointer<vtkRenderer> ren = vtkSmartPointer<vtkRenderer>::New(); ren->AddViewProp(actor); ren->SetViewport(pos[0]/640.0, pos[1]/640.0, (pos[0] + 80)/640.0, (pos[1] + 80)/640.0); renWin->AddRenderer(ren); } renWin->Render(); int retVal = vtkRegressionTestImage(renWin); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { iren->Start(); } return !retVal; } <|endoftext|>
<commit_before>// @(#)root/thread:$Id$ // Author: Danilo Piparo, CERN 11/2/2016 /************************************************************************* * Copyright (C) 1995-2016, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_TThreadedObject #define ROOT_TThreadedObject #include "TList.h" #include "TError.h" #include <functional> #include <map> #include <memory> #include <mutex> #include <string> #include <thread> #include <vector> #include "ROOT/TSpinMutex.hxx" #include "TROOT.h" class TH1; namespace ROOT { namespace Internal { namespace TThreadedObjectUtils { /// Get the unique index identifying a TThreadedObject. inline unsigned GetTThreadedObjectIndex() { static unsigned fgTThreadedObjectIndex = 0; return fgTThreadedObjectIndex++; } /// Return a copy of the object or a "Clone" if the copy constructor is not implemented. template<class T, bool isCopyConstructible = std::is_copy_constructible<T>::value> struct Cloner { static T *Clone(const T *obj, TDirectory* d = nullptr) { T* clone; if (d){ TDirectory::TContext ctxt(d); clone = new T(*obj); } else { clone = new T(*obj); } return clone; } }; template<class T> struct Cloner<T, false> { static T *Clone(const T *obj, TDirectory* d = nullptr) { T* clone; if (d){ TDirectory::TContext ctxt(d); clone = (T*)obj->Clone(); } else { clone = (T*)obj->Clone(); } return clone; } }; template<class T, bool ISHISTO = std::is_base_of<TH1,T>::value> struct DirCreator{ static std::vector<TDirectory*> Create(unsigned maxSlots) { std::string dirName = "__TThreaded_dir_"; dirName += std::to_string(ROOT::Internal::TThreadedObjectUtils::GetTThreadedObjectIndex()) + "_"; std::vector<TDirectory*> dirs; dirs.reserve(maxSlots); for (unsigned i=0; i< maxSlots;++i) { auto dir = gROOT->mkdir((dirName+std::to_string(i)).c_str()); dirs.emplace_back(dir); } return dirs; } }; template<class T> struct DirCreator<T, true>{ static std::vector<TDirectory*> Create(unsigned maxSlots) { std::vector<TDirectory*> dirs(maxSlots, nullptr); return dirs; } }; } // End of namespace TThreadedObjectUtils } // End of namespace Internals namespace TThreadedObjectUtils { template<class T> using MergeFunctionType = std::function<void(std::shared_ptr<T>, std::vector<std::shared_ptr<T>>&)>; /// Merge TObjects template<class T> void MergeTObjects(std::shared_ptr<T> target, std::vector<std::shared_ptr<T>> &objs) { if (!target) return; TList objTList; // Cannot do better than this for (auto obj : objs) { if (obj && obj != target) objTList.Add(obj.get()); } target->Merge(&objTList); } } // end of namespace TThreadedObjectUtils /** * \class ROOT::TThreadedObject * \brief A wrapper to make object instances thread private, lazily. * \tparam T Class of the object to be made thread private (e.g. TH1F) * \ingroup Multicore * * A wrapper which makes objects thread private. The methods of the underlying * object can be invoked via the the arrow operator. The object is created in * a specific thread lazily, i.e. upon invocation of one of its methods. * The correct object pointer from within a particular thread can be accessed * with the overloaded arrow operator or with the Get method. * In case an elaborate thread management is in place, e.g. in presence of * stream of operations or "processing slots", it is also possible to * manually select the correct object pointer explicitly. */ template<class T> class TThreadedObject { public: static unsigned fgMaxSlots; ///< The maximum number of processing slots (distinct threads) which the instances can manage TThreadedObject(const TThreadedObject&) = delete; /// Construct the TThreaded object and the "model" of the thread private /// objects. /// \tparam ARGS Arguments of the constructor of T template<class ...ARGS> TThreadedObject(ARGS&&... args): fObjPointers(fgMaxSlots, nullptr) { fDirectories = Internal::TThreadedObjectUtils::DirCreator<T>::Create(fgMaxSlots); TDirectory::TContext ctxt(fDirectories[0]); fModel.reset(new T(std::forward<ARGS>(args)...)); } /// Access a particular processing slot. This /// method is *thread-unsafe*: it cannot be invoked from two different /// threads with the same argument. std::shared_ptr<T> GetAtSlot(unsigned i) { if ( i >= fObjPointers.size()) { Warning("TThreadedObject::GetAtSlot", "Maximum number of slots reached."); return nullptr; } auto objPointer = fObjPointers[i]; if (!objPointer) { objPointer.reset(Internal::TThreadedObjectUtils::Cloner<T>::Clone(fModel.get(), fDirectories[i])); fObjPointers[i] = objPointer; } return objPointer; } /// Set the value of a particular slot. void SetAtSlot(unsigned i, std::shared_ptr<T> v) { fObjPointers[i] = v; } /// Access a particular slot which corresponds to a single thread. /// This is in general faster than the GetAtSlot method but it is /// responsibility of the caller to make sure that an object is /// initialised for the particular slot. std::shared_ptr<T> GetAtSlotUnchecked(unsigned i) const { return fObjPointers[i]; } /// Access the pointer corresponding to the current slot. This method is /// not adequate for being called inside tight loops as it implies a /// lookup in a mapping between the threadIDs and the slot indices. /// A good practice consists in copying the pointer onto the stack and /// proceed with the loop as shown in this work item (psudo-code) which /// will be sent to different threads: /// ~~~{.cpp} /// auto workItem = [](){ /// auto objPtr = tthreadedObject.Get(); /// for (auto i : ROOT::TSeqI(1000)) { /// // tthreadedObject->FastMethod(i); // don't do this! Inefficient! /// objPtr->FastMethod(i); /// } /// } /// ~~~ std::shared_ptr<T> Get() { return GetAtSlot(GetThisSlotNumber()); } /// Access the wrapped object and allow to call its methods. T *operator->() { return Get().get(); } /// Merge all the thread private objects. Can be called once: it does not /// create any new object but destroys the present bookkeping collapsing /// all objects into the one at slot 0. std::shared_ptr<T> Merge(TThreadedObjectUtils::MergeFunctionType<T> mergeFunction = TThreadedObjectUtils::MergeTObjects<T>) { // We do not return if we already merged. if (fIsMerged) { Warning("TThreadedObject::Merge", "This object was already merged. Returning the previous result."); return fObjPointers[0]; } mergeFunction(fObjPointers[0], fObjPointers); fIsMerged = true; return fObjPointers[0]; } /// Merge all the thread private objects. Can be called many times. It /// does create a new instance of class T to represent the "Sum" object. /// This method is not thread safe: correct or acceptable behaviours /// depend on the nature of T and of the merging function. std::unique_ptr<T> SnapshotMerge(TThreadedObjectUtils::MergeFunctionType<T> mergeFunction = TThreadedObjectUtils::MergeTObjects<T>) { if (fIsMerged) { Warning("TThreadedObject::SnapshotMerge", "This object was already merged. Returning the previous result."); return std::unique_ptr<T>(Internal::TThreadedObjectUtils::Cloner<T>::Clone(fObjPointers[0].get())); } auto targetPtr = Internal::TThreadedObjectUtils::Cloner<T>::Clone(fModel.get()); std::shared_ptr<T> targetPtrShared(targetPtr, [](T *) {}); mergeFunction(targetPtrShared, fObjPointers); return std::unique_ptr<T>(targetPtr); } private: std::unique_ptr<T> fModel; ///< Use to store a "model" of the object std::vector<std::shared_ptr<T>> fObjPointers; ///< A pointer per thread is kept. std::vector<TDirectory*> fDirectories; ///< A TDirectory per thread is kept. std::map<std::thread::id, unsigned> fThrIDSlotMap; ///< A mapping between the thread IDs and the slots unsigned fCurrMaxSlotIndex = 0; ///< The maximum slot index bool fIsMerged = false; ///< Remember if the objects have been merged already ROOT::TSpinMutex fThrIDSlotMutex; ///< Mutex to protect the ID-slot map access /// Get the slot number for this threadID. unsigned GetThisSlotNumber() { const auto thisThreadID = std::this_thread::get_id(); unsigned thisIndex; { std::lock_guard<ROOT::TSpinMutex> lg(fThrIDSlotMutex); auto thisSlotNumIt = fThrIDSlotMap.find(thisThreadID); if (thisSlotNumIt != fThrIDSlotMap.end()) return thisSlotNumIt->second; thisIndex = fCurrMaxSlotIndex++; fThrIDSlotMap[thisThreadID] = thisIndex; } return thisIndex; } }; template<class T> unsigned TThreadedObject<T>::fgMaxSlots = 64; } // End ROOT namespace #include <sstream> //////////////////////////////////////////////////////////////////////////////// /// Print a TThreadedObject at the prompt: namespace cling { template<class T> std::string printValue(ROOT::TThreadedObject<T> *val) { auto model = ((std::unique_ptr<T>*)(val))->get(); std::ostringstream ret; ret << "A wrapper to make object instances thread private, lazily. " << "The model which is replicated is " << printValue(model); return ret.str(); } } #endif <commit_msg>Further optimise TThreadedObject for histograms<commit_after>// @(#)root/thread:$Id$ // Author: Danilo Piparo, CERN 11/2/2016 /************************************************************************* * Copyright (C) 1995-2016, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_TThreadedObject #define ROOT_TThreadedObject #include "TList.h" #include "TError.h" #include <functional> #include <map> #include <memory> #include <mutex> #include <string> #include <thread> #include <vector> #include "ROOT/TSpinMutex.hxx" #include "TROOT.h" class TH1; namespace ROOT { namespace Internal { namespace TThreadedObjectUtils { /// Get the unique index identifying a TThreadedObject. inline unsigned GetTThreadedObjectIndex() { static unsigned fgTThreadedObjectIndex = 0; return fgTThreadedObjectIndex++; } /// Return a copy of the object or a "Clone" if the copy constructor is not implemented. template<class T, bool isCopyConstructible = std::is_copy_constructible<T>::value, bool ISHISTO = std::is_base_of<TH1,T>::value> struct Cloner { static T *Clone(const T *obj, TDirectory* d = nullptr) { T* clone; if (d){ TDirectory::TContext ctxt(d); clone = new T(*obj); } else { clone = new T(*obj); } return clone; } }; template<class T> struct Cloner<T, false, false> { static T *Clone(const T *obj, TDirectory* d = nullptr) { T* clone; if (d){ TDirectory::TContext ctxt(d); clone = (T*)obj->Clone(); } else { clone = (T*)obj->Clone(); } return clone; } }; template<class T> struct Cloner<T, true, true> { static T *Clone(const T *obj, TDirectory* d = nullptr) { T* clone; if (d){ clone = (T*)obj->Clone(); } else { clone = (T*)obj->Clone(); } clone->SetDirectory(nullptr); return clone; } }; template<class T, bool ISHISTO = std::is_base_of<TH1,T>::value> struct DirCreator{ static std::vector<TDirectory*> Create(unsigned maxSlots) { std::string dirName = "__TThreaded_dir_"; dirName += std::to_string(ROOT::Internal::TThreadedObjectUtils::GetTThreadedObjectIndex()) + "_"; std::vector<TDirectory*> dirs; dirs.reserve(maxSlots); for (unsigned i=0; i< maxSlots;++i) { auto dir = gROOT->mkdir((dirName+std::to_string(i)).c_str()); dirs.emplace_back(dir); } return dirs; } }; template<class T> struct DirCreator<T, true>{ static std::vector<TDirectory*> Create(unsigned maxSlots) { std::vector<TDirectory*> dirs(maxSlots, nullptr); return dirs; } }; } // End of namespace TThreadedObjectUtils } // End of namespace Internals namespace TThreadedObjectUtils { template<class T> using MergeFunctionType = std::function<void(std::shared_ptr<T>, std::vector<std::shared_ptr<T>>&)>; /// Merge TObjects template<class T> void MergeTObjects(std::shared_ptr<T> target, std::vector<std::shared_ptr<T>> &objs) { if (!target) return; TList objTList; // Cannot do better than this for (auto obj : objs) { if (obj && obj != target) objTList.Add(obj.get()); } target->Merge(&objTList); } } // end of namespace TThreadedObjectUtils /** * \class ROOT::TThreadedObject * \brief A wrapper to make object instances thread private, lazily. * \tparam T Class of the object to be made thread private (e.g. TH1F) * \ingroup Multicore * * A wrapper which makes objects thread private. The methods of the underlying * object can be invoked via the the arrow operator. The object is created in * a specific thread lazily, i.e. upon invocation of one of its methods. * The correct object pointer from within a particular thread can be accessed * with the overloaded arrow operator or with the Get method. * In case an elaborate thread management is in place, e.g. in presence of * stream of operations or "processing slots", it is also possible to * manually select the correct object pointer explicitly. */ template<class T> class TThreadedObject { public: static unsigned fgMaxSlots; ///< The maximum number of processing slots (distinct threads) which the instances can manage TThreadedObject(const TThreadedObject&) = delete; /// Construct the TThreaded object and the "model" of the thread private /// objects. /// \tparam ARGS Arguments of the constructor of T template<class ...ARGS> TThreadedObject(ARGS&&... args): fObjPointers(fgMaxSlots, nullptr) { fDirectories = Internal::TThreadedObjectUtils::DirCreator<T>::Create(fgMaxSlots); TDirectory::TContext ctxt(fDirectories[0]); fModel.reset(new T(std::forward<ARGS>(args)...)); } /// Access a particular processing slot. This /// method is *thread-unsafe*: it cannot be invoked from two different /// threads with the same argument. std::shared_ptr<T> GetAtSlot(unsigned i) { if ( i >= fObjPointers.size()) { Warning("TThreadedObject::GetAtSlot", "Maximum number of slots reached."); return nullptr; } auto objPointer = fObjPointers[i]; if (!objPointer) { objPointer.reset(Internal::TThreadedObjectUtils::Cloner<T>::Clone(fModel.get(), fDirectories[i])); fObjPointers[i] = objPointer; } return objPointer; } /// Set the value of a particular slot. void SetAtSlot(unsigned i, std::shared_ptr<T> v) { fObjPointers[i] = v; } /// Access a particular slot which corresponds to a single thread. /// This is in general faster than the GetAtSlot method but it is /// responsibility of the caller to make sure that an object is /// initialised for the particular slot. std::shared_ptr<T> GetAtSlotUnchecked(unsigned i) const { return fObjPointers[i]; } /// Access the pointer corresponding to the current slot. This method is /// not adequate for being called inside tight loops as it implies a /// lookup in a mapping between the threadIDs and the slot indices. /// A good practice consists in copying the pointer onto the stack and /// proceed with the loop as shown in this work item (psudo-code) which /// will be sent to different threads: /// ~~~{.cpp} /// auto workItem = [](){ /// auto objPtr = tthreadedObject.Get(); /// for (auto i : ROOT::TSeqI(1000)) { /// // tthreadedObject->FastMethod(i); // don't do this! Inefficient! /// objPtr->FastMethod(i); /// } /// } /// ~~~ std::shared_ptr<T> Get() { return GetAtSlot(GetThisSlotNumber()); } /// Access the wrapped object and allow to call its methods. T *operator->() { return Get().get(); } /// Merge all the thread private objects. Can be called once: it does not /// create any new object but destroys the present bookkeping collapsing /// all objects into the one at slot 0. std::shared_ptr<T> Merge(TThreadedObjectUtils::MergeFunctionType<T> mergeFunction = TThreadedObjectUtils::MergeTObjects<T>) { // We do not return if we already merged. if (fIsMerged) { Warning("TThreadedObject::Merge", "This object was already merged. Returning the previous result."); return fObjPointers[0]; } mergeFunction(fObjPointers[0], fObjPointers); fIsMerged = true; return fObjPointers[0]; } /// Merge all the thread private objects. Can be called many times. It /// does create a new instance of class T to represent the "Sum" object. /// This method is not thread safe: correct or acceptable behaviours /// depend on the nature of T and of the merging function. std::unique_ptr<T> SnapshotMerge(TThreadedObjectUtils::MergeFunctionType<T> mergeFunction = TThreadedObjectUtils::MergeTObjects<T>) { if (fIsMerged) { Warning("TThreadedObject::SnapshotMerge", "This object was already merged. Returning the previous result."); return std::unique_ptr<T>(Internal::TThreadedObjectUtils::Cloner<T>::Clone(fObjPointers[0].get())); } auto targetPtr = Internal::TThreadedObjectUtils::Cloner<T>::Clone(fModel.get()); std::shared_ptr<T> targetPtrShared(targetPtr, [](T *) {}); mergeFunction(targetPtrShared, fObjPointers); return std::unique_ptr<T>(targetPtr); } private: std::unique_ptr<T> fModel; ///< Use to store a "model" of the object std::vector<std::shared_ptr<T>> fObjPointers; ///< A pointer per thread is kept. std::vector<TDirectory*> fDirectories; ///< A TDirectory per thread is kept. std::map<std::thread::id, unsigned> fThrIDSlotMap; ///< A mapping between the thread IDs and the slots unsigned fCurrMaxSlotIndex = 0; ///< The maximum slot index bool fIsMerged = false; ///< Remember if the objects have been merged already ROOT::TSpinMutex fThrIDSlotMutex; ///< Mutex to protect the ID-slot map access /// Get the slot number for this threadID. unsigned GetThisSlotNumber() { const auto thisThreadID = std::this_thread::get_id(); unsigned thisIndex; { std::lock_guard<ROOT::TSpinMutex> lg(fThrIDSlotMutex); auto thisSlotNumIt = fThrIDSlotMap.find(thisThreadID); if (thisSlotNumIt != fThrIDSlotMap.end()) return thisSlotNumIt->second; thisIndex = fCurrMaxSlotIndex++; fThrIDSlotMap[thisThreadID] = thisIndex; } return thisIndex; } }; template<class T> unsigned TThreadedObject<T>::fgMaxSlots = 64; } // End ROOT namespace #include <sstream> //////////////////////////////////////////////////////////////////////////////// /// Print a TThreadedObject at the prompt: namespace cling { template<class T> std::string printValue(ROOT::TThreadedObject<T> *val) { auto model = ((std::unique_ptr<T>*)(val))->get(); std::ostringstream ret; ret << "A wrapper to make object instances thread private, lazily. " << "The model which is replicated is " << printValue(model); return ret.str(); } } #endif <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ // mapnik #include <mapnik/agg_renderer.hpp> #include <mapnik/agg_rasterizer.hpp> #include <mapnik/expression_evaluator.hpp> namespace mapnik { template <typename T> void agg_renderer<T>::process(text_symbolizer const& sym, Feature const& feature, proj_transform const& prj_trans) { // Use a boost::ptr_vector here instread of std::vector? std::vector<geometry_type*> geometries_to_process; unsigned num_geom = feature.num_geometries(); for (unsigned i=0; i<num_geom; ++i) { geometry_type const& geom = feature.get_geometry(i); if (geom.num_points() == 0) { // don't bother with empty geometries continue; } if ((geom.type() == Polygon) && sym.get_minimum_path_length() > 0) { // TODO - find less costly method than fetching full envelope box2d<double> gbox = t_.forward(geom.envelope(),prj_trans); if (gbox.width() < sym.get_minimum_path_length()) { continue; } } // TODO - calculate length here as well // TODO - sort on size to priorize labeling larger geom // https://github.com/mapnik/mapnik/issues/162 geometries_to_process.push_back(const_cast<geometry_type*>(&geom)); } if (!geometries_to_process.size() > 0) { return; // early return to avoid significant overhead of rendering setup } expression_ptr name_expr = sym.get_name(); if (!name_expr) { return; } value_type result = boost::apply_visitor(evaluate<Feature,value_type>(feature),*name_expr); UnicodeString text = result.to_unicode(); if (text.length() <= 0) { // if text is empty no reason to continue return; } if (sym.get_text_transform() == UPPERCASE) { text = text.toUpper(); } else if (sym.get_text_transform() == LOWERCASE) { text = text.toLower(); } else if (sym.get_text_transform() == CAPITALIZE) { text = text.toTitle(NULL); } color const& fill = sym.get_fill(); face_set_ptr faces; if (sym.get_fontset().size() > 0) { faces = font_manager_.get_face_set(sym.get_fontset()); } else { faces = font_manager_.get_face_set(sym.get_face_name()); } stroker_ptr strk = font_manager_.get_stroker(); if (!(faces->size() > 0 && strk)) { throw config_error("Unable to find specified font face '" + sym.get_face_name() + "'"); } typedef coord_transform2<CoordTransform,geometry_type> path_type; metawriter_with_properties writer = sym.get_metawriter(); text_renderer<T> ren(pixmap_, faces, *strk); ren.set_fill(fill); ren.set_halo_fill(sym.get_halo_fill()); ren.set_halo_radius(sym.get_halo_radius() * scale_factor_); ren.set_opacity(sym.get_text_opacity()); box2d<double> dims(0,0,width_,height_); placement_finder<label_collision_detector4> finder(*detector_,dims); string_info info(text); faces->get_string_info(info); bool placement_found = false; text_placement_info_ptr placement_options = sym.get_placement_options()->get_placement_info(); while (!placement_found && placement_options->next()) { ren.set_character_size(placement_options->text_size * scale_factor_); BOOST_FOREACH( geometry_type * geom, geometries_to_process ) { while (!placement_found && placement_options->next_position_only()) { placement text_placement(info, sym, scale_factor_); text_placement.avoid_edges = sym.get_avoid_edges(); if (writer.first) text_placement.collect_extents =true; // needed for inmem metawriter if (sym.get_label_placement() == POINT_PLACEMENT || sym.get_label_placement() == INTERIOR_PLACEMENT) { double label_x=0.0; double label_y=0.0; double z=0.0; if (sym.get_label_placement() == POINT_PLACEMENT) geom->label_position(&label_x, &label_y); else geom->label_interior_position(&label_x, &label_y); prj_trans.backward(label_x,label_y, z); t_.forward(&label_x,&label_y); double angle = 0.0; expression_ptr angle_expr = sym.get_orientation(); if (angle_expr) { // apply rotation value_type result = boost::apply_visitor( evaluate<Feature,value_type>(feature),*angle_expr); angle = result.to_double(); } finder.find_point_placement(text_placement, placement_options, label_x,label_y, angle, sym.get_line_spacing(), sym.get_character_spacing()); finder.update_detector(text_placement); } else if ( geom->num_points() > 1 && sym.get_label_placement() == LINE_PLACEMENT) { path_type path(t_,*geom,prj_trans); finder.find_line_placements<path_type>(text_placement, placement_options, path); } if (!text_placement.placements.size()) continue; placement_found = true; for (unsigned int ii = 0; ii < text_placement.placements.size(); ++ii) { double x = text_placement.placements[ii].starting_x; double y = text_placement.placements[ii].starting_y; ren.prepare_glyphs(&text_placement.placements[ii]); ren.render(x,y); } if (writer.first) writer.first->add_text(text_placement, faces, feature, t_, writer.second); } } } } template void agg_renderer<image_32>::process(text_symbolizer const&, Feature const&, proj_transform const&); } <commit_msg>Revert "text rendering: only create objects once rather than per geometry part/placement attempt - refs #162"<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ // mapnik #include <mapnik/agg_renderer.hpp> #include <mapnik/agg_rasterizer.hpp> #include <mapnik/expression_evaluator.hpp> namespace mapnik { template <typename T> void agg_renderer<T>::process(text_symbolizer const& sym, Feature const& feature, proj_transform const& prj_trans) { // Use a boost::ptr_vector here instread of std::vector? std::vector<geometry_type*> geometries_to_process; unsigned num_geom = feature.num_geometries(); for (unsigned i=0; i<num_geom; ++i) { geometry_type const& geom = feature.get_geometry(i); if (geom.num_points() == 0) continue; // don't bother with empty geometries if ((geom.type() == Polygon) && sym.get_minimum_path_length() > 0) { // TODO - find less costly method than fetching full envelope box2d<double> gbox = t_.forward(geom.envelope(),prj_trans); if (gbox.width() < sym.get_minimum_path_length()) { continue; } } // TODO - calculate length here as well geometries_to_process.push_back(const_cast<geometry_type*>(&geom)); } if (!geometries_to_process.size() > 0) return; // early return to avoid significant overhead of rendering setup typedef coord_transform2<CoordTransform,geometry_type> path_type; bool placement_found = false; text_placement_info_ptr placement_options = sym.get_placement_options()->get_placement_info(); while (!placement_found && placement_options->next()) { expression_ptr name_expr = sym.get_name(); if (!name_expr) return; value_type result = boost::apply_visitor(evaluate<Feature,value_type>(feature),*name_expr); UnicodeString text = result.to_unicode(); if ( sym.get_text_transform() == UPPERCASE) { text = text.toUpper(); } else if ( sym.get_text_transform() == LOWERCASE) { text = text.toLower(); } else if ( sym.get_text_transform() == CAPITALIZE) { text = text.toTitle(NULL); } if ( text.length() <= 0 ) continue; color const& fill = sym.get_fill(); face_set_ptr faces; if (sym.get_fontset().size() > 0) { faces = font_manager_.get_face_set(sym.get_fontset()); } else { faces = font_manager_.get_face_set(sym.get_face_name()); } stroker_ptr strk = font_manager_.get_stroker(); if (!(faces->size() > 0 && strk)) { throw config_error("Unable to find specified font face '" + sym.get_face_name() + "'"); } text_renderer<T> ren(pixmap_, faces, *strk); ren.set_character_size(placement_options->text_size * scale_factor_); ren.set_fill(fill); ren.set_halo_fill(sym.get_halo_fill()); ren.set_halo_radius(sym.get_halo_radius() * scale_factor_); ren.set_opacity(sym.get_text_opacity()); box2d<double> dims(0,0,width_,height_); placement_finder<label_collision_detector4> finder(*detector_,dims); string_info info(text); faces->get_string_info(info); metawriter_with_properties writer = sym.get_metawriter(); BOOST_FOREACH( geometry_type * geom, geometries_to_process ) { while (!placement_found && placement_options->next_position_only()) { placement text_placement(info, sym, scale_factor_); text_placement.avoid_edges = sym.get_avoid_edges(); if (writer.first) text_placement.collect_extents =true; // needed for inmem metawriter if (sym.get_label_placement() == POINT_PLACEMENT || sym.get_label_placement() == INTERIOR_PLACEMENT) { double label_x=0.0; double label_y=0.0; double z=0.0; if (sym.get_label_placement() == POINT_PLACEMENT) geom->label_position(&label_x, &label_y); else geom->label_interior_position(&label_x, &label_y); prj_trans.backward(label_x,label_y, z); t_.forward(&label_x,&label_y); double angle = 0.0; expression_ptr angle_expr = sym.get_orientation(); if (angle_expr) { // apply rotation value_type result = boost::apply_visitor(evaluate<Feature,value_type>(feature),*angle_expr); angle = result.to_double(); } finder.find_point_placement(text_placement, placement_options, label_x,label_y, angle, sym.get_line_spacing(), sym.get_character_spacing()); finder.update_detector(text_placement); } else if ( geom->num_points() > 1 && sym.get_label_placement() == LINE_PLACEMENT) { path_type path(t_,*geom,prj_trans); finder.find_line_placements<path_type>(text_placement, placement_options, path); } if (!text_placement.placements.size()) continue; placement_found = true; for (unsigned int ii = 0; ii < text_placement.placements.size(); ++ii) { double x = text_placement.placements[ii].starting_x; double y = text_placement.placements[ii].starting_y; ren.prepare_glyphs(&text_placement.placements[ii]); ren.render(x,y); } if (writer.first) writer.first->add_text(text_placement, faces, feature, t_, writer.second); } } } } template void agg_renderer<image_32>::process(text_symbolizer const&, Feature const&, proj_transform const&); } <|endoftext|>
<commit_before>/************************************************************************* * * * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. * * All rights reserved. Email: [email protected] Web: www.q12.org * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of EITHER: * * (1) The GNU Lesser General Public License as published by the Free * * Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. The text of the GNU Lesser * * General Public License is included with this library in the * * file LICENSE.TXT. * * (2) The BSD-style license that is included with this library in * * the file LICENSE-BSD.TXT. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files * * LICENSE.TXT and LICENSE-BSD.TXT for more details. * * * *************************************************************************/ #include <ode/config.h> #include <ode/misc.h> #include <ode/matrix.h> //**************************************************************************** // random numbers static unsigned long seed = 0; unsigned long dRand() { seed = (1664525L*seed + 1013904223L) & 0xffffffff; return seed; } unsigned long dRandGetSeed() { return seed; } void dRandSetSeed (unsigned long s) { seed = s; } int dTestRand() { unsigned long oldseed = seed; int ret = 1; seed = 0; if (dRand() != 0x3c6ef35f || dRand() != 0x47502932 || dRand() != 0xd1ccf6e9 || dRand() != 0xaaf95334 || dRand() != 0x6252e503) ret = 0; seed = oldseed; return ret; } int dRandInt (int n) { double a = double(n) / 4294967296.0; return (int) (double(dRand()) * a); } dReal dRandReal() { return ((dReal) dRand()) / ((dReal) 0xffffffff); } //**************************************************************************** // matrix utility stuff void dPrintMatrix (const dReal *A, int n, int m, char *fmt, FILE *f) { int i,j; int skip = dPAD(m); for (i=0; i<n; i++) { for (j=0; j<m; j++) fprintf (f,fmt,A[i*skip+j]); fprintf (f,"\n"); } } void dMakeRandomVector (dReal *A, int n, dReal range) { int i; for (i=0; i<n; i++) A[i] = (dRandReal()*REAL(2.0)-REAL(1.0))*range; } void dMakeRandomMatrix (dReal *A, int n, int m, dReal range) { int i,j; int skip = dPAD(m); dSetZero (A,n*skip); for (i=0; i<n; i++) { for (j=0; j<m; j++) A[i*skip+j] = (dRandReal()*REAL(2.0)-REAL(1.0))*range; } } void dClearUpperTriangle (dReal *A, int n) { int i,j; int skip = dPAD(n); for (i=0; i<n; i++) { for (j=i+1; j<n; j++) A[i*skip+j] = 0; } } dReal dMaxDifference (const dReal *A, const dReal *B, int n, int m) { int i,j; int skip = dPAD(m); dReal diff,max; max = 0; for (i=0; i<n; i++) { for (j=0; j<m; j++) { diff = dFabs(A[i*skip+j] - B[i*skip+j]); if (diff > max) max = diff; } } return max; } dReal dMaxDifferenceLowerTriangle (const dReal *A, const dReal *B, int n) { int i,j; int skip = dPAD(n); dReal diff,max; max = 0; for (i=0; i<n; i++) { for (j=0; j<=i; j++) { diff = dFabs(A[i*skip+j] - B[i*skip+j]); if (diff > max) max = diff; } } return max; } <commit_msg>Replaced dRandInt implementation as suggest by [1]. This also fixes a bug encountered by [2], where dRandInt would return a value greater than N (it should return a value between 0 and N-1).<commit_after>/************************************************************************* * * * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. * * All rights reserved. Email: [email protected] Web: www.q12.org * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of EITHER: * * (1) The GNU Lesser General Public License as published by the Free * * Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. The text of the GNU Lesser * * General Public License is included with this library in the * * file LICENSE.TXT. * * (2) The BSD-style license that is included with this library in * * the file LICENSE-BSD.TXT. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files * * LICENSE.TXT and LICENSE-BSD.TXT for more details. * * * *************************************************************************/ #include <ode/config.h> #include <ode/misc.h> #include <ode/matrix.h> //**************************************************************************** // random numbers static unsigned long seed = 0; unsigned long dRand() { seed = (1664525L*seed + 1013904223L) & 0xffffffff; return seed; } unsigned long dRandGetSeed() { return seed; } void dRandSetSeed (unsigned long s) { seed = s; } int dTestRand() { unsigned long oldseed = seed; int ret = 1; seed = 0; if (dRand() != 0x3c6ef35f || dRand() != 0x47502932 || dRand() != 0xd1ccf6e9 || dRand() != 0xaaf95334 || dRand() != 0x6252e503) ret = 0; seed = oldseed; return ret; } int dRandInt (int n) { seed = (seed * 16807) & 0x7fffffff; return ((seed >> 15) * n) >> 16; } dReal dRandReal() { return ((dReal) dRand()) / ((dReal) 0xffffffff); } //**************************************************************************** // matrix utility stuff void dPrintMatrix (const dReal *A, int n, int m, char *fmt, FILE *f) { int i,j; int skip = dPAD(m); for (i=0; i<n; i++) { for (j=0; j<m; j++) fprintf (f,fmt,A[i*skip+j]); fprintf (f,"\n"); } } void dMakeRandomVector (dReal *A, int n, dReal range) { int i; for (i=0; i<n; i++) A[i] = (dRandReal()*REAL(2.0)-REAL(1.0))*range; } void dMakeRandomMatrix (dReal *A, int n, int m, dReal range) { int i,j; int skip = dPAD(m); dSetZero (A,n*skip); for (i=0; i<n; i++) { for (j=0; j<m; j++) A[i*skip+j] = (dRandReal()*REAL(2.0)-REAL(1.0))*range; } } void dClearUpperTriangle (dReal *A, int n) { int i,j; int skip = dPAD(n); for (i=0; i<n; i++) { for (j=i+1; j<n; j++) A[i*skip+j] = 0; } } dReal dMaxDifference (const dReal *A, const dReal *B, int n, int m) { int i,j; int skip = dPAD(m); dReal diff,max; max = 0; for (i=0; i<n; i++) { for (j=0; j<m; j++) { diff = dFabs(A[i*skip+j] - B[i*skip+j]); if (diff > max) max = diff; } } return max; } dReal dMaxDifferenceLowerTriangle (const dReal *A, const dReal *B, int n) { int i,j; int skip = dPAD(n); dReal diff,max; max = 0; for (i=0; i<n; i++) { for (j=0; j<=i; j++) { diff = dFabs(A[i*skip+j] - B[i*skip+j]); if (diff > max) max = diff; } } return max; } <|endoftext|>
<commit_before>#include <iostream> #include <boost/function.hpp> #include <lcm/lcm.h> #include <lcm/lcm-cpp.hpp> #include "lcmtypes/drc_lcmtypes.hpp" #include <GL/gl.h> #include <bot_vis/bot_vis.h> #include <bot_core/rotations.h> #include <gdk/gdkkeysyms.h> #include <path_util/path_util.h> #include "RobotStateListener.hpp" #include "renderer_robot_state.hpp" #define RENDERER_NAME "Robot State Display" #define PARAM_SELECTION "Enable Selection" #define PARAM_WIRE "Show BBoxs For Meshes" #define PARAM_COLOR_ALPHA "Alpha" using namespace std; using namespace boost; using namespace Eigen; using namespace visualization_utils; using namespace collision; using namespace renderer_robot_state; typedef struct _RobotStateRendererStruc { BotRenderer renderer; BotViewer *viewer; BotGtkParamWidget *pw; boost::shared_ptr<renderer_robot_state::RobotStateListener> robotStateListener; boost::shared_ptr<lcm::LCM> lcm; //BotEventHandler *key_handler; BotEventHandler ehandler; bool selection_enabled; bool clicked; bool visualize_bbox; Eigen::Vector3f ray_start; Eigen::Vector3f ray_end; std::string* selection; // transparency of the model: float alpha; } RobotStateRendererStruc; static void _renderer_free (BotRenderer *super) { RobotStateRendererStruc *self = (RobotStateRendererStruc*) super->user; free(self); } //========================= Event Handling ================ static double pick_query (BotViewer *viewer, BotEventHandler *ehandler, const double ray_start[3], const double ray_dir[3]) { RobotStateRendererStruc *self = (RobotStateRendererStruc*) ehandler->user; if((self->selection_enabled==0)||(self->robotStateListener->_urdf_subscription_on)){ return -1.0; } //fprintf(stderr, "RobotStateRenderer Pick Query Active\n"); Eigen::Vector3f from,to; from << ray_start[0], ray_start[1], ray_start[2]; Eigen::Vector3f plane_normal,plane_pt; plane_normal << 0,0,1; plane_pt << 0,0,0; double lambda1 = ray_dir[0] * plane_normal[0]+ ray_dir[1] * plane_normal[1] + ray_dir[2] * plane_normal[2]; // check for degenerate case where ray is (more or less) parallel to plane if (fabs (lambda1) < 1e-9) return -1.0; double lambda2 = (plane_pt[0] - ray_start[0]) * plane_normal[0] + (plane_pt[1] - ray_start[1]) * plane_normal[1] + (plane_pt[2] - ray_start[2]) * plane_normal[2]; double t = lambda2 / lambda1;// =1; to << ray_start[0]+t*ray_dir[0], ray_start[1]+t*ray_dir[1], ray_start[2]+t*ray_dir[2]; self->ray_start = from; self->ray_end = to; Eigen::Vector3f hit_pt; collision::Collision_Object * intersected_object = NULL; if(self->robotStateListener->_gl_robot) // to make sure that _gl_robot is initialized { //self->robotStateListener->_gl_robot->_collision_detector->num_collisions(); self->robotStateListener->_gl_robot->_collision_detector->ray_test( from, to, intersected_object,hit_pt); } if( intersected_object != NULL ){ Eigen::Vector3f diff = (from-hit_pt); double distance = diff.norm(); // std::cout << "RobotStateRenderer distance " << distance << std::endl; return distance; } //std::cout << "RobotStateRenderer distance " << -1.0 << std::endl; return -1.0; } static int mouse_press (BotViewer *viewer, BotEventHandler *ehandler, const double ray_start[3], const double ray_dir[3], const GdkEventButton *event) { RobotStateRendererStruc *self = (RobotStateRendererStruc*) ehandler->user; // std::cout << "state ehandler->picking " << ehandler->picking << std::endl; if((ehandler->picking==0)||(self->selection_enabled==0)){ (*self->selection) = " "; // fprintf(stderr, "RobotStateRenderer Ehandler Not active\n"); return 0; } // fprintf(stderr, "RobotStateRenderer Ehandler Activated\n"); self->clicked = 1; //fprintf(stderr, "Mouse Press : %f,%f\n",ray_start[0], ray_start[1]); collision::Collision_Object * intersected_object = NULL; if(self->robotStateListener->_gl_robot) // to make sure that _gl_robot is initialized { //self->robotStateListener->_gl_robot->_collision_detector->num_collisions(); self->robotStateListener->_gl_robot->_collision_detector->ray_test( self->ray_start, self->ray_end, intersected_object ); } if( intersected_object != NULL ){ // std::cout << "prev selection :" << (*self->selection) << std::endl; (*self->selection) = std::string(intersected_object->id().c_str()); std::cout << "intersected :" << intersected_object->id().c_str() << std::endl; bot_viewer_request_redraw(self->viewer); //spawn_plan_execution_dock(self); return 0; } else{ (*self->selection) = " "; bot_viewer_request_redraw(self->viewer); return 0; } } static int mouse_release (BotViewer *viewer, BotEventHandler *ehandler, const double ray_start[3], const double ray_dir[3], const GdkEventButton *event) { RobotStateRendererStruc *self = (RobotStateRendererStruc*) ehandler->user; self->clicked = 0; if((ehandler->picking==0)||(self->selection_enabled==0)){ //if(self->selection_enabled==0){ //fprintf(stderr, "Ehandler Not active\n"); return 0; } if (ehandler->picking==1) ehandler->picking=0; //release picking(IMPORTANT) bot_viewer_request_redraw(self->viewer); return 0; } //================================= static void _renderer_draw (BotViewer *viewer, BotRenderer *super) { //int64_t tic = bot_timestamp_now(); RobotStateRendererStruc *self = (RobotStateRendererStruc*) super->user; glEnable(GL_DEPTH_TEST); //-draw glEnable(GL_LIGHTING); glEnable(GL_COLOR_MATERIAL); glEnable(GL_BLEND); //glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); glEnable (GL_RESCALE_NORMAL); if((self->ehandler.picking)&&(self->selection_enabled)&&(self->clicked)){ glLineWidth (3.0); glPushMatrix(); glBegin(GL_LINES); glVertex3f(self->ray_start[0], self->ray_start[1],self->ray_start[2]); // object coord glVertex3f(self->ray_end[0], self->ray_end[1],self->ray_end[2]); glEnd(); glPopMatrix(); } float c[3] = {0.1,0.1,0.1}; // was 0.3 //glColor3f(c[0],c[1],c[2]); glColor4f(c[0],c[1],c[2],self->alpha); float alpha = self->alpha; if(self->robotStateListener->_gl_robot) { self->robotStateListener->_gl_robot->show_bbox(self->visualize_bbox); self->robotStateListener->_gl_robot->enable_link_selection(self->selection_enabled); self->robotStateListener->_gl_robot->highlight_link((*self->selection)); //self->robotStateListener->_gl_robot->enable_whole_body_selection(self->selection_enabled); self->robotStateListener->_gl_robot->draw_body (c,alpha); } // int64_t toc = bot_timestamp_now(); // cout << bot_timestamp_useconds(toc-tic) << endl; } static void on_param_widget_changed(BotGtkParamWidget *pw, const char *name, void *user) { RobotStateRendererStruc *self = (RobotStateRendererStruc*) user; if (! strcmp(name, PARAM_SELECTION)) { if (bot_gtk_param_widget_get_bool(pw, PARAM_SELECTION)) { //bot_viewer_request_pick (self->viewer, &(self->ehandler)); self->selection_enabled = 1; } else{ self->selection_enabled = 0; } } else if(! strcmp(name, PARAM_WIRE)) { if (bot_gtk_param_widget_get_bool(pw, PARAM_WIRE)){ self->visualize_bbox= true; } else{ self->visualize_bbox = false; } }else if(! strcmp(name, PARAM_COLOR_ALPHA)) { self->alpha = (float) bot_gtk_param_widget_get_double(pw, PARAM_COLOR_ALPHA); bot_viewer_request_redraw(self->viewer); } } void setup_renderer_robot_state(BotViewer *viewer, int render_priority, lcm_t *lcm) { RobotStateRendererStruc *self = (RobotStateRendererStruc*) calloc (1, sizeof (RobotStateRendererStruc)); self->lcm = boost::shared_ptr<lcm::LCM>(new lcm::LCM(lcm)); self->robotStateListener = boost::shared_ptr<RobotStateListener>(new RobotStateListener(self->lcm, viewer)); BotRenderer *renderer = &self->renderer; renderer->draw = _renderer_draw; renderer->destroy = _renderer_free; renderer->widget = bot_gtk_param_widget_new(); renderer->name = (char *) RENDERER_NAME; renderer->user = self; renderer->enabled = 1; self->viewer = viewer; self->pw = BOT_GTK_PARAM_WIDGET(renderer->widget); bot_gtk_param_widget_add_booleans(self->pw, BOT_GTK_PARAM_WIDGET_CHECKBOX, PARAM_SELECTION, 0, NULL); bot_gtk_param_widget_add_booleans(self->pw, BOT_GTK_PARAM_WIDGET_CHECKBOX, PARAM_WIRE, 0, NULL); bot_gtk_param_widget_add_double (self->pw, PARAM_COLOR_ALPHA, BOT_GTK_PARAM_WIDGET_SLIDER, 0, 1, 0.001, 1); g_signal_connect(G_OBJECT(self->pw), "changed", G_CALLBACK(on_param_widget_changed), self); self->alpha = 1.0; self->selection_enabled = 0; bot_gtk_param_widget_set_bool(self->pw, PARAM_SELECTION,self->selection_enabled); self->clicked = 0; self->selection = new std::string(" "); self->visualize_bbox = false; bot_viewer_add_renderer(viewer, &self->renderer, render_priority); //---------- // create and register mode handler /*self->key_handler = (BotEventHandler*) calloc(1, sizeof(BotEventHandler)); self->key_handler->name = strdup(std::string("Mode Control").c_str()); self->key_handler->enabled = 0; self->key_handler->key_press = cb_key_press; //self->key_handler->key_release = cb_key_release; self->key_handler->user = self; bot_viewer_add_event_handler(viewer, self->key_handler, 1);*/ BotEventHandler *ehandler = &self->ehandler; ehandler->name = (char*) RENDERER_NAME; ehandler->enabled = 1; ehandler->pick_query = pick_query; ehandler->hover_query = NULL; ehandler->mouse_press = mouse_press; ehandler->mouse_release = mouse_release; ehandler->mouse_motion = NULL; ehandler->user = self; bot_viewer_add_event_handler(viewer, &self->ehandler, render_priority); } <commit_msg>minor<commit_after>#include <iostream> #include <boost/function.hpp> #include <lcm/lcm.h> #include <lcm/lcm-cpp.hpp> #include "lcmtypes/drc_lcmtypes.hpp" #include <GL/gl.h> #include <bot_vis/bot_vis.h> #include <bot_core/rotations.h> #include <gdk/gdkkeysyms.h> #include <path_util/path_util.h> #include "RobotStateListener.hpp" #include "renderer_robot_state.hpp" #define RENDERER_NAME "Robot State Display" #define PARAM_SELECTION "Enable Selection" #define PARAM_WIRE "Show BBoxs For Meshes" #define PARAM_COLOR_ALPHA "Alpha" using namespace std; using namespace boost; using namespace Eigen; using namespace visualization_utils; using namespace collision; using namespace renderer_robot_state; typedef struct _RobotStateRendererStruc { BotRenderer renderer; BotViewer *viewer; BotGtkParamWidget *pw; boost::shared_ptr<renderer_robot_state::RobotStateListener> robotStateListener; boost::shared_ptr<lcm::LCM> lcm; //BotEventHandler *key_handler; BotEventHandler ehandler; bool selection_enabled; bool clicked; bool visualize_bbox; Eigen::Vector3f ray_start; Eigen::Vector3f ray_end; std::string* selection; // transparency of the model: float alpha; } RobotStateRendererStruc; static void _renderer_free (BotRenderer *super) { RobotStateRendererStruc *self = (RobotStateRendererStruc*) super->user; free(self); } //========================= Event Handling ================ static double pick_query (BotViewer *viewer, BotEventHandler *ehandler, const double ray_start[3], const double ray_dir[3]) { RobotStateRendererStruc *self = (RobotStateRendererStruc*) ehandler->user; if((self->selection_enabled==0)||(self->robotStateListener->_urdf_subscription_on)){ return -1.0; } //fprintf(stderr, "RobotStateRenderer Pick Query Active\n"); Eigen::Vector3f from,to; from << ray_start[0], ray_start[1], ray_start[2]; Eigen::Vector3f plane_normal,plane_pt; plane_normal << 0,0,1; plane_pt << 0,0,0; double lambda1 = ray_dir[0] * plane_normal[0]+ ray_dir[1] * plane_normal[1] + ray_dir[2] * plane_normal[2]; // check for degenerate case where ray is (more or less) parallel to plane if (fabs (lambda1) < 1e-9) return -1.0; double lambda2 = (plane_pt[0] - ray_start[0]) * plane_normal[0] + (plane_pt[1] - ray_start[1]) * plane_normal[1] + (plane_pt[2] - ray_start[2]) * plane_normal[2]; double t = lambda2 / lambda1;// =1; to << ray_start[0]+t*ray_dir[0], ray_start[1]+t*ray_dir[1], ray_start[2]+t*ray_dir[2]; self->ray_start = from; self->ray_end = to; Eigen::Vector3f hit_pt; collision::Collision_Object * intersected_object = NULL; if(self->robotStateListener->_gl_robot) // to make sure that _gl_robot is initialized { //self->robotStateListener->_gl_robot->_collision_detector->num_collisions(); self->robotStateListener->_gl_robot->_collision_detector->ray_test( from, to, intersected_object,hit_pt); } if( intersected_object != NULL ){ Eigen::Vector3f diff = (from-hit_pt); double distance = diff.norm(); // std::cout << "RobotStateRenderer distance " << distance << std::endl; return distance; } //std::cout << "RobotStateRenderer distance " << -1.0 << std::endl; return -1.0; } static int mouse_press (BotViewer *viewer, BotEventHandler *ehandler, const double ray_start[3], const double ray_dir[3], const GdkEventButton *event) { RobotStateRendererStruc *self = (RobotStateRendererStruc*) ehandler->user; // std::cout << "state ehandler->picking " << ehandler->picking << std::endl; if((ehandler->picking==0)||(self->selection_enabled==0)){ (*self->selection) = " "; // fprintf(stderr, "RobotStateRenderer Ehandler Not active\n"); return 0; } // fprintf(stderr, "RobotStateRenderer Ehandler Activated\n"); self->clicked = 1; //fprintf(stderr, "Mouse Press : %f,%f\n",ray_start[0], ray_start[1]); collision::Collision_Object * intersected_object = NULL; if(self->robotStateListener->_gl_robot) // to make sure that _gl_robot is initialized { //self->robotStateListener->_gl_robot->_collision_detector->num_collisions(); self->robotStateListener->_gl_robot->_collision_detector->ray_test( self->ray_start, self->ray_end, intersected_object ); } if( intersected_object != NULL ){ // std::cout << "prev selection :" << (*self->selection) << std::endl; (*self->selection) = std::string(intersected_object->id().c_str()); std::cout << "intersected :" << intersected_object->id().c_str() << std::endl; bot_viewer_request_redraw(self->viewer); //spawn_plan_execution_dock(self); return 0; } else{ (*self->selection) = " "; bot_viewer_request_redraw(self->viewer); return 0; } } static int mouse_release (BotViewer *viewer, BotEventHandler *ehandler, const double ray_start[3], const double ray_dir[3], const GdkEventButton *event) { RobotStateRendererStruc *self = (RobotStateRendererStruc*) ehandler->user; self->clicked = 0; if((ehandler->picking==0)||(self->selection_enabled==0)){ //if(self->selection_enabled==0){ //fprintf(stderr, "Ehandler Not active\n"); return 0; } if (ehandler->picking==1) ehandler->picking=0; //release picking(IMPORTANT) bot_viewer_request_redraw(self->viewer); return 0; } //================================= static void _renderer_draw (BotViewer *viewer, BotRenderer *super) { //int64_t tic = bot_timestamp_now(); RobotStateRendererStruc *self = (RobotStateRendererStruc*) super->user; glEnable(GL_DEPTH_TEST); //-draw glEnable(GL_LIGHTING); glEnable(GL_COLOR_MATERIAL); glEnable(GL_BLEND); //glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); glEnable (GL_RESCALE_NORMAL); if((self->ehandler.picking)&&(self->selection_enabled)&&(self->clicked)){ glLineWidth (3.0); glPushMatrix(); glBegin(GL_LINES); glVertex3f(self->ray_start[0], self->ray_start[1],self->ray_start[2]); // object coord glVertex3f(self->ray_end[0], self->ray_end[1],self->ray_end[2]); glEnd(); glPopMatrix(); } float c[3] = {0.15,0.15,0.15}; // was 0.3 //glColor3f(c[0],c[1],c[2]); glColor4f(c[0],c[1],c[2],self->alpha); float alpha = self->alpha; if(self->robotStateListener->_gl_robot) { self->robotStateListener->_gl_robot->show_bbox(self->visualize_bbox); self->robotStateListener->_gl_robot->enable_link_selection(self->selection_enabled); self->robotStateListener->_gl_robot->highlight_link((*self->selection)); //self->robotStateListener->_gl_robot->enable_whole_body_selection(self->selection_enabled); self->robotStateListener->_gl_robot->draw_body (c,alpha); } // int64_t toc = bot_timestamp_now(); // cout << bot_timestamp_useconds(toc-tic) << endl; } static void on_param_widget_changed(BotGtkParamWidget *pw, const char *name, void *user) { RobotStateRendererStruc *self = (RobotStateRendererStruc*) user; if (! strcmp(name, PARAM_SELECTION)) { if (bot_gtk_param_widget_get_bool(pw, PARAM_SELECTION)) { //bot_viewer_request_pick (self->viewer, &(self->ehandler)); self->selection_enabled = 1; } else{ self->selection_enabled = 0; } } else if(! strcmp(name, PARAM_WIRE)) { if (bot_gtk_param_widget_get_bool(pw, PARAM_WIRE)){ self->visualize_bbox= true; } else{ self->visualize_bbox = false; } }else if(! strcmp(name, PARAM_COLOR_ALPHA)) { self->alpha = (float) bot_gtk_param_widget_get_double(pw, PARAM_COLOR_ALPHA); bot_viewer_request_redraw(self->viewer); } } void setup_renderer_robot_state(BotViewer *viewer, int render_priority, lcm_t *lcm) { RobotStateRendererStruc *self = (RobotStateRendererStruc*) calloc (1, sizeof (RobotStateRendererStruc)); self->lcm = boost::shared_ptr<lcm::LCM>(new lcm::LCM(lcm)); self->robotStateListener = boost::shared_ptr<RobotStateListener>(new RobotStateListener(self->lcm, viewer)); BotRenderer *renderer = &self->renderer; renderer->draw = _renderer_draw; renderer->destroy = _renderer_free; renderer->widget = bot_gtk_param_widget_new(); renderer->name = (char *) RENDERER_NAME; renderer->user = self; renderer->enabled = 1; self->viewer = viewer; self->pw = BOT_GTK_PARAM_WIDGET(renderer->widget); bot_gtk_param_widget_add_booleans(self->pw, BOT_GTK_PARAM_WIDGET_CHECKBOX, PARAM_SELECTION, 0, NULL); bot_gtk_param_widget_add_booleans(self->pw, BOT_GTK_PARAM_WIDGET_CHECKBOX, PARAM_WIRE, 0, NULL); bot_gtk_param_widget_add_double (self->pw, PARAM_COLOR_ALPHA, BOT_GTK_PARAM_WIDGET_SLIDER, 0, 1, 0.001, 1); g_signal_connect(G_OBJECT(self->pw), "changed", G_CALLBACK(on_param_widget_changed), self); self->alpha = 1.0; self->selection_enabled = 0; bot_gtk_param_widget_set_bool(self->pw, PARAM_SELECTION,self->selection_enabled); self->clicked = 0; self->selection = new std::string(" "); self->visualize_bbox = false; bot_viewer_add_renderer(viewer, &self->renderer, render_priority); //---------- // create and register mode handler /*self->key_handler = (BotEventHandler*) calloc(1, sizeof(BotEventHandler)); self->key_handler->name = strdup(std::string("Mode Control").c_str()); self->key_handler->enabled = 0; self->key_handler->key_press = cb_key_press; //self->key_handler->key_release = cb_key_release; self->key_handler->user = self; bot_viewer_add_event_handler(viewer, self->key_handler, 1);*/ BotEventHandler *ehandler = &self->ehandler; ehandler->name = (char*) RENDERER_NAME; ehandler->enabled = 1; ehandler->pick_query = pick_query; ehandler->hover_query = NULL; ehandler->mouse_press = mouse_press; ehandler->mouse_release = mouse_release; ehandler->mouse_motion = NULL; ehandler->user = self; bot_viewer_add_event_handler(viewer, &self->ehandler, render_priority); } <|endoftext|>
<commit_before>/* libs/graphics/animator/SkDisplayXMLParser.cpp ** ** Copyright 2006, 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. */ #include "SkDisplayXMLParser.h" #include "SkAnimateMaker.h" #include "SkDisplayApply.h" #include "SkUtils.h" #ifdef SK_DEBUG #include "SkTime.h" #endif static char const* const gErrorStrings[] = { "unknown error ", "apply scopes itself", "display tree too deep (circular reference?) ", "element missing parent ", "element type not allowed in parent ", "error adding <data> to <post> ", "error adding to <matrix> ", "error adding to <paint> ", "error adding to <path> ", "error in attribute value ", "error in script ", "expected movie in sink attribute ", "field not in target ", "number of offsets in gradient must match number of colors", "no offset in gradient may be greater than one", "last offset in gradient must be one", "offsets in gradient must be increasing", "first offset in gradient must be zero", "gradient attribute \"points\" must have length of four", "in include ", "in movie ", "include name unknown or missing ", "index out of range ", "movie name unknown or missing ", "no parent available to resolve sink attribute ", "parent element can't contain ", "saveLayer must specify a bounds", "target id not found ", "unexpected type " }; SkDisplayXMLParserError::~SkDisplayXMLParserError() { } void SkDisplayXMLParserError::getErrorString(SkString* str) const { if (fCode > kUnknownError) str->set(gErrorStrings[fCode - kUnknownError]); else str->reset(); INHERITED::getErrorString(str); } void SkDisplayXMLParserError::setInnerError(SkAnimateMaker* parent, const SkString& src) { SkString inner; getErrorString(&inner); inner.prepend(": "); inner.prependS32(getLineNumber()); inner.prepend(", line "); inner.prepend(src); parent->setErrorNoun(inner); } SkDisplayXMLParser::SkDisplayXMLParser(SkAnimateMaker& maker) : INHERITED(&maker.fError), fMaker(maker), fInInclude(maker.fInInclude), fInSkia(maker.fInInclude), fCurrDisplayable(NULL) { } SkDisplayXMLParser::~SkDisplayXMLParser() { if (fCurrDisplayable && fMaker.fChildren.find(fCurrDisplayable) < 0) delete fCurrDisplayable; for (Parent* parPtr = fParents.begin() + 1; parPtr < fParents.end(); parPtr++) { SkDisplayable* displayable = parPtr->fDisplayable; if (displayable == fCurrDisplayable) continue; SkASSERT(fMaker.fChildren.find(displayable) < 0); if (fMaker.fHelpers.find(displayable) < 0) delete displayable; } } bool SkDisplayXMLParser::onAddAttribute(const char name[], const char value[]) { return onAddAttributeLen(name, value, strlen(value)); } bool SkDisplayXMLParser::onAddAttributeLen(const char attrName[], const char attrValue[], size_t attrValueLen) { if (fCurrDisplayable == NULL) // this signals we should ignore attributes for this element return strncmp(attrName, "xmlns", sizeof("xmlns") - 1) != 0; SkDisplayable* displayable = fCurrDisplayable; SkDisplayTypes type = fCurrType; if (strcmp(attrName, "id") == 0) { if (fMaker.find(attrValue, attrValueLen, NULL)) { fError->setNoun(attrValue, attrValueLen); fError->setCode(SkXMLParserError::kDuplicateIDs); return true; } #ifdef SK_DEBUG displayable->_id.set(attrValue, attrValueLen); displayable->id = displayable->_id.c_str(); #endif fMaker.idsSet(attrValue, attrValueLen, displayable); int parentIndex = fParents.count() - 1; if (parentIndex > 0) { SkDisplayable* parent = fParents[parentIndex - 1].fDisplayable; parent->setChildHasID(); } return false; } const char* name = attrName; const SkMemberInfo* info = SkDisplayType::GetMember(&fMaker, type, &name); if (info == NULL) { fError->setNoun(name); fError->setCode(SkXMLParserError::kUnknownAttributeName); return true; } if (info->setValue(fMaker, NULL, 0, info->getCount(), displayable, info->getType(), attrValue, attrValueLen)) return false; if (fMaker.fError.hasError()) { fError->setNoun(attrValue, attrValueLen); return true; } SkDisplayable* ref = NULL; if (fMaker.find(attrValue, attrValueLen, &ref) == false) { ref = fMaker.createInstance(attrValue, attrValueLen); if (ref == NULL) { fError->setNoun(attrValue, attrValueLen); fError->setCode(SkXMLParserError::kErrorInAttributeValue); return true; } else fMaker.helperAdd(ref); } if (info->fType != SkType_MemberProperty) { fError->setNoun(name); fError->setCode(SkXMLParserError::kUnknownAttributeName); return true; } SkScriptValue scriptValue; scriptValue.fOperand.fDisplayable = ref; scriptValue.fType = ref->getType(); displayable->setProperty(info->propertyIndex(), scriptValue); return false; } #if defined(SKIA_BUILD_FOR_WIN32) #define SK_strcasecmp stricmp #define SK_strncasecmp strnicmp #else #define SK_strcasecmp strcasecmp #define SK_strncasecmp strncasecmp #endif bool SkDisplayXMLParser::onEndElement(const char elem[]) { int parentIndex = fParents.count() - 1; if (parentIndex >= 0) { Parent& container = fParents[parentIndex]; SkDisplayable* displayable = container.fDisplayable; fMaker.fEndDepth = parentIndex; displayable->onEndElement(fMaker); if (fMaker.fError.hasError()) return true; if (parentIndex > 0) { SkDisplayable* parent = fParents[parentIndex - 1].fDisplayable; bool result = parent->add(fMaker, displayable); if (fMaker.hasError()) return true; if (result == false) { int infoCount; const SkMemberInfo* info = SkDisplayType::GetMembers(&fMaker, fParents[parentIndex - 1].fType, &infoCount); const SkMemberInfo* foundInfo; if ((foundInfo = searchContainer(info, infoCount)) != NULL) { parent->setReference(foundInfo, displayable); // if (displayable->isHelper() == false) fMaker.helperAdd(displayable); } else { fMaker.setErrorCode(SkDisplayXMLParserError::kElementTypeNotAllowedInParent); return true; } } if (parent->childrenNeedDisposing()) delete displayable; } fParents.remove(parentIndex); } fCurrDisplayable = NULL; if (fInInclude == false && SK_strcasecmp(elem, "screenplay") == 0) { if (fMaker.fInMovie == false) { fMaker.fEnableTime = fMaker.getAppTime(); #if defined SK_DEBUG && defined SK_DEBUG_ANIMATION_TIMING if (fMaker.fDebugTimeBase == (SkMSec) -1) fMaker.fDebugTimeBase = fMaker.fEnableTime; SkString debugOut; SkMSec time = fMaker.getAppTime(); debugOut.appendS32(time - fMaker.fDebugTimeBase); debugOut.append(" onLoad enable="); debugOut.appendS32(fMaker.fEnableTime - fMaker.fDebugTimeBase); SkDebugf("%s\n", debugOut.c_str()); #endif fMaker.fEvents.doEvent(fMaker, SkDisplayEvent::kOnload, NULL); if (fMaker.fError.hasError()) return true; fMaker.fEvents.removeEvent(SkDisplayEvent::kOnload, NULL); } fInSkia = false; } return false; } bool SkDisplayXMLParser::onStartElement(const char name[]) { return onStartElementLen(name, strlen(name)); } bool SkDisplayXMLParser::onStartElementLen(const char name[], size_t len) { fCurrDisplayable = NULL; // init so we'll ignore attributes if we exit early if (SK_strncasecmp(name, "screenplay", len) == 0) { fInSkia = true; if (fInInclude == false) fMaker.idsSet(name, len, &fMaker.fScreenplay); return false; } if (fInSkia == false) return false; SkDisplayable* displayable = fMaker.createInstance(name, len); if (displayable == NULL) { fError->setNoun(name, len); fError->setCode(SkXMLParserError::kUnknownElement); return true; } SkDisplayTypes type = displayable->getType(); Parent record = { displayable, type }; *fParents.append() = record; if (fParents.count() == 1) fMaker.childrenAdd(displayable); else { Parent* parent = fParents.end() - 2; if (displayable->setParent(parent->fDisplayable)) { fError->setNoun(name, len); getError()->setCode(SkDisplayXMLParserError::kParentElementCantContain); return true; } } // set these for subsequent calls to addAttribute() fCurrDisplayable = displayable; fCurrType = type; return false; } const SkMemberInfo* SkDisplayXMLParser::searchContainer(const SkMemberInfo* infoBase, int infoCount) { const SkMemberInfo* bestDisplayable = NULL; const SkMemberInfo* lastResort = NULL; for (int index = 0; index < infoCount; index++) { const SkMemberInfo* info = &infoBase[index]; if (info->fType == SkType_BaseClassInfo) { const SkMemberInfo* inherited = info->getInherited(); const SkMemberInfo* result = searchContainer(inherited, info->fCount); if (result != NULL) return result; continue; } Parent* container = fParents.end() - 1; SkDisplayTypes type = (SkDisplayTypes) info->fType; if (type == SkType_MemberProperty) type = info->propertyType(); SkDisplayTypes containerType = container->fType; if (type == containerType && (type == SkType_Rect || type == SkType_Polygon || type == SkType_Array || type == SkType_Int || type == SkType_Bitmap)) goto rectNext; while (type != containerType) { if (containerType == SkType_Displayable) goto next; containerType = SkDisplayType::GetParent(&fMaker, containerType); if (containerType == SkType_Unknown) goto next; } return info; next: if (type == SkType_Drawable || type == SkType_Displayable && container->fDisplayable->isDrawable()) { rectNext: if (fParents.count() > 1) { Parent* parent = fParents.end() - 2; if (info == parent->fDisplayable->preferredChild(type)) bestDisplayable = info; else lastResort = info; } } } if (bestDisplayable) return bestDisplayable; if (lastResort) return lastResort; return NULL; } <commit_msg>Fix SK build macro.<commit_after>/* libs/graphics/animator/SkDisplayXMLParser.cpp ** ** Copyright 2006, 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. */ #include "SkDisplayXMLParser.h" #include "SkAnimateMaker.h" #include "SkDisplayApply.h" #include "SkUtils.h" #ifdef SK_DEBUG #include "SkTime.h" #endif static char const* const gErrorStrings[] = { "unknown error ", "apply scopes itself", "display tree too deep (circular reference?) ", "element missing parent ", "element type not allowed in parent ", "error adding <data> to <post> ", "error adding to <matrix> ", "error adding to <paint> ", "error adding to <path> ", "error in attribute value ", "error in script ", "expected movie in sink attribute ", "field not in target ", "number of offsets in gradient must match number of colors", "no offset in gradient may be greater than one", "last offset in gradient must be one", "offsets in gradient must be increasing", "first offset in gradient must be zero", "gradient attribute \"points\" must have length of four", "in include ", "in movie ", "include name unknown or missing ", "index out of range ", "movie name unknown or missing ", "no parent available to resolve sink attribute ", "parent element can't contain ", "saveLayer must specify a bounds", "target id not found ", "unexpected type " }; SkDisplayXMLParserError::~SkDisplayXMLParserError() { } void SkDisplayXMLParserError::getErrorString(SkString* str) const { if (fCode > kUnknownError) str->set(gErrorStrings[fCode - kUnknownError]); else str->reset(); INHERITED::getErrorString(str); } void SkDisplayXMLParserError::setInnerError(SkAnimateMaker* parent, const SkString& src) { SkString inner; getErrorString(&inner); inner.prepend(": "); inner.prependS32(getLineNumber()); inner.prepend(", line "); inner.prepend(src); parent->setErrorNoun(inner); } SkDisplayXMLParser::SkDisplayXMLParser(SkAnimateMaker& maker) : INHERITED(&maker.fError), fMaker(maker), fInInclude(maker.fInInclude), fInSkia(maker.fInInclude), fCurrDisplayable(NULL) { } SkDisplayXMLParser::~SkDisplayXMLParser() { if (fCurrDisplayable && fMaker.fChildren.find(fCurrDisplayable) < 0) delete fCurrDisplayable; for (Parent* parPtr = fParents.begin() + 1; parPtr < fParents.end(); parPtr++) { SkDisplayable* displayable = parPtr->fDisplayable; if (displayable == fCurrDisplayable) continue; SkASSERT(fMaker.fChildren.find(displayable) < 0); if (fMaker.fHelpers.find(displayable) < 0) delete displayable; } } bool SkDisplayXMLParser::onAddAttribute(const char name[], const char value[]) { return onAddAttributeLen(name, value, strlen(value)); } bool SkDisplayXMLParser::onAddAttributeLen(const char attrName[], const char attrValue[], size_t attrValueLen) { if (fCurrDisplayable == NULL) // this signals we should ignore attributes for this element return strncmp(attrName, "xmlns", sizeof("xmlns") - 1) != 0; SkDisplayable* displayable = fCurrDisplayable; SkDisplayTypes type = fCurrType; if (strcmp(attrName, "id") == 0) { if (fMaker.find(attrValue, attrValueLen, NULL)) { fError->setNoun(attrValue, attrValueLen); fError->setCode(SkXMLParserError::kDuplicateIDs); return true; } #ifdef SK_DEBUG displayable->_id.set(attrValue, attrValueLen); displayable->id = displayable->_id.c_str(); #endif fMaker.idsSet(attrValue, attrValueLen, displayable); int parentIndex = fParents.count() - 1; if (parentIndex > 0) { SkDisplayable* parent = fParents[parentIndex - 1].fDisplayable; parent->setChildHasID(); } return false; } const char* name = attrName; const SkMemberInfo* info = SkDisplayType::GetMember(&fMaker, type, &name); if (info == NULL) { fError->setNoun(name); fError->setCode(SkXMLParserError::kUnknownAttributeName); return true; } if (info->setValue(fMaker, NULL, 0, info->getCount(), displayable, info->getType(), attrValue, attrValueLen)) return false; if (fMaker.fError.hasError()) { fError->setNoun(attrValue, attrValueLen); return true; } SkDisplayable* ref = NULL; if (fMaker.find(attrValue, attrValueLen, &ref) == false) { ref = fMaker.createInstance(attrValue, attrValueLen); if (ref == NULL) { fError->setNoun(attrValue, attrValueLen); fError->setCode(SkXMLParserError::kErrorInAttributeValue); return true; } else fMaker.helperAdd(ref); } if (info->fType != SkType_MemberProperty) { fError->setNoun(name); fError->setCode(SkXMLParserError::kUnknownAttributeName); return true; } SkScriptValue scriptValue; scriptValue.fOperand.fDisplayable = ref; scriptValue.fType = ref->getType(); displayable->setProperty(info->propertyIndex(), scriptValue); return false; } #if defined(SK_BUILD_FOR_WIN32) #define SK_strcasecmp stricmp #define SK_strncasecmp strnicmp #else #define SK_strcasecmp strcasecmp #define SK_strncasecmp strncasecmp #endif bool SkDisplayXMLParser::onEndElement(const char elem[]) { int parentIndex = fParents.count() - 1; if (parentIndex >= 0) { Parent& container = fParents[parentIndex]; SkDisplayable* displayable = container.fDisplayable; fMaker.fEndDepth = parentIndex; displayable->onEndElement(fMaker); if (fMaker.fError.hasError()) return true; if (parentIndex > 0) { SkDisplayable* parent = fParents[parentIndex - 1].fDisplayable; bool result = parent->add(fMaker, displayable); if (fMaker.hasError()) return true; if (result == false) { int infoCount; const SkMemberInfo* info = SkDisplayType::GetMembers(&fMaker, fParents[parentIndex - 1].fType, &infoCount); const SkMemberInfo* foundInfo; if ((foundInfo = searchContainer(info, infoCount)) != NULL) { parent->setReference(foundInfo, displayable); // if (displayable->isHelper() == false) fMaker.helperAdd(displayable); } else { fMaker.setErrorCode(SkDisplayXMLParserError::kElementTypeNotAllowedInParent); return true; } } if (parent->childrenNeedDisposing()) delete displayable; } fParents.remove(parentIndex); } fCurrDisplayable = NULL; if (fInInclude == false && SK_strcasecmp(elem, "screenplay") == 0) { if (fMaker.fInMovie == false) { fMaker.fEnableTime = fMaker.getAppTime(); #if defined SK_DEBUG && defined SK_DEBUG_ANIMATION_TIMING if (fMaker.fDebugTimeBase == (SkMSec) -1) fMaker.fDebugTimeBase = fMaker.fEnableTime; SkString debugOut; SkMSec time = fMaker.getAppTime(); debugOut.appendS32(time - fMaker.fDebugTimeBase); debugOut.append(" onLoad enable="); debugOut.appendS32(fMaker.fEnableTime - fMaker.fDebugTimeBase); SkDebugf("%s\n", debugOut.c_str()); #endif fMaker.fEvents.doEvent(fMaker, SkDisplayEvent::kOnload, NULL); if (fMaker.fError.hasError()) return true; fMaker.fEvents.removeEvent(SkDisplayEvent::kOnload, NULL); } fInSkia = false; } return false; } bool SkDisplayXMLParser::onStartElement(const char name[]) { return onStartElementLen(name, strlen(name)); } bool SkDisplayXMLParser::onStartElementLen(const char name[], size_t len) { fCurrDisplayable = NULL; // init so we'll ignore attributes if we exit early if (SK_strncasecmp(name, "screenplay", len) == 0) { fInSkia = true; if (fInInclude == false) fMaker.idsSet(name, len, &fMaker.fScreenplay); return false; } if (fInSkia == false) return false; SkDisplayable* displayable = fMaker.createInstance(name, len); if (displayable == NULL) { fError->setNoun(name, len); fError->setCode(SkXMLParserError::kUnknownElement); return true; } SkDisplayTypes type = displayable->getType(); Parent record = { displayable, type }; *fParents.append() = record; if (fParents.count() == 1) fMaker.childrenAdd(displayable); else { Parent* parent = fParents.end() - 2; if (displayable->setParent(parent->fDisplayable)) { fError->setNoun(name, len); getError()->setCode(SkDisplayXMLParserError::kParentElementCantContain); return true; } } // set these for subsequent calls to addAttribute() fCurrDisplayable = displayable; fCurrType = type; return false; } const SkMemberInfo* SkDisplayXMLParser::searchContainer(const SkMemberInfo* infoBase, int infoCount) { const SkMemberInfo* bestDisplayable = NULL; const SkMemberInfo* lastResort = NULL; for (int index = 0; index < infoCount; index++) { const SkMemberInfo* info = &infoBase[index]; if (info->fType == SkType_BaseClassInfo) { const SkMemberInfo* inherited = info->getInherited(); const SkMemberInfo* result = searchContainer(inherited, info->fCount); if (result != NULL) return result; continue; } Parent* container = fParents.end() - 1; SkDisplayTypes type = (SkDisplayTypes) info->fType; if (type == SkType_MemberProperty) type = info->propertyType(); SkDisplayTypes containerType = container->fType; if (type == containerType && (type == SkType_Rect || type == SkType_Polygon || type == SkType_Array || type == SkType_Int || type == SkType_Bitmap)) goto rectNext; while (type != containerType) { if (containerType == SkType_Displayable) goto next; containerType = SkDisplayType::GetParent(&fMaker, containerType); if (containerType == SkType_Unknown) goto next; } return info; next: if (type == SkType_Drawable || type == SkType_Displayable && container->fDisplayable->isDrawable()) { rectNext: if (fParents.count() > 1) { Parent* parent = fParents.end() - 2; if (info == parent->fDisplayable->preferredChild(type)) bestDisplayable = info; else lastResort = info; } } } if (bestDisplayable) return bestDisplayable; if (lastResort) return lastResort; return NULL; } <|endoftext|>
<commit_before>/*++ Copyright (c) 2012 Microsoft Corporation Module Name: qffpa_tactic.cpp Abstract: Tactic for QF_FPA benchmarks. Author: Christoph (cwinter) 2012-01-16 Notes: --*/ #include"tactical.h" #include"simplify_tactic.h" #include"bit_blaster_tactic.h" #include"sat_tactic.h" #include"fpa2bv_tactic.h" #include"qffpa_tactic.h" tactic * mk_qffpa_tactic(ast_manager & m, params_ref const & p) { params_ref sat_simp_p = p; sat_simp_p .set_bool("elim_and", true); return and_then(mk_simplify_tactic(m, p), mk_fpa2bv_tactic(m, p), using_params(mk_simplify_tactic(m, p), sat_simp_p), mk_bit_blaster_tactic(m, p), using_params(mk_simplify_tactic(m, p), sat_simp_p), mk_sat_tactic(m, p), mk_fail_if_undecided_tactic()); } struct is_non_qffpa_predicate { struct found {}; ast_manager & m; float_util u; is_non_qffpa_predicate(ast_manager & _m) : m(_m), u(m) {} void operator()(var *) { throw found(); } void operator()(quantifier *) { throw found(); } void operator()(app * n) { sort * s = get_sort(n); if (!m.is_bool(s) && !u.is_float(s) && !u.is_rm(s)) throw found(); family_id fid = n->get_family_id(); if (fid == m.get_basic_family_id()) return; if (fid == u.get_family_id()) return; throw found(); } }; struct is_non_qffpabv_predicate { struct found {}; ast_manager & m; bv_util bu; float_util fu; is_non_qffpabv_predicate(ast_manager & _m) : m(_m), bu(m), fu(m) {} void operator()(var *) { throw found(); } void operator()(quantifier *) { throw found(); } void operator()(app * n) { sort * s = get_sort(n); if (!m.is_bool(s) && !fu.is_float(s) && !fu.is_rm(s) && !bu.is_bv_sort(s)) throw found(); family_id fid = n->get_family_id(); if (fid == m.get_basic_family_id()) return; if (fid == fu.get_family_id() || fid == bu.get_family_id()) return; throw found(); } }; class is_qffpa_probe : public probe { public: virtual result operator()(goal const & g) { return !test<is_non_qffpa_predicate>(g); } }; class is_qffpabv_probe : public probe { public: virtual result operator()(goal const & g) { return !test<is_non_qffpabv_predicate>(g); } }; probe * mk_is_qffpa_probe() { return alloc(is_qffpa_probe); } probe * mk_is_qffpabv_probe() { return alloc(is_qffpabv_probe); } <commit_msg>FPA probe bugfix<commit_after>/*++ Copyright (c) 2012 Microsoft Corporation Module Name: qffpa_tactic.cpp Abstract: Tactic for QF_FPA benchmarks. Author: Christoph (cwinter) 2012-01-16 Notes: --*/ #include"tactical.h" #include"simplify_tactic.h" #include"bit_blaster_tactic.h" #include"sat_tactic.h" #include"fpa2bv_tactic.h" #include"qffpa_tactic.h" tactic * mk_qffpa_tactic(ast_manager & m, params_ref const & p) { params_ref sat_simp_p = p; sat_simp_p .set_bool("elim_and", true); return and_then(mk_simplify_tactic(m, p), mk_fpa2bv_tactic(m, p), using_params(mk_simplify_tactic(m, p), sat_simp_p), mk_bit_blaster_tactic(m, p), using_params(mk_simplify_tactic(m, p), sat_simp_p), mk_sat_tactic(m, p), mk_fail_if_undecided_tactic()); } struct is_non_qffpa_predicate { struct found {}; ast_manager & m; float_util u; is_non_qffpa_predicate(ast_manager & _m) : m(_m), u(m) {} void operator()(var *) { throw found(); } void operator()(quantifier *) { throw found(); } void operator()(app * n) { sort * s = get_sort(n); if (!m.is_bool(s) && !u.is_float(s) && !u.is_rm(s)) throw found(); family_id fid = n->get_family_id(); if (fid == m.get_basic_family_id()) return; if (fid == u.get_family_id()) return; if (is_uninterp_const(n)) return; throw found(); } }; struct is_non_qffpabv_predicate { struct found {}; ast_manager & m; bv_util bu; float_util fu; is_non_qffpabv_predicate(ast_manager & _m) : m(_m), bu(m), fu(m) {} void operator()(var *) { throw found(); } void operator()(quantifier *) { throw found(); } void operator()(app * n) { sort * s = get_sort(n); if (!m.is_bool(s) && !fu.is_float(s) && !fu.is_rm(s) && !bu.is_bv_sort(s)) throw found(); family_id fid = n->get_family_id(); if (fid == m.get_basic_family_id()) return; if (fid == fu.get_family_id() || fid == bu.get_family_id()) return; if (is_uninterp_const(n)) return; throw found(); } }; class is_qffpa_probe : public probe { public: virtual result operator()(goal const & g) { return !test<is_non_qffpa_predicate>(g); } }; class is_qffpabv_probe : public probe { public: virtual result operator()(goal const & g) { return !test<is_non_qffpabv_predicate>(g); } }; probe * mk_is_qffpa_probe() { return alloc(is_qffpa_probe); } probe * mk_is_qffpabv_probe() { return alloc(is_qffpabv_probe); } <|endoftext|>
<commit_before>#include "atom.h" #include "variable.h" #include "number.h" #include <string> #include <iostream> using namespace std; bool Variable::match( Atom atom ){ if(_assignable){ _value = atom._symbol ; _assignable = false; this->Aptr = &atom; cout<<"the value of Aptr first match tom: "<<Aptr<<endl; cout<<"the value of atom first match tom: "<<&atom<<endl; return true; } else{ cout<<"the value of Aptr second match tom: "<<Aptr<<endl; cout<<"the value of atom second match tom: "<<&atom<<endl; if(Aptr == &atom) return true; else return false; } } bool Variable::match( Number N ){ if(_assignable){ _value = N.value() ; _assignable = false; this->Nptr = &N; return true; } else{ if(Nptr == &N) return true; else return false; } } <commit_msg>Delete mainVariable.cpp<commit_after><|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "robot_utils/ros_thread_image.h" class ROSImageObject: public ROSThreadImage { public: ROSImageObject(std::string namenew): ROSThreadImage(namenew) {} void InternalThreadEntry(); }; void ROSImageObject::InternalThreadEntry() { std::cout << "test" << std::endl; }; TEST(rosimagetest, testsetname) { ROSImageObject rt("test"); rt.joinInternalThread(); // rt.setName("newtestname"); EXPECT_EQ("newtestname", rt.getName()); EXPECT_FALSE("test" == rt.getName()); } // Run all the tests that were declared with TEST() int main(int argc, char **argv) { ros::init(argc, argv, "ros_thread_test"); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Made contructor explicit to fix codacy issue<commit_after>#include <gtest/gtest.h> #include "robot_utils/ros_thread_image.h" class ROSImageObject: public ROSThreadImage { public: explicit ROSImageObject(std::string namenew): ROSThreadImage(namenew) {} void InternalThreadEntry(); }; void ROSImageObject::InternalThreadEntry() { std::cout << "test" << std::endl; }; TEST(rosimagetest, testsetname) { ROSImageObject rt("test"); rt.joinInternalThread(); // rt.setName("newtestname"); EXPECT_EQ("newtestname", rt.getName()); EXPECT_FALSE("test" == rt.getName()); } // Run all the tests that were declared with TEST() int main(int argc, char **argv) { ros::init(argc, argv, "ros_thread_test"); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include "pacman_vision/estimator.h" #include "pacman_vision/utility.h" /////////////////// //Estimator Class// /////////////////// //Constructor Estimator::Estimator(ros::NodeHandle &n) { this->scene.reset(new PEC); this->nh = ros::NodeHandle (n, "estimator"); this->queue_ptr.reset(new ros::CallbackQueue); this->nh.setCallbackQueue(&(*this->queue_ptr)); this->db_path = (ros::package::getPath("pacman_vision") + "/database" ); if (!boost::filesystem::exists(db_path) || !boost::filesystem::is_directory(db_path)) ROS_WARN("[Estimator][%s] Database for pose estimation does not exists!! Plese put one in /database folder, before trying to perform a pose estimation.",__func__); this->srv_estimate = nh.advertiseService("estimate", &Estimator::cb_estimate, this); //init params calibration = false; iterations = 10; neighbors = 10; clus_tol = 0.05; downsampling = 1; no_segment=false; busy = false; pe.setParam("verbosity",2); pe.setParam("progItera",iterations); pe.setParam("icpReciprocal",1); pe.setParam("kNeighbors",neighbors); pe.setParam("downsampling",downsampling); pe.setDatabase(db_path); } Estimator::~Estimator() { this->nh.shutdown(); } int Estimator::extract_clusters() { if (scene->empty()) return -1; ROS_INFO("[Estimator][%s] Extracting object clusters with cluster tolerance of %g",__func__,clus_tol); //objects pcl::SACSegmentation<PET> seg; pcl::ExtractIndices<PET> extract; pcl::EuclideanClusterExtraction<PET> ec; pcl::search::KdTree<PET>::Ptr tree (new pcl::search::KdTree<PET>); PEC::Ptr table_top (new PEC); //coefficients pcl::PointIndices::Ptr inliers (new pcl::PointIndices); pcl::ModelCoefficients::Ptr coefficients (new pcl::ModelCoefficients); std::vector<pcl::PointIndices> cluster_indices; //plane segmentation //disable interruption during clustering, will be restored when di is destroyed boost::this_thread::disable_interruption di; if (!no_segment) { seg.setInputCloud(scene); seg.setOptimizeCoefficients (true); seg.setModelType (pcl::SACMODEL_PLANE); seg.setMethodType (pcl::SAC_RANSAC); seg.setMaxIterations (100); seg.setDistanceThreshold (0.02); seg.segment(*inliers, *coefficients); //extract what's on top of plane extract.setInputCloud(scene); extract.setIndices(inliers); extract.setNegative(true); extract.filter(*table_top); } else { pcl::copyPointCloud(*scene,*table_top); } //cluster extraction tree->setInputCloud(table_top); ec.setInputCloud(table_top); ec.setSearchMethod(tree); ec.setClusterTolerance(clus_tol); ec.setMinClusterSize(100); ec.setMaxClusterSize(table_top->points.size()); ec.extract(cluster_indices); int size = (int)cluster_indices.size(); clusters.clear(); clusters.resize(size); names.clear(); names.resize(size); ids.clear(); ids.resize(size); estimations.clear(); estimations.resize(size); int j=0; for (std::vector<pcl::PointIndices>::const_iterator it = cluster_indices.begin(); it != cluster_indices.end(); ++it, ++j) { PEC::Ptr object (new PEC); extract.setInputCloud(table_top); extract.setIndices(boost::make_shared<PointIndices>(*it)); extract.setNegative(false); /* for (std::vector<int>::const_iterator pit = it->indices.begin(); pit != it->indices.end(); ++pit) { object->points.push_back(table_top->points[*pit]); } object->width = object->points.size(); object->height = 1; object->is_dense = true; pcl::copyPointCloud(*object, clusters[j]); */ extract.filter(clusters[j]); } ROS_INFO("[Estimator][%s] Found %d clusters of possible objects.",__func__,size); return size; } bool Estimator::cb_estimate(pacman_vision_comm::estimate::Request& req, pacman_vision_comm::estimate::Response& res) { this->estimate(); geometry_msgs::Pose pose; tf::Transform trans; for (int i=0; i<estimations.size(); ++i) { fromEigen(estimations[i], pose, trans); pacman_vision_comm::pe pose_est; pose_est.pose = pose; pose_est.name = names[i]; pose_est.id = ids[i]; pose_est.parent_frame = "/camera_rgb_optical_frame"; res.estimated.poses.push_back(pose_est); } this->busy = false; this->up_broadcaster = true; this->up_tracker = true; ROS_INFO("[Estimator][%s] Pose Estimation complete!", __func__); return true; } void Estimator::estimate() { this->busy = true; //tell other modules that estimator is computing new estimations int size = this->extract_clusters(); if (size < 1) { ROS_ERROR("[Estimator][%s] No object clusters found in scene, aborting pose estimation...",__func__); this->busy = false; return; } pe.setParam("downsampling",this->downsampling); pe.setDatabase(db_path); for (int i=0; i<size; ++i) { pcl::PointCloud<pcl::PointXYZRGBA> query; pcl::copyPointCloud(clusters[i], query); pe.setQuery("object", query); pe.generateLists(); pe.refineCandidates(); boost::shared_ptr<Candidate> pest (new Candidate); pe.getEstimation(pest); std::string name; pest->getName(name); std::vector<std::string> vst; boost::split (vst, name, boost::is_any_of("_"), boost::token_compress_on); if (this->calibration) names[i] = "object"; else names[i] = vst.at(0); pe.getEstimationTransformation(estimations[i]); ids[i] = vst.at(0); ROS_INFO("[Estimator][%s] Found %s.",__func__,name.c_str()); } //first check if we have more copy of the same object in names for (int i=0; i<names.size(); ++i) { int count(1); string name_original = names[i]; if (i>0) { for (int j=0; j<i; ++j) { if (names[i].compare(names[j]) == 0) { //i-th name is equal to j-th name names[i] = name_original + "_" + std::to_string(++count); } } } } } void Estimator::spin_once() { //process this module callbacks this->queue_ptr->callAvailable(ros::WallDuration(0)); } <commit_msg>fixed merge<commit_after>#include "pacman_vision/estimator.h" #include "pacman_vision/utility.h" /////////////////// //Estimator Class// /////////////////// //Constructor Estimator::Estimator(ros::NodeHandle &n) { this->scene.reset(new PEC); this->nh = ros::NodeHandle (n, "estimator"); this->queue_ptr.reset(new ros::CallbackQueue); this->nh.setCallbackQueue(&(*this->queue_ptr)); this->db_path = (ros::package::getPath("pacman_vision") + "/database" ); if (!boost::filesystem::exists(db_path) || !boost::filesystem::is_directory(db_path)) ROS_WARN("[Estimator][%s] Database for pose estimation does not exists!! Plese put one in /database folder, before trying to perform a pose estimation.",__func__); this->srv_estimate = nh.advertiseService("estimate", &Estimator::cb_estimate, this); //init params calibration = false; iterations = 10; neighbors = 10; clus_tol = 0.05; downsampling = 1; no_segment=false; busy = false; pe.setParam("verbosity",2); pe.setParam("progItera",iterations); pe.setParam("icpReciprocal",1); pe.setParam("kNeighbors",neighbors); pe.setParam("downsampling",downsampling); pe.setDatabase(db_path); } Estimator::~Estimator() { this->nh.shutdown(); } int Estimator::extract_clusters() { if (scene->empty()) return -1; ROS_INFO("[Estimator][%s] Extracting object clusters with cluster tolerance of %g",__func__,clus_tol); //objects pcl::SACSegmentation<PET> seg; pcl::ExtractIndices<PET> extract; pcl::EuclideanClusterExtraction<PET> ec; pcl::search::KdTree<PET>::Ptr tree (new pcl::search::KdTree<PET>); PEC::Ptr table_top (new PEC); //coefficients pcl::PointIndices::Ptr inliers (new pcl::PointIndices); pcl::ModelCoefficients::Ptr coefficients (new pcl::ModelCoefficients); std::vector<pcl::PointIndices> cluster_indices; //plane segmentation //disable interruption during clustering, will be restored when di is destroyed boost::this_thread::disable_interruption di; if (!no_segment) { seg.setInputCloud(scene); seg.setOptimizeCoefficients (true); seg.setModelType (pcl::SACMODEL_PLANE); seg.setMethodType (pcl::SAC_RANSAC); seg.setMaxIterations (100); seg.setDistanceThreshold (0.02); seg.segment(*inliers, *coefficients); //extract what's on top of plane extract.setInputCloud(scene); extract.setIndices(inliers); extract.setNegative(true); extract.filter(*table_top); } else { pcl::copyPointCloud(*scene,*table_top); } //cluster extraction tree->setInputCloud(table_top); ec.setInputCloud(table_top); ec.setSearchMethod(tree); ec.setClusterTolerance(clus_tol); ec.setMinClusterSize(100); ec.setMaxClusterSize(table_top->points.size()); ec.extract(cluster_indices); int size = (int)cluster_indices.size(); clusters.clear(); clusters.resize(size); names.clear(); names.resize(size); ids.clear(); ids.resize(size); estimations.clear(); estimations.resize(size); int j=0; for (std::vector<pcl::PointIndices>::const_iterator it = cluster_indices.begin(); it != cluster_indices.end(); ++it, ++j) { PEC::Ptr object (new PEC); extract.setInputCloud(table_top); extract.setIndices(boost::make_shared<PointIndices>(*it)); extract.setNegative(false); /* for (std::vector<int>::const_iterator pit = it->indices.begin(); pit != it->indices.end(); ++pit) { object->points.push_back(table_top->points[*pit]); } object->width = object->points.size(); object->height = 1; object->is_dense = true; pcl::copyPointCloud(*object, clusters[j]); */ extract.filter(clusters[j]); } ROS_INFO("[Estimator][%s] Found %d clusters of possible objects.",__func__,size); return size; } bool Estimator::cb_estimate(pacman_vision_comm::estimate::Request& req, pacman_vision_comm::estimate::Response& res) { this->estimate(); geometry_msgs::Pose pose; tf::Transform trans; for (int i=0; i<estimations.size(); ++i) { fromEigen(estimations[i], pose, trans); pacman_vision_comm::pe pose_est; pose_est.pose = pose; pose_est.name = names[i]; pose_est.id = ids[i]; <<<<<<< HEAD pose_est.parent_frame = "/camera_rgb_optical_frame"; ======= pose_est.parent_frame = "/camera/rgb_optical_frame"; >>>>>>> 83d9edcd6dd0bec3412cbf8b3f5fb28c651dc15e res.estimated.poses.push_back(pose_est); } this->busy = false; this->up_broadcaster = true; this->up_tracker = true; ROS_INFO("[Estimator][%s] Pose Estimation complete!", __func__); return true; } void Estimator::estimate() { this->busy = true; //tell other modules that estimator is computing new estimations int size = this->extract_clusters(); if (size < 1) { ROS_ERROR("[Estimator][%s] No object clusters found in scene, aborting pose estimation...",__func__); this->busy = false; return; } pe.setParam("downsampling",this->downsampling); pe.setDatabase(db_path); for (int i=0; i<size; ++i) { pcl::PointCloud<pcl::PointXYZRGBA> query; pcl::copyPointCloud(clusters[i], query); pe.setQuery("object", query); pe.generateLists(); pe.refineCandidates(); boost::shared_ptr<Candidate> pest (new Candidate); pe.getEstimation(pest); std::string name; pest->getName(name); std::vector<std::string> vst; boost::split (vst, name, boost::is_any_of("_"), boost::token_compress_on); if (this->calibration) names[i] = "object"; else names[i] = vst.at(0); pe.getEstimationTransformation(estimations[i]); ids[i] = vst.at(0); ROS_INFO("[Estimator][%s] Found %s.",__func__,name.c_str()); } //first check if we have more copy of the same object in names for (int i=0; i<names.size(); ++i) { int count(1); string name_original = names[i]; if (i>0) { for (int j=0; j<i; ++j) { if (names[i].compare(names[j]) == 0) { //i-th name is equal to j-th name names[i] = name_original + "_" + std::to_string(++count); } } } } } void Estimator::spin_once() { //process this module callbacks this->queue_ptr->callAvailable(ros::WallDuration(0)); } <|endoftext|>
<commit_before>/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright (C) 2017, James R. Barlow (https://github.com/jbarlow83/) */ /* * Convert Python types <-> QPDFObjectHandle types */ #include <vector> #include <map> #include <qpdf/Constants.h> #include <qpdf/Types.h> #include <qpdf/DLL.h> #include <qpdf/QPDFExc.hh> #include <qpdf/QPDFObjGen.hh> #include <qpdf/PointerHolder.hh> #include <qpdf/Buffer.hh> #include <qpdf/QPDFObjectHandle.hh> #include <qpdf/QPDF.hh> #include <qpdf/QPDFWriter.hh> #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include "pikepdf.h" extern uint DECIMAL_PRECISION; std::map<std::string, QPDFObjectHandle> dict_builder(const py::dict dict) { StackGuard sg(" dict_builder"); std::map<std::string, QPDFObjectHandle> result; for (const auto& item: dict) { std::string key = item.first.cast<std::string>(); auto value = objecthandle_encode(item.second); result[key] = value; } return result; } std::vector<QPDFObjectHandle> array_builder(const py::iterable iter) { StackGuard sg(" array_builder"); std::vector<QPDFObjectHandle> result; int narg = 0; for (const auto& item: iter) { narg++; auto value = objecthandle_encode(item); result.push_back(value); } return result; } class DecimalPrecision { public: DecimalPrecision(uint calc_precision) : decimal_context(py::module::import("decimal").attr("getcontext")()), saved_precision(decimal_context.attr("prec").cast<uint>()) { decimal_context.attr("prec") = calc_precision; } ~DecimalPrecision() { decimal_context.attr("prec") = saved_precision; } DecimalPrecision(const DecimalPrecision& other) = delete; DecimalPrecision(DecimalPrecision&& other) = delete; DecimalPrecision& operator= (const DecimalPrecision& other) = delete; DecimalPrecision& operator= (DecimalPrecision&& other) = delete; private: py::object decimal_context; uint saved_precision; }; QPDFObjectHandle objecthandle_encode(const py::handle handle) { if (handle.is_none()) return QPDFObjectHandle::newNull(); // Ensure that when we return QPDFObjectHandle/pikepdf.Object to the Py // environment, that we can recover it try { auto as_qobj = handle.cast<QPDFObjectHandle>(); return as_qobj; } catch (const py::cast_error&) {} // Special-case booleans since pybind11 coerces nonzero integers to boolean if (py::isinstance<py::bool_>(handle)) { bool as_bool = handle.cast<bool>(); return QPDFObjectHandle::newBool(as_bool); } auto Decimal = py::module::import("decimal").attr("Decimal"); if (py::isinstance(handle, Decimal)) { DecimalPrecision dp(DECIMAL_PRECISION); auto rounded = py::reinterpret_steal<py::object>(PyNumber_Positive(handle.ptr())); return QPDFObjectHandle::newReal(py::str(rounded)); } else if (py::isinstance<py::int_>(handle)) { auto as_int = handle.cast<long long>(); return QPDFObjectHandle::newInteger(as_int); } else if (py::isinstance<py::float_>(handle)) { auto as_double = handle.cast<double>(); return QPDFObjectHandle::newReal(as_double); } py::object obj = py::reinterpret_borrow<py::object>(handle); if (py::isinstance<py::bytes>(obj)) { py::bytes py_bytes = obj; return QPDFObjectHandle::newString(static_cast<std::string>(py_bytes)); } else if (py::isinstance<py::str>(obj)) { py::str py_str = obj; return QPDFObjectHandle::newUnicodeString(static_cast<std::string>(py_str)); } if (py::hasattr(obj, "__iter__")) { //py::print(py::repr(obj)); bool is_mapping = false; // PyMapping_Check is unreliable in Py3 if (py::hasattr(obj, "keys")) is_mapping = true; bool is_sequence = PySequence_Check(obj.ptr()); if (is_mapping) { return QPDFObjectHandle::newDictionary(dict_builder(obj)); } else if (is_sequence) { return QPDFObjectHandle::newArray(array_builder(obj)); } } throw py::cast_error(std::string("don't know how to encode value ") + std::string(py::repr(obj))); } py::object decimal_from_pdfobject(QPDFObjectHandle h) { auto decimal_constructor = py::module::import("decimal").attr("Decimal"); if (h.getTypeCode() == QPDFObject::object_type_e::ot_integer) { auto value = h.getIntValue(); return decimal_constructor(py::cast(value)); } else if (h.getTypeCode() == QPDFObject::object_type_e::ot_real) { auto value = h.getRealValue(); return decimal_constructor(py::cast(value)); } else if (h.getTypeCode() == QPDFObject::object_type_e::ot_boolean) { auto value = h.getBoolValue(); return decimal_constructor(py::cast(value)); } throw py::type_error("object has no Decimal() representation"); } <commit_msg>Prevent conversion of NaN and infinity to PDF Real<commit_after>/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright (C) 2017, James R. Barlow (https://github.com/jbarlow83/) */ /* * Convert Python types <-> QPDFObjectHandle types */ #include <vector> #include <map> #include <cmath> #include <qpdf/Constants.h> #include <qpdf/Types.h> #include <qpdf/DLL.h> #include <qpdf/QPDFExc.hh> #include <qpdf/QPDFObjGen.hh> #include <qpdf/PointerHolder.hh> #include <qpdf/Buffer.hh> #include <qpdf/QPDFObjectHandle.hh> #include <qpdf/QPDF.hh> #include <qpdf/QPDFWriter.hh> #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include "pikepdf.h" extern uint DECIMAL_PRECISION; std::map<std::string, QPDFObjectHandle> dict_builder(const py::dict dict) { StackGuard sg(" dict_builder"); std::map<std::string, QPDFObjectHandle> result; for (const auto& item: dict) { std::string key = item.first.cast<std::string>(); auto value = objecthandle_encode(item.second); result[key] = value; } return result; } std::vector<QPDFObjectHandle> array_builder(const py::iterable iter) { StackGuard sg(" array_builder"); std::vector<QPDFObjectHandle> result; int narg = 0; for (const auto& item: iter) { narg++; auto value = objecthandle_encode(item); result.push_back(value); } return result; } class DecimalPrecision { public: DecimalPrecision(uint calc_precision) : decimal_context(py::module::import("decimal").attr("getcontext")()), saved_precision(decimal_context.attr("prec").cast<uint>()) { decimal_context.attr("prec") = calc_precision; } ~DecimalPrecision() { decimal_context.attr("prec") = saved_precision; } DecimalPrecision(const DecimalPrecision& other) = delete; DecimalPrecision(DecimalPrecision&& other) = delete; DecimalPrecision& operator= (const DecimalPrecision& other) = delete; DecimalPrecision& operator= (DecimalPrecision&& other) = delete; private: py::object decimal_context; uint saved_precision; }; QPDFObjectHandle objecthandle_encode(const py::handle handle) { if (handle.is_none()) return QPDFObjectHandle::newNull(); // Ensure that when we return QPDFObjectHandle/pikepdf.Object to the Py // environment, that we can recover it try { auto as_qobj = handle.cast<QPDFObjectHandle>(); return as_qobj; } catch (const py::cast_error&) {} // Special-case booleans since pybind11 coerces nonzero integers to boolean if (py::isinstance<py::bool_>(handle)) { bool as_bool = handle.cast<bool>(); return QPDFObjectHandle::newBool(as_bool); } auto decimal_module = py::module::import("decimal"); auto Decimal = decimal_module.attr("Decimal"); if (py::isinstance(handle, Decimal)) { DecimalPrecision dp(DECIMAL_PRECISION); auto rounded = py::reinterpret_steal<py::object>(PyNumber_Positive(handle.ptr())); if (! rounded.attr("is_finite")().cast<bool>()) throw py::value_error("Can't convert NaN or Infinity to PDF real number"); return QPDFObjectHandle::newReal(py::str(rounded)); } else if (py::isinstance<py::int_>(handle)) { auto as_int = handle.cast<long long>(); return QPDFObjectHandle::newInteger(as_int); } else if (py::isinstance<py::float_>(handle)) { auto as_double = handle.cast<double>(); if (! isfinite(as_double)) throw py::value_error("Can't convert NaN or Infinity to PDF real number"); return QPDFObjectHandle::newReal(as_double); } py::object obj = py::reinterpret_borrow<py::object>(handle); if (py::isinstance<py::bytes>(obj)) { py::bytes py_bytes = obj; return QPDFObjectHandle::newString(static_cast<std::string>(py_bytes)); } else if (py::isinstance<py::str>(obj)) { py::str py_str = obj; return QPDFObjectHandle::newUnicodeString(static_cast<std::string>(py_str)); } if (py::hasattr(obj, "__iter__")) { //py::print(py::repr(obj)); bool is_mapping = false; // PyMapping_Check is unreliable in Py3 if (py::hasattr(obj, "keys")) is_mapping = true; bool is_sequence = PySequence_Check(obj.ptr()); if (is_mapping) { return QPDFObjectHandle::newDictionary(dict_builder(obj)); } else if (is_sequence) { return QPDFObjectHandle::newArray(array_builder(obj)); } } throw py::cast_error(std::string("don't know how to encode value ") + std::string(py::repr(obj))); } py::object decimal_from_pdfobject(QPDFObjectHandle h) { auto decimal_constructor = py::module::import("decimal").attr("Decimal"); if (h.getTypeCode() == QPDFObject::object_type_e::ot_integer) { auto value = h.getIntValue(); return decimal_constructor(py::cast(value)); } else if (h.getTypeCode() == QPDFObject::object_type_e::ot_real) { auto value = h.getRealValue(); return decimal_constructor(py::cast(value)); } else if (h.getTypeCode() == QPDFObject::object_type_e::ot_boolean) { auto value = h.getBoolValue(); return decimal_constructor(py::cast(value)); } throw py::type_error("object has no Decimal() representation"); } <|endoftext|>
<commit_before>#include "resources.h" #ifdef _MSC_VER #define WIN32_LEAN_AND_MEAN #include <windows.h> #else #include <dirent.h> #endif #include <cstdio> #include <filesystem> #include <SDL.h> #ifdef ANDROID #include <SDL.h> #include <jni.h> #include <android/asset_manager.h> #include <android/asset_manager_jni.h> #endif PVector<ResourceProvider> resourceProviders; ResourceProvider::ResourceProvider() { resourceProviders.push_back(this); } bool ResourceProvider::searchMatch(const string name, const string searchPattern) { std::vector<string> parts = searchPattern.split("*"); int pos = 0; if (parts[0].length() > 0) { if (name.find(parts[0]) != 0) return false; } for(unsigned int n=1; n<parts.size(); n++) { int offset = name.find(parts[n], pos); if (offset < 0) return false; pos = offset + static_cast<int>(parts[n].length()); } return pos == static_cast<int>(name.length()); } string ResourceStream::readLine() { string ret; char c; while(true) { if (read(&c, 1) < 1) return ret; if (c == '\n') return ret; ret += string(c); } } string ResourceStream::readAll() { string result; result.resize(getSize()); read(result.data(), result.size()); return result; } class FileResourceStream : public ResourceStream { SDL_RWops *io; size_t size = 0; bool open_success; public: FileResourceStream(string filename) { #ifndef ANDROID std::error_code ec; if(!std::filesystem::is_regular_file(filename.c_str(), ec)) { //Error code "no such file or directory" thrown really often, so no trace here //not to spam the log io = nullptr; } else io = SDL_RWFromFile(filename.c_str(), "rb"); #else //Android reads from the assets bundle, so we cannot check if the file exists and is a regular file io = SDL_RWFromFile(filename.c_str(), "rb"); #endif } virtual ~FileResourceStream() { if (io) io->close(io); } bool isOpen() { return io != nullptr; } virtual size_t read(void* data, size_t size) override { return io->read(io, data, 1, size); } virtual size_t seek(size_t position) override { auto offset = io->seek(io, position, RW_SEEK_SET); SDL_assert(offset != -1); return static_cast<size_t>(offset); } virtual size_t tell() override { auto offset = io->seek(io, 0, RW_SEEK_CUR); SDL_assert(offset != -1); return static_cast<size_t>(offset); } virtual size_t getSize() override { if (size == 0) { size_t cur = tell(); auto end_offset = io->seek(io, 0, RW_SEEK_END); SDL_assert(end_offset != -1); size = static_cast<size_t>(end_offset); seek(cur); } return size; } }; DirectoryResourceProvider::DirectoryResourceProvider(string basepath) { this->basepath = basepath.rstrip("\\/"); } P<ResourceStream> DirectoryResourceProvider::getResourceStream(string filename) { P<FileResourceStream> stream = new FileResourceStream(basepath + "/" + filename); if (stream->isOpen()) return stream; return nullptr; } std::vector<string> DirectoryResourceProvider::findResources(string searchPattern) { std::vector<string> found_files; #if defined(ANDROID) //Limitation : //As far as I know, Android NDK won't provide a way to list subdirectories //So we will only list files in the first level directory static jobject asset_manager_jobject; static AAssetManager* asset_manager = nullptr; if (!asset_manager) { JNIEnv* env = (JNIEnv*)SDL_AndroidGetJNIEnv(); jobject activity = (jobject)SDL_AndroidGetActivity(); jclass clazz(env->GetObjectClass(activity)); jmethodID method_id = env->GetMethodID(clazz, "getAssets", "()Landroid/content/res/AssetManager;"); asset_manager_jobject = env->CallObjectMethod(activity, method_id); asset_manager = AAssetManager_fromJava(env, asset_manager_jobject); env->DeleteLocalRef(activity); env->DeleteLocalRef(clazz); } if(asset_manager) { int idx = searchPattern.rfind("/"); string forced_path = basepath; string prefix = ""; if (idx > -1) { prefix = searchPattern.substr(0, idx); forced_path += "/" + prefix; prefix += "/"; } AAssetDir* dir = AAssetManager_openDir(asset_manager, (forced_path).c_str()); if (dir) { const char* filename; while ((filename = AAssetDir_getNextFileName(dir)) != nullptr) { if (searchMatch(prefix + filename, searchPattern)) found_files.push_back(prefix + filename); } AAssetDir_close(dir); } } #else findResources(found_files, "", searchPattern); #endif return found_files; } void DirectoryResourceProvider::findResources(std::vector<string>& found_files, const string path, const string searchPattern) { #ifdef _MSC_VER WIN32_FIND_DATAA data; string search_root(basepath + "/" + path); if (!search_root.endswith("/")) { search_root += "/"; } HANDLE handle = FindFirstFileA((search_root + "*").c_str(), &data); if (handle == INVALID_HANDLE_VALUE) return; do { if (data.cFileName[0] == '.') continue; string name = path + string(data.cFileName); if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { findResources(found_files, name + "/", searchPattern); } else { if (searchMatch(name, searchPattern)) found_files.push_back(name); } } while (FindNextFileA(handle, &data)); FindClose(handle); #else DIR* dir = opendir((basepath + "/" + path).c_str()); if (!dir) return; struct dirent *entry; while ((entry = readdir(dir)) != nullptr) { if (entry->d_name[0] == '.') continue; string name = path + string(entry->d_name); if (searchMatch(name, searchPattern)) found_files.push_back(name); findResources(found_files, path + string(entry->d_name) + "/", searchPattern); } closedir(dir); #endif } P<ResourceStream> getResourceStream(string filename) { foreach(ResourceProvider, rp, resourceProviders) { P<ResourceStream> stream = rp->getResourceStream(filename); if (stream) return stream; } return NULL; } std::vector<string> findResources(string searchPattern) { std::vector<string> foundFiles; foreach(ResourceProvider, rp, resourceProviders) { std::vector<string> res = rp->findResources(searchPattern); foundFiles.insert(foundFiles.end(), res.begin(), res.end()); } return foundFiles; } <commit_msg>Sdl2 findresources using std::fs (#183)<commit_after>#include "resources.h" #include <cstdio> #include <filesystem> #include <SDL.h> #ifdef ANDROID #include <jni.h> #include <android/asset_manager.h> #include <android/asset_manager_jni.h> #endif PVector<ResourceProvider> resourceProviders; ResourceProvider::ResourceProvider() { resourceProviders.push_back(this); } bool ResourceProvider::searchMatch(const string name, const string searchPattern) { std::vector<string> parts = searchPattern.split("*"); int pos = 0; if (parts[0].length() > 0) { if (name.find(parts[0]) != 0) return false; } for(unsigned int n=1; n<parts.size(); n++) { int offset = name.find(parts[n], pos); if (offset < 0) return false; pos = offset + static_cast<int>(parts[n].length()); } return pos == static_cast<int>(name.length()); } string ResourceStream::readLine() { string ret; char c; while(true) { if (read(&c, 1) < 1) return ret; if (c == '\n') return ret; ret += string(c); } } string ResourceStream::readAll() { string result; result.resize(getSize()); read(result.data(), result.size()); return result; } class FileResourceStream : public ResourceStream { SDL_RWops *io; size_t size = 0; bool open_success; public: FileResourceStream(string filename) { #ifndef ANDROID std::error_code ec; if(!std::filesystem::is_regular_file(filename.c_str(), ec)) { //Error code "no such file or directory" thrown really often, so no trace here //not to spam the log io = nullptr; } else io = SDL_RWFromFile(filename.c_str(), "rb"); #else //Android reads from the assets bundle, so we cannot check if the file exists and is a regular file io = SDL_RWFromFile(filename.c_str(), "rb"); #endif } virtual ~FileResourceStream() { if (io) io->close(io); } bool isOpen() { return io != nullptr; } virtual size_t read(void* data, size_t size) override { return io->read(io, data, 1, size); } virtual size_t seek(size_t position) override { auto offset = io->seek(io, position, RW_SEEK_SET); SDL_assert(offset != -1); return static_cast<size_t>(offset); } virtual size_t tell() override { auto offset = io->seek(io, 0, RW_SEEK_CUR); SDL_assert(offset != -1); return static_cast<size_t>(offset); } virtual size_t getSize() override { if (size == 0) { size_t cur = tell(); auto end_offset = io->seek(io, 0, RW_SEEK_END); SDL_assert(end_offset != -1); size = static_cast<size_t>(end_offset); seek(cur); } return size; } }; DirectoryResourceProvider::DirectoryResourceProvider(string basepath) { this->basepath = basepath.rstrip("\\/"); } P<ResourceStream> DirectoryResourceProvider::getResourceStream(string filename) { P<FileResourceStream> stream = new FileResourceStream(basepath + "/" + filename); if (stream->isOpen()) return stream; return nullptr; } std::vector<string> DirectoryResourceProvider::findResources(string searchPattern) { std::vector<string> found_files; #if defined(ANDROID) //Limitation : //As far as I know, Android NDK won't provide a way to list subdirectories //So we will only list files in the first level directory static jobject asset_manager_jobject; static AAssetManager* asset_manager = nullptr; if (!asset_manager) { JNIEnv* env = (JNIEnv*)SDL_AndroidGetJNIEnv(); jobject activity = (jobject)SDL_AndroidGetActivity(); jclass clazz(env->GetObjectClass(activity)); jmethodID method_id = env->GetMethodID(clazz, "getAssets", "()Landroid/content/res/AssetManager;"); asset_manager_jobject = env->CallObjectMethod(activity, method_id); asset_manager = AAssetManager_fromJava(env, asset_manager_jobject); env->DeleteLocalRef(activity); env->DeleteLocalRef(clazz); } if(asset_manager) { int idx = searchPattern.rfind("/"); string forced_path = basepath; string prefix = ""; if (idx > -1) { prefix = searchPattern.substr(0, idx); forced_path += "/" + prefix; prefix += "/"; } AAssetDir* dir = AAssetManager_openDir(asset_manager, (forced_path).c_str()); if (dir) { const char* filename; while ((filename = AAssetDir_getNextFileName(dir)) != nullptr) { if (searchMatch(prefix + filename, searchPattern)) found_files.push_back(prefix + filename); } AAssetDir_close(dir); } } #else findResources(found_files, "", searchPattern); #endif return found_files; } void DirectoryResourceProvider::findResources(std::vector<string>& found_files, const string directory, const string searchPattern) { #if !defined(ANDROID) namespace fs = std::filesystem; fs::path root{ basepath.c_str() }; root /= directory.c_str(); if (fs::is_directory(root)) { constexpr auto traversal_options{ fs::directory_options::follow_directory_symlink | fs::directory_options::skip_permission_denied }; std::error_code error_code{}; for (const auto& entry : fs::recursive_directory_iterator(root, traversal_options, error_code)) { if (!error_code) { auto relative_path = fs::relative(entry.path(), root).u8string(); if (!entry.is_directory() && searchMatch(relative_path, searchPattern)) found_files.push_back(relative_path); } } } #endif } P<ResourceStream> getResourceStream(string filename) { foreach(ResourceProvider, rp, resourceProviders) { P<ResourceStream> stream = rp->getResourceStream(filename); if (stream) return stream; } return NULL; } std::vector<string> findResources(string searchPattern) { std::vector<string> foundFiles; foreach(ResourceProvider, rp, resourceProviders) { std::vector<string> res = rp->findResources(searchPattern); foundFiles.insert(foundFiles.end(), res.begin(), res.end()); } return foundFiles; } <|endoftext|>
<commit_before>#if defined(HAVE_CONFIG_H) #include "config/bitcoin-config.h" #endif #include "smartrewardslist.h" #include "ui_smartrewardslist.h" #include "addresstablemodel.h" #include "bitcoinunits.h" #include "guiutil.h" #include "optionsmodel.h" #include "platformstyle.h" #include "txmempool.h" #include "walletmodel.h" #include "coincontrol.h" #include "init.h" #include "main.h" // For minRelayTxFee #include "wallet/wallet.h" #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <QIcon> #include <QMenu> #include <QMessageBox> #include <QSortFilterProxyModel> #include <QTableWidget> SmartrewardsList::SmartrewardsList(const PlatformStyle *platformStyle, QWidget *parent) : QWidget(parent), ui(new Ui::SmartrewardsList), model(0) { ui->setupUi(this); int columnAliasWidth = 200; int columnAddressWidth = 250; int columnAmountWidth = 160; int columnSmartAmountWidth = 200; ui->tableWidget->setColumnWidth(0, columnAliasWidth); ui->tableWidget->setColumnWidth(1, columnAddressWidth); ui->tableWidget->setColumnWidth(2, columnAmountWidth); ui->tableWidget->setColumnWidth(3, columnSmartAmountWidth); } SmartrewardsList::~SmartrewardsList() { delete ui; } void SmartrewardsList::setModel(WalletModel *model) { this->model = model; if(!model) { return; } ui->tableWidget->setAlternatingRowColors(true); int nDisplayUnit = model->getOptionsModel()->getDisplayUnit(); std::map<QString, std::vector<COutput> > mapCoins; model->listCoins(mapCoins); //ui->tableWidget->setRowCount(10); ui->tableWidget->setColumnCount(4); ui->tableWidget->setShowGrid(false); int nNewRow = 0; BOOST_FOREACH(const PAIRTYPE(QString, std::vector<COutput>)& coins, mapCoins) { QString sWalletAddress = coins.first; QString sWalletLabel = model->getAddressTableModel()->labelForAddress(sWalletAddress); if (sWalletLabel.isEmpty()) sWalletLabel = tr("(no label)"); ui->tableWidget->insertRow(nNewRow); CAmount nSum = 0; double dPrioritySum = 0; int nChildren = 0; int nInputSum = 0; BOOST_FOREACH(const COutput& out, coins.second) { int nInputSize = 0; nSum += out.tx->vout[out.i].nValue; nChildren++; // address CTxDestination outputAddress; QString sAddress = ""; if(ExtractDestination(out.tx->vout[out.i].scriptPubKey, outputAddress)) { sAddress = QString::fromStdString(CBitcoinAddress(outputAddress).ToString()); } ui->tableWidget->setItem(nNewRow, 0, new QTableWidgetItem(sWalletLabel)); ui->tableWidget->setItem(nNewRow, 1, new QTableWidgetItem(sWalletAddress)); ui->tableWidget->setItem(nNewRow, 2, new QTableWidgetItem(BitcoinUnits::format(nDisplayUnit, out.tx->vout[out.i].nValue))); } nNewRow++; } } <commit_msg>Fix InstantPay Build (#22)<commit_after>#if defined(HAVE_CONFIG_H) #include "config/bitcoin-config.h" #endif #include "smartrewardslist.h" #include "ui_smartrewardslist.h" #include "addresstablemodel.h" #include "bitcoinunits.h" #include "guiutil.h" #include "optionsmodel.h" #include "platformstyle.h" #include "txmempool.h" #include "walletmodel.h" #include "coincontrol.h" #include "init.h" #include "main.h" // For minRelayTxFee #include "wallet/wallet.h" #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <QIcon> #include <QMenu> #include <QMessageBox> #include <QSortFilterProxyModel> #include <QTableWidget> SmartrewardsList::SmartrewardsList(const PlatformStyle *platformStyle, QWidget *parent) : QWidget(parent), ui(new Ui::SmartrewardsList), model(0) { ui->setupUi(this); int columnAliasWidth = 200; int columnAddressWidth = 250; int columnAmountWidth = 160; int columnSmartAmountWidth = 200; ui->tableWidget->setColumnWidth(0, columnAliasWidth); ui->tableWidget->setColumnWidth(1, columnAddressWidth); ui->tableWidget->setColumnWidth(2, columnAmountWidth); ui->tableWidget->setColumnWidth(3, columnSmartAmountWidth); } SmartrewardsList::~SmartrewardsList() { delete ui; } void SmartrewardsList::setModel(WalletModel *model) { this->model = model; if(!model) { return; } ui->tableWidget->setAlternatingRowColors(true); int nDisplayUnit = model->getOptionsModel()->getDisplayUnit(); std::map<QString, std::vector<COutput> > mapCoins; model->listCoins(mapCoins); //ui->tableWidget->setRowCount(10); ui->tableWidget->setColumnCount(4); ui->tableWidget->setShowGrid(false); int nNewRow = 0; BOOST_FOREACH(const PAIRTYPE(QString, std::vector<COutput>)& coins, mapCoins) { QString sWalletAddress = coins.first; QString sWalletLabel = model->getAddressTableModel()->labelForAddress(sWalletAddress); if (sWalletLabel.isEmpty()) sWalletLabel = tr("(no label)"); ui->tableWidget->insertRow(nNewRow); CAmount nSum = 0; //double dPrioritySum = 0; int nChildren = 0; //int nInputSum = 0; BOOST_FOREACH(const COutput& out, coins.second) { //int nInputSize = 0; nSum += out.tx->vout[out.i].nValue; nChildren++; // address CTxDestination outputAddress; QString sAddress = ""; if(ExtractDestination(out.tx->vout[out.i].scriptPubKey, outputAddress)) { sAddress = QString::fromStdString(CBitcoinAddress(outputAddress).ToString()); } ui->tableWidget->setItem(nNewRow, 0, new QTableWidgetItem(sWalletLabel)); ui->tableWidget->setItem(nNewRow, 1, new QTableWidgetItem(sWalletAddress)); ui->tableWidget->setItem(nNewRow, 2, new QTableWidgetItem(BitcoinUnits::format(nDisplayUnit, out.tx->vout[out.i].nValue))); } nNewRow++; } } <|endoftext|>
<commit_before>/*============================================================================= Library: CTK Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics 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 "ctkPluginFrameworkContext_p.h" #include "ctkPluginFrameworkUtil_p.h" #include "ctkPluginFrameworkPrivate_p.h" #include "ctkPluginArchive_p.h" #include "ctkPluginConstants.h" #include "ctkServices_p.h" #include "ctkUtils.h" //---------------------------------------------------------------------------- QMutex ctkPluginFrameworkContext::globalFwLock; int ctkPluginFrameworkContext::globalId = 1; //---------------------------------------------------------------------------- ctkPluginFrameworkContext::ctkPluginFrameworkContext( const ctkProperties& initProps) : plugins(0), listeners(this), services(0), systemPlugin(new ctkPluginFramework()), storage(0), firstInit(true), props(initProps), debug(props), initialized(false) { { QMutexLocker lock(&globalFwLock); id = globalId++; systemPlugin->ctkPlugin::init(new ctkPluginFrameworkPrivate(systemPlugin, this)); } initProperties(); log() << "created"; } //---------------------------------------------------------------------------- ctkPluginFrameworkContext::~ctkPluginFrameworkContext() { if (initialized) { this->uninit(); } } //---------------------------------------------------------------------------- void ctkPluginFrameworkContext::initProperties() { props[ctkPluginConstants::FRAMEWORK_VERSION] = "0.9"; props[ctkPluginConstants::FRAMEWORK_VENDOR] = "CommonTK"; } //---------------------------------------------------------------------------- void ctkPluginFrameworkContext::init() { log() << "initializing"; if (firstInit && ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT == props[ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN]) { deleteFWDir(); firstInit = false; } ctkPluginFrameworkPrivate* const systemPluginPrivate = systemPlugin->d_func(); systemPluginPrivate->initSystemPlugin(); storage = new ctkPluginStorage(this); dataStorage = ctkPluginFrameworkUtil::getFileStorage(this, "data"); services = new ctkServices(this); plugins = new ctkPlugins(this); plugins->load(); log() << "inited"; initialized = true; log() << "Installed plugins:"; // Use the ordering in the plugin storage to get a sorted list of plugins. QList<ctkPluginArchive*> allPAs = storage->getAllPluginArchives(); for (int i = 0; i < allPAs.size(); ++i) { ctkPluginArchive* pa = allPAs[i]; QSharedPointer<ctkPlugin> plugin = plugins->getPlugin(pa->getPluginLocation().toString()); log() << " #" << plugin->getPluginId() << " " << plugin->getSymbolicName() << ":" << plugin->getVersion() << " location:" << plugin->getLocation(); } } //---------------------------------------------------------------------------- void ctkPluginFrameworkContext::uninit() { if (!initialized) return; log() << "uninit"; ctkPluginFrameworkPrivate* const systemPluginPrivate = systemPlugin->d_func(); systemPluginPrivate->uninitSystemPlugin(); plugins->clear(); delete plugins; plugins = 0; delete storage; // calls storage->close() storage = 0; delete services; services = 0; initialized = false; } //---------------------------------------------------------------------------- int ctkPluginFrameworkContext::getId() const { return id; } //---------------------------------------------------------------------------- QFileInfo ctkPluginFrameworkContext::getDataStorage(long id) { return QFileInfo(dataStorage.absolutePath() + '/' + QString::number(id) + '/'); } //---------------------------------------------------------------------------- void ctkPluginFrameworkContext::checkOurPlugin(ctkPlugin* plugin) const { ctkPluginPrivate* pp = plugin->d_func(); if (this != pp->fwCtx) { throw std::invalid_argument("ctkPlugin does not belong to this framework: " + plugin->getSymbolicName().toStdString()); } } //---------------------------------------------------------------------------- QDebug ctkPluginFrameworkContext::log() const { static QString nirvana; nirvana.clear(); if (debug.framework) return qDebug() << "Framework instance " << getId() << ": "; else return QDebug(&nirvana); } //---------------------------------------------------------------------------- void ctkPluginFrameworkContext::resolvePlugin(ctkPluginPrivate* plugin) { if (debug.resolve) { qDebug() << "resolve:" << plugin->symbolicName << "[" << plugin->id << "]"; } // If we enter with tempResolved set, it means that we already have // resolved plugins. Check that it is true! if (tempResolved.size() > 0 && !tempResolved.contains(plugin)) { ctkPluginException pe("resolve: InternalError1!", ctkPluginException::RESOLVE_ERROR); listeners.frameworkError(plugin->q_func(), pe); throw pe; } tempResolved.clear(); tempResolved.insert(plugin); checkRequirePlugin(plugin); tempResolved.clear(); if (debug.resolve) { qDebug() << "resolve: Done for" << plugin->symbolicName << "[" << plugin->id << "]"; } } //---------------------------------------------------------------------------- void ctkPluginFrameworkContext::checkRequirePlugin(ctkPluginPrivate *plugin) { if (!plugin->require.isEmpty()) { if (debug.resolve) { qDebug() << "checkRequirePlugin: check requiring plugin" << plugin->id; } QListIterator<ctkRequirePlugin*> i(plugin->require); while (i.hasNext()) { ctkRequirePlugin* pr = i.next(); QList<ctkPlugin*> pl = plugins->getPlugins(pr->name, pr->pluginRange); ctkPluginPrivate* ok = 0; for (QListIterator<ctkPlugin*> pci(pl); pci.hasNext() && ok == 0; ) { ctkPluginPrivate* p2 = pci.next()->d_func(); if (tempResolved.contains(p2)) { ok = p2; } else if (ctkPluginPrivate::RESOLVED_FLAGS & p2->state) { ok = p2; } else if (p2->state == ctkPlugin::INSTALLED) { QSet<ctkPluginPrivate*> oldTempResolved = tempResolved; tempResolved.insert(p2); checkRequirePlugin(p2); tempResolved = oldTempResolved; ok = p2; } } if (!ok && pr->resolution == ctkPluginConstants::RESOLUTION_MANDATORY) { tempResolved.clear(); if (debug.resolve) { qDebug() << "checkRequirePlugin: failed to satisfy:" << pr->name; } throw ctkPluginException(QString("Failed to resolve required plugin: %1").arg(pr->name)); } } } } //---------------------------------------------------------------------------- void ctkPluginFrameworkContext::deleteFWDir() { QString d = ctkPluginFrameworkUtil::getFrameworkDir(this); QFileInfo fwDirInfo(d); if (fwDirInfo.exists()) { if(fwDirInfo.isDir()) { log() << "deleting old framework directory."; bool bOK = ctk::removeDirRecursively(fwDirInfo.absoluteFilePath()); if(!bOK) { qDebug() << "Failed to remove existing fwdir" << fwDirInfo.absoluteFilePath(); } } } } <commit_msg>During resolving a plug-in, set the state of resolved dependencies.<commit_after>/*============================================================================= Library: CTK Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics 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 "ctkPluginFrameworkContext_p.h" #include "ctkPluginFrameworkUtil_p.h" #include "ctkPluginFrameworkPrivate_p.h" #include "ctkPluginArchive_p.h" #include "ctkPluginConstants.h" #include "ctkServices_p.h" #include "ctkUtils.h" //---------------------------------------------------------------------------- QMutex ctkPluginFrameworkContext::globalFwLock; int ctkPluginFrameworkContext::globalId = 1; //---------------------------------------------------------------------------- ctkPluginFrameworkContext::ctkPluginFrameworkContext( const ctkProperties& initProps) : plugins(0), listeners(this), services(0), systemPlugin(new ctkPluginFramework()), storage(0), firstInit(true), props(initProps), debug(props), initialized(false) { { QMutexLocker lock(&globalFwLock); id = globalId++; systemPlugin->ctkPlugin::init(new ctkPluginFrameworkPrivate(systemPlugin, this)); } initProperties(); log() << "created"; } //---------------------------------------------------------------------------- ctkPluginFrameworkContext::~ctkPluginFrameworkContext() { if (initialized) { this->uninit(); } } //---------------------------------------------------------------------------- void ctkPluginFrameworkContext::initProperties() { props[ctkPluginConstants::FRAMEWORK_VERSION] = "0.9"; props[ctkPluginConstants::FRAMEWORK_VENDOR] = "CommonTK"; } //---------------------------------------------------------------------------- void ctkPluginFrameworkContext::init() { log() << "initializing"; if (firstInit && ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT == props[ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN]) { deleteFWDir(); firstInit = false; } ctkPluginFrameworkPrivate* const systemPluginPrivate = systemPlugin->d_func(); systemPluginPrivate->initSystemPlugin(); storage = new ctkPluginStorage(this); dataStorage = ctkPluginFrameworkUtil::getFileStorage(this, "data"); services = new ctkServices(this); plugins = new ctkPlugins(this); plugins->load(); log() << "inited"; initialized = true; log() << "Installed plugins:"; // Use the ordering in the plugin storage to get a sorted list of plugins. QList<ctkPluginArchive*> allPAs = storage->getAllPluginArchives(); for (int i = 0; i < allPAs.size(); ++i) { ctkPluginArchive* pa = allPAs[i]; QSharedPointer<ctkPlugin> plugin = plugins->getPlugin(pa->getPluginLocation().toString()); log() << " #" << plugin->getPluginId() << " " << plugin->getSymbolicName() << ":" << plugin->getVersion() << " location:" << plugin->getLocation(); } } //---------------------------------------------------------------------------- void ctkPluginFrameworkContext::uninit() { if (!initialized) return; log() << "uninit"; ctkPluginFrameworkPrivate* const systemPluginPrivate = systemPlugin->d_func(); systemPluginPrivate->uninitSystemPlugin(); plugins->clear(); delete plugins; plugins = 0; delete storage; // calls storage->close() storage = 0; delete services; services = 0; initialized = false; } //---------------------------------------------------------------------------- int ctkPluginFrameworkContext::getId() const { return id; } //---------------------------------------------------------------------------- QFileInfo ctkPluginFrameworkContext::getDataStorage(long id) { return QFileInfo(dataStorage.absolutePath() + '/' + QString::number(id) + '/'); } //---------------------------------------------------------------------------- void ctkPluginFrameworkContext::checkOurPlugin(ctkPlugin* plugin) const { ctkPluginPrivate* pp = plugin->d_func(); if (this != pp->fwCtx) { throw std::invalid_argument("ctkPlugin does not belong to this framework: " + plugin->getSymbolicName().toStdString()); } } //---------------------------------------------------------------------------- QDebug ctkPluginFrameworkContext::log() const { static QString nirvana; nirvana.clear(); if (debug.framework) return qDebug() << "Framework instance " << getId() << ": "; else return QDebug(&nirvana); } //---------------------------------------------------------------------------- void ctkPluginFrameworkContext::resolvePlugin(ctkPluginPrivate* plugin) { if (debug.resolve) { qDebug() << "resolve:" << plugin->symbolicName << "[" << plugin->id << "]"; } // If we enter with tempResolved set, it means that we already have // resolved plugins. Check that it is true! if (tempResolved.size() > 0 && !tempResolved.contains(plugin)) { ctkPluginException pe("resolve: InternalError1!", ctkPluginException::RESOLVE_ERROR); listeners.frameworkError(plugin->q_func(), pe); throw pe; } tempResolved.clear(); tempResolved.insert(plugin); checkRequirePlugin(plugin); tempResolved.clear(); if (debug.resolve) { qDebug() << "resolve: Done for" << plugin->symbolicName << "[" << plugin->id << "]"; } } //---------------------------------------------------------------------------- void ctkPluginFrameworkContext::checkRequirePlugin(ctkPluginPrivate *plugin) { if (!plugin->require.isEmpty()) { if (debug.resolve) { qDebug() << "checkRequirePlugin: check requiring plugin" << plugin->id; } QListIterator<ctkRequirePlugin*> i(plugin->require); while (i.hasNext()) { ctkRequirePlugin* pr = i.next(); QList<ctkPlugin*> pl = plugins->getPlugins(pr->name, pr->pluginRange); ctkPluginPrivate* ok = 0; for (QListIterator<ctkPlugin*> pci(pl); pci.hasNext() && ok == 0; ) { ctkPluginPrivate* p2 = pci.next()->d_func(); if (tempResolved.contains(p2)) { ok = p2; } else if (ctkPluginPrivate::RESOLVED_FLAGS & p2->state) { ok = p2; } else if (p2->state == ctkPlugin::INSTALLED) { QSet<ctkPluginPrivate*> oldTempResolved = tempResolved; tempResolved.insert(p2); // TODO check if operation locking is correct in case of // multi-threaded plug-in start up. Maybe refactor out the dependency // checking (use the "package" lock) ctkPluginPrivate::Locker sync(&p2->operationLock); p2->operation.fetchAndStoreOrdered(ctkPluginPrivate::RESOLVING); checkRequirePlugin(p2); tempResolved = oldTempResolved; p2->state = ctkPlugin::RESOLVED; listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::RESOLVED, p2->q_func())); p2->operation.fetchAndStoreOrdered(ctkPluginPrivate::IDLE); ok = p2; } } if (!ok && pr->resolution == ctkPluginConstants::RESOLUTION_MANDATORY) { tempResolved.clear(); if (debug.resolve) { qDebug() << "checkRequirePlugin: failed to satisfy:" << pr->name; } throw ctkPluginException(QString("Failed to resolve required plugin: %1").arg(pr->name)); } } } } //---------------------------------------------------------------------------- void ctkPluginFrameworkContext::deleteFWDir() { QString d = ctkPluginFrameworkUtil::getFrameworkDir(this); QFileInfo fwDirInfo(d); if (fwDirInfo.exists()) { if(fwDirInfo.isDir()) { log() << "deleting old framework directory."; bool bOK = ctk::removeDirRecursively(fwDirInfo.absoluteFilePath()); if(!bOK) { qDebug() << "Failed to remove existing fwdir" << fwDirInfo.absoluteFilePath(); } } } } <|endoftext|>
<commit_before>#include "crt.h" #include "map.h" #include "node.h" #include "scanner.h" #include "token.h" #include "exceptions.h" #include <iostream> namespace YAML { Map::Map() { } Map::~Map() { Clear(); } void Map::Clear() { for(node_map::const_iterator it=m_data.begin();it!=m_data.end();++it) { delete it->first; delete it->second; } m_data.clear(); } bool Map::GetBegin(std::map <Node *, Node *, ltnode>::const_iterator& it) const { it = m_data.begin(); return true; } bool Map::GetEnd(std::map <Node *, Node *, ltnode>::const_iterator& it) const { it = m_data.end(); return true; } void Map::Parse(Scanner *pScanner, const ParserState& state) { Clear(); // split based on start token switch(pScanner->peek().type) { case TT_BLOCK_MAP_START: ParseBlock(pScanner, state); break; case TT_FLOW_MAP_START: ParseFlow(pScanner, state); break; } } void Map::ParseBlock(Scanner *pScanner, const ParserState& state) { // eat start token pScanner->pop(); while(1) { if(pScanner->empty()) throw ParserException(-1, -1, ErrorMsg::END_OF_MAP); Token token = pScanner->peek(); if(token.type != TT_KEY && token.type != TT_BLOCK_END) throw ParserException(token.line, token.column, ErrorMsg::END_OF_MAP); pScanner->pop(); if(token.type == TT_BLOCK_END) break; Node *pKey = new Node; Node *pValue = new Node; try { // grab key pKey->Parse(pScanner, state); // now grab value (optional) if(!pScanner->empty() && pScanner->peek().type == TT_VALUE) { pScanner->pop(); pValue->Parse(pScanner, state); } m_data[pKey] = pValue; } catch(Exception&) { delete pKey; delete pValue; throw; } } } void Map::ParseFlow(Scanner *pScanner, const ParserState& state) { // eat start token pScanner->pop(); while(1) { if(pScanner->empty()) throw ParserException(-1, -1, ErrorMsg::END_OF_MAP_FLOW); Token& token = pScanner->peek(); // first check for end if(token.type == TT_FLOW_MAP_END) { pScanner->pop(); break; } // now it better be a key if(token.type != TT_KEY) throw ParserException(token.line, token.column, ErrorMsg::END_OF_MAP_FLOW); pScanner->pop(); Node *pKey = new Node; Node *pValue = new Node; try { // grab key pKey->Parse(pScanner, state); // now grab value (optional) if(!pScanner->empty() && pScanner->peek().type == TT_VALUE) { pScanner->pop(); pValue->Parse(pScanner, state); } // now eat the separator (or could be a map end, which we ignore - but if it's neither, then it's a bad node) Token& nextToken = pScanner->peek(); if(nextToken.type == TT_FLOW_ENTRY) pScanner->pop(); else if(nextToken.type != TT_FLOW_MAP_END) throw ParserException(nextToken.line, nextToken.column, ErrorMsg::END_OF_MAP_FLOW); m_data[pKey] = pValue; } catch(Exception&) { // clean up and rethrow delete pKey; delete pValue; throw; } } } void Map::Write(std::ostream& out, int indent, bool startedLine, bool onlyOneCharOnLine) { if(startedLine && !onlyOneCharOnLine) out << "\n"; for(node_map::const_iterator it=m_data.begin();it!=m_data.end();++it) { if((startedLine && !onlyOneCharOnLine) || it != m_data.begin()) { for(int i=0;i<indent;i++) out << " "; } out << "? "; it->first->Write(out, indent + 1, true, it!= m_data.begin() || !startedLine || onlyOneCharOnLine); for(int i=0;i<indent;i++) out << " "; out << ": "; it->second->Write(out, indent + 1, true, true); } if(m_data.empty()) out << "\n"; } int Map::Compare(Content *pContent) { return -pContent->Compare(this); } int Map::Compare(Map *pMap) { node_map::const_iterator it = m_data.begin(), jt = pMap->m_data.begin(); while(1) { if(it == m_data.end()) { if(jt == pMap->m_data.end()) return 0; else return -1; } if(jt == pMap->m_data.end()) return 1; int cmp = it->first->Compare(*jt->first); if(cmp != 0) return cmp; cmp = it->second->Compare(*jt->second); if(cmp != 0) return cmp; } return 0; } } <commit_msg>Replaced a pointer-centered try/catch block with std::auto_ptr<commit_after>#include "crt.h" #include "map.h" #include "node.h" #include "scanner.h" #include "token.h" #include "exceptions.h" #include <iostream> #include <memory> namespace YAML { Map::Map() { } Map::~Map() { Clear(); } void Map::Clear() { for(node_map::const_iterator it=m_data.begin();it!=m_data.end();++it) { delete it->first; delete it->second; } m_data.clear(); } bool Map::GetBegin(std::map <Node *, Node *, ltnode>::const_iterator& it) const { it = m_data.begin(); return true; } bool Map::GetEnd(std::map <Node *, Node *, ltnode>::const_iterator& it) const { it = m_data.end(); return true; } void Map::Parse(Scanner *pScanner, const ParserState& state) { Clear(); // split based on start token switch(pScanner->peek().type) { case TT_BLOCK_MAP_START: ParseBlock(pScanner, state); break; case TT_FLOW_MAP_START: ParseFlow(pScanner, state); break; } } void Map::ParseBlock(Scanner *pScanner, const ParserState& state) { // eat start token pScanner->pop(); while(1) { if(pScanner->empty()) throw ParserException(-1, -1, ErrorMsg::END_OF_MAP); Token token = pScanner->peek(); if(token.type != TT_KEY && token.type != TT_BLOCK_END) throw ParserException(token.line, token.column, ErrorMsg::END_OF_MAP); pScanner->pop(); if(token.type == TT_BLOCK_END) break; std::auto_ptr <Node> pKey(new Node), pValue(new Node); // grab key pKey->Parse(pScanner, state); // now grab value (optional) if(!pScanner->empty() && pScanner->peek().type == TT_VALUE) { pScanner->pop(); pValue->Parse(pScanner, state); } // assign the map with the actual pointers m_data[pKey.release()] = pValue.release(); } } void Map::ParseFlow(Scanner *pScanner, const ParserState& state) { // eat start token pScanner->pop(); while(1) { if(pScanner->empty()) throw ParserException(-1, -1, ErrorMsg::END_OF_MAP_FLOW); Token& token = pScanner->peek(); // first check for end if(token.type == TT_FLOW_MAP_END) { pScanner->pop(); break; } // now it better be a key if(token.type != TT_KEY) throw ParserException(token.line, token.column, ErrorMsg::END_OF_MAP_FLOW); pScanner->pop(); std::auto_ptr <Node> pKey(new Node), pValue(new Node); // grab key pKey->Parse(pScanner, state); // now grab value (optional) if(!pScanner->empty() && pScanner->peek().type == TT_VALUE) { pScanner->pop(); pValue->Parse(pScanner, state); } // now eat the separator (or could be a map end, which we ignore - but if it's neither, then it's a bad node) Token& nextToken = pScanner->peek(); if(nextToken.type == TT_FLOW_ENTRY) pScanner->pop(); else if(nextToken.type != TT_FLOW_MAP_END) throw ParserException(nextToken.line, nextToken.column, ErrorMsg::END_OF_MAP_FLOW); // assign the map with the actual pointers m_data[pKey.release()] = pValue.release(); } } void Map::Write(std::ostream& out, int indent, bool startedLine, bool onlyOneCharOnLine) { if(startedLine && !onlyOneCharOnLine) out << "\n"; for(node_map::const_iterator it=m_data.begin();it!=m_data.end();++it) { if((startedLine && !onlyOneCharOnLine) || it != m_data.begin()) { for(int i=0;i<indent;i++) out << " "; } out << "? "; it->first->Write(out, indent + 1, true, it!= m_data.begin() || !startedLine || onlyOneCharOnLine); for(int i=0;i<indent;i++) out << " "; out << ": "; it->second->Write(out, indent + 1, true, true); } if(m_data.empty()) out << "\n"; } int Map::Compare(Content *pContent) { return -pContent->Compare(this); } int Map::Compare(Map *pMap) { node_map::const_iterator it = m_data.begin(), jt = pMap->m_data.begin(); while(1) { if(it == m_data.end()) { if(jt == pMap->m_data.end()) return 0; else return -1; } if(jt == pMap->m_data.end()) return 1; int cmp = it->first->Compare(*jt->first); if(cmp != 0) return cmp; cmp = it->second->Compare(*jt->second); if(cmp != 0) return cmp; } return 0; } } <|endoftext|>
<commit_before>#include <spsc_queue.h> #include "gtest/gtest.h" #include <atomic> #include <memory> #include <thread> using namespace std; using namespace mndy; TEST(SpscQueueTest, SimpleOneThread) { spsc_queue<int> q; spsc_reader<int> r(q); spsc_writer<int> w(q); for (int i = 0; i < 8; i++) { w.push(unique_ptr<int>(new int(i))); unique_ptr<int> ptr; bool valid = r.pop(ptr); ASSERT_TRUE(valid); if (valid) { ASSERT_EQ(*ptr, i); } } w.close(); unique_ptr<int> ptr; ASSERT_FALSE(r.pop(ptr)); ASSERT_EQ(ptr, nullptr); } TEST(SpscQueueTest, SimpleTwoThread) { spsc_queue<int> q; const int num_msgs = 8; atomic<int> msgs_rcvd(0); thread producer([&q, &num_msgs]() { spsc_writer<int> w(q); for (int i = 0; i < num_msgs; i++) { w.push(unique_ptr<int>(new int(i))); } }); thread consumer([&q, &msgs_rcvd]() { spsc_reader<int> r(q); while(true) { unique_ptr<int> ptr; bool valid = r.pop(ptr); if (valid) { ASSERT_EQ(msgs_rcvd++, *ptr); } else { return; } } }); producer.join(); consumer.join(); ASSERT_EQ(msgs_rcvd.load(), num_msgs); } TEST(SpscQueueTest, TwoReaderError) { bool exception_thrown = false; try { spsc_queue<int> q; spsc_reader<int> r1(q); spsc_reader<int> r2(q); } catch (spsc_reader_exists e) { exception_thrown = true; } ASSERT_TRUE(exception_thrown); } TEST(SpscQueueTest, TwoWriterError) { bool exception_thrown = false; try { spsc_queue<int> q; spsc_writer<int> w1(q); spsc_writer<int> w2(q); } catch (spsc_writer_exists e) { exception_thrown = true; } ASSERT_TRUE(exception_thrown); } <commit_msg>Make exceptions const refs.<commit_after>#include <spsc_queue.h> #include "gtest/gtest.h" #include <atomic> #include <memory> #include <thread> using namespace std; using namespace mndy; TEST(SpscQueueTest, SimpleOneThread) { spsc_queue<int> q; spsc_reader<int> r(q); spsc_writer<int> w(q); for (int i = 0; i < 8; i++) { w.push(unique_ptr<int>(new int(i))); unique_ptr<int> ptr; bool valid = r.pop(ptr); ASSERT_TRUE(valid); if (valid) { ASSERT_EQ(*ptr, i); } } w.close(); unique_ptr<int> ptr; ASSERT_FALSE(r.pop(ptr)); ASSERT_EQ(ptr, nullptr); } TEST(SpscQueueTest, SimpleTwoThread) { spsc_queue<int> q; const int num_msgs = 8; atomic<int> msgs_rcvd(0); thread producer([&q, &num_msgs]() { spsc_writer<int> w(q); for (int i = 0; i < num_msgs; i++) { w.push(unique_ptr<int>(new int(i))); } }); thread consumer([&q, &msgs_rcvd]() { spsc_reader<int> r(q); while(true) { unique_ptr<int> ptr; bool valid = r.pop(ptr); if (valid) { ASSERT_EQ(msgs_rcvd++, *ptr); } else { return; } } }); producer.join(); consumer.join(); ASSERT_EQ(msgs_rcvd.load(), num_msgs); } TEST(SpscQueueTest, TwoReaderError) { bool exception_thrown = false; try { spsc_queue<int> q; spsc_reader<int> r1(q); spsc_reader<int> r2(q); } catch (const spsc_reader_exists& e) { exception_thrown = true; } ASSERT_TRUE(exception_thrown); } TEST(SpscQueueTest, TwoWriterError) { bool exception_thrown = false; try { spsc_queue<int> q; spsc_writer<int> w1(q); spsc_writer<int> w2(q); } catch (const spsc_writer_exists& e) { exception_thrown = true; } ASSERT_TRUE(exception_thrown); } <|endoftext|>
<commit_before>//.............................................................................. // // This file is part of the AXL library. // // AXL is distributed under the MIT license. // For details see accompanying license.txt file, // the public copy of which is also available at: // http://tibbo.com/downloads/archive/axl/license.txt // //.............................................................................. #include "pch.h" #include "axl_io_FilePathUtils.h" #include "axl_err_Error.h" #include "axl_enc_Utf.h" //.............................................................................. #if (_AXL_OS_DARWIN) char* get_current_dir_name () { size_t size = 128; for (;;) { char* buffer = (char*) ::malloc (size); char* result = ::getcwd (buffer, size); if (result == buffer) return buffer; ::free (buffer); if (errno != ERANGE) return NULL; size *= 2; } } #endif namespace axl { namespace io { //.............................................................................. sl::String getTempDir () { #if (_AXL_OS_WIN) wchar_t dir [1024] = { 0 }; ::GetTempPathW (countof (dir) - 1, dir); return dir; #elif (_AXL_OS_POSIX) return "/tmp"; #endif } sl::String getCurrentDir () { #if (_AXL_OS_WIN) wchar_t dir [1024] = { 0 }; ::GetCurrentDirectoryW (countof (dir) - 1, dir); return dir; #elif (_AXL_OS_POSIX) char* p = ::get_current_dir_name (); sl::String dir = p; ::free (p); return dir; #endif } bool setCurrentDir (const sl::StringRef& dir) { #if (_AXL_OS_WIN) bool_t result = ::SetCurrentDirectoryW (dir.sz ()); return err::complete (result); #elif (_AXL_OS_POSIX) int result = ::chdir (dir.sz ()); return err::complete (result == 0); #endif } sl::String getExeFilePath () { char buffer [1024] = { 0 }; #if (_AXL_OS_WIN) ::GetModuleFileNameA (::GetModuleHandle (NULL), buffer, countof (buffer) - 1); #elif (_AXL_OS_POSIX) # if (_AXL_OS_LINUX) ::readlink ("/proc/self/exe", buffer, countof (buffer) - 1); # elif (_AXL_OS_DARWIN) uint32_t size = sizeof (buffer); _NSGetExecutablePath (buffer, &size); # else # error unsupported POSIX flavor # endif #endif return buffer; } sl::String getExeDir () { return io::getDir (io::getExeFilePath ()); } bool doesFileExist (const sl::StringRef& fileName) { #if (_AXL_OS_WIN) char buffer [256]; sl::String_w fileName_w (ref::BufKind_Stack, buffer, sizeof (buffer)); fileName_w = fileName; dword_t attributes = ::GetFileAttributesW (fileName_w); return attributes != INVALID_FILE_ATTRIBUTES; #elif (_AXL_OS_POSIX) return ::access (fileName.sz (), F_OK) != -1; #endif } #if (_AXL_OS_WIN) bool isDir (const sl::StringRef_w& fileName) { dword_t attributes = ::GetFileAttributesW (fileName.sz ()); return attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0; } bool isDir (const sl::StringRef& fileName) { char buffer [256]; sl::String_w fileName_w (ref::BufKind_Stack, buffer, sizeof (buffer)); return isDir (fileName_w); } bool ensureDirExists (const sl::StringRef& fileName) { char buffer [256] = { 0 }; sl::String_w fileName_w (ref::BufKind_Stack, buffer, sizeof (buffer)); fileName_w = fileName; if (fileName_w.isEmpty () || isDir (fileName_w)) return true; const wchar_t* p = fileName_w; if (p [1] == ':') p += 2; while (*p == '\\' || *p == '/') // skip root p++; while (*p) { const wchar_t* p2 = p + 1; while (*p2 && *p2 != '\\' && *p2 != '/') p2++; wchar_t c = *p2; // save *(wchar_t*) p2 = 0; if (!isDir (fileName_w)) { bool_t result = ::CreateDirectoryW (fileName_w, NULL); if (!result) return err::failWithLastSystemError (); } *(wchar_t*) p2 = c; // restore p = p2 + 1; while (*p == '\\' || *p == '/') // skip separators p++; } return true; } #elif (_AXL_OS_POSIX) bool isDir (const sl::StringRef& fileName) { struct stat st; int result = ::stat (fileName.sz (), &st); return result == 0 && S_ISDIR (st.st_mode); } bool ensureDirExists (const sl::StringRef& fileName0) { sl::String fileName = fileName0; if (isDir (fileName)) return true; const char* p = fileName.p (); // ensure exclusive buffer (we're going to modify it) while (*p == '/') // skip root p++; while (*p) { const char* p2 = p + 1; while (*p2 && *p2 != '/') p2++; char c = *p2; // save *(char*) p2 = 0; if (!isDir (fileName)) { int result = ::mkdir (fileName, S_IRWXU); if (result != 0) return err::failWithLastSystemError (); } *(char*) p2 = c; // restore p = p2 + 1; while (*p == '/') // skip separators p++; } return true; } #endif sl::String getFullFilePath (const sl::StringRef& fileName) { #if (_AXL_OS_WIN) char buffer [256]; sl::String_w fileName_w (ref::BufKind_Stack, buffer, sizeof (buffer)); fileName_w = fileName; size_t length = ::GetFullPathNameW (fileName_w, 0, NULL, NULL); if (!length) return err::failWithLastSystemError (NULL); sl::String_w filePath; wchar_t* p = filePath.createBuffer (length); ::GetFullPathNameW (fileName_w, length, p, NULL); return filePath; #elif (_AXL_OS_POSIX) char fullPath [PATH_MAX] = { 0 }; ::realpath (fileName.sz (), fullPath); return fullPath; #endif } sl::String getDir (const sl::StringRef& filePath) { #if (_AXL_OS_WIN) char buffer [256]; sl::String_w filePath_w (ref::BufKind_Stack, buffer, sizeof (buffer)); filePath_w = filePath; wchar_t drive [4] = { 0 }; wchar_t dir [1024] = { 0 }; _wsplitpath_s ( filePath_w, drive, countof (drive) - 1, dir, countof (dir) - 1, NULL, 0, NULL, 0 ); sl::String string = drive; string.append (dir); return string; #elif (_AXL_OS_POSIX) const char* p0 = filePath.sz (); const char* p = strrchr (p0, '/'); return p ? sl::String (p0, p - p0) : filePath; #endif } sl::String getFileName (const sl::StringRef& filePath) { #if (_AXL_OS_WIN) char buffer [256]; sl::String_w filePath_w (ref::BufKind_Stack, buffer, sizeof (buffer)); filePath_w = filePath; wchar_t fileName [1024] = { 0 }; wchar_t extension [1024] = { 0 }; _wsplitpath_s ( filePath_w, NULL, 0, NULL, 0, fileName, countof (fileName) - 1, extension, countof (extension) - 1 ); sl::String string = fileName; string.append (extension); return string; #elif (_AXL_OS_POSIX) const char* p = strrchr (filePath.sz (), '/'); return p ? sl::String (p + 1) : filePath; #endif } sl::String getExtension (const sl::StringRef& filePath) { size_t i = filePath.find ('.'); return i != -1 ? filePath.getSubString (i) : NULL; } sl::String concatFilePath ( sl::String* filePath, const sl::StringRef& fileName ) { if (filePath->isEmpty ()) { *filePath = fileName; return *filePath; } char last = (*filePath) [filePath->getLength () - 1]; #if (_AXL_OS_WIN) if (last != '\\' && last != '/') filePath->append ('\\'); #elif (_AXL_OS_POSIX) if (last != '/') filePath->append ('/'); #endif filePath->append (fileName); return *filePath; } sl::String findFilePath ( const sl::StringRef& fileName, const sl::StringRef& firstDir, const sl::BoxList <sl::String>* dirList, bool doFindInCurrentDir ) { sl::String filePath; if (!firstDir.isEmpty ()) { filePath = concatFilePath (firstDir, fileName); if (doesFileExist (filePath)) return getFullFilePath (filePath); } if (doFindInCurrentDir) if (doesFileExist (fileName)) return getFullFilePath (fileName); if (dirList) { sl::BoxIterator <sl::String> dir = dirList->getHead (); for (; dir; dir++) { filePath.forceCopy (*dir); concatFilePath (&filePath, fileName); if (doesFileExist (filePath)) return getFullFilePath (filePath); } } return sl::String (); } //.............................................................................. } // namespace io } // namespace axl <commit_msg>[axl_io] fixed type mismatch in io::setCurrentDir<commit_after>//.............................................................................. // // This file is part of the AXL library. // // AXL is distributed under the MIT license. // For details see accompanying license.txt file, // the public copy of which is also available at: // http://tibbo.com/downloads/archive/axl/license.txt // //.............................................................................. #include "pch.h" #include "axl_io_FilePathUtils.h" #include "axl_err_Error.h" #include "axl_enc_Utf.h" //.............................................................................. #if (_AXL_OS_DARWIN) char* get_current_dir_name () { size_t size = 128; for (;;) { char* buffer = (char*) ::malloc (size); char* result = ::getcwd (buffer, size); if (result == buffer) return buffer; ::free (buffer); if (errno != ERANGE) return NULL; size *= 2; } } #endif namespace axl { namespace io { //.............................................................................. sl::String getTempDir () { #if (_AXL_OS_WIN) wchar_t dir [1024] = { 0 }; ::GetTempPathW (countof (dir) - 1, dir); return dir; #elif (_AXL_OS_POSIX) return "/tmp"; #endif } sl::String getCurrentDir () { #if (_AXL_OS_WIN) wchar_t dir [1024] = { 0 }; ::GetCurrentDirectoryW (countof (dir) - 1, dir); return dir; #elif (_AXL_OS_POSIX) char* p = ::get_current_dir_name (); sl::String dir = p; ::free (p); return dir; #endif } bool setCurrentDir (const sl::StringRef& dir) { #if (_AXL_OS_WIN) bool_t result = ::SetCurrentDirectoryW (dir.s2 ().sz ()); return err::complete (result); #elif (_AXL_OS_POSIX) int result = ::chdir (dir.sz ()); return err::complete (result == 0); #endif } sl::String getExeFilePath () { char buffer [1024] = { 0 }; #if (_AXL_OS_WIN) ::GetModuleFileNameA (::GetModuleHandle (NULL), buffer, countof (buffer) - 1); #elif (_AXL_OS_POSIX) # if (_AXL_OS_LINUX) ::readlink ("/proc/self/exe", buffer, countof (buffer) - 1); # elif (_AXL_OS_DARWIN) uint32_t size = sizeof (buffer); _NSGetExecutablePath (buffer, &size); # else # error unsupported POSIX flavor # endif #endif return buffer; } sl::String getExeDir () { return io::getDir (io::getExeFilePath ()); } bool doesFileExist (const sl::StringRef& fileName) { #if (_AXL_OS_WIN) char buffer [256]; sl::String_w fileName_w (ref::BufKind_Stack, buffer, sizeof (buffer)); fileName_w = fileName; dword_t attributes = ::GetFileAttributesW (fileName_w); return attributes != INVALID_FILE_ATTRIBUTES; #elif (_AXL_OS_POSIX) return ::access (fileName.sz (), F_OK) != -1; #endif } #if (_AXL_OS_WIN) bool isDir (const sl::StringRef_w& fileName) { dword_t attributes = ::GetFileAttributesW (fileName.sz ()); return attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0; } bool isDir (const sl::StringRef& fileName) { char buffer [256]; sl::String_w fileName_w (ref::BufKind_Stack, buffer, sizeof (buffer)); return isDir (fileName_w); } bool ensureDirExists (const sl::StringRef& fileName) { char buffer [256] = { 0 }; sl::String_w fileName_w (ref::BufKind_Stack, buffer, sizeof (buffer)); fileName_w = fileName; if (fileName_w.isEmpty () || isDir (fileName_w)) return true; const wchar_t* p = fileName_w; if (p [1] == ':') p += 2; while (*p == '\\' || *p == '/') // skip root p++; while (*p) { const wchar_t* p2 = p + 1; while (*p2 && *p2 != '\\' && *p2 != '/') p2++; wchar_t c = *p2; // save *(wchar_t*) p2 = 0; if (!isDir (fileName_w)) { bool_t result = ::CreateDirectoryW (fileName_w, NULL); if (!result) return err::failWithLastSystemError (); } *(wchar_t*) p2 = c; // restore p = p2 + 1; while (*p == '\\' || *p == '/') // skip separators p++; } return true; } #elif (_AXL_OS_POSIX) bool isDir (const sl::StringRef& fileName) { struct stat st; int result = ::stat (fileName.sz (), &st); return result == 0 && S_ISDIR (st.st_mode); } bool ensureDirExists (const sl::StringRef& fileName0) { sl::String fileName = fileName0; if (isDir (fileName)) return true; const char* p = fileName.p (); // ensure exclusive buffer (we're going to modify it) while (*p == '/') // skip root p++; while (*p) { const char* p2 = p + 1; while (*p2 && *p2 != '/') p2++; char c = *p2; // save *(char*) p2 = 0; if (!isDir (fileName)) { int result = ::mkdir (fileName, S_IRWXU); if (result != 0) return err::failWithLastSystemError (); } *(char*) p2 = c; // restore p = p2 + 1; while (*p == '/') // skip separators p++; } return true; } #endif sl::String getFullFilePath (const sl::StringRef& fileName) { #if (_AXL_OS_WIN) char buffer [256]; sl::String_w fileName_w (ref::BufKind_Stack, buffer, sizeof (buffer)); fileName_w = fileName; size_t length = ::GetFullPathNameW (fileName_w, 0, NULL, NULL); if (!length) return err::failWithLastSystemError (NULL); sl::String_w filePath; wchar_t* p = filePath.createBuffer (length); ::GetFullPathNameW (fileName_w, length, p, NULL); return filePath; #elif (_AXL_OS_POSIX) char fullPath [PATH_MAX] = { 0 }; ::realpath (fileName.sz (), fullPath); return fullPath; #endif } sl::String getDir (const sl::StringRef& filePath) { #if (_AXL_OS_WIN) char buffer [256]; sl::String_w filePath_w (ref::BufKind_Stack, buffer, sizeof (buffer)); filePath_w = filePath; wchar_t drive [4] = { 0 }; wchar_t dir [1024] = { 0 }; _wsplitpath_s ( filePath_w, drive, countof (drive) - 1, dir, countof (dir) - 1, NULL, 0, NULL, 0 ); sl::String string = drive; string.append (dir); return string; #elif (_AXL_OS_POSIX) const char* p0 = filePath.sz (); const char* p = strrchr (p0, '/'); return p ? sl::String (p0, p - p0) : filePath; #endif } sl::String getFileName (const sl::StringRef& filePath) { #if (_AXL_OS_WIN) char buffer [256]; sl::String_w filePath_w (ref::BufKind_Stack, buffer, sizeof (buffer)); filePath_w = filePath; wchar_t fileName [1024] = { 0 }; wchar_t extension [1024] = { 0 }; _wsplitpath_s ( filePath_w, NULL, 0, NULL, 0, fileName, countof (fileName) - 1, extension, countof (extension) - 1 ); sl::String string = fileName; string.append (extension); return string; #elif (_AXL_OS_POSIX) const char* p = strrchr (filePath.sz (), '/'); return p ? sl::String (p + 1) : filePath; #endif } sl::String getExtension (const sl::StringRef& filePath) { size_t i = filePath.find ('.'); return i != -1 ? filePath.getSubString (i) : NULL; } sl::String concatFilePath ( sl::String* filePath, const sl::StringRef& fileName ) { if (filePath->isEmpty ()) { *filePath = fileName; return *filePath; } char last = (*filePath) [filePath->getLength () - 1]; #if (_AXL_OS_WIN) if (last != '\\' && last != '/') filePath->append ('\\'); #elif (_AXL_OS_POSIX) if (last != '/') filePath->append ('/'); #endif filePath->append (fileName); return *filePath; } sl::String findFilePath ( const sl::StringRef& fileName, const sl::StringRef& firstDir, const sl::BoxList <sl::String>* dirList, bool doFindInCurrentDir ) { sl::String filePath; if (!firstDir.isEmpty ()) { filePath = concatFilePath (firstDir, fileName); if (doesFileExist (filePath)) return getFullFilePath (filePath); } if (doFindInCurrentDir) if (doesFileExist (fileName)) return getFullFilePath (fileName); if (dirList) { sl::BoxIterator <sl::String> dir = dirList->getHead (); for (; dir; dir++) { filePath.forceCopy (*dir); concatFilePath (&filePath, fileName); if (doesFileExist (filePath)) return getFullFilePath (filePath); } } return sl::String (); } //.............................................................................. } // namespace io } // namespace axl <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: flushcode.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-07 22:18:51 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "sal/config.h" #include "flushcode.hxx" extern "C" void doFlushCode(unsigned long address, unsigned long count); namespace bridges { namespace cpp_uno { namespace cc50_solaris_sparc { void flushCode(void const * begin, void const * end) { unsigned long n = static_cast< char const * >(end) - static_cast< char const * >(begin); if (n != 0) { unsigned long adr = reinterpret_cast< unsigned long >(begin); unsigned long off = adr & 7; doFlushCode(adr - off, (n + off + 7) >> 3); } } } } } <commit_msg>INTEGRATION: CWS pchfix02 (1.3.70); FILE MERGED 2006/09/01 17:17:29 kaib 1.3.70.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: flushcode.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2006-09-16 15:45:00 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_bridges.hxx" #include "sal/config.h" #include "flushcode.hxx" extern "C" void doFlushCode(unsigned long address, unsigned long count); namespace bridges { namespace cpp_uno { namespace cc50_solaris_sparc { void flushCode(void const * begin, void const * end) { unsigned long n = static_cast< char const * >(end) - static_cast< char const * >(begin); if (n != 0) { unsigned long adr = reinterpret_cast< unsigned long >(begin); unsigned long off = adr & 7; doFlushCode(adr - off, (n + off + 7) >> 3); } } } } } <|endoftext|>
<commit_before>/* * Copyright (c)2015 Oasis LMF Limited * 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 original author of this software 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 <iostream> #include <stdio.h> #include <stdlib.h> #include "../include/oasis.hpp" void doit() { float randno; char line[4096]; int lineno=0; while (fgets(line, sizeof(line), stdin) != 0) { if (sscanf(line, "%f", &randno) != 1){ fprintf(stderr, "Invalid data in line %d:\n%s", lineno, line); return; } else { fwrite(&randno, sizeof(randno), 1, stdout); } lineno++; } } int main() { initstreams("", ""); doit(); return 0; } <commit_msg>Add skip header support to randtobin<commit_after>/* * Copyright (c)2015 Oasis LMF Limited * 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 original author of this software 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 <iostream> #include <stdio.h> #include <stdlib.h> #include "../include/oasis.hpp" void doit() { float randno; char line[4096]; int lineno=0; fgets(line, sizeof(line), stdin); // skip first line while (fgets(line, sizeof(line), stdin) != 0) { if (sscanf(line, "%f", &randno) != 1){ fprintf(stderr, "Invalid data in line %d:\n%s", lineno, line); return; } else { fwrite(&randno, sizeof(randno), 1, stdout); } lineno++; } } int main() { initstreams("", ""); doit(); return 0; } <|endoftext|>
<commit_before>#include "tokenizer.h" #include "token.h" #include <string> #include <cctype> namespace { static const char EndOfFileChar = std::char_traits<char>::to_char_type(std::char_traits<char>::eof()); } //-------------------------------------------------------------------------------------------------- Tokenizer::Tokenizer() : input_(nullptr), inputLength_(0), cursorPos_(0), cursorLine_(0) { } //-------------------------------------------------------------------------------------------------- Tokenizer::~Tokenizer() { } //-------------------------------------------------------------------------------------------------- void Tokenizer::Reset(const char* input, std::size_t startingLine) { input_ = input; inputLength_ = std::char_traits<char>::length(input); cursorPos_ = 0; cursorLine_ = startingLine; } //-------------------------------------------------------------------------------------------------- char Tokenizer::GetChar() { char c = input_[cursorPos_]; prevCursorPos_ = cursorPos_; prevCursorLine_ = cursorLine_; // New line moves the cursor to the new line if(c == '\n') cursorLine_++; cursorPos_++; return c; } //-------------------------------------------------------------------------------------------------- void Tokenizer::UngetChar() { cursorLine_ = prevCursorLine_; cursorPos_ = prevCursorPos_; } //-------------------------------------------------------------------------------------------------- char Tokenizer::peek() const { return !is_eof() ? input_[cursorPos_] : EndOfFileChar; } //-------------------------------------------------------------------------------------------------- char Tokenizer::GetLeadingChar() { char c; for(c = GetChar(); !is_eof(); c = GetChar()) { // If this is a whitespace character skip it std::char_traits<char>::int_type intc = std::char_traits<char>::to_int_type(c); if(std::isspace(intc) || std::iscntrl(intc)) continue; // If this is a single line comment char next = peek(); if(c == '/' && next == '/') { // Search for the end of the line for (c = GetChar(); c != EndOfFileChar && c != '\n'; c = GetChar()); // Go to the next continue; } // If this is a block comment if(c == '/' && next == '*') { // Search for the end of the block comment for (c = GetChar(), next = peek(); c != EndOfFileChar && (c != '*' || next != '/'); c = GetChar(), next = peek()); // Skip past the slash if(c != EndOfFileChar) GetChar(); // Move to the next character continue; } break; } return c; } //-------------------------------------------------------------------------------------------------- bool Tokenizer::GetToken(Token &token) { // Get the next character char c = GetLeadingChar(); char p = peek(); std::char_traits<char>::int_type intc = std::char_traits<char>::to_int_type(c); std::char_traits<char>::int_type intp = std::char_traits<char>::to_int_type(p); if(!std::char_traits<char>::not_eof(intc)) { UngetChar(); return false; } // Record the start of the token position token.startPos = prevCursorPos_; token.startLine = prevCursorLine_; token.token.clear(); token.tokenType = TokenType::kNone; // Alphanumeric token if(std::isalpha(intc) || c == '_') { // Read the rest of the alphanumeric characters do { token.token.push_back(c); c = GetChar(); intc = std::char_traits<char>::to_int_type(c); } while(std::isalnum(intc) || c == '_'); // Put back the last read character since it's not part of the identifier UngetChar(); // Set the type of the token token.tokenType = TokenType::kIdentifier; if(token.token == "true") { token.tokenType = TokenType::kConst; token.constType = ConstType::kBoolean; token.boolConst = true; } else if(token.token == "false") { token.tokenType = TokenType::kConst; token.constType = ConstType::kBoolean; token.boolConst = false; } return true; } // Constant else if(std::isdigit(intc) || ((c == '-' || c == '+') && std::isdigit(intp))) { bool isFloat = false; bool isHex = false; bool isNegated = c == '-'; do { if(c == '.') isFloat = true; if(c == 'x' || c == 'X') isHex = true; token.token.push_back(c); c = GetChar(); intc = std::char_traits<char>::to_int_type(c); } while(std::isdigit(intc) || (!isFloat && c == '.') || (!isHex && (c == 'X' || c == 'x')) || (isHex && std::isxdigit(intc))); if(!isFloat || (c != 'f' && c != 'F')) UngetChar(); token.tokenType = TokenType::kConst; if(!isFloat) { try { if(isNegated) { token.int32Const = std::stoi(token.token, 0, 0); token.constType = ConstType::kInt32; } else { token.uint32Const = std::stoul(token.token, 0, 0); token.constType = ConstType::kUInt32; } } catch(std::out_of_range) { if(isNegated) { token.int64Const = std::stoll(token.token, 0, 0); token.constType = ConstType::kInt64; } else { token.uint64Const = std::stoull(token.token, 0, 0); token.constType = ConstType::kUInt64; } } } else { token.realConst = std::stod(token.token); token.constType = ConstType::kReal; } return true; } else if(c == '"') { c = GetChar(); while(c != '"' && std::char_traits<char>::not_eof(std::char_traits<char>::to_int_type(c))) { if(c == '\\') { c = GetChar(); if(!std::char_traits<char>::not_eof(std::char_traits<char>::to_int_type(c))) break; else if(c == 'n') c = '\n'; else if(c == 't') c = '\t'; else if(c == 'r') c = '\r'; else if(c == '"') c = '"'; } token.token.push_back(c); c = GetChar(); } if(c != '"') UngetChar(); token.tokenType = TokenType::kConst; token.constType = ConstType::kString; token.stringConst = token.token; return true; } // Symbol else { // Push back the symbol token.token.push_back(c); #define PAIR(cc,dd) (c==cc&&d==dd) /* Comparison macro for two characters */ const char d = GetChar(); if(PAIR('<', '<') || PAIR('-', '>') || PAIR('>', '>') || PAIR('!', '=') || PAIR('<', '=') || PAIR('>', '=') || PAIR('+', '+') || PAIR('-', '-') || PAIR('+', '=') || PAIR('-', '=') || PAIR('*', '=') || PAIR('/', '=') || PAIR('^', '=') || PAIR('|', '=') || PAIR('&', '=') || PAIR('~', '=') || PAIR('%', '=') || PAIR('&', '&') || PAIR('|', '|') || PAIR('=', '=') || PAIR(':', ':') ) #undef PAIR { token.token.push_back(d); } else UngetChar(); token.tokenType = TokenType::kSymbol; return true; } return false; } //-------------------------------------------------------------------------------------------------- bool Tokenizer::is_eof() const { return cursorPos_ >= inputLength_; } //-------------------------------------------------------------------------------------------------- bool Tokenizer::GetIdentifier(Token &token) { if(!GetToken(token)) return false; if(token.tokenType == TokenType::kIdentifier) return true; UngetToken(token); return false; } //-------------------------------------------------------------------------------------------------- void Tokenizer::UngetToken(const Token &token) { cursorLine_ = token.startLine; cursorPos_ = token.startPos; } //-------------------------------------------------------------------------------------------------- bool Tokenizer::MatchIdentifier(const char *identifier) { Token token; if(GetToken(token)) { if(token.tokenType == TokenType::kIdentifier && token.token == identifier) return true; UngetToken(token); } return false; } //-------------------------------------------------------------------------------------------------- bool Tokenizer::MatchSymbol(const char *symbol) { Token token; if(GetToken(token)) { if(token.tokenType == TokenType::kSymbol && token.token == symbol) return true; UngetToken(token); } return false; } //-------------------------------------------------------------------------------------------------- void Tokenizer::RequireIdentifier(const char *identifier) { if(!MatchIdentifier(identifier)) throw; } //-------------------------------------------------------------------------------------------------- void Tokenizer::RequireSymbol(const char *symbol) { if(!MatchSymbol(symbol)) throw; } <commit_msg>Added <stdexcept> to includes for out_of_range exception<commit_after>#include "tokenizer.h" #include "token.h" #include <string> #include <cctype> #include <stdexcept> namespace { static const char EndOfFileChar = std::char_traits<char>::to_char_type(std::char_traits<char>::eof()); } //-------------------------------------------------------------------------------------------------- Tokenizer::Tokenizer() : input_(nullptr), inputLength_(0), cursorPos_(0), cursorLine_(0) { } //-------------------------------------------------------------------------------------------------- Tokenizer::~Tokenizer() { } //-------------------------------------------------------------------------------------------------- void Tokenizer::Reset(const char* input, std::size_t startingLine) { input_ = input; inputLength_ = std::char_traits<char>::length(input); cursorPos_ = 0; cursorLine_ = startingLine; } //-------------------------------------------------------------------------------------------------- char Tokenizer::GetChar() { char c = input_[cursorPos_]; prevCursorPos_ = cursorPos_; prevCursorLine_ = cursorLine_; // New line moves the cursor to the new line if(c == '\n') cursorLine_++; cursorPos_++; return c; } //-------------------------------------------------------------------------------------------------- void Tokenizer::UngetChar() { cursorLine_ = prevCursorLine_; cursorPos_ = prevCursorPos_; } //-------------------------------------------------------------------------------------------------- char Tokenizer::peek() const { return !is_eof() ? input_[cursorPos_] : EndOfFileChar; } //-------------------------------------------------------------------------------------------------- char Tokenizer::GetLeadingChar() { char c; for(c = GetChar(); !is_eof(); c = GetChar()) { // If this is a whitespace character skip it std::char_traits<char>::int_type intc = std::char_traits<char>::to_int_type(c); if(std::isspace(intc) || std::iscntrl(intc)) continue; // If this is a single line comment char next = peek(); if(c == '/' && next == '/') { // Search for the end of the line for (c = GetChar(); c != EndOfFileChar && c != '\n'; c = GetChar()); // Go to the next continue; } // If this is a block comment if(c == '/' && next == '*') { // Search for the end of the block comment for (c = GetChar(), next = peek(); c != EndOfFileChar && (c != '*' || next != '/'); c = GetChar(), next = peek()); // Skip past the slash if(c != EndOfFileChar) GetChar(); // Move to the next character continue; } break; } return c; } //-------------------------------------------------------------------------------------------------- bool Tokenizer::GetToken(Token &token) { // Get the next character char c = GetLeadingChar(); char p = peek(); std::char_traits<char>::int_type intc = std::char_traits<char>::to_int_type(c); std::char_traits<char>::int_type intp = std::char_traits<char>::to_int_type(p); if(!std::char_traits<char>::not_eof(intc)) { UngetChar(); return false; } // Record the start of the token position token.startPos = prevCursorPos_; token.startLine = prevCursorLine_; token.token.clear(); token.tokenType = TokenType::kNone; // Alphanumeric token if(std::isalpha(intc) || c == '_') { // Read the rest of the alphanumeric characters do { token.token.push_back(c); c = GetChar(); intc = std::char_traits<char>::to_int_type(c); } while(std::isalnum(intc) || c == '_'); // Put back the last read character since it's not part of the identifier UngetChar(); // Set the type of the token token.tokenType = TokenType::kIdentifier; if(token.token == "true") { token.tokenType = TokenType::kConst; token.constType = ConstType::kBoolean; token.boolConst = true; } else if(token.token == "false") { token.tokenType = TokenType::kConst; token.constType = ConstType::kBoolean; token.boolConst = false; } return true; } // Constant else if(std::isdigit(intc) || ((c == '-' || c == '+') && std::isdigit(intp))) { bool isFloat = false; bool isHex = false; bool isNegated = c == '-'; do { if(c == '.') isFloat = true; if(c == 'x' || c == 'X') isHex = true; token.token.push_back(c); c = GetChar(); intc = std::char_traits<char>::to_int_type(c); } while(std::isdigit(intc) || (!isFloat && c == '.') || (!isHex && (c == 'X' || c == 'x')) || (isHex && std::isxdigit(intc))); if(!isFloat || (c != 'f' && c != 'F')) UngetChar(); token.tokenType = TokenType::kConst; if(!isFloat) { try { if(isNegated) { token.int32Const = std::stoi(token.token, 0, 0); token.constType = ConstType::kInt32; } else { token.uint32Const = std::stoul(token.token, 0, 0); token.constType = ConstType::kUInt32; } } catch(std::out_of_range) { if(isNegated) { token.int64Const = std::stoll(token.token, 0, 0); token.constType = ConstType::kInt64; } else { token.uint64Const = std::stoull(token.token, 0, 0); token.constType = ConstType::kUInt64; } } } else { token.realConst = std::stod(token.token); token.constType = ConstType::kReal; } return true; } else if(c == '"') { c = GetChar(); while(c != '"' && std::char_traits<char>::not_eof(std::char_traits<char>::to_int_type(c))) { if(c == '\\') { c = GetChar(); if(!std::char_traits<char>::not_eof(std::char_traits<char>::to_int_type(c))) break; else if(c == 'n') c = '\n'; else if(c == 't') c = '\t'; else if(c == 'r') c = '\r'; else if(c == '"') c = '"'; } token.token.push_back(c); c = GetChar(); } if(c != '"') UngetChar(); token.tokenType = TokenType::kConst; token.constType = ConstType::kString; token.stringConst = token.token; return true; } // Symbol else { // Push back the symbol token.token.push_back(c); #define PAIR(cc,dd) (c==cc&&d==dd) /* Comparison macro for two characters */ const char d = GetChar(); if(PAIR('<', '<') || PAIR('-', '>') || PAIR('>', '>') || PAIR('!', '=') || PAIR('<', '=') || PAIR('>', '=') || PAIR('+', '+') || PAIR('-', '-') || PAIR('+', '=') || PAIR('-', '=') || PAIR('*', '=') || PAIR('/', '=') || PAIR('^', '=') || PAIR('|', '=') || PAIR('&', '=') || PAIR('~', '=') || PAIR('%', '=') || PAIR('&', '&') || PAIR('|', '|') || PAIR('=', '=') || PAIR(':', ':') ) #undef PAIR { token.token.push_back(d); } else UngetChar(); token.tokenType = TokenType::kSymbol; return true; } return false; } //-------------------------------------------------------------------------------------------------- bool Tokenizer::is_eof() const { return cursorPos_ >= inputLength_; } //-------------------------------------------------------------------------------------------------- bool Tokenizer::GetIdentifier(Token &token) { if(!GetToken(token)) return false; if(token.tokenType == TokenType::kIdentifier) return true; UngetToken(token); return false; } //-------------------------------------------------------------------------------------------------- void Tokenizer::UngetToken(const Token &token) { cursorLine_ = token.startLine; cursorPos_ = token.startPos; } //-------------------------------------------------------------------------------------------------- bool Tokenizer::MatchIdentifier(const char *identifier) { Token token; if(GetToken(token)) { if(token.tokenType == TokenType::kIdentifier && token.token == identifier) return true; UngetToken(token); } return false; } //-------------------------------------------------------------------------------------------------- bool Tokenizer::MatchSymbol(const char *symbol) { Token token; if(GetToken(token)) { if(token.tokenType == TokenType::kSymbol && token.token == symbol) return true; UngetToken(token); } return false; } //-------------------------------------------------------------------------------------------------- void Tokenizer::RequireIdentifier(const char *identifier) { if(!MatchIdentifier(identifier)) throw; } //-------------------------------------------------------------------------------------------------- void Tokenizer::RequireSymbol(const char *symbol) { if(!MatchSymbol(symbol)) throw; } <|endoftext|>
<commit_before>#line 2 "togo/hash/hash_combiner.hpp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. @file @brief HashCombiner interface. @ingroup hash @ingroup hash_combiner */ #pragma once #include <togo/config.hpp> #include <togo/types.hpp> #include <togo/string/string.hpp> #include <togo/hash/types.hpp> #include <togo/hash/hash.hpp> namespace togo { namespace hash_combiner { /** @addtogroup hash_combiner @{ */ /// Number of bytes combined. template<class H> inline unsigned size(HashCombiner<H> const& combiner) { return combiner._impl.size(); } /// Returns true if any bytes have been combined. template<class H> inline bool any(HashCombiner<H> const& combiner) { return hash_combiner::size(combiner) != 0; } /// Returns true if no bytes have been combined. template<class H> inline bool empty(HashCombiner<H> const& combiner) { return hash_combiner::size(combiner) == 0; } /// Initialize. /// /// This will return the combiner to its initial state. /// The combiner's initial state is initialized, so this does not /// need to be called right after constructing the object. template<class H> inline void init( HashCombiner<H>& combiner ) { combiner._impl.init(); } /// Add bytes. template<class H> inline void add( HashCombiner<H>& combiner, char const* const data, unsigned const size ) { combiner._impl.add(data, size); } /// Add string. template<class H> inline void add( HashCombiner<H>& combiner, StringRef const& str ) { hash_combiner::add(combiner, str.data, str.size); } /// Calculate current value. /// /// This does not affect the state of the combiner. template<class H> inline H value(HashCombiner<H> const& combiner) { return hash_combiner::empty(combiner) ? hash::traits<H>::identity : combiner._impl.value() ; } /** @} */ // end of doc-group hash_combiner } // namespace hash_combiner } // namespace togo <commit_msg>hash/hash_combiner: logical intent.<commit_after>#line 2 "togo/hash/hash_combiner.hpp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. @file @brief HashCombiner interface. @ingroup hash @ingroup hash_combiner */ #pragma once #include <togo/config.hpp> #include <togo/types.hpp> #include <togo/string/string.hpp> #include <togo/hash/types.hpp> #include <togo/hash/hash.hpp> namespace togo { namespace hash_combiner { /** @addtogroup hash_combiner @{ */ /// Number of bytes combined. template<class H> inline unsigned size(HashCombiner<H> const& combiner) { return combiner._impl.size(); } /// Returns true if any bytes have been combined. template<class H> inline bool any(HashCombiner<H> const& combiner) { return hash_combiner::size(combiner) > 0; } /// Returns true if no bytes have been combined. template<class H> inline bool empty(HashCombiner<H> const& combiner) { return hash_combiner::size(combiner) == 0; } /// Initialize. /// /// This will return the combiner to its initial state. /// The combiner's initial state is initialized, so this does not /// need to be called right after constructing the object. template<class H> inline void init( HashCombiner<H>& combiner ) { combiner._impl.init(); } /// Add bytes. template<class H> inline void add( HashCombiner<H>& combiner, char const* const data, unsigned const size ) { combiner._impl.add(data, size); } /// Add string. template<class H> inline void add( HashCombiner<H>& combiner, StringRef const& str ) { hash_combiner::add(combiner, str.data, str.size); } /// Calculate current value. /// /// This does not affect the state of the combiner. template<class H> inline H value(HashCombiner<H> const& combiner) { return hash_combiner::empty(combiner) ? hash::traits<H>::identity : combiner._impl.value() ; } /** @} */ // end of doc-group hash_combiner } // namespace hash_combiner } // namespace togo <|endoftext|>
<commit_before>/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ // ok is an experimental test harness, maybe to replace DM. Key features: // * work is balanced across separate processes for stability and isolation; // * ok is entirely opt-in. No more maintaining huge --blacklists. #include "SkGraphics.h" #include "SkImage.h" #include "ok.h" #include <chrono> #include <future> #include <list> #include <stdio.h> #include <stdlib.h> #include <thread> #include <vector> #if !defined(__has_include) #define __has_include(x) 0 #endif static thread_local const char* tls_currently_running = ""; #if __has_include(<execinfo.h>) && __has_include(<fcntl.h>) && __has_include(<signal.h>) #include <execinfo.h> #include <fcntl.h> #include <signal.h> static int log_fd = 2/*stderr*/; static void log(const char* msg) { write(log_fd, msg, strlen(msg)); } static void setup_crash_handler() { static void (*original_handlers[32])(int); for (int sig : std::vector<int>{ SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV }) { original_handlers[sig] = signal(sig, [](int sig) { lockf(log_fd, F_LOCK, 0); log("\ncaught signal "); switch (sig) { #define CASE(s) case s: log(#s); break CASE(SIGABRT); CASE(SIGBUS); CASE(SIGFPE); CASE(SIGILL); CASE(SIGSEGV); #undef CASE } log(" while running '"); log(tls_currently_running); log("'\n"); void* stack[128]; int frames = backtrace(stack, sizeof(stack)/sizeof(*stack)); backtrace_symbols_fd(stack, frames, log_fd); lockf(log_fd, F_ULOCK, 0); signal(sig, original_handlers[sig]); raise(sig); }); } } static void defer_logging() { log_fd = fileno(tmpfile()); atexit([] { lseek(log_fd, 0, SEEK_SET); char buf[1024]; while (size_t bytes = read(log_fd, buf, sizeof(buf))) { write(2, buf, bytes); } }); } void ok_log(const char* msg) { lockf(log_fd, F_LOCK, 0); log("["); log(tls_currently_running); log("]\t"); log(msg); log("\n"); lockf(log_fd, F_ULOCK, 0); } #else static void setup_crash_handler() {} static void defer_logging() {} void ok_log(const char* msg) { fprintf(stderr, "%s\n", msg); } #endif struct Engine { virtual ~Engine() {} virtual bool spawn(std::function<Status(void)>) = 0; virtual Status wait_one() = 0; }; struct SerialEngine : Engine { Status last = Status::None; bool spawn(std::function<Status(void)> fn) override { last = fn(); return true; } Status wait_one() override { Status s = last; last = Status::None; return s; } }; struct ThreadEngine : Engine { std::list<std::future<Status>> live; const std::chrono::steady_clock::time_point the_past = std::chrono::steady_clock::now(); bool spawn(std::function<Status(void)> fn) override { live.push_back(std::async(std::launch::async, fn)); return true; } Status wait_one() override { if (live.empty()) { return Status::None; } for (;;) { for (auto it = live.begin(); it != live.end(); it++) { if (it->wait_until(the_past) == std::future_status::ready) { Status s = it->get(); live.erase(it); return s; } } } } }; #if defined(_MSC_VER) using ForkEngine = ThreadEngine; #else #include <sys/wait.h> #include <unistd.h> struct ForkEngine : Engine { bool spawn(std::function<Status(void)> fn) override { switch (fork()) { case 0: _exit((int)fn()); case -1: return false; default: return true; } } Status wait_one() override { do { int status; if (wait(&status) > 0) { return WIFEXITED(status) ? (Status)WEXITSTATUS(status) : Status::Crashed; } } while (errno == EINTR); return Status::None; } }; #endif struct StreamType { const char *name, *help; std::unique_ptr<Stream> (*factory)(Options); }; static std::vector<StreamType> stream_types; struct DstType { const char *name, *help; std::unique_ptr<Dst> (*factory)(Options); }; static std::vector<DstType> dst_types; struct ViaType { const char *name, *help; std::unique_ptr<Dst> (*factory)(Options, std::unique_ptr<Dst>); }; static std::vector<ViaType> via_types; template <typename T> static std::string help_for(std::vector<T> registered) { std::string help; for (auto r : registered) { help += "\n "; help += r.name; help += ": "; help += r.help; } return help; } int main(int argc, char** argv) { SkGraphics::Init(); setup_crash_handler(); int jobs{1}; std::unique_ptr<Stream> stream; std::function<std::unique_ptr<Dst>(void)> dst_factory = []{ // A default Dst that's enough for unit tests and not much else. struct : Dst { Status draw(Src* src) override { return src->draw(nullptr); } sk_sp<SkImage> image() override { return nullptr; } } dst; return move_unique(dst); }; auto help = [&] { std::string stream_help = help_for(stream_types), dst_help = help_for( dst_types), via_help = help_for( via_types); printf("%s [-j N] src[:k=v,...] dst[:k=v,...] [via[:k=v,...] ...] \n" " -j: Run at most N processes at any time. \n" " If <0, use -N threads instead. \n" " If 0, use one thread in one process. \n" " If 1 (default) or -1, auto-detect N. \n" " src: content to draw%s \n" " dst: how to draw that content%s \n" " via: wrappers around dst%s \n" " Most srcs, dsts and vias have options, e.g. skp:dir=skps sw:ct=565 \n", argv[0], stream_help.c_str(), dst_help.c_str(), via_help.c_str()); return 1; }; for (int i = 1; i < argc; i++) { if (0 == strcmp("-j", argv[i])) { jobs = atoi(argv[++i]); } if (0 == strcmp("-h", argv[i])) { return help(); } if (0 == strcmp("--help", argv[i])) { return help(); } for (auto s : stream_types) { size_t len = strlen(s.name); if (0 == strncmp(s.name, argv[i], len)) { switch (argv[i][len]) { case ':': len++; case '\0': stream = s.factory(Options{argv[i]+len}); } } } for (auto d : dst_types) { size_t len = strlen(d.name); if (0 == strncmp(d.name, argv[i], len)) { switch (argv[i][len]) { case ':': len++; case '\0': dst_factory = [=]{ return d.factory(Options{argv[i]+len}); }; } } } for (auto v : via_types) { size_t len = strlen(v.name); if (0 == strncmp(v.name, argv[i], len)) { if (!dst_factory) { return help(); } switch (argv[i][len]) { case ':': len++; case '\0': dst_factory = [=]{ return v.factory(Options{argv[i]+len}, dst_factory()); }; } } } } if (!stream) { return help(); } std::unique_ptr<Engine> engine; if (jobs == 0) { engine.reset(new SerialEngine); } if (jobs > 0) { engine.reset(new ForkEngine); defer_logging(); } if (jobs < 0) { engine.reset(new ThreadEngine); jobs = -jobs; } if (jobs == 1) { jobs = std::thread::hardware_concurrency(); } int ok = 0, failed = 0, crashed = 0, skipped = 0; auto update_stats = [&](Status s) { switch (s) { case Status::OK: ok++; break; case Status::Failed: failed++; break; case Status::Crashed: crashed++; break; case Status::Skipped: skipped++; break; case Status::None: return; } const char* leader = "\r"; auto print = [&](int count, const char* label) { if (count) { printf("%s%d %s", leader, count, label); leader = ", "; } }; print(ok, "ok"); print(failed, "failed"); print(crashed, "crashed"); print(skipped, "skipped"); fflush(stdout); }; auto spawn = [&](std::function<Status(void)> fn) { if (--jobs < 0) { update_stats(engine->wait_one()); } while (!engine->spawn(fn)) { update_stats(engine->wait_one()); } }; for (std::unique_ptr<Src> owned = stream->next(); owned; owned = stream->next()) { Src* raw = owned.release(); // Can't move std::unique_ptr into a lambda in C++11. :( spawn([=] { std::unique_ptr<Src> src{raw}; std::string name = src->name(); tls_currently_running = name.c_str(); return dst_factory()->draw(src.get()); }); } for (Status s = Status::OK; s != Status::None; ) { s = engine->wait_one(); update_stats(s); } printf("\n"); return (failed || crashed) ? 1 : 0; } Register::Register(const char* name, const char* help, std::unique_ptr<Stream> (*factory)(Options)) { stream_types.push_back(StreamType{name, help, factory}); } Register::Register(const char* name, const char* help, std::unique_ptr<Dst> (*factory)(Options)) { dst_types.push_back(DstType{name, help, factory}); } Register::Register(const char* name, const char* help, std::unique_ptr<Dst> (*factory)(Options, std::unique_ptr<Dst>)) { via_types.push_back(ViaType{name, help, factory}); } Options::Options(std::string str) { std::string k,v, *curr = &k; for (auto c : str) { switch(c) { case ',': (*this)[k] = v; curr = &(k = ""); break; case '=': curr = &(v = ""); break; default: *curr += c; } } (*this)[k] = v; } std::string& Options::operator[](std::string k) { return this->kv[k]; } std::string Options::operator()(std::string k, std::string fallback) const { for (auto it = kv.find(k); it != kv.end(); ) { return it->second; } return fallback; } <commit_msg>ok, exit() child processes instead of _exit()<commit_after>/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ // ok is an experimental test harness, maybe to replace DM. Key features: // * work is balanced across separate processes for stability and isolation; // * ok is entirely opt-in. No more maintaining huge --blacklists. #include "SkGraphics.h" #include "SkImage.h" #include "ok.h" #include <chrono> #include <future> #include <list> #include <stdio.h> #include <stdlib.h> #include <thread> #include <vector> #if !defined(__has_include) #define __has_include(x) 0 #endif static thread_local const char* tls_currently_running = ""; #if __has_include(<execinfo.h>) && __has_include(<fcntl.h>) && __has_include(<signal.h>) #include <execinfo.h> #include <fcntl.h> #include <signal.h> static int log_fd = 2/*stderr*/; static void log(const char* msg) { write(log_fd, msg, strlen(msg)); } static void setup_crash_handler() { static void (*original_handlers[32])(int); for (int sig : std::vector<int>{ SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV }) { original_handlers[sig] = signal(sig, [](int sig) { lockf(log_fd, F_LOCK, 0); log("\ncaught signal "); switch (sig) { #define CASE(s) case s: log(#s); break CASE(SIGABRT); CASE(SIGBUS); CASE(SIGFPE); CASE(SIGILL); CASE(SIGSEGV); #undef CASE } log(" while running '"); log(tls_currently_running); log("'\n"); void* stack[128]; int frames = backtrace(stack, sizeof(stack)/sizeof(*stack)); backtrace_symbols_fd(stack, frames, log_fd); lockf(log_fd, F_ULOCK, 0); signal(sig, original_handlers[sig]); raise(sig); }); } } static void defer_logging() { log_fd = fileno(tmpfile()); } static void print_deferred_logs() { lseek(log_fd, 0, SEEK_SET); char buf[1024]; while (size_t bytes = read(log_fd, buf, sizeof(buf))) { write(2/*stderr*/, buf, bytes); } } void ok_log(const char* msg) { lockf(log_fd, F_LOCK, 0); log("["); log(tls_currently_running); log("]\t"); log(msg); log("\n"); lockf(log_fd, F_ULOCK, 0); } #else static void setup_crash_handler() {} static void defer_logging() {} static void print_deferred_logs() {} void ok_log(const char* msg) { fprintf(stderr, "%s\n", msg); } #endif struct Engine { virtual ~Engine() {} virtual bool spawn(std::function<Status(void)>) = 0; virtual Status wait_one() = 0; }; struct SerialEngine : Engine { Status last = Status::None; bool spawn(std::function<Status(void)> fn) override { last = fn(); return true; } Status wait_one() override { Status s = last; last = Status::None; return s; } }; struct ThreadEngine : Engine { std::list<std::future<Status>> live; const std::chrono::steady_clock::time_point the_past = std::chrono::steady_clock::now(); bool spawn(std::function<Status(void)> fn) override { live.push_back(std::async(std::launch::async, fn)); return true; } Status wait_one() override { if (live.empty()) { return Status::None; } for (;;) { for (auto it = live.begin(); it != live.end(); it++) { if (it->wait_until(the_past) == std::future_status::ready) { Status s = it->get(); live.erase(it); return s; } } } } }; #if defined(_MSC_VER) using ForkEngine = ThreadEngine; #else #include <sys/wait.h> #include <unistd.h> struct ForkEngine : Engine { bool spawn(std::function<Status(void)> fn) override { switch (fork()) { case 0: exit((int)fn()); case -1: return false; default: return true; } } Status wait_one() override { do { int status; if (wait(&status) > 0) { return WIFEXITED(status) ? (Status)WEXITSTATUS(status) : Status::Crashed; } } while (errno == EINTR); return Status::None; } }; #endif struct StreamType { const char *name, *help; std::unique_ptr<Stream> (*factory)(Options); }; static std::vector<StreamType> stream_types; struct DstType { const char *name, *help; std::unique_ptr<Dst> (*factory)(Options); }; static std::vector<DstType> dst_types; struct ViaType { const char *name, *help; std::unique_ptr<Dst> (*factory)(Options, std::unique_ptr<Dst>); }; static std::vector<ViaType> via_types; template <typename T> static std::string help_for(std::vector<T> registered) { std::string help; for (auto r : registered) { help += "\n "; help += r.name; help += ": "; help += r.help; } return help; } int main(int argc, char** argv) { SkGraphics::Init(); setup_crash_handler(); int jobs{1}; std::unique_ptr<Stream> stream; std::function<std::unique_ptr<Dst>(void)> dst_factory = []{ // A default Dst that's enough for unit tests and not much else. struct : Dst { Status draw(Src* src) override { return src->draw(nullptr); } sk_sp<SkImage> image() override { return nullptr; } } dst; return move_unique(dst); }; auto help = [&] { std::string stream_help = help_for(stream_types), dst_help = help_for( dst_types), via_help = help_for( via_types); printf("%s [-j N] src[:k=v,...] dst[:k=v,...] [via[:k=v,...] ...] \n" " -j: Run at most N processes at any time. \n" " If <0, use -N threads instead. \n" " If 0, use one thread in one process. \n" " If 1 (default) or -1, auto-detect N. \n" " src: content to draw%s \n" " dst: how to draw that content%s \n" " via: wrappers around dst%s \n" " Most srcs, dsts and vias have options, e.g. skp:dir=skps sw:ct=565 \n", argv[0], stream_help.c_str(), dst_help.c_str(), via_help.c_str()); return 1; }; for (int i = 1; i < argc; i++) { if (0 == strcmp("-j", argv[i])) { jobs = atoi(argv[++i]); } if (0 == strcmp("-h", argv[i])) { return help(); } if (0 == strcmp("--help", argv[i])) { return help(); } for (auto s : stream_types) { size_t len = strlen(s.name); if (0 == strncmp(s.name, argv[i], len)) { switch (argv[i][len]) { case ':': len++; case '\0': stream = s.factory(Options{argv[i]+len}); } } } for (auto d : dst_types) { size_t len = strlen(d.name); if (0 == strncmp(d.name, argv[i], len)) { switch (argv[i][len]) { case ':': len++; case '\0': dst_factory = [=]{ return d.factory(Options{argv[i]+len}); }; } } } for (auto v : via_types) { size_t len = strlen(v.name); if (0 == strncmp(v.name, argv[i], len)) { if (!dst_factory) { return help(); } switch (argv[i][len]) { case ':': len++; case '\0': dst_factory = [=]{ return v.factory(Options{argv[i]+len}, dst_factory()); }; } } } } if (!stream) { return help(); } std::unique_ptr<Engine> engine; if (jobs == 0) { engine.reset(new SerialEngine); } if (jobs > 0) { engine.reset(new ForkEngine); defer_logging(); } if (jobs < 0) { engine.reset(new ThreadEngine); jobs = -jobs; } if (jobs == 1) { jobs = std::thread::hardware_concurrency(); } int ok = 0, failed = 0, crashed = 0, skipped = 0; auto update_stats = [&](Status s) { switch (s) { case Status::OK: ok++; break; case Status::Failed: failed++; break; case Status::Crashed: crashed++; break; case Status::Skipped: skipped++; break; case Status::None: return; } const char* leader = "\r"; auto print = [&](int count, const char* label) { if (count) { printf("%s%d %s", leader, count, label); leader = ", "; } }; print(ok, "ok"); print(failed, "failed"); print(crashed, "crashed"); print(skipped, "skipped"); fflush(stdout); }; auto spawn = [&](std::function<Status(void)> fn) { if (--jobs < 0) { update_stats(engine->wait_one()); } while (!engine->spawn(fn)) { update_stats(engine->wait_one()); } }; for (std::unique_ptr<Src> owned = stream->next(); owned; owned = stream->next()) { Src* raw = owned.release(); // Can't move std::unique_ptr into a lambda in C++11. :( spawn([=] { std::unique_ptr<Src> src{raw}; std::string name = src->name(); tls_currently_running = name.c_str(); return dst_factory()->draw(src.get()); }); } for (Status s = Status::OK; s != Status::None; ) { s = engine->wait_one(); update_stats(s); } printf("\n"); print_deferred_logs(); return (failed || crashed) ? 1 : 0; } Register::Register(const char* name, const char* help, std::unique_ptr<Stream> (*factory)(Options)) { stream_types.push_back(StreamType{name, help, factory}); } Register::Register(const char* name, const char* help, std::unique_ptr<Dst> (*factory)(Options)) { dst_types.push_back(DstType{name, help, factory}); } Register::Register(const char* name, const char* help, std::unique_ptr<Dst> (*factory)(Options, std::unique_ptr<Dst>)) { via_types.push_back(ViaType{name, help, factory}); } Options::Options(std::string str) { std::string k,v, *curr = &k; for (auto c : str) { switch(c) { case ',': (*this)[k] = v; curr = &(k = ""); break; case '=': curr = &(v = ""); break; default: *curr += c; } } (*this)[k] = v; } std::string& Options::operator[](std::string k) { return this->kv[k]; } std::string Options::operator()(std::string k, std::string fallback) const { for (auto it = kv.find(k); it != kv.end(); ) { return it->second; } return fallback; } <|endoftext|>
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved. #include "containers/disk_backed_queue.hpp" #include "arch/io/disk.hpp" #include "buffer_cache/alt/alt.hpp" #include "buffer_cache/alt/blob.hpp" #include "buffer_cache/alt/cache_balancer.hpp" #include "buffer_cache/alt/alt_serialize_onto_blob.hpp" #include "serializer/config.hpp" #define DBQ_MAX_REF_SIZE 251 internal_disk_backed_queue_t::internal_disk_backed_queue_t(io_backender_t *io_backender, const serializer_filepath_t &filename, perfmon_collection_t *stats_parent) : perfmon_membership(stats_parent, &perfmon_collection, filename.permanent_path().c_str()), queue_size(0), head_block_id(NULL_BLOCK_ID), tail_block_id(NULL_BLOCK_ID) { filepath_file_opener_t file_opener(filename, io_backender); standard_serializer_t::create(&file_opener, standard_serializer_t::static_config_t()); serializer.init(new standard_serializer_t(standard_serializer_t::dynamic_config_t(), &file_opener, &perfmon_collection)); /* Remove the file we just created from the filesystem, so that it will get deleted as soon as the serializer is destroyed or if the process crashes. */ file_opener.unlink_serializer_file(); balancer.init(new dummy_cache_balancer_t(MEGABYTE)); cache.init(new cache_t(serializer.get(), balancer.get(), &perfmon_collection)); cache_conn.init(new cache_conn_t(cache.get())); // Emulate cache_t::create behavior by zeroing the block with id SUPERBLOCK_ID. txn_t txn(cache_conn.get(), write_durability_t::HARD, repli_timestamp_t::distant_past, 1); buf_lock_t block(&txn, SUPERBLOCK_ID, alt_create_t::create); buf_write_t write(&block); const block_size_t block_size = cache->max_block_size(); void *buf = write.get_data_write(block_size.value()); memset(buf, 0, block_size.value()); } internal_disk_backed_queue_t::~internal_disk_backed_queue_t() { } void internal_disk_backed_queue_t::push(const write_message_t &wm) { mutex_t::acq_t mutex_acq(&mutex); // There's no need for hard durability with an unlinked dbq file. txn_t txn(cache_conn.get(), write_durability_t::SOFT, repli_timestamp_t::distant_past, 2); push_single(&txn, wm); } void internal_disk_backed_queue_t::push(const scoped_array_t<write_message_t> &wms) { mutex_t::acq_t mutex_acq(&mutex); // There's no need for hard durability with an unlinked dbq file. txn_t txn(cache_conn.get(), write_durability_t::SOFT, repli_timestamp_t::distant_past, 2); for (size_t i = 0; i < wms.size(); ++i) { push_single(&txn, wms[i]); } } void internal_disk_backed_queue_t::push_single(txn_t *txn, const write_message_t &wm) { if (head_block_id == NULL_BLOCK_ID) { add_block_to_head(txn); } auto _head = make_scoped<buf_lock_t>(buf_parent_t(txn), head_block_id, access_t::write); auto write = make_scoped<buf_write_t>(_head.get()); queue_block_t *head = static_cast<queue_block_t *>(write->get_data_write()); char buffer[DBQ_MAX_REF_SIZE]; memset(buffer, 0, DBQ_MAX_REF_SIZE); blob_t blob(cache->max_block_size(), buffer, DBQ_MAX_REF_SIZE); write_onto_blob(buf_parent_t(_head.get()), &blob, wm); if (static_cast<size_t>((head->data + head->data_size) - reinterpret_cast<char *>(head)) + blob.refsize(cache->max_block_size()) > cache->max_block_size().value()) { // The data won't fit in our current head block, so it's time to make a new one. head = NULL; write.reset(); _head.reset(); add_block_to_head(txn); _head.init(new buf_lock_t(buf_parent_t(txn), head_block_id, access_t::write)); write.init(new buf_write_t(_head.get())); head = static_cast<queue_block_t *>(write->get_data_write()); } memcpy(head->data + head->data_size, buffer, blob.refsize(cache->max_block_size())); head->data_size += blob.refsize(cache->max_block_size()); queue_size++; } void internal_disk_backed_queue_t::pop(buffer_group_viewer_t *viewer) { guarantee(size() != 0); mutex_t::acq_t mutex_acq(&mutex); char buffer[DBQ_MAX_REF_SIZE]; // No need for hard durability with an unlinked dbq file. txn_t txn(cache_conn.get(), write_durability_t::SOFT, repli_timestamp_t::distant_past, 2); buf_lock_t _tail(buf_parent_t(&txn), tail_block_id, access_t::write); /* Grab the data from the blob and delete it. */ { buf_read_t read(&_tail); const queue_block_t *tail = static_cast<const queue_block_t *>(read.get_data_read()); rassert(tail->data_size != tail->live_data_offset); memcpy(buffer, tail->data + tail->live_data_offset, blob::ref_size(cache->max_block_size(), tail->data + tail->live_data_offset, DBQ_MAX_REF_SIZE)); } /* Grab the data from the blob and delete it. */ std::vector<char> data_vec; blob_t blob(cache->max_block_size(), buffer, DBQ_MAX_REF_SIZE); { blob_acq_t acq_group; buffer_group_t blob_group; blob.expose_all(buf_parent_t(&_tail), access_t::read, &blob_group, &acq_group); viewer->view_buffer_group(const_view(&blob_group)); } int32_t data_size; int32_t live_data_offset; { buf_write_t write(&_tail); queue_block_t *tail = static_cast<queue_block_t *>(write.get_data_write()); /* Record how far along in the blob we are. */ tail->live_data_offset += blob.refsize(cache->max_block_size()); data_size = tail->data_size; live_data_offset = tail->live_data_offset; } blob.clear(buf_parent_t(&_tail)); queue_size--; _tail.reset_buf_lock(); /* If that was the last blob in this block move on to the next one. */ if (live_data_offset == data_size) { remove_block_from_tail(&txn); } } bool internal_disk_backed_queue_t::empty() { return queue_size == 0; } int64_t internal_disk_backed_queue_t::size() { return queue_size; } void internal_disk_backed_queue_t::add_block_to_head(txn_t *txn) { buf_lock_t _new_head(buf_parent_t(txn), alt_create_t::create); buf_write_t write(&_new_head); queue_block_t *new_head = static_cast<queue_block_t *>(write.get_data_write()); if (head_block_id == NULL_BLOCK_ID) { rassert(tail_block_id == NULL_BLOCK_ID); head_block_id = tail_block_id = _new_head.block_id(); } else { buf_lock_t _old_head(buf_parent_t(txn), head_block_id, access_t::write); buf_write_t old_write(&_old_head); queue_block_t *old_head = static_cast<queue_block_t *>(old_write.get_data_write()); rassert(old_head->next == NULL_BLOCK_ID); old_head->next = _new_head.block_id(); head_block_id = _new_head.block_id(); } new_head->next = NULL_BLOCK_ID; new_head->data_size = 0; new_head->live_data_offset = 0; } void internal_disk_backed_queue_t::remove_block_from_tail(txn_t *txn) { rassert(tail_block_id != NULL_BLOCK_ID); buf_lock_t _old_tail(buf_parent_t(txn), tail_block_id, access_t::write); { buf_write_t old_write(&_old_tail); queue_block_t *old_tail = static_cast<queue_block_t *>(old_write.get_data_write()); if (old_tail->next == NULL_BLOCK_ID) { rassert(head_block_id == _old_tail.block_id()); tail_block_id = head_block_id = NULL_BLOCK_ID; } else { tail_block_id = old_tail->next; } } _old_tail.mark_deleted(); } <commit_msg>changing disk-backed queues to have a base cache size of 2 MB<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved. #include "containers/disk_backed_queue.hpp" #include "arch/io/disk.hpp" #include "buffer_cache/alt/alt.hpp" #include "buffer_cache/alt/blob.hpp" #include "buffer_cache/alt/cache_balancer.hpp" #include "buffer_cache/alt/alt_serialize_onto_blob.hpp" #include "serializer/config.hpp" #define DBQ_MAX_REF_SIZE 251 internal_disk_backed_queue_t::internal_disk_backed_queue_t(io_backender_t *io_backender, const serializer_filepath_t &filename, perfmon_collection_t *stats_parent) : perfmon_membership(stats_parent, &perfmon_collection, filename.permanent_path().c_str()), queue_size(0), head_block_id(NULL_BLOCK_ID), tail_block_id(NULL_BLOCK_ID) { filepath_file_opener_t file_opener(filename, io_backender); standard_serializer_t::create(&file_opener, standard_serializer_t::static_config_t()); serializer.init(new standard_serializer_t(standard_serializer_t::dynamic_config_t(), &file_opener, &perfmon_collection)); /* Remove the file we just created from the filesystem, so that it will get deleted as soon as the serializer is destroyed or if the process crashes. */ file_opener.unlink_serializer_file(); balancer.init(new dummy_cache_balancer_t(2 * MEGABYTE)); cache.init(new cache_t(serializer.get(), balancer.get(), &perfmon_collection)); cache_conn.init(new cache_conn_t(cache.get())); // Emulate cache_t::create behavior by zeroing the block with id SUPERBLOCK_ID. txn_t txn(cache_conn.get(), write_durability_t::HARD, repli_timestamp_t::distant_past, 1); buf_lock_t block(&txn, SUPERBLOCK_ID, alt_create_t::create); buf_write_t write(&block); const block_size_t block_size = cache->max_block_size(); void *buf = write.get_data_write(block_size.value()); memset(buf, 0, block_size.value()); } internal_disk_backed_queue_t::~internal_disk_backed_queue_t() { } void internal_disk_backed_queue_t::push(const write_message_t &wm) { mutex_t::acq_t mutex_acq(&mutex); // There's no need for hard durability with an unlinked dbq file. txn_t txn(cache_conn.get(), write_durability_t::SOFT, repli_timestamp_t::distant_past, 2); push_single(&txn, wm); } void internal_disk_backed_queue_t::push(const scoped_array_t<write_message_t> &wms) { mutex_t::acq_t mutex_acq(&mutex); // There's no need for hard durability with an unlinked dbq file. txn_t txn(cache_conn.get(), write_durability_t::SOFT, repli_timestamp_t::distant_past, 2); for (size_t i = 0; i < wms.size(); ++i) { push_single(&txn, wms[i]); } } void internal_disk_backed_queue_t::push_single(txn_t *txn, const write_message_t &wm) { if (head_block_id == NULL_BLOCK_ID) { add_block_to_head(txn); } auto _head = make_scoped<buf_lock_t>(buf_parent_t(txn), head_block_id, access_t::write); auto write = make_scoped<buf_write_t>(_head.get()); queue_block_t *head = static_cast<queue_block_t *>(write->get_data_write()); char buffer[DBQ_MAX_REF_SIZE]; memset(buffer, 0, DBQ_MAX_REF_SIZE); blob_t blob(cache->max_block_size(), buffer, DBQ_MAX_REF_SIZE); write_onto_blob(buf_parent_t(_head.get()), &blob, wm); if (static_cast<size_t>((head->data + head->data_size) - reinterpret_cast<char *>(head)) + blob.refsize(cache->max_block_size()) > cache->max_block_size().value()) { // The data won't fit in our current head block, so it's time to make a new one. head = NULL; write.reset(); _head.reset(); add_block_to_head(txn); _head.init(new buf_lock_t(buf_parent_t(txn), head_block_id, access_t::write)); write.init(new buf_write_t(_head.get())); head = static_cast<queue_block_t *>(write->get_data_write()); } memcpy(head->data + head->data_size, buffer, blob.refsize(cache->max_block_size())); head->data_size += blob.refsize(cache->max_block_size()); queue_size++; } void internal_disk_backed_queue_t::pop(buffer_group_viewer_t *viewer) { guarantee(size() != 0); mutex_t::acq_t mutex_acq(&mutex); char buffer[DBQ_MAX_REF_SIZE]; // No need for hard durability with an unlinked dbq file. txn_t txn(cache_conn.get(), write_durability_t::SOFT, repli_timestamp_t::distant_past, 2); buf_lock_t _tail(buf_parent_t(&txn), tail_block_id, access_t::write); /* Grab the data from the blob and delete it. */ { buf_read_t read(&_tail); const queue_block_t *tail = static_cast<const queue_block_t *>(read.get_data_read()); rassert(tail->data_size != tail->live_data_offset); memcpy(buffer, tail->data + tail->live_data_offset, blob::ref_size(cache->max_block_size(), tail->data + tail->live_data_offset, DBQ_MAX_REF_SIZE)); } /* Grab the data from the blob and delete it. */ std::vector<char> data_vec; blob_t blob(cache->max_block_size(), buffer, DBQ_MAX_REF_SIZE); { blob_acq_t acq_group; buffer_group_t blob_group; blob.expose_all(buf_parent_t(&_tail), access_t::read, &blob_group, &acq_group); viewer->view_buffer_group(const_view(&blob_group)); } int32_t data_size; int32_t live_data_offset; { buf_write_t write(&_tail); queue_block_t *tail = static_cast<queue_block_t *>(write.get_data_write()); /* Record how far along in the blob we are. */ tail->live_data_offset += blob.refsize(cache->max_block_size()); data_size = tail->data_size; live_data_offset = tail->live_data_offset; } blob.clear(buf_parent_t(&_tail)); queue_size--; _tail.reset_buf_lock(); /* If that was the last blob in this block move on to the next one. */ if (live_data_offset == data_size) { remove_block_from_tail(&txn); } } bool internal_disk_backed_queue_t::empty() { return queue_size == 0; } int64_t internal_disk_backed_queue_t::size() { return queue_size; } void internal_disk_backed_queue_t::add_block_to_head(txn_t *txn) { buf_lock_t _new_head(buf_parent_t(txn), alt_create_t::create); buf_write_t write(&_new_head); queue_block_t *new_head = static_cast<queue_block_t *>(write.get_data_write()); if (head_block_id == NULL_BLOCK_ID) { rassert(tail_block_id == NULL_BLOCK_ID); head_block_id = tail_block_id = _new_head.block_id(); } else { buf_lock_t _old_head(buf_parent_t(txn), head_block_id, access_t::write); buf_write_t old_write(&_old_head); queue_block_t *old_head = static_cast<queue_block_t *>(old_write.get_data_write()); rassert(old_head->next == NULL_BLOCK_ID); old_head->next = _new_head.block_id(); head_block_id = _new_head.block_id(); } new_head->next = NULL_BLOCK_ID; new_head->data_size = 0; new_head->live_data_offset = 0; } void internal_disk_backed_queue_t::remove_block_from_tail(txn_t *txn) { rassert(tail_block_id != NULL_BLOCK_ID); buf_lock_t _old_tail(buf_parent_t(txn), tail_block_id, access_t::write); { buf_write_t old_write(&_old_tail); queue_block_t *old_tail = static_cast<queue_block_t *>(old_write.get_data_write()); if (old_tail->next == NULL_BLOCK_ID) { rassert(head_block_id == _old_tail.block_id()); tail_block_id = head_block_id = NULL_BLOCK_ID; } else { tail_block_id = old_tail->next; } } _old_tail.mark_deleted(); } <|endoftext|>
<commit_before><?hh //strict /** * This file is part of specify. * * (c) Noritaka Horio <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace specify\reporter; use specify\LifeCycleEvent; use specify\LifeCycleMessageSubscriber; use specify\event\ExamplePackageStart; use specify\event\ExampleStart; use specify\event\ExampleFinish; use specify\event\ExamplePackageFinish; use specify\io\ConsoleOutput; use specify\io\Console; final class DotReporter implements LifeCycleMessageSubscriber { private CompositionReporter $reporter; public function __construct( private Console $writer = new ConsoleOutput() ) { $this->reporter = new CompositionReporter(ImmVector { new ProcessingTimeReporter($this->writer), new SummaryReporter($this->writer) }); } public function handle(LifeCycleEvent $event) : void { if ($event instanceof ExamplePackageStart) { $this->onExamplePackageStart($event); } else if ($event instanceof ExampleFinish) { $this->onExampleFinish($event); } else if ($event instanceof ExamplePackageFinish) { $this->onExamplePackageFinish($event); } } private function onExamplePackageStart(ExamplePackageStart $event) : void { $this->writer->writeln(''); } private function onExampleFinish(ExampleFinish $event) : void { $value = '.'; if ($event->isFailed()) { $value = '<red>F</red>'; } else if ($event->isPending()) { $value = '<cyan>P</cyan>'; } $this->writer->write($value); } private function onExamplePackageFinish(ExamplePackageFinish $event) : void { $this->writer->writeln("\n"); $event->sendTo($this->reporter); $this->writer->write("\n"); } } <commit_msg>Update DotReporter format<commit_after><?hh //strict /** * This file is part of specify. * * (c) Noritaka Horio <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace specify\reporter; use specify\LifeCycleEvent; use specify\LifeCycleMessageSubscriber; use specify\event\ExamplePackageStart; use specify\event\ExampleStart; use specify\event\ExampleFinish; use specify\event\ExamplePackageFinish; use specify\io\ConsoleOutput; use specify\io\Console; final class DotReporter implements LifeCycleMessageSubscriber { private CompositionReporter $reporter; public function __construct( private Console $writer = new ConsoleOutput() ) { $this->reporter = new CompositionReporter(ImmVector { new ProcessingTimeReporter($this->writer), new SummaryReporter($this->writer), new FailedExampleReporter($this->writer) }); } public function handle(LifeCycleEvent $event) : void { if ($event instanceof ExamplePackageStart) { $this->onExamplePackageStart($event); } else if ($event instanceof ExampleFinish) { $this->onExampleFinish($event); } else if ($event instanceof ExamplePackageFinish) { $this->onExamplePackageFinish($event); } } private function onExamplePackageStart(ExamplePackageStart $event) : void { $this->writer->writeln(''); } private function onExampleFinish(ExampleFinish $event) : void { $value = '.'; if ($event->isFailed()) { $value = '<red>F</red>'; } else if ($event->isPending()) { $value = '<cyan>P</cyan>'; } $this->writer->write($value); } private function onExamplePackageFinish(ExamplePackageFinish $event) : void { $this->writer->writeln("\n"); $event->sendTo($this->reporter); } } <|endoftext|>
<commit_before>#include "example_generator.h" #include <string> #include "helper/bounding_box.h" #include "loader/loader_imagenet_det.h" #include "helper/high_res_timer.h" #include "helper/helper.h" #include "helper/image_proc.h" using std::string; // Choose whether to shift boxes using the motion model or using a uniform distribution. const bool shift_motion_model = true; ExampleGenerator::ExampleGenerator(const double lambda_shift, const double lambda_scale, const double min_scale, const double max_scale) : lambda_shift_(lambda_shift), lambda_scale_(lambda_scale), min_scale_(min_scale), max_scale_(max_scale) { } void ExampleGenerator::Reset(const BoundingBox& bbox_prev, const BoundingBox& bbox_curr, const cv::Mat& image_prev, const cv::Mat& image_curr) { // Get padded target from previous image to feed the network. CropPadImage(bbox_prev, image_prev, &target_pad_); // Save the current image. image_curr_ = image_curr; // Save the current ground-truth bounding box. bbox_curr_gt_ = bbox_curr; // Save the previous ground-truth bounding box. bbox_prev_gt_ = bbox_prev; } void ExampleGenerator::MakeTrainingExamples(const int num_examples, std::vector<cv::Mat>* images, std::vector<cv::Mat>* targets, std::vector<BoundingBox>* bboxes_gt_scaled) { for (int i = 0; i < num_examples; ++i) { cv::Mat image_rand_focus; cv::Mat target_pad; BoundingBox bbox_gt_scaled; // Make training example by synthetically shifting and scaling the image, // creating an apparent translation and scale change of the target object. MakeTrainingExampleBBShift(&image_rand_focus, &target_pad, &bbox_gt_scaled); images->push_back(image_rand_focus); targets->push_back(target_pad); bboxes_gt_scaled->push_back(bbox_gt_scaled); } } void ExampleGenerator::MakeTrueExample(cv::Mat* curr_search_region, cv::Mat* target_pad, BoundingBox* bbox_gt_scaled) const { *target_pad = target_pad_; // Get a tight prior prediction of the target's location in the current image. // For simplicity, we use the object's previous location as our guess. // TODO - use a motion model? const BoundingBox& curr_prior_tight = bbox_prev_gt_; // Crop the current image based on the prior estimate, with some padding // to define a search region within the current image. BoundingBox curr_search_location; double edge_spacing_x, edge_spacing_y; CropPadImage(curr_prior_tight, image_curr_, curr_search_region, &curr_search_location, &edge_spacing_x, &edge_spacing_y); // Recenter the ground-truth bbox relative to the search location. BoundingBox bbox_gt_recentered; bbox_curr_gt_.Recenter(curr_search_location, edge_spacing_x, edge_spacing_y, &bbox_gt_recentered); // Scale the bounding box relative to current crop. bbox_gt_recentered.Scale(*curr_search_region, bbox_gt_scaled); } void ExampleGenerator::get_default_bb_params(BBParams* default_params) const { default_params->lambda_scale = lambda_scale_; default_params->lambda_shift = lambda_shift_; default_params->min_scale = min_scale_; default_params->max_scale = max_scale_; } void ExampleGenerator::MakeTrainingExampleBBShift(cv::Mat* image_rand_focus, cv::Mat* target_pad, BoundingBox* bbox_gt_scaled) const { // Get default parameters for how much translation and scale change to apply to the // training example. BBParams default_bb_params; get_default_bb_params(&default_bb_params); // Generate training examples. const bool visualize_example = false; MakeTrainingExampleBBShift(visualize_example, default_bb_params, image_rand_focus, target_pad, bbox_gt_scaled); } void ExampleGenerator::MakeTrainingExampleBBShift( const bool visualize_example, cv::Mat* image_rand_focus, cv::Mat* target_pad, BoundingBox* bbox_gt_scaled) const { // Get default parameters for how much translation and scale change to apply to the // training example. BBParams default_bb_params; get_default_bb_params(&default_bb_params); // Generate training examples. MakeTrainingExampleBBShift(visualize_example, default_bb_params, image_rand_focus, target_pad, bbox_gt_scaled); } void ExampleGenerator::MakeTrainingExampleBBShift(const bool visualize_example, const BBParams& bbparams, cv::Mat* rand_search_region, cv::Mat* target_pad, BoundingBox* bbox_gt_scaled) const { *target_pad = target_pad_; // Randomly transform the current image (translation and scale changes). BoundingBox bbox_curr_shift; bbox_curr_gt_.Shift(image_curr_, bbparams.lambda_scale, bbparams.lambda_shift, bbparams.min_scale, bbparams.max_scale, shift_motion_model, &bbox_curr_shift); // Crop the image based at the new location (after applying translation and scale changes). double edge_spacing_x, edge_spacing_y; BoundingBox rand_search_location; CropPadImage(bbox_curr_shift, image_curr_, rand_search_region, &rand_search_location, &edge_spacing_x, &edge_spacing_y); // Find the shifted ground-truth bounding box location relative to the image crop. BoundingBox bbox_gt_recentered; bbox_curr_gt_.Recenter(rand_search_location, edge_spacing_x, edge_spacing_y, &bbox_gt_recentered); // Scale the ground-truth bounding box relative to the random transformation. bbox_gt_recentered.Scale(*rand_search_region, bbox_gt_scaled); if (visualize_example) { VisualizeExample(*target_pad, *rand_search_region, *bbox_gt_scaled); } } void ExampleGenerator::VisualizeExample(const cv::Mat& target_pad, const cv::Mat& image_rand_focus, const BoundingBox& bbox_gt_scaled) const { const bool save_images = false; // Show resized target. cv::Mat target_resize; cv::resize(target_pad, target_resize, cv::Size(227,227)); cv::namedWindow("Target object", cv::WINDOW_AUTOSIZE );// Create a window for display. cv::imshow("Target object", target_resize); // Show our image inside it. if (save_images) { const string target_name = "Image" + num2str(video_index_) + "_" + num2str(frame_index_) + "target.jpg"; cv::imwrite(target_name, target_resize); } // Resize the image. cv::Mat image_resize; cv::resize(image_rand_focus, image_resize, cv::Size(227, 227)); // Draw gt bbox. BoundingBox bbox_gt_unscaled; bbox_gt_scaled.Unscale(image_resize, &bbox_gt_unscaled); bbox_gt_unscaled.Draw(0, 255, 0, &image_resize); // Show image with bbox. cv::namedWindow("Search_region+gt", cv::WINDOW_AUTOSIZE );// Create a window for display. cv::imshow("Search_region+gt", image_resize ); // Show our image inside it. if (save_images) { const string image_name = "Image" + num2str(video_index_) + "_" + num2str(frame_index_) + "image.jpg"; cv::imwrite(image_name, image_resize); } cv::waitKey(0); } <commit_msg>Update example_generator.cpp<commit_after>#define CPU_ONLY 1 #include "example_generator.h" #include <string> #include "helper/bounding_box.h" #include "loader/loader_imagenet_det.h" #include "helper/high_res_timer.h" #include "helper/helper.h" #include "helper/image_proc.h" using std::string; // Choose whether to shift boxes using the motion model or using a uniform distribution. const bool shift_motion_model = true; ExampleGenerator::ExampleGenerator(const double lambda_shift, const double lambda_scale, const double min_scale, const double max_scale) : lambda_shift_(lambda_shift), lambda_scale_(lambda_scale), min_scale_(min_scale), max_scale_(max_scale) { } void ExampleGenerator::Reset(const BoundingBox& bbox_prev, const BoundingBox& bbox_curr, const cv::Mat& image_prev, const cv::Mat& image_curr) { // Get padded target from previous image to feed the network. CropPadImage(bbox_prev, image_prev, &target_pad_); // Save the current image. image_curr_ = image_curr; // Save the current ground-truth bounding box. bbox_curr_gt_ = bbox_curr; // Save the previous ground-truth bounding box. bbox_prev_gt_ = bbox_prev; } void ExampleGenerator::MakeTrainingExamples(const int num_examples, std::vector<cv::Mat>* images, std::vector<cv::Mat>* targets, std::vector<BoundingBox>* bboxes_gt_scaled) { for (int i = 0; i < num_examples; ++i) { cv::Mat image_rand_focus; cv::Mat target_pad; BoundingBox bbox_gt_scaled; // Make training example by synthetically shifting and scaling the image, // creating an apparent translation and scale change of the target object. MakeTrainingExampleBBShift(&image_rand_focus, &target_pad, &bbox_gt_scaled); images->push_back(image_rand_focus); targets->push_back(target_pad); bboxes_gt_scaled->push_back(bbox_gt_scaled); } } void ExampleGenerator::MakeTrueExample(cv::Mat* curr_search_region, cv::Mat* target_pad, BoundingBox* bbox_gt_scaled) const { *target_pad = target_pad_; // Get a tight prior prediction of the target's location in the current image. // For simplicity, we use the object's previous location as our guess. // TODO - use a motion model? const BoundingBox& curr_prior_tight = bbox_prev_gt_; // Crop the current image based on the prior estimate, with some padding // to define a search region within the current image. BoundingBox curr_search_location; double edge_spacing_x, edge_spacing_y; CropPadImage(curr_prior_tight, image_curr_, curr_search_region, &curr_search_location, &edge_spacing_x, &edge_spacing_y); // Recenter the ground-truth bbox relative to the search location. BoundingBox bbox_gt_recentered; bbox_curr_gt_.Recenter(curr_search_location, edge_spacing_x, edge_spacing_y, &bbox_gt_recentered); // Scale the bounding box relative to current crop. bbox_gt_recentered.Scale(*curr_search_region, bbox_gt_scaled); } void ExampleGenerator::get_default_bb_params(BBParams* default_params) const { default_params->lambda_scale = lambda_scale_; default_params->lambda_shift = lambda_shift_; default_params->min_scale = min_scale_; default_params->max_scale = max_scale_; } void ExampleGenerator::MakeTrainingExampleBBShift(cv::Mat* image_rand_focus, cv::Mat* target_pad, BoundingBox* bbox_gt_scaled) const { // Get default parameters for how much translation and scale change to apply to the // training example. BBParams default_bb_params; get_default_bb_params(&default_bb_params); // Generate training examples. const bool visualize_example = false; MakeTrainingExampleBBShift(visualize_example, default_bb_params, image_rand_focus, target_pad, bbox_gt_scaled); } void ExampleGenerator::MakeTrainingExampleBBShift( const bool visualize_example, cv::Mat* image_rand_focus, cv::Mat* target_pad, BoundingBox* bbox_gt_scaled) const { // Get default parameters for how much translation and scale change to apply to the // training example. BBParams default_bb_params; get_default_bb_params(&default_bb_params); // Generate training examples. MakeTrainingExampleBBShift(visualize_example, default_bb_params, image_rand_focus, target_pad, bbox_gt_scaled); } void ExampleGenerator::MakeTrainingExampleBBShift(const bool visualize_example, const BBParams& bbparams, cv::Mat* rand_search_region, cv::Mat* target_pad, BoundingBox* bbox_gt_scaled) const { *target_pad = target_pad_; // Randomly transform the current image (translation and scale changes). BoundingBox bbox_curr_shift; bbox_curr_gt_.Shift(image_curr_, bbparams.lambda_scale, bbparams.lambda_shift, bbparams.min_scale, bbparams.max_scale, shift_motion_model, &bbox_curr_shift); // Crop the image based at the new location (after applying translation and scale changes). double edge_spacing_x, edge_spacing_y; BoundingBox rand_search_location; CropPadImage(bbox_curr_shift, image_curr_, rand_search_region, &rand_search_location, &edge_spacing_x, &edge_spacing_y); // Find the shifted ground-truth bounding box location relative to the image crop. BoundingBox bbox_gt_recentered; bbox_curr_gt_.Recenter(rand_search_location, edge_spacing_x, edge_spacing_y, &bbox_gt_recentered); // Scale the ground-truth bounding box relative to the random transformation. bbox_gt_recentered.Scale(*rand_search_region, bbox_gt_scaled); if (visualize_example) { VisualizeExample(*target_pad, *rand_search_region, *bbox_gt_scaled); } } void ExampleGenerator::VisualizeExample(const cv::Mat& target_pad, const cv::Mat& image_rand_focus, const BoundingBox& bbox_gt_scaled) const { const bool save_images = false; // Show resized target. cv::Mat target_resize; cv::resize(target_pad, target_resize, cv::Size(227,227)); cv::namedWindow("Target object", cv::WINDOW_AUTOSIZE );// Create a window for display. cv::imshow("Target object", target_resize); // Show our image inside it. if (save_images) { const string target_name = "Image" + num2str(video_index_) + "_" + num2str(frame_index_) + "target.jpg"; cv::imwrite(target_name, target_resize); } // Resize the image. cv::Mat image_resize; cv::resize(image_rand_focus, image_resize, cv::Size(227, 227)); // Draw gt bbox. BoundingBox bbox_gt_unscaled; bbox_gt_scaled.Unscale(image_resize, &bbox_gt_unscaled); bbox_gt_unscaled.Draw(0, 255, 0, &image_resize); // Show image with bbox. cv::namedWindow("Search_region+gt", cv::WINDOW_AUTOSIZE );// Create a window for display. cv::imshow("Search_region+gt", image_resize ); // Show our image inside it. if (save_images) { const string image_name = "Image" + num2str(video_index_) + "_" + num2str(frame_index_) + "image.jpg"; cv::imwrite(image_name, image_resize); } cv::waitKey(0); } <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "ClientAuthentication.h" /* system implementation headers */ #include <string> #include <assert.h> #ifdef HAVE_KRB5 #include <com_err.h> #define err(x,y,z) if (debugLevel >= 1) com_err(x,y,z) #endif #ifdef HAVE_KRB5 krb5_context ClientAuthentication::context = NULL; krb5_ccache ClientAuthentication::cc = NULL; krb5_auth_context ClientAuthentication::auth_context = NULL; krb5_data ClientAuthentication::packet; krb5_data ClientAuthentication::inbuf; krb5_creds ClientAuthentication::creds; krb5_creds *ClientAuthentication::new_creds; krb5_principal ClientAuthentication::client; krb5_principal ClientAuthentication::server; char ClientAuthentication::principalName[128]; #endif bool ClientAuthentication::authentication = false; #ifdef HAVE_KRB5 void ClientAuthentication::init(const char *username, const char *password) #else void ClientAuthentication::init(const char *username, const char *) #endif // HAVE_KRB5 { strncpy(principalName, username, 128); principalName[127] = 0; #ifdef HAVE_KRB5 assert(context == NULL); assert(cc == NULL); krb5_error_code retval; krb5_creds my_creds; // Initializing kerberos library if ((retval = krb5_init_context(&context))) err("bzflag:", retval, "while initializing krb5"); // Getting a default cache specifically for bzflag if (context && (retval = krb5_cc_set_default_name(context, "FILE:/tmp/krb5_cc_bzflag"))) err("bzflag", retval, "setting default cache"); // Getting credential cache if (!retval && (retval = krb5_cc_default(context, &cc))) err("bzflag:", retval, "getting credentials cache"); char clientName[139]; snprintf(clientName, 139, "%[email protected]", username); if (cc && (retval = krb5_parse_name(context, clientName, &client))) err("bzflag", retval, "parsing principal name"); // Initing credential cache if (!retval && (retval = krb5_cc_initialize(context, cc, client))) err("bzflag", retval, "initializing credential cache"); char intPassword[128]; strncpy(intPassword, password, 128); intPassword[127] = 0; // Get credentials for server if (!retval && (retval = krb5_get_init_creds_password(context, &my_creds, client, intPassword, krb5_prompter_posix, NULL, 0, NULL, NULL))) err("bzflag", retval, "getting credential"); // Store credentials in cache if (!retval && (retval = krb5_cc_store_cred(context, cc, &my_creds))) err("bzflag", retval, "storing credential in cache"); if (!retval && (retval = krb5_parse_name(context, "krbtgt/[email protected]", &server))) err("bzflag:", retval, "setting up tgt server name"); authentication = (retval == 0); #endif } #ifdef HAVE_KRB5 void ClientAuthentication::sendCredential(ServerLink &serverLink) #else void ClientAuthentication::sendCredential(ServerLink&) #endif // HAVE_KRB5 { if (!authentication) return; #ifdef HAVE_KRB5 assert(context != NULL); assert(cc != NULL); krb5_error_code retval; /* Get credentials for server */ memset((char*)&creds, 0, sizeof(creds)); memcpy(&creds.client, &client, sizeof(client)); memcpy(&creds.server, &server, sizeof(server)); /* Get credentials for server */ if ((retval = krb5_get_credentials(context, KRB5_GC_CACHED, cc, &creds, &new_creds))) err("bzflag:", retval, "getting TGT"); if (!retval) { serverLink.sendKerberosTicket(principalName, &new_creds->ticket); } #endif } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>make the cache file name less platform specific<commit_after>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "ClientAuthentication.h" /* system implementation headers */ #include <string> #include <assert.h> #ifdef HAVE_KRB5 #include <com_err.h> #define err(x,y,z) if (debugLevel >= 1) com_err(x,y,z) #endif #include "DirectoryNames.h" #ifdef HAVE_KRB5 krb5_context ClientAuthentication::context = NULL; krb5_ccache ClientAuthentication::cc = NULL; krb5_auth_context ClientAuthentication::auth_context = NULL; krb5_data ClientAuthentication::packet; krb5_data ClientAuthentication::inbuf; krb5_creds ClientAuthentication::creds; krb5_creds *ClientAuthentication::new_creds; krb5_principal ClientAuthentication::client; krb5_principal ClientAuthentication::server; char ClientAuthentication::principalName[128]; #endif bool ClientAuthentication::authentication = false; #ifdef HAVE_KRB5 void ClientAuthentication::init(const char *username, const char *password) #else void ClientAuthentication::init(const char *username, const char *) #endif // HAVE_KRB5 { strncpy(principalName, username, 128); principalName[127] = 0; #ifdef HAVE_KRB5 assert(context == NULL); assert(cc == NULL); krb5_error_code retval; krb5_creds my_creds; // Initializing kerberos library if ((retval = krb5_init_context(&context))) err("bzflag:", retval, "while initializing krb5"); // Getting a default cache specifically for bzflag std::string ccfile = "FILE:" + getConfigDirName() + "krb5_cc"; if (context && (retval = krb5_cc_set_default_name(context, ccfile.c_str()))) err("bzflag", retval, "setting default cache"); // Getting credential cache if (!retval && (retval = krb5_cc_default(context, &cc))) err("bzflag:", retval, "getting credentials cache"); char clientName[139]; snprintf(clientName, 139, "%[email protected]", username); if (cc && (retval = krb5_parse_name(context, clientName, &client))) err("bzflag", retval, "parsing principal name"); // Initing credential cache if (!retval && (retval = krb5_cc_initialize(context, cc, client))) err("bzflag", retval, "initializing credential cache"); char intPassword[128]; strncpy(intPassword, password, 128); intPassword[127] = 0; // Get credentials for server if (!retval && (retval = krb5_get_init_creds_password(context, &my_creds, client, intPassword, krb5_prompter_posix, NULL, 0, NULL, NULL))) err("bzflag", retval, "getting credential"); // Store credentials in cache if (!retval && (retval = krb5_cc_store_cred(context, cc, &my_creds))) err("bzflag", retval, "storing credential in cache"); if (!retval && (retval = krb5_parse_name(context, "krbtgt/[email protected]", &server))) err("bzflag:", retval, "setting up tgt server name"); authentication = (retval == 0); #endif } #ifdef HAVE_KRB5 void ClientAuthentication::sendCredential(ServerLink &serverLink) #else void ClientAuthentication::sendCredential(ServerLink&) #endif // HAVE_KRB5 { if (!authentication) return; #ifdef HAVE_KRB5 assert(context != NULL); assert(cc != NULL); krb5_error_code retval; /* Get credentials for server */ memset((char*)&creds, 0, sizeof(creds)); memcpy(&creds.client, &client, sizeof(client)); memcpy(&creds.server, &server, sizeof(server)); /* Get credentials for server */ if ((retval = krb5_get_credentials(context, KRB5_GC_CACHED, cc, &creds, &new_creds))) err("bzflag:", retval, "getting TGT"); if (!retval) { serverLink.sendKerberosTicket(principalName, &new_creds->ticket); } #endif } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ // ok is an experimental test harness, maybe to replace DM. Key features: // * work is balanced across separate processes for stability and isolation; // * ok is entirely opt-in. No more maintaining huge --blacklists. #include "SkGraphics.h" #include "ok.h" #include <chrono> #include <future> #include <list> #include <stdio.h> #include <stdlib.h> #include <thread> #include <vector> #if !defined(__has_include) #define __has_include(x) 0 #endif static thread_local const char* tls_currently_running = ""; #if __has_include(<execinfo.h>) && __has_include(<fcntl.h>) && __has_include(<signal.h>) #include <execinfo.h> #include <fcntl.h> #include <signal.h> static int log_fd = 2/*stderr*/; static void log(const char* msg) { write(log_fd, msg, strlen(msg)); } static void setup_crash_handler() { static void (*original_handlers[32])(int); for (int sig : std::vector<int>{ SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV }) { original_handlers[sig] = signal(sig, [](int sig) { lockf(log_fd, F_LOCK, 0); log("\ncaught signal "); switch (sig) { #define CASE(s) case s: log(#s); break CASE(SIGABRT); CASE(SIGBUS); CASE(SIGFPE); CASE(SIGILL); CASE(SIGSEGV); #undef CASE } log(" while running '"); log(tls_currently_running); log("'\n"); void* stack[128]; int frames = backtrace(stack, sizeof(stack)/sizeof(*stack)); backtrace_symbols_fd(stack, frames, log_fd); lockf(log_fd, F_ULOCK, 0); signal(sig, original_handlers[sig]); raise(sig); }); } } static void defer_logging() { log_fd = fileno(tmpfile()); atexit([] { lseek(log_fd, 0, SEEK_SET); char buf[1024]; while (size_t bytes = read(log_fd, buf, sizeof(buf))) { write(2, buf, bytes); } }); } void ok_log(const char* msg) { lockf(log_fd, F_LOCK, 0); log("["); log(tls_currently_running); log("]\t"); log(msg); log("\n"); lockf(log_fd, F_ULOCK, 0); } #else static void setup_crash_handler() {} static void defer_logging() {} void ok_log(const char* msg) { fprintf(stderr, "%s\n", msg); } #endif struct Engine { virtual ~Engine() {} virtual bool spawn(std::function<Status(void)>) = 0; virtual Status wait_one() = 0; }; struct SerialEngine : Engine { Status last = Status::None; bool spawn(std::function<Status(void)> fn) override { last = fn(); return true; } Status wait_one() override { Status s = last; last = Status::None; return s; } }; struct ThreadEngine : Engine { std::list<std::future<Status>> live; bool spawn(std::function<Status(void)> fn) override { live.push_back(std::async(std::launch::async, fn)); return true; } Status wait_one() override { if (live.empty()) { return Status::None; } for (;;) { for (auto it = live.begin(); it != live.end(); it++) { if (it->wait_for(std::chrono::seconds::zero()) == std::future_status::ready) { Status s = it->get(); live.erase(it); return s; } } } } }; #if defined(_MSC_VER) using ForkEngine = ThreadEngine; #else #include <sys/wait.h> #include <unistd.h> struct ForkEngine : Engine { bool spawn(std::function<Status(void)> fn) override { switch (fork()) { case 0: _exit((int)fn()); case -1: return false; default: return true; } } Status wait_one() override { do { int status; if (wait(&status) > 0) { return WIFEXITED(status) ? (Status)WEXITSTATUS(status) : Status::Crashed; } } while (errno == EINTR); return Status::None; } }; #endif struct StreamType { const char *name, *help; std::unique_ptr<Stream> (*factory)(Options); }; static std::vector<StreamType> stream_types; struct DstType { const char *name, *help; std::unique_ptr<Dst> (*factory)(Options); }; static std::vector<DstType> dst_types; struct ViaType { const char *name, *help; std::unique_ptr<Dst> (*factory)(Options, std::unique_ptr<Dst>); }; static std::vector<ViaType> via_types; template <typename T> static std::string help_for(std::vector<T> registered) { std::string help; for (auto r : registered) { help += "\n "; help += r.name; help += ": "; help += r.help; } return help; } int main(int argc, char** argv) { SkGraphics::Init(); setup_crash_handler(); int jobs{1}; std::unique_ptr<Stream> stream; std::function<std::unique_ptr<Dst>(void)> dst_factory = []{ // A default Dst that's enough for unit tests and not much else. struct : Dst { Status draw(Src* src) override { return src->draw(nullptr); } sk_sp<SkImage> image() override { return nullptr; } } dst; return move_unique(dst); }; auto help = [&] { std::string stream_help = help_for(stream_types), dst_help = help_for( dst_types), via_help = help_for( via_types); printf("%s [-j N] [-m regex] [-s regex] [-w dir] [-h] \n" " src[:k=v,...] dst[:k=v,...] [via[:k=v,...] ...] \n" " -j: Run at most N processes at any time. \n" " If <0, use -N threads instead. \n" " If 0, use one thread in one process. \n" " If 1 (default) or -1, auto-detect N. \n" " -h: Print this message and exit. \n" " src: content to draw%s \n" " dst: how to draw that content%s \n" " via: wrappers around dst%s \n" " Most srcs, dsts and vias have options, e.g. skp:dir=skps sw:ct=565 \n", argv[0], stream_help.c_str(), dst_help.c_str(), via_help.c_str()); return 1; }; for (int i = 1; i < argc; i++) { if (0 == strcmp("-j", argv[i])) { jobs = atoi(argv[++i]); } if (0 == strcmp("-h", argv[i])) { return help(); } for (auto s : stream_types) { size_t len = strlen(s.name); if (0 == strncmp(s.name, argv[i], len)) { switch (argv[i][len]) { case ':': len++; case '\0': stream = s.factory(Options{argv[i]+len}); } } } for (auto d : dst_types) { size_t len = strlen(d.name); if (0 == strncmp(d.name, argv[i], len)) { switch (argv[i][len]) { case ':': len++; case '\0': dst_factory = [=]{ return d.factory(Options{argv[i]+len}); }; } } } for (auto v : via_types) { size_t len = strlen(v.name); if (0 == strncmp(v.name, argv[i], len)) { if (!dst_factory) { return help(); } switch (argv[i][len]) { case ':': len++; case '\0': dst_factory = [=]{ return v.factory(Options{argv[i]+len}, dst_factory()); }; } } } } if (!stream) { return help(); } std::unique_ptr<Engine> engine; if (jobs == 0) { engine.reset(new SerialEngine); } if (jobs > 0) { engine.reset(new ForkEngine); defer_logging(); } if (jobs < 0) { engine.reset(new ThreadEngine); jobs = -jobs; } if (jobs == 1) { jobs = std::thread::hardware_concurrency(); } int ok = 0, failed = 0, crashed = 0, skipped = 0; auto update_stats = [&](Status s) { switch (s) { case Status::OK: ok++; break; case Status::Failed: failed++; break; case Status::Crashed: crashed++; break; case Status::Skipped: skipped++; break; case Status::None: return; } const char* leader = "\r"; auto print = [&](int count, const char* label) { if (count) { printf("%s%d %s", leader, count, label); leader = ", "; } }; print(ok, "ok"); print(failed, "failed"); print(crashed, "crashed"); print(skipped, "skipped"); fflush(stdout); }; auto spawn = [&](std::function<Status(void)> fn) { if (--jobs < 0) { update_stats(engine->wait_one()); } while (!engine->spawn(fn)) { update_stats(engine->wait_one()); } }; for (std::unique_ptr<Src> owned = stream->next(); owned; owned = stream->next()) { Src* raw = owned.release(); // Can't move std::unique_ptr into a lambda in C++11. :( spawn([=] { std::unique_ptr<Src> src{raw}; std::string name = src->name(); tls_currently_running = name.c_str(); return dst_factory()->draw(src.get()); }); } for (Status s = Status::OK; s != Status::None; ) { s = engine->wait_one(); update_stats(s); } printf("\n"); return (failed || crashed) ? 1 : 0; } Register::Register(const char* name, const char* help, std::unique_ptr<Stream> (*factory)(Options)) { stream_types.push_back(StreamType{name, help, factory}); } Register::Register(const char* name, const char* help, std::unique_ptr<Dst> (*factory)(Options)) { dst_types.push_back(DstType{name, help, factory}); } Register::Register(const char* name, const char* help, std::unique_ptr<Dst> (*factory)(Options, std::unique_ptr<Dst>)) { via_types.push_back(ViaType{name, help, factory}); } Options::Options(std::string str) { std::string k,v, *curr = &k; for (auto c : str) { switch(c) { case ',': (*this)[k] = v; curr = &(k = ""); break; case '=': curr = &(v = ""); break; default: *curr += c; } } (*this)[k] = v; } std::string& Options::operator[](std::string k) { return this->kv[k]; } std::string Options::operator()(std::string k, std::string fallback) const { for (auto it = kv.find(k); it != kv.end(); ) { return it->second; } return fallback; } <commit_msg>tidy up ok help<commit_after>/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ // ok is an experimental test harness, maybe to replace DM. Key features: // * work is balanced across separate processes for stability and isolation; // * ok is entirely opt-in. No more maintaining huge --blacklists. #include "SkGraphics.h" #include "ok.h" #include <chrono> #include <future> #include <list> #include <stdio.h> #include <stdlib.h> #include <thread> #include <vector> #if !defined(__has_include) #define __has_include(x) 0 #endif static thread_local const char* tls_currently_running = ""; #if __has_include(<execinfo.h>) && __has_include(<fcntl.h>) && __has_include(<signal.h>) #include <execinfo.h> #include <fcntl.h> #include <signal.h> static int log_fd = 2/*stderr*/; static void log(const char* msg) { write(log_fd, msg, strlen(msg)); } static void setup_crash_handler() { static void (*original_handlers[32])(int); for (int sig : std::vector<int>{ SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV }) { original_handlers[sig] = signal(sig, [](int sig) { lockf(log_fd, F_LOCK, 0); log("\ncaught signal "); switch (sig) { #define CASE(s) case s: log(#s); break CASE(SIGABRT); CASE(SIGBUS); CASE(SIGFPE); CASE(SIGILL); CASE(SIGSEGV); #undef CASE } log(" while running '"); log(tls_currently_running); log("'\n"); void* stack[128]; int frames = backtrace(stack, sizeof(stack)/sizeof(*stack)); backtrace_symbols_fd(stack, frames, log_fd); lockf(log_fd, F_ULOCK, 0); signal(sig, original_handlers[sig]); raise(sig); }); } } static void defer_logging() { log_fd = fileno(tmpfile()); atexit([] { lseek(log_fd, 0, SEEK_SET); char buf[1024]; while (size_t bytes = read(log_fd, buf, sizeof(buf))) { write(2, buf, bytes); } }); } void ok_log(const char* msg) { lockf(log_fd, F_LOCK, 0); log("["); log(tls_currently_running); log("]\t"); log(msg); log("\n"); lockf(log_fd, F_ULOCK, 0); } #else static void setup_crash_handler() {} static void defer_logging() {} void ok_log(const char* msg) { fprintf(stderr, "%s\n", msg); } #endif struct Engine { virtual ~Engine() {} virtual bool spawn(std::function<Status(void)>) = 0; virtual Status wait_one() = 0; }; struct SerialEngine : Engine { Status last = Status::None; bool spawn(std::function<Status(void)> fn) override { last = fn(); return true; } Status wait_one() override { Status s = last; last = Status::None; return s; } }; struct ThreadEngine : Engine { std::list<std::future<Status>> live; bool spawn(std::function<Status(void)> fn) override { live.push_back(std::async(std::launch::async, fn)); return true; } Status wait_one() override { if (live.empty()) { return Status::None; } for (;;) { for (auto it = live.begin(); it != live.end(); it++) { if (it->wait_for(std::chrono::seconds::zero()) == std::future_status::ready) { Status s = it->get(); live.erase(it); return s; } } } } }; #if defined(_MSC_VER) using ForkEngine = ThreadEngine; #else #include <sys/wait.h> #include <unistd.h> struct ForkEngine : Engine { bool spawn(std::function<Status(void)> fn) override { switch (fork()) { case 0: _exit((int)fn()); case -1: return false; default: return true; } } Status wait_one() override { do { int status; if (wait(&status) > 0) { return WIFEXITED(status) ? (Status)WEXITSTATUS(status) : Status::Crashed; } } while (errno == EINTR); return Status::None; } }; #endif struct StreamType { const char *name, *help; std::unique_ptr<Stream> (*factory)(Options); }; static std::vector<StreamType> stream_types; struct DstType { const char *name, *help; std::unique_ptr<Dst> (*factory)(Options); }; static std::vector<DstType> dst_types; struct ViaType { const char *name, *help; std::unique_ptr<Dst> (*factory)(Options, std::unique_ptr<Dst>); }; static std::vector<ViaType> via_types; template <typename T> static std::string help_for(std::vector<T> registered) { std::string help; for (auto r : registered) { help += "\n "; help += r.name; help += ": "; help += r.help; } return help; } int main(int argc, char** argv) { SkGraphics::Init(); setup_crash_handler(); int jobs{1}; std::unique_ptr<Stream> stream; std::function<std::unique_ptr<Dst>(void)> dst_factory = []{ // A default Dst that's enough for unit tests and not much else. struct : Dst { Status draw(Src* src) override { return src->draw(nullptr); } sk_sp<SkImage> image() override { return nullptr; } } dst; return move_unique(dst); }; auto help = [&] { std::string stream_help = help_for(stream_types), dst_help = help_for( dst_types), via_help = help_for( via_types); printf("%s [-j N] src[:k=v,...] dst[:k=v,...] [via[:k=v,...] ...] \n" " -j: Run at most N processes at any time. \n" " If <0, use -N threads instead. \n" " If 0, use one thread in one process. \n" " If 1 (default) or -1, auto-detect N. \n" " src: content to draw%s \n" " dst: how to draw that content%s \n" " via: wrappers around dst%s \n" " Most srcs, dsts and vias have options, e.g. skp:dir=skps sw:ct=565 \n", argv[0], stream_help.c_str(), dst_help.c_str(), via_help.c_str()); return 1; }; for (int i = 1; i < argc; i++) { if (0 == strcmp("-j", argv[i])) { jobs = atoi(argv[++i]); } if (0 == strcmp("-h", argv[i])) { return help(); } if (0 == strcmp("--help", argv[i])) { return help(); } for (auto s : stream_types) { size_t len = strlen(s.name); if (0 == strncmp(s.name, argv[i], len)) { switch (argv[i][len]) { case ':': len++; case '\0': stream = s.factory(Options{argv[i]+len}); } } } for (auto d : dst_types) { size_t len = strlen(d.name); if (0 == strncmp(d.name, argv[i], len)) { switch (argv[i][len]) { case ':': len++; case '\0': dst_factory = [=]{ return d.factory(Options{argv[i]+len}); }; } } } for (auto v : via_types) { size_t len = strlen(v.name); if (0 == strncmp(v.name, argv[i], len)) { if (!dst_factory) { return help(); } switch (argv[i][len]) { case ':': len++; case '\0': dst_factory = [=]{ return v.factory(Options{argv[i]+len}, dst_factory()); }; } } } } if (!stream) { return help(); } std::unique_ptr<Engine> engine; if (jobs == 0) { engine.reset(new SerialEngine); } if (jobs > 0) { engine.reset(new ForkEngine); defer_logging(); } if (jobs < 0) { engine.reset(new ThreadEngine); jobs = -jobs; } if (jobs == 1) { jobs = std::thread::hardware_concurrency(); } int ok = 0, failed = 0, crashed = 0, skipped = 0; auto update_stats = [&](Status s) { switch (s) { case Status::OK: ok++; break; case Status::Failed: failed++; break; case Status::Crashed: crashed++; break; case Status::Skipped: skipped++; break; case Status::None: return; } const char* leader = "\r"; auto print = [&](int count, const char* label) { if (count) { printf("%s%d %s", leader, count, label); leader = ", "; } }; print(ok, "ok"); print(failed, "failed"); print(crashed, "crashed"); print(skipped, "skipped"); fflush(stdout); }; auto spawn = [&](std::function<Status(void)> fn) { if (--jobs < 0) { update_stats(engine->wait_one()); } while (!engine->spawn(fn)) { update_stats(engine->wait_one()); } }; for (std::unique_ptr<Src> owned = stream->next(); owned; owned = stream->next()) { Src* raw = owned.release(); // Can't move std::unique_ptr into a lambda in C++11. :( spawn([=] { std::unique_ptr<Src> src{raw}; std::string name = src->name(); tls_currently_running = name.c_str(); return dst_factory()->draw(src.get()); }); } for (Status s = Status::OK; s != Status::None; ) { s = engine->wait_one(); update_stats(s); } printf("\n"); return (failed || crashed) ? 1 : 0; } Register::Register(const char* name, const char* help, std::unique_ptr<Stream> (*factory)(Options)) { stream_types.push_back(StreamType{name, help, factory}); } Register::Register(const char* name, const char* help, std::unique_ptr<Dst> (*factory)(Options)) { dst_types.push_back(DstType{name, help, factory}); } Register::Register(const char* name, const char* help, std::unique_ptr<Dst> (*factory)(Options, std::unique_ptr<Dst>)) { via_types.push_back(ViaType{name, help, factory}); } Options::Options(std::string str) { std::string k,v, *curr = &k; for (auto c : str) { switch(c) { case ',': (*this)[k] = v; curr = &(k = ""); break; case '=': curr = &(v = ""); break; default: *curr += c; } } (*this)[k] = v; } std::string& Options::operator[](std::string k) { return this->kv[k]; } std::string Options::operator()(std::string k, std::string fallback) const { for (auto it = kv.find(k); it != kv.end(); ) { return it->second; } return fallback; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/eff_config/timing.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include <fapi2.H> #include <mss.H> #include <lib/utils/find.H> #include <lib/eff_config/timing.H> namespace mss { // Proposed DDR4 Full spec update(79-4B) // Item No. 1716.78C // pg.46 // Table 24 - tREFI and tRFC parameters (in ps) constexpr uint64_t TREFI_BASE = 7800000; // Proposed DDR4 3DS Addendum // Item No. 1727.58A // pg. 69 - 71 // Table 42 - Refresh parameters by logical rank density static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR1 = { // { density in GBs, tRFC4(min) in picoseconds } {4, 90000}, {8, 120000}, // 16Gb - TBD }; // Proposed DDR4 3DS Addendum // Item No. 1727.58A // pg. 69 - 71 // Table 42 - Refresh parameters by logical rank density static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR2 = { // { density in GBs, tRFC4(min) in picoseconds } {4, 55000}, {8, 90000} // 16Gb - TBD }; // Proposed DDR4 3DS Addendum // Item No. 1727.58A // pg. 69 - 71 // Table 42 - Refresh parameters by logical rank density static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR4 = { // { density in GBs, tRFC4(min) in picoseconds } {4, 40000}, {8, 55000} // 16Gb - TBD }; /// @brief Calculates refresh interval time /// @param[in] i_mode fine refresh rate mode /// @param[in] i_temp_refresh_range temperature refresh range /// @param[out] o_value timing val in ps /// @return fapi2::ReturnCode /// fapi2::ReturnCode calc_trefi( const refresh_rate i_mode, const uint8_t i_temp_refresh_range, uint64_t& o_timing ) { uint64_t l_multiplier = 0; switch(i_temp_refresh_range) { case fapi2::ENUM_ATTR_MSS_MRW_TEMP_REFRESH_RANGE_NORMAL: l_multiplier = temp_mode::NORMAL; break; case fapi2::ENUM_ATTR_MSS_MRW_TEMP_REFRESH_RANGE_EXTEND: l_multiplier = temp_mode::EXTENDED; break; default: // Temperature Refresh Range will be a platform attribute set by the MRW, // which they "shouldn't" mess up as long as use "attribute" enums. // if someone messes this up we can at least catch it FAPI_ERR( "Incorrect Temperature Ref. Range received: %d ", i_temp_refresh_range); return fapi2::FAPI2_RC_INVALID_PARAMETER; break; } const uint64_t l_quotient = TREFI_BASE / ( uint64_t(i_mode) * l_multiplier ); const uint64_t l_remainder = TREFI_BASE % ( uint64_t(i_mode) * l_multiplier ); o_timing = l_quotient + (l_remainder == 0 ? 0 : 1); FAPI_INF( "tREFI: %d, quotient: %d, remainder: %d, tREFI_base: %d", o_timing, l_quotient, l_remainder, TREFI_BASE ); return fapi2::FAPI2_RC_SUCCESS; } }// mss <commit_msg>Remove eff_config hardcoded values, mirroring, trfc_dlr, & modify ut's<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/eff_config/timing.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include <fapi2.H> #include <mss.H> #include <lib/utils/find.H> #include <lib/eff_config/timing.H> namespace mss { // Proposed DDR4 Full spec update(79-4B) // Item No. 1716.78C // pg.46 // Table 24 - tREFI and tRFC parameters (in ps) constexpr uint64_t TREFI_BASE = 7800000; // Proposed DDR4 3DS Addendum // Item No. 1727.58A // pg. 69 - 71 // Table 42 - Refresh parameters by logical rank density static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR1 = { // { density in GBs, tRFC4(min) in picoseconds } {4, 90000}, {8, 120000}, // 16Gb - TBD }; // Proposed DDR4 3DS Addendum // Item No. 1727.58A // pg. 69 - 71 // Table 42 - Refresh parameters by logical rank density static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR2 = { // { density in GBs, tRFC4(min) in picoseconds } {4, 55000}, {8, 90000} // 16Gb - TBD }; // Proposed DDR4 3DS Addendum // Item No. 1727.58A // pg. 69 - 71 // Table 42 - Refresh parameters by logical rank density static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR4 = { // { density in GBs, tRFC4(min) in picoseconds } {4, 40000}, {8, 55000} // 16Gb - TBD }; /// @brief Calculates refresh interval time /// @param[in] i_mode fine refresh rate mode /// @param[in] i_temp_refresh_range temperature refresh range /// @param[out] o_value timing val in ps /// @return fapi2::ReturnCode /// fapi2::ReturnCode calc_trefi( const refresh_rate i_mode, const uint8_t i_temp_refresh_range, uint64_t& o_timing ) { uint64_t l_multiplier = 0; switch(i_temp_refresh_range) { case fapi2::ENUM_ATTR_MSS_MRW_TEMP_REFRESH_RANGE_NORMAL: l_multiplier = temp_mode::NORMAL; break; case fapi2::ENUM_ATTR_MSS_MRW_TEMP_REFRESH_RANGE_EXTEND: l_multiplier = temp_mode::EXTENDED; break; default: // Temperature Refresh Range will be a platform attribute set by the MRW, // which they "shouldn't" mess up as long as use "attribute" enums. // if someone messes this up we can at least catch it FAPI_ERR( "Incorrect Temperature Ref. Range received: %d ", i_temp_refresh_range); return fapi2::FAPI2_RC_INVALID_PARAMETER; break; } const uint64_t l_quotient = TREFI_BASE / ( uint64_t(i_mode) * l_multiplier ); const uint64_t l_remainder = TREFI_BASE % ( uint64_t(i_mode) * l_multiplier ); o_timing = l_quotient + (l_remainder == 0 ? 0 : 1); FAPI_INF( "tREFI: %d, quotient: %d, remainder: %d, tREFI_base: %d", o_timing, l_quotient, l_remainder, TREFI_BASE ); return fapi2::FAPI2_RC_SUCCESS; } /// @brief Calculates Minimum Refresh Recovery Delay Time (different logical rank) /// @param[in] i_mode fine refresh rate mode /// @param[in] i_density SDRAM density /// @param[out] o_trfc_in_ps timing val in ps /// @return fapi2::FAPI2_RC_SUCCESS iff okay /// fapi2::ReturnCode calc_trfc_dlr(const uint8_t i_refresh_mode, const uint8_t i_density, uint64_t& o_trfc_in_ps) { bool l_is_val_found = 0; // Selects appropriate tRFC based on fine refresh mode switch(i_refresh_mode) { case fapi2::ENUM_ATTR_MSS_MRW_FINE_REFRESH_MODE_NORMAL: l_is_val_found = find_value_from_key(TRFC_DLR1, i_density, o_trfc_in_ps); break; case fapi2::ENUM_ATTR_MSS_MRW_FINE_REFRESH_MODE_FIXED_2X: case fapi2::ENUM_ATTR_MSS_MRW_FINE_REFRESH_MODE_FLY_2X: l_is_val_found = find_value_from_key(TRFC_DLR2, i_density, o_trfc_in_ps); break; case fapi2::ENUM_ATTR_MSS_MRW_FINE_REFRESH_MODE_FIXED_4X: case fapi2::ENUM_ATTR_MSS_MRW_FINE_REFRESH_MODE_FLY_4X: l_is_val_found = find_value_from_key(TRFC_DLR4, i_density, o_trfc_in_ps); break; default: // Fine Refresh Mode will be a platform attribute set by the MRW, // which they "shouldn't" mess up as long as use "attribute" enums. // if openpower messes this up we can at least catch it FAPI_ERR( "Incorrect Fine Refresh Mode received: %d ", i_refresh_mode); return fapi2::FAPI2_RC_INVALID_PARAMETER; break; }// switch if(l_is_val_found) { return fapi2::FAPI2_RC_SUCCESS; } FAPI_ERR("Unable to find tRFC (ps) from map with SDRAM density key %d", i_density); return fapi2::FAPI2_RC_FALSE; } }// mss <|endoftext|>
<commit_before>/* Resembla: Word-based Japanese similar sentence search library https://github.com/tuem/resembla Copyright 2017 Takashi Uemura 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 __RESEMBLA_REGRESSION_HPP__ #define __RESEMBLA_REGRESSION_HPP__ #include <string> #include <vector> #include <memory> #include <unordered_map> #include <fstream> #include <resembla/resembla_interface.hpp> #include <resembla/reranker.hpp> namespace resembla { template<class Preprocessor, class ScoreFunction> class ResemblaRegression: public ResemblaInterface { public: ResemblaRegression(size_t max_candidate, std::shared_ptr<Preprocessor> preprocess, std::shared_ptr<ScoreFunction> score_func, std::string corpus_path = "", size_t col = 2): max_candidate(max_candidate), preprocess(preprocess), score_func(score_func), reranker(), preprocess_corpus(!corpus_path.empty()) { if(preprocess_corpus){ loadCorpusFeatures(corpus_path, col); } } void append(const std::string name, const std::shared_ptr<ResemblaInterface> resembla, bool is_primary) { resemblas[name] = resembla; if(is_primary){ primary_resembla_name = name; } } std::vector<response_type> getSimilarTexts(const string_type& input, size_t max_response, double threshold) { std::vector<string_type> candidate_texts; std::unordered_map<string_type, StringFeatureMap> aggregated; // primary resembla auto initial_results = resemblas[primary_resembla_name]->getSimilarTexts(input, max_candidate, threshold); for(auto c: initial_results){ candidate_texts.push_back(c.text); aggregated[c.text] = preprocess_corpus ? corpus_features[c.text] : ((*preprocess)(c.text)); aggregated[c.text][primary_resembla_name] = Feature::toText(c.score); } // other resemblas for(auto p: resemblas){ if(p.first == primary_resembla_name){ continue; } for(auto r: p.second->getSimilarTexts(input, candidate_texts)){ if(aggregated.find(r.text) == aggregated.end()){ aggregated[r.text] = preprocess_corpus ? corpus_features[r.text] : ((*preprocess)(r.text)); } aggregated[r.text][p.first] = Feature::toText(r.score); } } std::vector<std::pair<string_type, StringFeatureMap>> candidates; for(auto a: aggregated){ candidates.push_back(std::make_pair(a.first, a.second)); } // rerank by its own metric std::pair<string_type, StringFeatureMap> input_data = std::make_pair(input, (*preprocess)(input)); auto reranked = reranker.rerank(input_data, std::begin(candidates), std::end(candidates), *score_func); std::vector<ResemblaInterface::response_type> results; for(const auto& r: reranked){ if(r.second < threshold || results.size() >= max_response){ break; } results.push_back({r.first, score_func->name, r.second}); } return results; } std::vector<response_type> getSimilarTexts(const string_type& query, const std::vector<string_type>& targets) { return resemblas[primary_resembla_name]->getSimilarTexts(query, targets); /*TODO std::vector<WorkData> candidates; auto original_results = resembla->getSimilarTexts(query, targets); for(const auto& r: original_results){ candidates.push_back(std::make_pair(r.text, (*preprocess)(r, preprocess_corpus ? corpus_features[r.text] : decltype((*preprocess)(r.text))()))); } // rerank by its own metric WorkData query_data = std::make_pair(query, (*preprocess)(query)); auto reranked = reranker.rerank(query_data, std::begin(candidates), std::end(candidates), *score_func); std::vector<ResemblaInterface::response_type> results; for(const auto& r: reranked){ results.push_back({r.first, score_func->name, r.second}); } return results; */ } protected: struct WorkData { string_type text; typename Preprocessor::return_type features; }; //using WorkData = std::pair<string_type, typename Preprocessor::return_type>; std::unordered_map<std::string, std::shared_ptr<ResemblaInterface>> resemblas; //const std::shared_ptr<ResemblaInterface> resembla; std::string primary_resembla_name; const size_t max_candidate; const std::shared_ptr<Preprocessor> preprocess; const std::shared_ptr<ScoreFunction> score_func; const Reranker<string_type> reranker; const bool preprocess_corpus; std::unordered_map<string_type, typename Preprocessor::return_type> corpus_features; void loadCorpusFeatures(const std::string& corpus_path, size_t col) { std::ifstream ifs(corpus_path); if(ifs.fail()){ throw std::runtime_error("input file is not available: " + corpus_path); } while(ifs.good()){ std::string line; std::getline(ifs, line); if(ifs.eof() || line.length() == 0){ break; } auto columns = split(line, '\t'); if(columns.size() + 1 < col){ continue; } corpus_features[cast_string<string_type>(columns[0])] = (*preprocess)(columns[0], columns[1]); } } }; } #endif <commit_msg>remove unused variable<commit_after>/* Resembla: Word-based Japanese similar sentence search library https://github.com/tuem/resembla Copyright 2017 Takashi Uemura 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 __RESEMBLA_REGRESSION_HPP__ #define __RESEMBLA_REGRESSION_HPP__ #include <string> #include <vector> #include <memory> #include <unordered_map> #include <fstream> #include <resembla/resembla_interface.hpp> #include <resembla/reranker.hpp> namespace resembla { template<class Preprocessor, class ScoreFunction> class ResemblaRegression: public ResemblaInterface { public: ResemblaRegression(size_t max_candidate, std::shared_ptr<Preprocessor> preprocess, std::shared_ptr<ScoreFunction> score_func, std::string corpus_path = "", size_t col = 2): max_candidate(max_candidate), preprocess(preprocess), score_func(score_func), reranker(), preprocess_corpus(!corpus_path.empty()) { if(preprocess_corpus){ loadCorpusFeatures(corpus_path, col); } } void append(const std::string name, const std::shared_ptr<ResemblaInterface> resembla, bool is_primary) { resemblas[name] = resembla; if(is_primary){ primary_resembla_name = name; } } std::vector<response_type> getSimilarTexts(const string_type& input, size_t max_response, double threshold) { std::vector<string_type> candidate_texts; std::unordered_map<string_type, StringFeatureMap> aggregated; // primary resembla auto initial_results = resemblas[primary_resembla_name]->getSimilarTexts(input, max_candidate, threshold); for(auto c: initial_results){ candidate_texts.push_back(c.text); aggregated[c.text] = preprocess_corpus ? corpus_features[c.text] : ((*preprocess)(c.text)); aggregated[c.text][primary_resembla_name] = Feature::toText(c.score); } // other resemblas for(auto p: resemblas){ if(p.first == primary_resembla_name){ continue; } for(auto r: p.second->getSimilarTexts(input, candidate_texts)){ if(aggregated.find(r.text) == aggregated.end()){ aggregated[r.text] = preprocess_corpus ? corpus_features[r.text] : ((*preprocess)(r.text)); } aggregated[r.text][p.first] = Feature::toText(r.score); } } std::vector<std::pair<string_type, StringFeatureMap>> candidates; for(auto a: aggregated){ candidates.push_back(std::make_pair(a.first, a.second)); } // rerank by its own metric std::pair<string_type, StringFeatureMap> input_data = std::make_pair(input, (*preprocess)(input)); auto reranked = reranker.rerank(input_data, std::begin(candidates), std::end(candidates), *score_func); std::vector<ResemblaInterface::response_type> results; for(const auto& r: reranked){ if(r.second < threshold || results.size() >= max_response){ break; } results.push_back({r.first, score_func->name, r.second}); } return results; } std::vector<response_type> getSimilarTexts(const string_type& query, const std::vector<string_type>& targets) { return resemblas[primary_resembla_name]->getSimilarTexts(query, targets); /*TODO std::vector<WorkData> candidates; auto original_results = resembla->getSimilarTexts(query, targets); for(const auto& r: original_results){ candidates.push_back(std::make_pair(r.text, (*preprocess)(r, preprocess_corpus ? corpus_features[r.text] : decltype((*preprocess)(r.text))()))); } // rerank by its own metric WorkData query_data = std::make_pair(query, (*preprocess)(query)); auto reranked = reranker.rerank(query_data, std::begin(candidates), std::end(candidates), *score_func); std::vector<ResemblaInterface::response_type> results; for(const auto& r: reranked){ results.push_back({r.first, score_func->name, r.second}); } return results; */ } protected: using WorkData = std::pair<string_type, typename Preprocessor::return_type>; std::unordered_map<std::string, std::shared_ptr<ResemblaInterface>> resemblas; std::string primary_resembla_name; const size_t max_candidate; const std::shared_ptr<Preprocessor> preprocess; const std::shared_ptr<ScoreFunction> score_func; const Reranker<string_type> reranker; const bool preprocess_corpus; std::unordered_map<string_type, typename Preprocessor::return_type> corpus_features; void loadCorpusFeatures(const std::string& corpus_path, size_t col) { std::ifstream ifs(corpus_path); if(ifs.fail()){ throw std::runtime_error("input file is not available: " + corpus_path); } while(ifs.good()){ std::string line; std::getline(ifs, line); if(ifs.eof() || line.length() == 0){ break; } auto columns = split(line, '\t'); if(columns.size() + 1 < col){ continue; } corpus_features[cast_string<string_type>(columns[0])] = (*preprocess)(columns[0], columns[1]); } } }; } #endif <|endoftext|>
<commit_before>/* Demonstration of Modified Nodal Analysis Originally by Antonio Carlos M. de Queiroz ([email protected]) Modified by Dhiana Deva, Felipe de Leo, Silvino Vieira */ /* Elementos aceitos e linhas do netlist: Resistor: R<nome> <no+> <no-> <resistencia> VCCS: G<nome> <io+> <io-> <vi+> <vi-> <transcondutancia> VCVC: E<nome> <vo+> <vo-> <vi+> <vi-> <ganho de tensao> CCCS: F<nome> <io+> <io-> <ii+> <ii-> <ganho de corrente> CCVS: H<nome> <vo+> <vo-> <ii+> <ii-> <transresistencia> Fonte I: I<nome> <io+> <io-> <corrente> Fonte V: V<nome> <vo+> <vo-> <tensao> Amp. op.: O<nome> <vo1> <vo2> <vi1> <vi2> As fontes F e H tem o ramo de entrada em curto O amplificador operacional ideal tem a saida suspensa Os nos podem ser nomes */ #include "matrix/solve.h" #include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <string> #include <vector> #include <cstdlib> #include <cmath> using namespace std; #define DEBUG static const int MAX_LINHA = 80; static const int MAX_NOME = 11; static const int MAX_ELEM = 50; typedef struct elemento { /* Elemento do netlist */ string nome; double valor; int a,b,c,d,x,y; } elemento; /* Rotina que conta os nos e atribui numeros a eles */ inline int numero(const char *nome, int &nv, vector<string> &lista){ int i=0, achou=0; while (!achou && i<=nv) if (!(achou=!lista[i].compare(nome))) i++; if (!achou) { if (nv==MAX_NOS) { cout << "O programa so aceita ate " << nv << " nos" << endl; exit(1); } nv++; lista[nv] = nome; return nv; /* novo no */ } else { return i; /* no ja conhecido */ } } int main(int argc, char **argv){ cout << endl; cout << "Modified Nodal Analysis" << endl; cout << "Originally by Antonio Carlos M. de Queiroz ([email protected])" << endl; cout << "Modified by Dhiana Deva, Felipe de Leo and Silvino Vieira" << endl; cout << endl; ifstream netlistFile; const char *filepath; switch(argc) { case 1: { string input; cout << "Enter path to netlist file: "; cin >> input; filepath = input.c_str(); break; } case 2: { filepath = argv[1]; break; } default: cerr << "FAILURE: Too much information!" << endl; exit(EXIT_FAILURE); } netlistFile.open(filepath, ifstream::in); if(!netlistFile.is_open()){ cerr << "FAILURE: Cannot open file " << filepath << endl; exit(EXIT_FAILURE); } string txt; vector<string> lista(MAX_NOME+2); /*Tem que caber jx antes do nome */ lista[0] = "0"; vector<elemento> netlist(MAX_ELEM); int ne=0, /* Elementos */ nv=0, /* Variaveis */ nn=0; /* Nos */ /* Foram colocados limites nos formatos de leitura para alguma protecao contra excesso de caracteres nestas variaveis */ char tipo, na[MAX_NOME], nb[MAX_NOME], nc[MAX_NOME], nd[MAX_NOME]; double g, Yn[MAX_NOS+1][MAX_NOS+2]; cout << "Lendo netlist:" << endl; getline(netlistFile, txt); cout << "Titulo: " << txt; while (getline(netlistFile, txt)) { ne++; /* Nao usa o netlist[0] */ if (ne>MAX_ELEM) { cout << "O programa so aceita ate " << MAX_ELEM << " elementos" << endl; exit(1); } txt[0]=toupper(txt[0]); tipo=txt[0]; //TODO: verificar necessidade da string txt // ver se eh possivel usar stringstream no getline stringstream txtstream(txt); txtstream >> netlist[ne].nome; //TODO: talvez nao seja preciso usar p string p(txt, netlist[ne].nome.size(), string::npos); txtstream.str(p); /* O que e lido depende do tipo */ if (tipo=='R' || tipo=='I' || tipo=='V') { txtstream >> na >> nb >> netlist[ne].valor; cout << netlist[ne].nome << " " << na << " " << nb << " " << netlist[ne].valor << endl; netlist[ne].a = numero(na, nv, lista); netlist[ne].b = numero(nb, nv, lista); } else if (tipo=='G' || tipo=='E' || tipo=='F' || tipo=='H') { txtstream >> na >> nb >> nc >> nd >> netlist[ne].valor; cout << netlist[ne].nome << " " << na << " " << nb << " " << nc << " " << nd << " "<< netlist[ne].valor << endl; netlist[ne].a = numero(na, nv, lista); netlist[ne].b = numero(nb, nv, lista); netlist[ne].c = numero(nc, nv, lista); netlist[ne].d = numero(nd, nv, lista); } else if (tipo=='O') { txtstream >> na >> nb >> nc >> nd; cout << netlist[ne].nome << " " << na << " " << nb << " " << nc << " " << nd << " " << endl; netlist[ne].a = numero(na, nv, lista); netlist[ne].b = numero(nb, nv, lista); netlist[ne].c = numero(nc, nv, lista); netlist[ne].d = numero(nd, nv, lista); } else if (tipo=='*') { /* Comentario comeca com "*" */ cout << "Comentario: " << txt; ne--; } else { cout << "Elemento desconhecido: " << txt << endl; cin.get(); exit(1); } } netlistFile.close(); /* Acrescenta variaveis de corrente acima dos nos, anotando no netlist */ nn=nv; for (int i=1; i<=ne; i++) { tipo=netlist[i].nome[0]; if (tipo=='V' || tipo=='E' || tipo=='F' || tipo=='O') { nv++; if (nv>MAX_NOS) { cout << "As correntes extra excederam o numero de variaveis permitido (" << MAX_NOS << ")" << endl; exit(1); } lista[nv] = "j"; /* Tem espaco para mais dois caracteres */ lista[nv].append( netlist[i].nome ); netlist[i].x=nv; } else if (tipo=='H') { nv=nv+2; if (nv>MAX_NOS) { cout << "As correntes extra excederam o numero de variaveis permitido (" << MAX_NOS << ")" << endl; exit(1); } lista[nv-1] = "jx"; lista[nv-1].append(netlist[i].nome); netlist[i].x=nv-1; lista[nv] = "jy"; lista[nv].append( netlist[i].nome ); netlist[i].y=nv; } } cin.get(); /* Lista tudo */ cout << "Variaveis internas: " << endl; for (int i=0; i<=nv; i++) cout << i << " -> " << lista[i] << endl; cin.get(); cout << "Netlist interno final" << endl; for (int i=1; i<=ne; i++) { tipo=netlist[i].nome[0]; if (tipo=='R' || tipo=='I' || tipo=='V') { cout << netlist[i].nome << " " << netlist[i].a << " " << netlist[i].b << " " << netlist[i].valor << endl; } else if (tipo=='G' || tipo=='E' || tipo=='F' || tipo=='H') { cout << netlist[i].nome << " " << netlist[i].a << " " << netlist[i].b << " " << netlist[i].c << " " << netlist[i].d << " " << netlist[i].valor << endl; } else if (tipo=='O') { cout << netlist[i].nome << " " << netlist[i].a << " " << netlist[i].b << " " << netlist[i].c << " " << netlist[i].d << endl; } if (tipo=='V' || tipo=='E' || tipo=='F' || tipo=='O') cout << "Corrente jx: " << netlist[i].x << endl; else if (tipo=='H') cout << "Correntes jx e jy: " << netlist[i].x << ", " << netlist[i].y << endl; } cin.get(); /* Monta o sistema nodal modificado */ cout << "O circuito tem " << nn << " nos, " << nv << " variaveis e " << ne << " elementos" << endl; cin.get(); /* Zera sistema */ for (int i=0; i<=nv; i++) { for (int j=0; j<=nv+1; j++) Yn[i][j]=0; } /* Monta estampas */ for (int i=1; i<=ne; i++) { tipo=netlist[i].nome[0]; if (tipo=='R') { g=1/netlist[i].valor; Yn[netlist[i].a][netlist[i].a]+=g; Yn[netlist[i].b][netlist[i].b]+=g; Yn[netlist[i].a][netlist[i].b]-=g; Yn[netlist[i].b][netlist[i].a]-=g; } else if (tipo=='G') { g=netlist[i].valor; Yn[netlist[i].a][netlist[i].c]+=g; Yn[netlist[i].b][netlist[i].d]+=g; Yn[netlist[i].a][netlist[i].d]-=g; Yn[netlist[i].b][netlist[i].c]-=g; } else if (tipo=='I') { g=netlist[i].valor; Yn[netlist[i].a][nv+1]-=g; Yn[netlist[i].b][nv+1]+=g; } else if (tipo=='V') { Yn[netlist[i].a][netlist[i].x]+=1; Yn[netlist[i].b][netlist[i].x]-=1; Yn[netlist[i].x][netlist[i].a]-=1; Yn[netlist[i].x][netlist[i].b]+=1; Yn[netlist[i].x][nv+1]-=netlist[i].valor; } else if (tipo=='E') { g=netlist[i].valor; Yn[netlist[i].a][netlist[i].x]+=1; Yn[netlist[i].b][netlist[i].x]-=1; Yn[netlist[i].x][netlist[i].a]-=1; Yn[netlist[i].x][netlist[i].b]+=1; Yn[netlist[i].x][netlist[i].c]+=g; Yn[netlist[i].x][netlist[i].d]-=g; } else if (tipo=='F') { g=netlist[i].valor; Yn[netlist[i].a][netlist[i].x]+=g; Yn[netlist[i].b][netlist[i].x]-=g; Yn[netlist[i].c][netlist[i].x]+=1; Yn[netlist[i].d][netlist[i].x]-=1; Yn[netlist[i].x][netlist[i].c]-=1; Yn[netlist[i].x][netlist[i].d]+=1; } else if (tipo=='H') { g=netlist[i].valor; Yn[netlist[i].a][netlist[i].y]+=1; Yn[netlist[i].b][netlist[i].y]-=1; Yn[netlist[i].c][netlist[i].x]+=1; Yn[netlist[i].d][netlist[i].x]-=1; Yn[netlist[i].y][netlist[i].a]-=1; Yn[netlist[i].y][netlist[i].b]+=1; Yn[netlist[i].x][netlist[i].c]-=1; Yn[netlist[i].x][netlist[i].d]+=1; Yn[netlist[i].y][netlist[i].x]+=g; } else if (tipo=='O') { Yn[netlist[i].a][netlist[i].x]+=1; Yn[netlist[i].b][netlist[i].x]-=1; Yn[netlist[i].x][netlist[i].c]+=1; Yn[netlist[i].x][netlist[i].d]-=1; } #ifdef DEBUG /* Opcional: Mostra o sistema apos a montagem da estampa */ cout << "Sistema apos a estampa de " << netlist[i].nome << endl; for (int k=1; k<=nv; k++) { for (int j=1; j<=nv+1; j++) if (Yn[k][j]!=0){ cout << setprecision( 1 ) << fixed << setw( 3 ) << showpos; cout << Yn[k][j] << " "; } else cout << " ... "; cout << endl; } cin.get(); #endif } /* Resolve o sistema */ if (solve(nv, Yn)) { cin.get(); exit(0); } #ifdef DEBUG /* Opcional: Mostra o sistema resolvido */ cout << "Sistema resolvido:" << endl; for (int i=1; i<=nv; i++) { for (int j=1; j<=nv+1; j++) if (Yn[i][j]!=0){ cout << setprecision( 1 ) << fixed << setw( 3 ) << showpos; cout << Yn[i][j] << " "; } else cout << " ... "; cout << endl; } cin.get(); #endif /* Mostra solucao */ cout << "Solucao:" << endl; txt = "Tensao"; for (int i=1; i<=nv; i++) { if (i==nn+1) txt = "Corrente"; cout << txt << " " << lista[i] << ": " << Yn[i][nv+1] << endl; } cin.get(); } <commit_msg>Fixes input netlist prompt<commit_after>/* Demonstration of Modified Nodal Analysis Originally by Antonio Carlos M. de Queiroz ([email protected]) Modified by Dhiana Deva, Felipe de Leo, Silvino Vieira */ /* Elementos aceitos e linhas do netlist: Resistor: R<nome> <no+> <no-> <resistencia> VCCS: G<nome> <io+> <io-> <vi+> <vi-> <transcondutancia> VCVC: E<nome> <vo+> <vo-> <vi+> <vi-> <ganho de tensao> CCCS: F<nome> <io+> <io-> <ii+> <ii-> <ganho de corrente> CCVS: H<nome> <vo+> <vo-> <ii+> <ii-> <transresistencia> Fonte I: I<nome> <io+> <io-> <corrente> Fonte V: V<nome> <vo+> <vo-> <tensao> Amp. op.: O<nome> <vo1> <vo2> <vi1> <vi2> As fontes F e H tem o ramo de entrada em curto O amplificador operacional ideal tem a saida suspensa Os nos podem ser nomes */ #include "matrix/solve.h" #include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <string> #include <vector> #include <cstdlib> #include <cmath> using namespace std; #define DEBUG static const int MAX_LINHA = 80; static const int MAX_NOME = 11; static const int MAX_ELEM = 50; typedef struct elemento { /* Elemento do netlist */ string nome; double valor; int a,b,c,d,x,y; } elemento; /* Rotina que conta os nos e atribui numeros a eles */ inline int numero(const char *nome, int &nv, vector<string> &lista){ int i=0, achou=0; while (!achou && i<=nv) if (!(achou=!lista[i].compare(nome))) i++; if (!achou) { if (nv==MAX_NOS) { cout << "O programa so aceita ate " << nv << " nos" << endl; exit(1); } nv++; lista[nv] = nome; return nv; /* novo no */ } else { return i; /* no ja conhecido */ } } int main(int argc, char **argv){ cout << endl; cout << "Modified Nodal Analysis" << endl; cout << "Originally by Antonio Carlos M. de Queiroz ([email protected])" << endl; cout << "Modified by Dhiana Deva, Felipe de Leo and Silvino Vieira" << endl; cout << endl; ifstream netlistFile; string filepath; switch(argc) { case 1: { cout << "Enter path to netlist file: "; cin >> filepath; break; } case 2: { filepath = argv[1]; break; } default: cerr << "FAILURE: Too much information!" << endl; exit(EXIT_FAILURE); } netlistFile.open(filepath, ifstream::in); if(!netlistFile.is_open()){ cerr << "FAILURE: Cannot open file " << filepath << endl; exit(EXIT_FAILURE); } string txt; vector<string> lista(MAX_NOME+2); /*Tem que caber jx antes do nome */ lista[0] = "0"; vector<elemento> netlist(MAX_ELEM); int ne=0, /* Elementos */ nv=0, /* Variaveis */ nn=0; /* Nos */ /* Foram colocados limites nos formatos de leitura para alguma protecao contra excesso de caracteres nestas variaveis */ char tipo, na[MAX_NOME], nb[MAX_NOME], nc[MAX_NOME], nd[MAX_NOME]; double g, Yn[MAX_NOS+1][MAX_NOS+2]; cout << "Lendo netlist:" << endl; getline(netlistFile, txt); cout << "Titulo: " << txt; while (getline(netlistFile, txt)) { ne++; /* Nao usa o netlist[0] */ if (ne>MAX_ELEM) { cout << "O programa so aceita ate " << MAX_ELEM << " elementos" << endl; exit(1); } txt[0]=toupper(txt[0]); tipo=txt[0]; //TODO: verificar necessidade da string txt // ver se eh possivel usar stringstream no getline stringstream txtstream(txt); txtstream >> netlist[ne].nome; //TODO: talvez nao seja preciso usar p string p(txt, netlist[ne].nome.size(), string::npos); txtstream.str(p); /* O que e lido depende do tipo */ if (tipo=='R' || tipo=='I' || tipo=='V') { txtstream >> na >> nb >> netlist[ne].valor; cout << netlist[ne].nome << " " << na << " " << nb << " " << netlist[ne].valor << endl; netlist[ne].a = numero(na, nv, lista); netlist[ne].b = numero(nb, nv, lista); } else if (tipo=='G' || tipo=='E' || tipo=='F' || tipo=='H') { txtstream >> na >> nb >> nc >> nd >> netlist[ne].valor; cout << netlist[ne].nome << " " << na << " " << nb << " " << nc << " " << nd << " "<< netlist[ne].valor << endl; netlist[ne].a = numero(na, nv, lista); netlist[ne].b = numero(nb, nv, lista); netlist[ne].c = numero(nc, nv, lista); netlist[ne].d = numero(nd, nv, lista); } else if (tipo=='O') { txtstream >> na >> nb >> nc >> nd; cout << netlist[ne].nome << " " << na << " " << nb << " " << nc << " " << nd << " " << endl; netlist[ne].a = numero(na, nv, lista); netlist[ne].b = numero(nb, nv, lista); netlist[ne].c = numero(nc, nv, lista); netlist[ne].d = numero(nd, nv, lista); } else if (tipo=='*') { /* Comentario comeca com "*" */ cout << "Comentario: " << txt; ne--; } else { cout << "Elemento desconhecido: " << txt << endl; cin.get(); exit(1); } } netlistFile.close(); /* Acrescenta variaveis de corrente acima dos nos, anotando no netlist */ nn=nv; for (int i=1; i<=ne; i++) { tipo=netlist[i].nome[0]; if (tipo=='V' || tipo=='E' || tipo=='F' || tipo=='O') { nv++; if (nv>MAX_NOS) { cout << "As correntes extra excederam o numero de variaveis permitido (" << MAX_NOS << ")" << endl; exit(1); } lista[nv] = "j"; /* Tem espaco para mais dois caracteres */ lista[nv].append( netlist[i].nome ); netlist[i].x=nv; } else if (tipo=='H') { nv=nv+2; if (nv>MAX_NOS) { cout << "As correntes extra excederam o numero de variaveis permitido (" << MAX_NOS << ")" << endl; exit(1); } lista[nv-1] = "jx"; lista[nv-1].append(netlist[i].nome); netlist[i].x=nv-1; lista[nv] = "jy"; lista[nv].append( netlist[i].nome ); netlist[i].y=nv; } } cin.get(); /* Lista tudo */ cout << "Variaveis internas: " << endl; for (int i=0; i<=nv; i++) cout << i << " -> " << lista[i] << endl; cin.get(); cout << "Netlist interno final" << endl; for (int i=1; i<=ne; i++) { tipo=netlist[i].nome[0]; if (tipo=='R' || tipo=='I' || tipo=='V') { cout << netlist[i].nome << " " << netlist[i].a << " " << netlist[i].b << " " << netlist[i].valor << endl; } else if (tipo=='G' || tipo=='E' || tipo=='F' || tipo=='H') { cout << netlist[i].nome << " " << netlist[i].a << " " << netlist[i].b << " " << netlist[i].c << " " << netlist[i].d << " " << netlist[i].valor << endl; } else if (tipo=='O') { cout << netlist[i].nome << " " << netlist[i].a << " " << netlist[i].b << " " << netlist[i].c << " " << netlist[i].d << endl; } if (tipo=='V' || tipo=='E' || tipo=='F' || tipo=='O') cout << "Corrente jx: " << netlist[i].x << endl; else if (tipo=='H') cout << "Correntes jx e jy: " << netlist[i].x << ", " << netlist[i].y << endl; } cin.get(); /* Monta o sistema nodal modificado */ cout << "O circuito tem " << nn << " nos, " << nv << " variaveis e " << ne << " elementos" << endl; cin.get(); /* Zera sistema */ for (int i=0; i<=nv; i++) { for (int j=0; j<=nv+1; j++) Yn[i][j]=0; } /* Monta estampas */ for (int i=1; i<=ne; i++) { tipo=netlist[i].nome[0]; if (tipo=='R') { g=1/netlist[i].valor; Yn[netlist[i].a][netlist[i].a]+=g; Yn[netlist[i].b][netlist[i].b]+=g; Yn[netlist[i].a][netlist[i].b]-=g; Yn[netlist[i].b][netlist[i].a]-=g; } else if (tipo=='G') { g=netlist[i].valor; Yn[netlist[i].a][netlist[i].c]+=g; Yn[netlist[i].b][netlist[i].d]+=g; Yn[netlist[i].a][netlist[i].d]-=g; Yn[netlist[i].b][netlist[i].c]-=g; } else if (tipo=='I') { g=netlist[i].valor; Yn[netlist[i].a][nv+1]-=g; Yn[netlist[i].b][nv+1]+=g; } else if (tipo=='V') { Yn[netlist[i].a][netlist[i].x]+=1; Yn[netlist[i].b][netlist[i].x]-=1; Yn[netlist[i].x][netlist[i].a]-=1; Yn[netlist[i].x][netlist[i].b]+=1; Yn[netlist[i].x][nv+1]-=netlist[i].valor; } else if (tipo=='E') { g=netlist[i].valor; Yn[netlist[i].a][netlist[i].x]+=1; Yn[netlist[i].b][netlist[i].x]-=1; Yn[netlist[i].x][netlist[i].a]-=1; Yn[netlist[i].x][netlist[i].b]+=1; Yn[netlist[i].x][netlist[i].c]+=g; Yn[netlist[i].x][netlist[i].d]-=g; } else if (tipo=='F') { g=netlist[i].valor; Yn[netlist[i].a][netlist[i].x]+=g; Yn[netlist[i].b][netlist[i].x]-=g; Yn[netlist[i].c][netlist[i].x]+=1; Yn[netlist[i].d][netlist[i].x]-=1; Yn[netlist[i].x][netlist[i].c]-=1; Yn[netlist[i].x][netlist[i].d]+=1; } else if (tipo=='H') { g=netlist[i].valor; Yn[netlist[i].a][netlist[i].y]+=1; Yn[netlist[i].b][netlist[i].y]-=1; Yn[netlist[i].c][netlist[i].x]+=1; Yn[netlist[i].d][netlist[i].x]-=1; Yn[netlist[i].y][netlist[i].a]-=1; Yn[netlist[i].y][netlist[i].b]+=1; Yn[netlist[i].x][netlist[i].c]-=1; Yn[netlist[i].x][netlist[i].d]+=1; Yn[netlist[i].y][netlist[i].x]+=g; } else if (tipo=='O') { Yn[netlist[i].a][netlist[i].x]+=1; Yn[netlist[i].b][netlist[i].x]-=1; Yn[netlist[i].x][netlist[i].c]+=1; Yn[netlist[i].x][netlist[i].d]-=1; } #ifdef DEBUG /* Opcional: Mostra o sistema apos a montagem da estampa */ cout << "Sistema apos a estampa de " << netlist[i].nome << endl; for (int k=1; k<=nv; k++) { for (int j=1; j<=nv+1; j++) if (Yn[k][j]!=0){ cout << setprecision( 1 ) << fixed << setw( 3 ) << showpos; cout << Yn[k][j] << " "; } else cout << " ... "; cout << endl; } cin.get(); #endif } /* Resolve o sistema */ if (solve(nv, Yn)) { cin.get(); exit(0); } #ifdef DEBUG /* Opcional: Mostra o sistema resolvido */ cout << "Sistema resolvido:" << endl; for (int i=1; i<=nv; i++) { for (int j=1; j<=nv+1; j++) if (Yn[i][j]!=0){ cout << setprecision( 1 ) << fixed << setw( 3 ) << showpos; cout << Yn[i][j] << " "; } else cout << " ... "; cout << endl; } cin.get(); #endif /* Mostra solucao */ cout << "Solucao:" << endl; txt = "Tensao"; for (int i=1; i<=nv; i++) { if (i==nn+1) txt = "Corrente"; cout << txt << " " << lista[i] << ": " << Yn[i][nv+1] << endl; } cin.get(); } <|endoftext|>
<commit_before>#include "item.h" #include "itemdb.h" using namespace RoseCommon; Item::Item() : type_(Item::WEARABLE), id_(0), isCreated_(false), gemOpt_(0), durability_(0), life_(0), hasSocket_(false), isAppraised_(false), refine_(0), count_(0), isStackable_(false), atk_(0), def_(0), range_(0) {} Item::Item(const ItemDef& def) : type_(def.type), id_(def.id), isCreated_(false), gemOpt_(0), durability_(10), life_(100), hasSocket_(false), isAppraised_(false), refine_(0), count_(1), isStackable_(def.type == Item::CONSUMABLE ? true : false), atk_(0), def_(0), range_(0) {} uint32_t Item::getVisible() const { return (refine_ << 20) | (hasSocket_ << 19) | (gemOpt_ << 10) | id_; } uint16_t Item::getHeader() const { return (isCreated_ << 15) | (id_ << 5) | type_; } uint32_t Item::getData() const { if (isStackable_) return count_; return (refine_ << 28) | (isAppraised_ << 27) | (hasSocket_ << 26) | (life_ << 16) | (durability_ << 9) | gemOpt_; } <commit_msg>Update item.cpp<commit_after>#include "item.h" #include "itemdb.h" using namespace RoseCommon; Item::Item() : type_(Item::WEARABLE), id_(0), isCreated_(false), gemOpt_(0), durability_(0), life_(0), hasSocket_(false), isAppraised_(false), refine_(0), count_(0), isStackable_(false), atk_(0), def_(0), range_(0) {} Item::Item(const ItemDef& def) : type_(def.type), id_(def.id), isCreated_(false), gemOpt_(0), durability_(10), life_(100), hasSocket_(false), isAppraised_(false), refine_(0), count_(1), isStackable_(def.type >= 10 && def.type <= 13 ? true : false), atk_(0), def_(0), range_(0) {} uint32_t Item::getVisible() const { return (refine_ << 20) | (hasSocket_ << 19) | (gemOpt_ << 10) | id_; } uint16_t Item::getHeader() const { return (isCreated_ << 15) | (id_ << 5) | type_; } uint32_t Item::getData() const { if (isStackable_) return count_; return (refine_ << 28) | (isAppraised_ << 27) | (hasSocket_ << 26) | (life_ << 16) | (durability_ << 9) | gemOpt_; } <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "mlabelview.h" #include "mlabelview_p.h" #include "mlabelmodel.h" #include "mlabel.h" #include "mviewcreator.h" #include <QPainter> #include <QTextDocument> #include <QTextCursor> #include <QFontMetrics> #include <QPixmapCache> #include <QAbstractTextDocumentLayout> #include <QGraphicsSceneMouseEvent> #include <QGraphicsSceneResizeEvent> MLabelViewSimple::MLabelViewSimple(MLabelViewPrivate *viewPrivate) : viewPrivate(viewPrivate), preferredSize(-1, -1), dirty(true), cachedElidedText("") { } MLabelViewSimple::~MLabelViewSimple() { } #ifdef __arm__ void MLabelViewSimple::drawContents(QPainter *painter, const QSizeF &size) { Q_UNUSED(size); const MLabelModel *model = viewPrivate->model(); const MLabelStyle *style = viewPrivate->style(); QRectF paintingRect(viewPrivate->boundingRect().adjusted(style->paddingLeft(), style->paddingTop(), -style->paddingRight(), -style->paddingBottom())); QString textToRender = model->text(); if (model->textElide() && textToRender.size() > 4) { if(cachedElidedText.isEmpty()) { QFontMetrics fm(viewPrivate->controller->font()); cachedElidedText = fm.elidedText(model->text(), Qt::ElideRight, paintingRect.width()); } textToRender = cachedElidedText; } if (textToRender.isEmpty()) { return; } painter->setFont(viewPrivate->controller->font()); painter->setPen(model->color().isValid() ? model->color() : style->color()); painter->setLayoutDirection(model->textDirection()); painter->drawText(paintingRect, viewPrivate->textOptions.alignment() | Qt::TextSingleLine, textToRender); } #else void MLabelViewSimple::drawContents(QPainter *painter, const QSizeF &size) { Q_UNUSED(size); painter->drawImage(textOffset, generateImage()); } #endif QPixmap MLabelViewSimple::generatePixmap() { return QPixmap(); } QImage MLabelViewSimple::generateImage() { if(!dirty) return cachedImage; dirty = false; const MLabelModel *model = viewPrivate->model(); const MLabelStyle *style = viewPrivate->style(); QRectF paintingRect(viewPrivate->boundingRect().adjusted(style->paddingLeft(), style->paddingTop(), -style->paddingRight(), -style->paddingBottom())); QSizeF paintingRectSize = paintingRect.size(); textOffset = paintingRect.topLeft().toPoint(); QString textToRender = model->text(); if (model->textElide() && textToRender.size() > 4) { QFontMetrics fm(viewPrivate->controller->font()); textToRender = fm.elidedText(model->text(), Qt::ElideRight, paintingRect.width()); } if (textToRender.isEmpty()) { cachedImage = QImage(); return cachedImage; } if(cachedImage.size() != paintingRect.size().toSize()) { cachedImage = QImage(paintingRect.size().toSize(), QImage::Format_ARGB32_Premultiplied); } QImage &image = cachedImage; if (!image.isNull()) { image.fill(0); QPainter painter(&image); painter.setRenderHint(QPainter::TextAntialiasing); painter.setFont(viewPrivate->controller->font()); painter.setPen(model->color().isValid() ? model->color() : style->color()); painter.setLayoutDirection(model->textDirection()); painter.drawText(0, 0, paintingRectSize.width(), paintingRectSize.height(), viewPrivate->textOptions.alignment() | Qt::TextSingleLine, textToRender); } return image; } bool MLabelViewSimple::resizeEvent(QGraphicsSceneResizeEvent *event) { // There is no way to specify sizeHint for a text without knowing possible width. // 1st phase, when Qt calls sizeHint, view will return approximate values for // minimum and preferred size. When resizeEvent comes, layout already knows // sizes of components, and here comes // 2nd phase, when we identify widget's height, based on width. Our height will // change and we don't want to occupy more space then need, so we have to call // updateGeometry, to tell layout to update sizeHint cache. This function // return true if such update is needed. QFontMetricsF fm(viewPrivate->controller->font()); QRectF bR = fm.boundingRect(QRectF(QPoint(0, 0), event->newSize()), viewPrivate->textOptions.alignment(), viewPrivate->model()->text()); if (bR.height() > fm.height()) { preferredSize = QSizeF(bR.width(), bR.height()); return true; } else return false; } QSizeF MLabelViewSimple::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const { switch (which) { case Qt::MinimumSize: { QFontMetricsF fm(viewPrivate->controller->font()); QRectF r(0, 0, constraint.width(), constraint.height()); if (r.width() < 0) { r.setWidth(QWIDGETSIZE_MAX); } if (r.height() < 0) { r.setHeight(QWIDGETSIZE_MAX); } QRectF bR(fm.boundingRect(r, viewPrivate->textOptions.alignment() | Qt::TextSingleLine, viewPrivate->model()->text())); return QSizeF(fm.width(""), bR.height()); } case Qt::PreferredSize: { qreal w = constraint.width(); qreal h = constraint.height(); if (w < 0) { w = QWIDGETSIZE_MAX; } if (h < 0) { h = QWIDGETSIZE_MAX; } if (preferredSize.width() >= 0 && preferredSize.width() < w) w = preferredSize.width(); if (preferredSize.height() >= 0 && preferredSize.height() < h) h = preferredSize.height(); QFontMetricsF fm(viewPrivate->controller->font()); QRectF bR(fm.boundingRect(QRectF(0, 0, w, h), viewPrivate->textOptions.alignment() | Qt::TextSingleLine, viewPrivate->model()->text())); return bR.size().boundedTo(QSizeF(w, h)); } case Qt::MaximumSize: { return QSizeF(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX); } default: qWarning("MLabel::sizeHint() don't know how to handle the value of 'which' "); } return QSizeF(0, 0); } void MLabelViewSimple::setupModel() { viewPrivate->textOptions.setTextDirection(viewPrivate->model()->textDirection()); viewPrivate->textOptions.setAlignment(viewPrivate->model()->alignment()); } bool MLabelViewSimple::updateData(const QList<const char *>& modifications) { const char *member = NULL; bool needUpdate = false; foreach(member, modifications) { if (member == MLabelModel::Text) { preferredSize = QSizeF(-1, -1); needUpdate = true; } else if (member == MLabelModel::WordWrap) { if (viewPrivate->model()->wordWrap()) { viewPrivate->textOptions.setWrapMode(QTextOption::WordWrap); } else { viewPrivate->textOptions.setWrapMode(QTextOption::ManualWrap); } } else if (member == MLabelModel::TextDirection) { viewPrivate->textOptions.setTextDirection(viewPrivate->model()->textDirection()); } else if (member == MLabelModel::Alignment) { viewPrivate->textOptions.setAlignment(viewPrivate->model()->alignment()); } else if (member == MLabelModel::UseModelFont || member == MLabelModel::Font) { needUpdate = true; } } return needUpdate; } bool MLabelViewSimple::isRich() { return false; } void MLabelViewSimple::mousePressEvent(QGraphicsSceneMouseEvent *event) { event->ignore(); //propagate link up to owner of label } void MLabelViewSimple::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { Q_UNUSED(event); } void MLabelViewSimple::cancelEvent(MCancelEvent *event) { Q_UNUSED(event); } void MLabelViewSimple::longPressEvent(QGraphicsSceneContextMenuEvent *event) { Q_UNUSED(event); } void MLabelViewSimple::applyStyle() { } void MLabelViewSimple::markDirty() { dirty = true; cachedElidedText = ""; } <commit_msg>Fixes: NB#161300 DuiLabel text set by setText is not displayed<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "mlabelview.h" #include "mlabelview_p.h" #include "mlabelmodel.h" #include "mlabel.h" #include "mviewcreator.h" #include <QPainter> #include <QTextDocument> #include <QTextCursor> #include <QFontMetrics> #include <QPixmapCache> #include <QAbstractTextDocumentLayout> #include <QGraphicsSceneMouseEvent> #include <QGraphicsSceneResizeEvent> MLabelViewSimple::MLabelViewSimple(MLabelViewPrivate *viewPrivate) : viewPrivate(viewPrivate), preferredSize(-1, -1), dirty(true), cachedElidedText("") { } MLabelViewSimple::~MLabelViewSimple() { } #ifdef __arm__ void MLabelViewSimple::drawContents(QPainter *painter, const QSizeF &size) { Q_UNUSED(size); const MLabelModel *model = viewPrivate->model(); const MLabelStyle *style = viewPrivate->style(); QRectF paintingRect(viewPrivate->boundingRect().adjusted(style->paddingLeft(), style->paddingTop(), -style->paddingRight(), -style->paddingBottom())); QString textToRender = model->text(); if (model->textElide() && textToRender.size() > 4) { if(cachedElidedText.isEmpty()) { QFontMetrics fm(viewPrivate->controller->font()); cachedElidedText = fm.elidedText(model->text(), Qt::ElideRight, paintingRect.width()); } textToRender = cachedElidedText; } if (textToRender.isEmpty()) { return; } painter->setFont(viewPrivate->controller->font()); painter->setPen(model->color().isValid() ? model->color() : style->color()); painter->setLayoutDirection(model->textDirection()); painter->drawText(paintingRect, viewPrivate->textOptions.alignment() | Qt::TextSingleLine, textToRender); } #else void MLabelViewSimple::drawContents(QPainter *painter, const QSizeF &size) { Q_UNUSED(size); painter->drawImage(textOffset, generateImage()); } #endif QPixmap MLabelViewSimple::generatePixmap() { return QPixmap(); } QImage MLabelViewSimple::generateImage() { if(!dirty) return cachedImage; dirty = false; const MLabelModel *model = viewPrivate->model(); const MLabelStyle *style = viewPrivate->style(); QRectF paintingRect(viewPrivate->boundingRect().adjusted(style->paddingLeft(), style->paddingTop(), -style->paddingRight(), -style->paddingBottom())); QSizeF paintingRectSize = paintingRect.size(); textOffset = paintingRect.topLeft().toPoint(); QString textToRender = model->text(); if (model->textElide() && textToRender.size() > 4) { QFontMetrics fm(viewPrivate->controller->font()); textToRender = fm.elidedText(model->text(), Qt::ElideRight, paintingRect.width()); } if (textToRender.isEmpty()) { cachedImage = QImage(); return cachedImage; } if(cachedImage.size() != paintingRect.size().toSize()) { cachedImage = QImage(paintingRect.size().toSize(), QImage::Format_ARGB32_Premultiplied); } QImage &image = cachedImage; if (!image.isNull()) { image.fill(0); QPainter painter(&image); painter.setRenderHint(QPainter::TextAntialiasing); painter.setFont(viewPrivate->controller->font()); painter.setPen(model->color().isValid() ? model->color() : style->color()); painter.setLayoutDirection(model->textDirection()); painter.drawText(0, 0, paintingRectSize.width(), paintingRectSize.height(), viewPrivate->textOptions.alignment() | Qt::TextSingleLine, textToRender); } return image; } bool MLabelViewSimple::resizeEvent(QGraphicsSceneResizeEvent *event) { // There is no way to specify sizeHint for a text without knowing possible width. // 1st phase, when Qt calls sizeHint, view will return approximate values for // minimum and preferred size. When resizeEvent comes, layout already knows // sizes of components, and here comes // 2nd phase, when we identify widget's height, based on width. Our height will // change and we don't want to occupy more space then need, so we have to call // updateGeometry, to tell layout to update sizeHint cache. This function // return true if such update is needed. QFontMetricsF fm(viewPrivate->controller->font()); QRectF bR = fm.boundingRect(QRectF(QPoint(0, 0), event->newSize()), viewPrivate->textOptions.alignment(), viewPrivate->model()->text()); if (bR.height() > fm.height()) { preferredSize = QSizeF(bR.width(), bR.height()); return true; } else return false; } QSizeF MLabelViewSimple::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const { switch (which) { case Qt::MinimumSize: { QFontMetricsF fm(viewPrivate->controller->font()); QRectF r(0, 0, constraint.width(), constraint.height()); if (r.width() < 0) { r.setWidth(QWIDGETSIZE_MAX); } if (r.height() < 0) { r.setHeight(QWIDGETSIZE_MAX); } QRectF bR(fm.boundingRect(r, viewPrivate->textOptions.alignment() | Qt::TextSingleLine, viewPrivate->model()->text())); return QSizeF(fm.width("x"), bR.height()); } case Qt::PreferredSize: { qreal w = constraint.width(); qreal h = constraint.height(); if (w < 0) { w = QWIDGETSIZE_MAX; } if (h < 0) { h = QWIDGETSIZE_MAX; } if (preferredSize.width() >= 0 && preferredSize.width() < w) w = preferredSize.width(); if (preferredSize.height() >= 0 && preferredSize.height() < h) h = preferredSize.height(); QFontMetricsF fm(viewPrivate->controller->font()); QRectF bR(fm.boundingRect(QRectF(0, 0, w, h), viewPrivate->textOptions.alignment() | Qt::TextSingleLine, viewPrivate->model()->text())); return bR.size().boundedTo(QSizeF(w, h)); } case Qt::MaximumSize: { return QSizeF(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX); } default: qWarning("MLabel::sizeHint() don't know how to handle the value of 'which' "); } return QSizeF(0, 0); } void MLabelViewSimple::setupModel() { viewPrivate->textOptions.setTextDirection(viewPrivate->model()->textDirection()); viewPrivate->textOptions.setAlignment(viewPrivate->model()->alignment()); } bool MLabelViewSimple::updateData(const QList<const char *>& modifications) { const char *member = NULL; bool needUpdate = false; foreach(member, modifications) { if (member == MLabelModel::Text) { preferredSize = QSizeF(-1, -1); needUpdate = true; } else if (member == MLabelModel::WordWrap) { if (viewPrivate->model()->wordWrap()) { viewPrivate->textOptions.setWrapMode(QTextOption::WordWrap); } else { viewPrivate->textOptions.setWrapMode(QTextOption::ManualWrap); } } else if (member == MLabelModel::TextDirection) { viewPrivate->textOptions.setTextDirection(viewPrivate->model()->textDirection()); } else if (member == MLabelModel::Alignment) { viewPrivate->textOptions.setAlignment(viewPrivate->model()->alignment()); } else if (member == MLabelModel::UseModelFont || member == MLabelModel::Font) { needUpdate = true; } } return needUpdate; } bool MLabelViewSimple::isRich() { return false; } void MLabelViewSimple::mousePressEvent(QGraphicsSceneMouseEvent *event) { event->ignore(); //propagate link up to owner of label } void MLabelViewSimple::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { Q_UNUSED(event); } void MLabelViewSimple::cancelEvent(MCancelEvent *event) { Q_UNUSED(event); } void MLabelViewSimple::longPressEvent(QGraphicsSceneContextMenuEvent *event) { Q_UNUSED(event); } void MLabelViewSimple::applyStyle() { } void MLabelViewSimple::markDirty() { dirty = true; cachedElidedText = ""; } <|endoftext|>
<commit_before>#include "HalideRuntime.h" #include "HalideRuntimeCuda.h" #include "HalideRuntimeOpenGL.h" #include "HalideRuntimeOpenGLCompute.h" #include "HalideRuntimeOpenCL.h" #include "HalideRuntimeRenderscript.h" #include "HalideRuntimeMetal.h" #include "HalideRuntimeIon.h" #include "runtime_internal.h" // This runtime module will contain extern declarations of the Halide // API and the types it uses. It's useful for compiling modules that // use the API without including a copy of it (e.g. JIT, NoRuntime). // Can be generated via the following: // cat src/runtime/runtime_internal.h src/runtime/HalideRuntime*.h | grep "^[^ ][^(]*halide_[^ ]*(" | grep -v '#define' | sed "s/[^(]*halide/halide/" | sed "s/(.*//" | sed "s/^h/ \(void *)\&h/" | sed "s/$/,/" | sort | uniq namespace { __attribute__((used)) void *runtime_api_functions[] = { (void *)&halide_copy_to_device, (void *)&halide_copy_to_host, (void *)&halide_cuda_detach_device_ptr, (void *)&halide_cuda_device_interface, (void *)&halide_cuda_get_device_ptr, (void *)&halide_cuda_initialize_kernels, (void *)&halide_cuda_run, (void *)&halide_cuda_wrap_device_ptr, (void *)&halide_current_time_ns, (void *)&halide_debug_to_file, (void *)&halide_device_free, (void *)&halide_device_free_as_destructor, (void *)&halide_device_malloc, (void *)&halide_device_release, (void *)&halide_device_sync, (void *)&halide_do_par_for, (void *)&halide_double_to_string, (void *)&halide_enumerate_registered_filters, (void *)&halide_error, (void *)&halide_error_access_out_of_bounds, (void *)&halide_error_bad_elem_size, (void *)&halide_error_bounds_inference_call_failed, (void *)&halide_error_buffer_allocation_too_large, (void *)&halide_error_buffer_argument_is_null, (void *)&halide_error_buffer_extents_too_large, (void *)&halide_error_constraint_violated, (void *)&halide_error_constraints_make_required_region_smaller, (void *)&halide_error_debug_to_file_failed, (void *)&halide_error_explicit_bounds_too_small, (void *)&halide_error_extern_stage_failed, (void *)&halide_error_out_of_memory, (void *)&halide_error_param_too_large_f64, (void *)&halide_error_param_too_large_i64, (void *)&halide_error_param_too_large_u64, (void *)&halide_error_param_too_small_f64, (void *)&halide_error_param_too_small_i64, (void *)&halide_error_param_too_small_u64, (void *)&halide_float16_bits_to_double, (void *)&halide_float16_bits_to_float, (void *)&halide_free, (void *)&halide_get_gpu_device, (void *)&halide_get_library_symbol, (void *)&halide_get_symbol, (void *)&halide_get_trace_file, (void *)&halide_hexagon_run, (void *)&halide_int64_to_string, (void *)&halide_ion_detach_device_ptr, (void *)&halide_ion_device_interface, (void *)&halide_ion_get_device_ptr, (void *)&halide_ion_wrap_device_ptr, (void *)&halide_load_library, (void *)&halide_malloc, (void *)&halide_matlab_call_pipeline, (void *)&halide_memoization_cache_cleanup, (void *)&halide_memoization_cache_lookup, (void *)&halide_memoization_cache_release, (void *)&halide_memoization_cache_set_size, (void *)&halide_memoization_cache_store, (void *)&halide_metal_acquire_context, (void *)&halide_metal_detach_buffer, (void *)&halide_metal_device_interface, (void *)&halide_metal_get_buffer, (void *)&halide_metal_initialize_kernels, (void *)&halide_metal_release_context, (void *)&halide_metal_run, (void *)&halide_metal_wrap_buffer, (void *)&halide_mutex_cleanup, (void *)&halide_mutex_lock, (void *)&halide_mutex_unlock, (void *)&halide_opencl_detach_cl_mem, (void *)&halide_opencl_device_interface, (void *)&halide_opencl_get_cl_mem, (void *)&halide_opencl_get_device_type, (void *)&halide_opencl_get_platform_name, (void *)&halide_opencl_initialize_kernels, (void *)&halide_opencl_run, (void *)&halide_opencl_set_device_type, (void *)&halide_opencl_set_platform_name, (void *)&halide_opencl_wrap_cl_mem, (void *)&halide_opengl_context_lost, (void *)&halide_opengl_create_context, (void *)&halide_opengl_detach_texture, (void *)&halide_opengl_device_interface, (void *)&halide_opengl_get_proc_address, (void *)&halide_opengl_get_texture, (void *)&halide_opengl_initialize_kernels, (void *)&halide_opengl_run, (void *)&halide_opengl_wrap_render_target, (void *)&halide_opengl_wrap_texture, (void *)&halide_openglcompute_device_interface, (void *)&halide_openglcompute_initialize_kernels, (void *)&halide_openglcompute_run, (void *)&halide_pointer_to_string, (void *)&halide_print, (void *)&halide_profiler_get_state, (void *)&halide_profiler_pipeline_start, (void *)&halide_profiler_report, (void *)&halide_profiler_reset, (void *)&halide_release_jit_module, (void *)&halide_renderscript_device_interface, (void *)&halide_renderscript_initialize_kernels, (void *)&halide_renderscript_run, (void *)&halide_runtime_internal_register_metadata, (void *)&halide_set_gpu_device, (void *)&halide_set_num_threads, (void *)&halide_set_trace_file, (void *)&halide_shutdown_thread_pool, (void *)&halide_shutdown_trace, (void *)&halide_sleep_ms, (void *)&halide_spawn_thread, (void *)&halide_start_clock, (void *)&halide_string_to_string, (void *)&halide_trace, (void *)&halide_uint64_to_string, (void *)&halide_use_jit_module, }; } <commit_msg>Fix missing include of HalideRuntimeHexagon.h<commit_after>#include "HalideRuntime.h" #include "HalideRuntimeCuda.h" #include "HalideRuntimeOpenGL.h" #include "HalideRuntimeOpenGLCompute.h" #include "HalideRuntimeOpenCL.h" #include "HalideRuntimeRenderscript.h" #include "HalideRuntimeMetal.h" #include "HalideRuntimeIon.h" #include "HalideRuntimeHexagon.h" #include "runtime_internal.h" // This runtime module will contain extern declarations of the Halide // API and the types it uses. It's useful for compiling modules that // use the API without including a copy of it (e.g. JIT, NoRuntime). // Can be generated via the following: // cat src/runtime/runtime_internal.h src/runtime/HalideRuntime*.h | grep "^[^ ][^(]*halide_[^ ]*(" | grep -v '#define' | sed "s/[^(]*halide/halide/" | sed "s/(.*//" | sed "s/^h/ \(void *)\&h/" | sed "s/$/,/" | sort | uniq namespace { __attribute__((used)) void *runtime_api_functions[] = { (void *)&halide_copy_to_device, (void *)&halide_copy_to_host, (void *)&halide_cuda_detach_device_ptr, (void *)&halide_cuda_device_interface, (void *)&halide_cuda_get_device_ptr, (void *)&halide_cuda_initialize_kernels, (void *)&halide_cuda_run, (void *)&halide_cuda_wrap_device_ptr, (void *)&halide_current_time_ns, (void *)&halide_debug_to_file, (void *)&halide_device_free, (void *)&halide_device_free_as_destructor, (void *)&halide_device_malloc, (void *)&halide_device_release, (void *)&halide_device_sync, (void *)&halide_do_par_for, (void *)&halide_double_to_string, (void *)&halide_enumerate_registered_filters, (void *)&halide_error, (void *)&halide_error_access_out_of_bounds, (void *)&halide_error_bad_elem_size, (void *)&halide_error_bounds_inference_call_failed, (void *)&halide_error_buffer_allocation_too_large, (void *)&halide_error_buffer_argument_is_null, (void *)&halide_error_buffer_extents_too_large, (void *)&halide_error_constraint_violated, (void *)&halide_error_constraints_make_required_region_smaller, (void *)&halide_error_debug_to_file_failed, (void *)&halide_error_explicit_bounds_too_small, (void *)&halide_error_extern_stage_failed, (void *)&halide_error_out_of_memory, (void *)&halide_error_param_too_large_f64, (void *)&halide_error_param_too_large_i64, (void *)&halide_error_param_too_large_u64, (void *)&halide_error_param_too_small_f64, (void *)&halide_error_param_too_small_i64, (void *)&halide_error_param_too_small_u64, (void *)&halide_float16_bits_to_double, (void *)&halide_float16_bits_to_float, (void *)&halide_free, (void *)&halide_get_gpu_device, (void *)&halide_get_library_symbol, (void *)&halide_get_symbol, (void *)&halide_get_trace_file, (void *)&halide_hexagon_run, (void *)&halide_int64_to_string, (void *)&halide_ion_detach_device_ptr, (void *)&halide_ion_device_interface, (void *)&halide_ion_get_device_ptr, (void *)&halide_ion_wrap_device_ptr, (void *)&halide_load_library, (void *)&halide_malloc, (void *)&halide_matlab_call_pipeline, (void *)&halide_memoization_cache_cleanup, (void *)&halide_memoization_cache_lookup, (void *)&halide_memoization_cache_release, (void *)&halide_memoization_cache_set_size, (void *)&halide_memoization_cache_store, (void *)&halide_metal_acquire_context, (void *)&halide_metal_detach_buffer, (void *)&halide_metal_device_interface, (void *)&halide_metal_get_buffer, (void *)&halide_metal_initialize_kernels, (void *)&halide_metal_release_context, (void *)&halide_metal_run, (void *)&halide_metal_wrap_buffer, (void *)&halide_mutex_cleanup, (void *)&halide_mutex_lock, (void *)&halide_mutex_unlock, (void *)&halide_opencl_detach_cl_mem, (void *)&halide_opencl_device_interface, (void *)&halide_opencl_get_cl_mem, (void *)&halide_opencl_get_device_type, (void *)&halide_opencl_get_platform_name, (void *)&halide_opencl_initialize_kernels, (void *)&halide_opencl_run, (void *)&halide_opencl_set_device_type, (void *)&halide_opencl_set_platform_name, (void *)&halide_opencl_wrap_cl_mem, (void *)&halide_opengl_context_lost, (void *)&halide_opengl_create_context, (void *)&halide_opengl_detach_texture, (void *)&halide_opengl_device_interface, (void *)&halide_opengl_get_proc_address, (void *)&halide_opengl_get_texture, (void *)&halide_opengl_initialize_kernels, (void *)&halide_opengl_run, (void *)&halide_opengl_wrap_render_target, (void *)&halide_opengl_wrap_texture, (void *)&halide_openglcompute_device_interface, (void *)&halide_openglcompute_initialize_kernels, (void *)&halide_openglcompute_run, (void *)&halide_pointer_to_string, (void *)&halide_print, (void *)&halide_profiler_get_state, (void *)&halide_profiler_pipeline_start, (void *)&halide_profiler_report, (void *)&halide_profiler_reset, (void *)&halide_release_jit_module, (void *)&halide_renderscript_device_interface, (void *)&halide_renderscript_initialize_kernels, (void *)&halide_renderscript_run, (void *)&halide_runtime_internal_register_metadata, (void *)&halide_set_gpu_device, (void *)&halide_set_num_threads, (void *)&halide_set_trace_file, (void *)&halide_shutdown_thread_pool, (void *)&halide_shutdown_trace, (void *)&halide_sleep_ms, (void *)&halide_spawn_thread, (void *)&halide_start_clock, (void *)&halide_string_to_string, (void *)&halide_trace, (void *)&halide_uint64_to_string, (void *)&halide_use_jit_module, }; } <|endoftext|>
<commit_before>#ifndef FROMEVENT_HPP #define FROMEVENT_HPP #include "FlagStatus.hpp" #include "IOLogWrapper.hpp" #include "List.hpp" #include "Params.hpp" #include "Vector.hpp" #include "bridge.h" namespace org_pqrs_Karabiner { class FromEvent; class FromEventManager { friend class FromEvent; public: class Item final : public List::Item { public: Item(const FromEvent* p) : fromEvent_(p) {} ~Item(void); const FromEvent* getFromEvent(void) const { return fromEvent_; } private: const FromEvent* fromEvent_; }; static void clear(void) { list_.clear(); } static void push_back(const FromEvent* p) { list_.push_back(new Item(p)); } static void erase_One(const FromEvent* p) { for (Item* q = static_cast<Item*>(list_.safe_front()); q; q = static_cast<Item*>(q->getnext())) { if (q->getFromEvent() == p) { list_.erase_and_delete(q); return; } } } static void erase_all(const FromEvent* p) { Item* q = static_cast<Item*>(list_.safe_front()); while (q) { if (q->getFromEvent() == p) { q = static_cast<Item*>(list_.erase_and_delete(q)); } else { q = static_cast<Item*>(q->getnext()); } } } private: static List list_; }; class FromEvent final { public: class Type final { public: enum Value { NONE, KEY, CONSUMER_KEY, // Mute, VolumeIncrement, VolumeDecrement, etcetc. POINTING_BUTTON, }; }; FromEvent(void) : isPressing_(false), type_(Type::NONE) {} explicit FromEvent(KeyCode v) : isPressing_(false), type_(Type::KEY), key_(v) {} explicit FromEvent(ConsumerKeyCode v) : isPressing_(false), type_(Type::CONSUMER_KEY), consumer_(v) {} explicit FromEvent(PointingButton v) : isPressing_(false), type_(Type::POINTING_BUTTON), button_(v) {} explicit FromEvent(const Params_Base& paramsBase) : isPressing_(false) { type_ = Type::NONE; { auto p = paramsBase.get_Params_KeyboardEventCallBack(); if (p) { type_ = Type::KEY; key_ = p->key; return; } } { auto p = paramsBase.get_Params_KeyboardSpecialEventCallback(); if (p) { type_ = Type::CONSUMER_KEY; consumer_ = p->key; return; } } { auto p = paramsBase.get_Params_RelativePointerEventCallback(); if (p) { type_ = Type::POINTING_BUTTON; button_ = p->ex_button; return; } } } FromEvent(AddDataType datatype, AddValue v) : isPressing_(false) { switch (datatype) { case BRIDGE_DATATYPE_KEYCODE: type_ = Type::KEY; key_ = KeyCode(v); break; case BRIDGE_DATATYPE_CONSUMERKEYCODE: type_ = Type::CONSUMER_KEY; consumer_ = ConsumerKeyCode(v); break; case BRIDGE_DATATYPE_POINTINGBUTTON: type_ = Type::POINTING_BUTTON; button_ = PointingButton(v); break; default: IOLOG_ERROR("Unknown datatype: %u\n", static_cast<unsigned int>(datatype)); type_ = Type::NONE; break; } } Type::Value getType(void) const { return type_; } // Return whether pressing state is changed. bool changePressingState(const Params_Base& paramsBase, const FlagStatus& currentFlags, const Vector_ModifierFlag& fromFlags); bool isPressing(void) const { return isPressing_; } // Primitive functions: // These functions do not treat Flags. // Use changePressingState in general. bool isTargetEvent(const Params_Base& paramsBase) const; bool isTargetDownEvent(const Params_Base& paramsBase) const; bool isTargetUpEvent(const Params_Base& paramsBase) const; // Get ModifierFlag from KeyCode. ModifierFlag getModifierFlag(void) const { if (type_ != Type::KEY) return ModifierFlag::ZERO; return key_.getModifierFlag(); } PointingButton getPointingButton(void) const { if (type_ != Type::POINTING_BUTTON) return PointingButton::NONE; return button_; } private: bool isTargetEvent(bool& isDown, const Params_Base& paramsBase) const; bool isPressing_; // Do not store Flags in FromEvent because SimultaneousKeyPresses uses multiple FromEvents. Type::Value type_; KeyCode key_; ConsumerKeyCode consumer_; PointingButton button_; }; DECLARE_VECTOR(FromEvent); } #endif <commit_msg>implement destructor<commit_after>#ifndef FROMEVENT_HPP #define FROMEVENT_HPP #include "FlagStatus.hpp" #include "IOLogWrapper.hpp" #include "List.hpp" #include "Params.hpp" #include "Vector.hpp" #include "bridge.h" namespace org_pqrs_Karabiner { class FromEvent; class FromEventManager { friend class FromEvent; public: class Item final : public List::Item { public: Item(const FromEvent* p) : fromEvent_(p) {} ~Item(void) {} const FromEvent* getFromEvent(void) const { return fromEvent_; } private: const FromEvent* fromEvent_; }; static void clear(void) { list_.clear(); } static void push_back(const FromEvent* p) { list_.push_back(new Item(p)); } static void erase_One(const FromEvent* p) { for (Item* q = static_cast<Item*>(list_.safe_front()); q; q = static_cast<Item*>(q->getnext())) { if (q->getFromEvent() == p) { list_.erase_and_delete(q); return; } } } static void erase_all(const FromEvent* p) { Item* q = static_cast<Item*>(list_.safe_front()); while (q) { if (q->getFromEvent() == p) { q = static_cast<Item*>(list_.erase_and_delete(q)); } else { q = static_cast<Item*>(q->getnext()); } } } private: static List list_; }; class FromEvent final { public: class Type final { public: enum Value { NONE, KEY, CONSUMER_KEY, // Mute, VolumeIncrement, VolumeDecrement, etcetc. POINTING_BUTTON, }; }; FromEvent(void) : isPressing_(false), type_(Type::NONE) {} explicit FromEvent(KeyCode v) : isPressing_(false), type_(Type::KEY), key_(v) {} explicit FromEvent(ConsumerKeyCode v) : isPressing_(false), type_(Type::CONSUMER_KEY), consumer_(v) {} explicit FromEvent(PointingButton v) : isPressing_(false), type_(Type::POINTING_BUTTON), button_(v) {} explicit FromEvent(const Params_Base& paramsBase) : isPressing_(false) { type_ = Type::NONE; { auto p = paramsBase.get_Params_KeyboardEventCallBack(); if (p) { type_ = Type::KEY; key_ = p->key; return; } } { auto p = paramsBase.get_Params_KeyboardSpecialEventCallback(); if (p) { type_ = Type::CONSUMER_KEY; consumer_ = p->key; return; } } { auto p = paramsBase.get_Params_RelativePointerEventCallback(); if (p) { type_ = Type::POINTING_BUTTON; button_ = p->ex_button; return; } } } FromEvent(AddDataType datatype, AddValue v) : isPressing_(false) { switch (datatype) { case BRIDGE_DATATYPE_KEYCODE: type_ = Type::KEY; key_ = KeyCode(v); break; case BRIDGE_DATATYPE_CONSUMERKEYCODE: type_ = Type::CONSUMER_KEY; consumer_ = ConsumerKeyCode(v); break; case BRIDGE_DATATYPE_POINTINGBUTTON: type_ = Type::POINTING_BUTTON; button_ = PointingButton(v); break; default: IOLOG_ERROR("Unknown datatype: %u\n", static_cast<unsigned int>(datatype)); type_ = Type::NONE; break; } } Type::Value getType(void) const { return type_; } // Return whether pressing state is changed. bool changePressingState(const Params_Base& paramsBase, const FlagStatus& currentFlags, const Vector_ModifierFlag& fromFlags); bool isPressing(void) const { return isPressing_; } // Primitive functions: // These functions do not treat Flags. // Use changePressingState in general. bool isTargetEvent(const Params_Base& paramsBase) const; bool isTargetDownEvent(const Params_Base& paramsBase) const; bool isTargetUpEvent(const Params_Base& paramsBase) const; // Get ModifierFlag from KeyCode. ModifierFlag getModifierFlag(void) const { if (type_ != Type::KEY) return ModifierFlag::ZERO; return key_.getModifierFlag(); } PointingButton getPointingButton(void) const { if (type_ != Type::POINTING_BUTTON) return PointingButton::NONE; return button_; } private: bool isTargetEvent(bool& isDown, const Params_Base& paramsBase) const; bool isPressing_; // Do not store Flags in FromEvent because SimultaneousKeyPresses uses multiple FromEvents. Type::Value type_; KeyCode key_; ConsumerKeyCode consumer_; PointingButton button_; }; DECLARE_VECTOR(FromEvent); } #endif <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "mlocalebuckets.h" #include "mlocalebuckets_p.h" MLocaleBucketsPrivate::MLocaleBucketsPrivate() : locale() #ifdef HAVE_ICU , collator(locale) #endif { #ifdef HAVE_ICU allBuckets = locale.exemplarCharactersIndex(); #endif } void MLocaleBucketsPrivate::setItems(const QStringList &unsortedItems, Qt::SortOrder sortOrder) { // Remember to call clear() first if this is called from somewhere else than a constructor! QList<MLocaleBucketItem> items; for (int i=0; i < unsortedItems.size(); ++i) { items.append(MLocaleBucketItem(unsortedItems.at(i), i)); } qStableSort(items.begin(), items.end(), MLocaleBucketItemComparator(sortOrder)); QString lastBucket; QStringList lastBucketItems; QList<int> lastBucketOrigIndices; foreach (MLocaleBucketItem item, items) { #ifdef HAVE_ICU QString bucket = locale.indexBucket(item.text, allBuckets, collator); #else // Simplistic fallback if there is no libICU: Use the first character QString bucket = item.text.isEmpty() ? "" : QString(item.text[0]); #endif if (bucket != lastBucket) { if (!lastBucketItems.isEmpty()) { // Found a new bucket - store away the old one buckets << lastBucket; bucketItems << lastBucketItems; origIndices << lastBucketOrigIndices; lastBucketItems.clear(); lastBucketOrigIndices.clear(); } lastBucket = bucket; } lastBucketItems << item.text; lastBucketOrigIndices << item.origIndex; } if (!lastBucketItems.isEmpty()) { buckets << lastBucket; bucketItems << lastBucketItems; origIndices << lastBucketOrigIndices; } } void MLocaleBucketsPrivate::clear() { buckets.clear(); bucketItems.clear(); origIndices.clear(); } MLocaleBuckets::MLocaleBuckets(): d_ptr(new MLocaleBucketsPrivate()) { Q_D(MLocaleBuckets); d->q_ptr = this; } MLocaleBuckets::MLocaleBuckets(const QStringList &unsortedItems, Qt::SortOrder sortOrder) : d_ptr(new MLocaleBucketsPrivate()) { Q_D(MLocaleBuckets); d->q_ptr = this; d->setItems(unsortedItems, sortOrder); } MLocaleBuckets::~MLocaleBuckets() { Q_D(MLocaleBuckets); delete d; } void MLocaleBuckets::setItems(const QStringList &items, Qt::SortOrder sortOrder) { Q_D(MLocaleBuckets); d->clear(); d->setItems(items, sortOrder); } int MLocaleBuckets::bucketCount() const { Q_D(const MLocaleBuckets); return d->buckets.count(); } QString MLocaleBuckets::bucketName(int bucketIndex) const { Q_D(const MLocaleBuckets); if (bucketIndex < 0 || bucketIndex >= d->buckets.size()) return QString(); else return d->buckets.at(bucketIndex); } QString MLocaleBuckets::bucketName(const QString &item) const { #ifdef HAVE_ICU Q_D(const MLocaleBuckets); return d->locale.indexBucket(item, d->allBuckets, d->collator); #else return item.isEmpty() ? "" : QString(item[0]); #endif } int MLocaleBuckets::bucketIndex(const QString &bucketName) const { Q_D(const MLocaleBuckets); return d->buckets.indexOf(bucketName); } QStringList MLocaleBuckets::bucketContent(int bucketIndex) const { Q_D(const MLocaleBuckets); if (bucketIndex < 0 || bucketIndex >= d->buckets.size()) return QStringList(); else return d->bucketItems.at(bucketIndex); } int MLocaleBuckets::origItemIndex(int bucketIndex, int indexInBucket) const { Q_D(const MLocaleBuckets); if (bucketIndex >= 0 && bucketIndex < d->buckets.size()) { const QList<int> &origIndices = d->origIndices.at(bucketIndex); if (indexInBucket >= 0 && indexInBucket < origIndices.size()) { return origIndices.at(indexInBucket); } } return -1; } int MLocaleBuckets::bucketSize(int bucketIndex) const { Q_D(const MLocaleBuckets); if (bucketIndex < 0 || bucketIndex >= d->buckets.size()) return -1; else return d->bucketItems.at(bucketIndex).size(); } bool MLocaleBuckets::isEmpty() const { Q_D(const MLocaleBuckets); return d->bucketItems.isEmpty(); } void MLocaleBuckets::clear() { Q_D(MLocaleBuckets); d->clear(); } <commit_msg>Fixes: NB#239544 - (bogus) coverity problem<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "mlocalebuckets.h" #include "mlocalebuckets_p.h" MLocaleBucketsPrivate::MLocaleBucketsPrivate() : locale(), #ifdef HAVE_ICU collator(locale), #endif q_ptr(0) { #ifdef HAVE_ICU allBuckets = locale.exemplarCharactersIndex(); #endif } void MLocaleBucketsPrivate::setItems(const QStringList &unsortedItems, Qt::SortOrder sortOrder) { // Remember to call clear() first if this is called from somewhere else than a constructor! QList<MLocaleBucketItem> items; for (int i=0; i < unsortedItems.size(); ++i) { items.append(MLocaleBucketItem(unsortedItems.at(i), i)); } qStableSort(items.begin(), items.end(), MLocaleBucketItemComparator(sortOrder)); QString lastBucket; QStringList lastBucketItems; QList<int> lastBucketOrigIndices; foreach (MLocaleBucketItem item, items) { #ifdef HAVE_ICU QString bucket = locale.indexBucket(item.text, allBuckets, collator); #else // Simplistic fallback if there is no libICU: Use the first character QString bucket = item.text.isEmpty() ? "" : QString(item.text[0]); #endif if (bucket != lastBucket) { if (!lastBucketItems.isEmpty()) { // Found a new bucket - store away the old one buckets << lastBucket; bucketItems << lastBucketItems; origIndices << lastBucketOrigIndices; lastBucketItems.clear(); lastBucketOrigIndices.clear(); } lastBucket = bucket; } lastBucketItems << item.text; lastBucketOrigIndices << item.origIndex; } if (!lastBucketItems.isEmpty()) { buckets << lastBucket; bucketItems << lastBucketItems; origIndices << lastBucketOrigIndices; } } void MLocaleBucketsPrivate::clear() { buckets.clear(); bucketItems.clear(); origIndices.clear(); } MLocaleBuckets::MLocaleBuckets(): d_ptr(new MLocaleBucketsPrivate()) { Q_D(MLocaleBuckets); d->q_ptr = this; } MLocaleBuckets::MLocaleBuckets(const QStringList &unsortedItems, Qt::SortOrder sortOrder) : d_ptr(new MLocaleBucketsPrivate()) { Q_D(MLocaleBuckets); d->q_ptr = this; d->setItems(unsortedItems, sortOrder); } MLocaleBuckets::~MLocaleBuckets() { Q_D(MLocaleBuckets); delete d; } void MLocaleBuckets::setItems(const QStringList &items, Qt::SortOrder sortOrder) { Q_D(MLocaleBuckets); d->clear(); d->setItems(items, sortOrder); } int MLocaleBuckets::bucketCount() const { Q_D(const MLocaleBuckets); return d->buckets.count(); } QString MLocaleBuckets::bucketName(int bucketIndex) const { Q_D(const MLocaleBuckets); if (bucketIndex < 0 || bucketIndex >= d->buckets.size()) return QString(); else return d->buckets.at(bucketIndex); } QString MLocaleBuckets::bucketName(const QString &item) const { #ifdef HAVE_ICU Q_D(const MLocaleBuckets); return d->locale.indexBucket(item, d->allBuckets, d->collator); #else return item.isEmpty() ? "" : QString(item[0]); #endif } int MLocaleBuckets::bucketIndex(const QString &bucketName) const { Q_D(const MLocaleBuckets); return d->buckets.indexOf(bucketName); } QStringList MLocaleBuckets::bucketContent(int bucketIndex) const { Q_D(const MLocaleBuckets); if (bucketIndex < 0 || bucketIndex >= d->buckets.size()) return QStringList(); else return d->bucketItems.at(bucketIndex); } int MLocaleBuckets::origItemIndex(int bucketIndex, int indexInBucket) const { Q_D(const MLocaleBuckets); if (bucketIndex >= 0 && bucketIndex < d->buckets.size()) { const QList<int> &origIndices = d->origIndices.at(bucketIndex); if (indexInBucket >= 0 && indexInBucket < origIndices.size()) { return origIndices.at(indexInBucket); } } return -1; } int MLocaleBuckets::bucketSize(int bucketIndex) const { Q_D(const MLocaleBuckets); if (bucketIndex < 0 || bucketIndex >= d->buckets.size()) return -1; else return d->bucketItems.at(bucketIndex).size(); } bool MLocaleBuckets::isEmpty() const { Q_D(const MLocaleBuckets); return d->bucketItems.isEmpty(); } void MLocaleBuckets::clear() { Q_D(MLocaleBuckets); d->clear(); } <|endoftext|>
<commit_before>/* * ===================================================================================== * * Filename: scheduler.cpp * * Description: TouchNet 2 Scheduler * * Version: 0.1 * Created: 05/03/13 15:54:32 * Revision: none * Compiler: g++ * * Author: Daniel Bugl <[email protected]> * Organization: TouchLay * * ===================================================================================== */ // Headers #include "scheduler.h" void Scheduler::reset(void) { start = clock(); } unsigned long Scheduler::elapsedTime(void) { return ((unsigned long) clock() - start) / CLOCKS_PER_SEC; } int Scheduler::addEvent(void *func, int timeout) { // TODO: add an event to the array } void Scheduler::delEvent(int id) { // TODO: remove event by id } void Scheduler::tick(void) { // TODO: loop through events and check if one occured } Scheduler::Scheduler() { #ifdef DEBUG std::cout << "[DEBUG] [scheduler ] Starting scheduler loop..." << std::endl; #endif while (true) tick(); } <commit_msg>Improved scheduler messages.<commit_after>/* * ===================================================================================== * * Filename: scheduler.cpp * * Description: TouchNet 2 Scheduler * * Version: 0.1 * Created: 05/03/13 15:54:32 * Revision: none * Compiler: g++ * * Author: Daniel Bugl <[email protected]> * Organization: TouchLay * * ===================================================================================== */ // Headers #include "scheduler.h" void Scheduler::reset(void) { start = clock(); } unsigned long Scheduler::elapsedTime(void) { return ((unsigned long) clock() - start) / CLOCKS_PER_SEC; } int Scheduler::addEvent(void *func, int timeout) { // TODO: add an event to the array } void Scheduler::delEvent(int id) { // TODO: remove event by id } void Scheduler::tick(void) { // TODO: loop through events and check if one occured } Scheduler::Scheduler() { std::cout << "[TEST ] [scheduler ] Starting scheduler test..." << std::endl; #ifdef DEBUG std::cout << "[DEBUG] [scheduler ] Starting scheduler loop..." << std::endl; #endif while (true) tick(); } <|endoftext|>
<commit_before>/* Copyright (c) 2016 Ravi Peters 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 <limits> #include <random> #include <pcl/common/common.h> #ifdef VERBOSEPRINT #include <chrono> #include <iostream> #endif // OpenMP #ifdef WITH_OPENMP #include <omp.h> #endif #ifdef VERBOSEPRINT typedef std::chrono::high_resolution_clock Clock; #endif /* // Vrui #include <vrui/Geometry/ComponentArray.h> #include <vrui/Math/Math.h> #ifdef VERBOSEPRINT #include <vrui/Misc/Timer.h> #endif // kdtree2 #include <kdtree2/kdtree2.hpp> */ // typedefs #include "simplify_processing.h" //============================== // SIMPLIFY //============================== void compute_lfs(ma_data &madata, double bisec_threshold, bool only_inner = true) { #ifdef VERBOSEPRINT auto start_time = Clock::now(); #endif int N = 2 * madata.m; if (only_inner) { N = madata.m; (*madata.ma_coords).resize(N); // HACK this will destroy permanently the exterior ma_coords! } // compute bisector and filter .. rebuild kdtree .. compute lfs .. compute grid .. thin each cell Vector3List ma_bisec(N); //madata.ma_bisec = &ma_bisec; for (int i = 0; i < N; i++) { if (madata.ma_qidx[i] != -1) { Vector3 f1_in = (*madata.coords)[i%madata.m].getVector3fMap() - (*madata.ma_coords)[i].getVector3fMap(); Vector3 f2_in = (*madata.coords)[madata.ma_qidx[i]].getVector3fMap() - (*madata.ma_coords)[i].getVector3fMap(); ma_bisec[i] = (f1_in + f2_in).normalized(); } } #ifdef VERBOSEPRINT auto elapsed_time = std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start_time); std::cout << "Computed bisectors in " << elapsed_time.count() << " ms" << std::endl; start_time = Clock::now(); #endif int k = 2, count = 0; { pcl::search::KdTree<Point>::Ptr kd_tree(new pcl::search::KdTree<Point>()); madata.kd_tree->setInputCloud(madata.ma_coords); #ifdef VERBOSEPRINT auto elapsed_time = std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start_time); std::cout << "Constructed kd-tree in " << elapsed_time.count() << " ms" << std::endl; start_time = Clock::now(); #endif // Results from our search std::vector<int> k_indices(k); std::vector<Scalar> k_distances(k); #pragma omp parallel for shared(k_indices) for (int i = 0; i < N; i++) { madata.mask[i] = false; if (madata.ma_qidx[i] != -1) { kd_tree->nearestKSearch((*madata.ma_coords)[i], k, k_indices, k_distances); // find closest point to c float bisec_angle = std::acos(ma_bisec[k_indices[1]].dot(ma_bisec[i])); if (bisec_angle < bisec_threshold) madata.mask[i] = true; } } for (int i = 0; i < N; i++) if (madata.mask[i]) count++; #ifdef VERBOSEPRINT elapsed_time = std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start_time); std::cout << "Cleaned MA points in " << elapsed_time.count() << " ms" << std::endl; start_time = Clock::now(); #endif } // mask and copy pointlist ma_coords PointCloud::Ptr ma_coords_masked(new PointCloud); ma_coords_masked->reserve(count); for (int i = 0; i < N; i++) { if (madata.mask[i]) ma_coords_masked->push_back((*madata.ma_coords)[i]); } #ifdef VERBOSEPRINT elapsed_time = std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start_time); std::cout << "Copied cleaned MA points in " << elapsed_time.count() << " ms" << std::endl; start_time = Clock::now(); #endif k = 1; { // rebuild kd-tree pcl::search::KdTree<Point>::Ptr kd_tree(new pcl::search::KdTree<Point>()); madata.kd_tree->setInputCloud(ma_coords_masked); // kd_tree = new kdtree2::KDTree; #ifdef VERBOSEPRINT elapsed_time = std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start_time); std::cout << "Constructed cleaned kd-tree in " << elapsed_time.count() << " ms" << std::endl; start_time = Clock::now(); #endif // Results from our search std::vector<int> k_indices(k); std::vector<Scalar> k_distances(k); #pragma omp parallel for shared(k_distances) for (int i = 0; i < madata.m; i++) { kd_tree->nearestKSearch((*madata.coords)[i], k, k_indices, k_distances); // find closest point to c madata.lfs[i] = std::sqrt(k_distances[0]); } #ifdef VERBOSEPRINT elapsed_time = std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start_time); std::cout << "Computed LFS in " << elapsed_time.count() << " ms" << std::endl; start_time = Clock::now(); #endif } } inline int flatindex(int ind[], int size[], bool true_z_dim) { if (!true_z_dim) return ind[0] + size[0] * ind[1]; return ind[0] + size[0] * (ind[1] + ind[2] * size[1]); } void simplify(ma_data &madata, double cellsize, double epsilon, bool true_z_dim = true, double elevation_threshold = 0.0, double maximum_density = 0, bool squared = false) { #ifdef VERBOSEPRINT auto start_time = Clock::now(); #endif Point minPt; Point maxPt; pcl::getMinMax3D(*(madata.coords), minPt, maxPt); float size[3]; size[0] = maxPt.x - minPt.x; size[1] = maxPt.y - minPt.y; if (true_z_dim) size[2] = maxPt.z - minPt.z; Point origin = minPt; //Box::Size size = madata.bbox.getSize(); //Point origin = Point(madata.bbox.min); int* resolution = new int[3]; #ifdef VERBOSEPRINT std::cout << "Grid resolution: "; #endif // x, y, z - resolution resolution[0] = int(size[0] / cellsize) + 1; resolution[1] = int(size[1] / cellsize) + 1; if (true_z_dim) resolution[2] = int(size[2] / cellsize) + 1; #ifdef VERBOSEPRINT std::cout << resolution[0] << " "; std::cout << resolution[1] << " "; if (true_z_dim) std::cout << resolution[2] << " "; std::cout << std::endl; #endif int ncells = 1; ncells *= resolution[0]; ncells *= resolution[1]; if (true_z_dim) ncells *= resolution[2]; intList** grid = new intList*[ncells]; for (int i = 0; i < ncells; i++) { grid[i] = NULL; } int* idx = new int[3]; int index; for (int i = 0; i < madata.m; i++) { idx[0] = int(((*madata.coords)[i].x - origin.x) / cellsize); idx[1] = int(((*madata.coords)[i].y - origin.y) / cellsize); if (true_z_dim) idx[2] = int(((*madata.coords)[i].z - origin.z) / cellsize); index = flatindex(idx, resolution, true_z_dim); if (grid[index] == NULL) { intList *ilist = new intList; // std::unique_ptr<intList> ilist(new intList); grid[index] = ilist; } (*grid[index]).push_back(i); } delete[] resolution; resolution = NULL; delete[] idx; idx = NULL; double mean_lfs, target_n, A = cellsize*cellsize; std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution<float> randu(0, 1); double target_n_max = maximum_density * A; // parallelize? for (int i = 0; i < ncells; i++) if (grid[i] != NULL) { size_t n = grid[i]->size(); float sum = 0, max_z, min_z; max_z = min_z = (*madata.coords)[(*grid[i])[0]].z; for (auto j : *grid[i]) { sum += madata.lfs[j]; float z = (*madata.coords)[j].z; if (z > max_z) max_z = z; if (z < min_z) min_z = z; } mean_lfs = sum / n; if (squared) mean_lfs = pow(mean_lfs, 2); if (elevation_threshold != 0 && (max_z - min_z) > elevation_threshold) // mean_lfs /= 5; mean_lfs = 0.01; target_n = A / pow(epsilon*mean_lfs, 2); if(target_n_max != 0 && target_n > target_n_max) target_n = target_n_max; for (auto j : *grid[i]) madata.mask[j] = randu(gen) <= target_n / n; } #ifdef VERBOSEPRINT auto elapsed_time = std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start_time); std::cout << "Performed grid simplification in " << elapsed_time.count() << " ms" << std::endl; start_time = Clock::now(); #endif // clear some memory in non-smart ptr way for (int i = 0; i < ncells; i++) { delete grid[i]; } delete[] grid; } void simplify_lfs(simplify_parameters &input_parameters, ma_data& madata) { // compute lfs, simplify if (input_parameters.compute_lfs) compute_lfs(madata, input_parameters.bisec_threshold, input_parameters.only_inner); simplify(madata, input_parameters.cellsize, input_parameters.epsilon, input_parameters.true_z_dim, input_parameters.elevation_threshold, input_parameters.maximum_density, input_parameters.squared); } void simplify(normals_parameters &normals_params, ma_parameters &ma_params, simplify_parameters &simplify_params, PointCloud::Ptr coords, bool *mask) // mask *must* be allocated ahead of time to be an array of size "2*coords.size()". { /////////////////////////// // Step 0: prepare data struct: ma_data madata = {}; madata.m = coords->size(); madata.coords = coords; // add to the reference count /////////////////////////// // Step 1: compute normals: NormalCloud::Ptr normals(new NormalCloud); normals->resize(madata.m); madata.normals = normals; // add to the reference count compute_normals(normals_params, madata); /////////////////////////// // Step 2: compute ma PointCloud::Ptr ma_coords(new PointCloud); ma_coords->resize(2*madata.m); madata.ma_coords = ma_coords; // add to the reference count madata.ma_qidx.resize(2 * madata.m); compute_masb_points(ma_params, madata); //delete madata.kdtree_coords; madata.kdtree_coords = NULL; /////////////////////////// // Step 3: Simplify // madata.bbox = Box(Point(coords[0]), Point(coords[0])); // for (int i = 0; i < madata.m; i++) { // madata.bbox.addPoint(coords[i]); // } madata.mask.resize(madata.m); madata.lfs.resize(madata.m); void simplify_lfs(simplify_parameters &input_parameters, ma_data& madata); /////////////////////////// // Pass back the results in a safe way. std::copy(madata.mask.begin(), madata.mask.end(), mask); //memcpy(mask, &madata.mask[0], madata.mask.size() * sizeof(bool)); } <commit_msg>fix reference to wrong kd_tree in simplify processing<commit_after>/* Copyright (c) 2016 Ravi Peters 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 <limits> #include <random> #include <pcl/common/common.h> #ifdef VERBOSEPRINT #include <chrono> #include <iostream> #endif // OpenMP #ifdef WITH_OPENMP #include <omp.h> #endif #ifdef VERBOSEPRINT typedef std::chrono::high_resolution_clock Clock; #endif /* // Vrui #include <vrui/Geometry/ComponentArray.h> #include <vrui/Math/Math.h> #ifdef VERBOSEPRINT #include <vrui/Misc/Timer.h> #endif // kdtree2 #include <kdtree2/kdtree2.hpp> */ // typedefs #include "simplify_processing.h" //============================== // SIMPLIFY //============================== void compute_lfs(ma_data &madata, double bisec_threshold, bool only_inner = true) { #ifdef VERBOSEPRINT auto start_time = Clock::now(); #endif int N = 2 * madata.m; if (only_inner) { N = madata.m; (*madata.ma_coords).resize(N); // HACK this will destroy permanently the exterior ma_coords! } // compute bisector and filter .. rebuild kdtree .. compute lfs .. compute grid .. thin each cell Vector3List ma_bisec(N); //madata.ma_bisec = &ma_bisec; for (int i = 0; i < N; i++) { if (madata.ma_qidx[i] != -1) { Vector3 f1_in = (*madata.coords)[i%madata.m].getVector3fMap() - (*madata.ma_coords)[i].getVector3fMap(); Vector3 f2_in = (*madata.coords)[madata.ma_qidx[i]].getVector3fMap() - (*madata.ma_coords)[i].getVector3fMap(); ma_bisec[i] = (f1_in + f2_in).normalized(); } } #ifdef VERBOSEPRINT auto elapsed_time = std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start_time); std::cout << "Computed bisectors in " << elapsed_time.count() << " ms" << std::endl; start_time = Clock::now(); #endif int k = 2, count = 0; { pcl::search::KdTree<Point>::Ptr kd_tree(new pcl::search::KdTree<Point>()); kd_tree->setInputCloud(madata.ma_coords); #ifdef VERBOSEPRINT auto elapsed_time = std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start_time); std::cout << "Constructed kd-tree in " << elapsed_time.count() << " ms" << std::endl; start_time = Clock::now(); #endif // Results from our search std::vector<int> k_indices(k); std::vector<Scalar> k_distances(k); #pragma omp parallel for shared(k_indices) for (int i = 0; i < N; i++) { madata.mask[i] = false; if (madata.ma_qidx[i] != -1) { kd_tree->nearestKSearch((*madata.ma_coords)[i], k, k_indices, k_distances); // find closest point to c float bisec_angle = std::acos(ma_bisec[k_indices[1]].dot(ma_bisec[i])); if (bisec_angle < bisec_threshold) madata.mask[i] = true; } } for (int i = 0; i < N; i++) if (madata.mask[i]) count++; #ifdef VERBOSEPRINT elapsed_time = std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start_time); std::cout << "Cleaned MA points in " << elapsed_time.count() << " ms" << std::endl; start_time = Clock::now(); #endif } // mask and copy pointlist ma_coords PointCloud::Ptr ma_coords_masked(new PointCloud); ma_coords_masked->reserve(count); for (int i = 0; i < N; i++) { if (madata.mask[i]) ma_coords_masked->push_back((*madata.ma_coords)[i]); } #ifdef VERBOSEPRINT elapsed_time = std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start_time); std::cout << "Copied cleaned MA points in " << elapsed_time.count() << " ms" << std::endl; start_time = Clock::now(); #endif k = 1; { // rebuild kd-tree pcl::search::KdTree<Point>::Ptr kd_tree(new pcl::search::KdTree<Point>()); madata.kd_tree->setInputCloud(ma_coords_masked); // kd_tree = new kdtree2::KDTree; #ifdef VERBOSEPRINT elapsed_time = std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start_time); std::cout << "Constructed cleaned kd-tree in " << elapsed_time.count() << " ms" << std::endl; start_time = Clock::now(); #endif // Results from our search std::vector<int> k_indices(k); std::vector<Scalar> k_distances(k); #pragma omp parallel for shared(k_distances) for (int i = 0; i < madata.m; i++) { kd_tree->nearestKSearch((*madata.coords)[i], k, k_indices, k_distances); // find closest point to c madata.lfs[i] = std::sqrt(k_distances[0]); } #ifdef VERBOSEPRINT elapsed_time = std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start_time); std::cout << "Computed LFS in " << elapsed_time.count() << " ms" << std::endl; start_time = Clock::now(); #endif } } inline int flatindex(int ind[], int size[], bool true_z_dim) { if (!true_z_dim) return ind[0] + size[0] * ind[1]; return ind[0] + size[0] * (ind[1] + ind[2] * size[1]); } void simplify(ma_data &madata, double cellsize, double epsilon, bool true_z_dim = true, double elevation_threshold = 0.0, double maximum_density = 0, bool squared = false) { #ifdef VERBOSEPRINT auto start_time = Clock::now(); #endif Point minPt; Point maxPt; pcl::getMinMax3D(*(madata.coords), minPt, maxPt); float size[3]; size[0] = maxPt.x - minPt.x; size[1] = maxPt.y - minPt.y; if (true_z_dim) size[2] = maxPt.z - minPt.z; Point origin = minPt; //Box::Size size = madata.bbox.getSize(); //Point origin = Point(madata.bbox.min); int* resolution = new int[3]; #ifdef VERBOSEPRINT std::cout << "Grid resolution: "; #endif // x, y, z - resolution resolution[0] = int(size[0] / cellsize) + 1; resolution[1] = int(size[1] / cellsize) + 1; if (true_z_dim) resolution[2] = int(size[2] / cellsize) + 1; #ifdef VERBOSEPRINT std::cout << resolution[0] << " "; std::cout << resolution[1] << " "; if (true_z_dim) std::cout << resolution[2] << " "; std::cout << std::endl; #endif int ncells = 1; ncells *= resolution[0]; ncells *= resolution[1]; if (true_z_dim) ncells *= resolution[2]; intList** grid = new intList*[ncells]; for (int i = 0; i < ncells; i++) { grid[i] = NULL; } int* idx = new int[3]; int index; for (int i = 0; i < madata.m; i++) { idx[0] = int(((*madata.coords)[i].x - origin.x) / cellsize); idx[1] = int(((*madata.coords)[i].y - origin.y) / cellsize); if (true_z_dim) idx[2] = int(((*madata.coords)[i].z - origin.z) / cellsize); index = flatindex(idx, resolution, true_z_dim); if (grid[index] == NULL) { intList *ilist = new intList; // std::unique_ptr<intList> ilist(new intList); grid[index] = ilist; } (*grid[index]).push_back(i); } delete[] resolution; resolution = NULL; delete[] idx; idx = NULL; double mean_lfs, target_n, A = cellsize*cellsize; std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution<float> randu(0, 1); double target_n_max = maximum_density * A; // parallelize? for (int i = 0; i < ncells; i++) if (grid[i] != NULL) { size_t n = grid[i]->size(); float sum = 0, max_z, min_z; max_z = min_z = (*madata.coords)[(*grid[i])[0]].z; for (auto j : *grid[i]) { sum += madata.lfs[j]; float z = (*madata.coords)[j].z; if (z > max_z) max_z = z; if (z < min_z) min_z = z; } mean_lfs = sum / n; if (squared) mean_lfs = pow(mean_lfs, 2); if (elevation_threshold != 0 && (max_z - min_z) > elevation_threshold) // mean_lfs /= 5; mean_lfs = 0.01; target_n = A / pow(epsilon*mean_lfs, 2); if(target_n_max != 0 && target_n > target_n_max) target_n = target_n_max; for (auto j : *grid[i]) madata.mask[j] = randu(gen) <= target_n / n; } #ifdef VERBOSEPRINT auto elapsed_time = std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start_time); std::cout << "Performed grid simplification in " << elapsed_time.count() << " ms" << std::endl; start_time = Clock::now(); #endif // clear some memory in non-smart ptr way for (int i = 0; i < ncells; i++) { delete grid[i]; } delete[] grid; } void simplify_lfs(simplify_parameters &input_parameters, ma_data& madata) { // compute lfs, simplify if (input_parameters.compute_lfs) compute_lfs(madata, input_parameters.bisec_threshold, input_parameters.only_inner); simplify(madata, input_parameters.cellsize, input_parameters.epsilon, input_parameters.true_z_dim, input_parameters.elevation_threshold, input_parameters.maximum_density, input_parameters.squared); } void simplify(normals_parameters &normals_params, ma_parameters &ma_params, simplify_parameters &simplify_params, PointCloud::Ptr coords, bool *mask) // mask *must* be allocated ahead of time to be an array of size "2*coords.size()". { /////////////////////////// // Step 0: prepare data struct: ma_data madata = {}; madata.m = coords->size(); madata.coords = coords; // add to the reference count /////////////////////////// // Step 1: compute normals: NormalCloud::Ptr normals(new NormalCloud); normals->resize(madata.m); madata.normals = normals; // add to the reference count compute_normals(normals_params, madata); /////////////////////////// // Step 2: compute ma PointCloud::Ptr ma_coords(new PointCloud); ma_coords->resize(2*madata.m); madata.ma_coords = ma_coords; // add to the reference count madata.ma_qidx.resize(2 * madata.m); compute_masb_points(ma_params, madata); //delete madata.kdtree_coords; madata.kdtree_coords = NULL; /////////////////////////// // Step 3: Simplify // madata.bbox = Box(Point(coords[0]), Point(coords[0])); // for (int i = 0; i < madata.m; i++) { // madata.bbox.addPoint(coords[i]); // } madata.mask.resize(madata.m); madata.lfs.resize(madata.m); void simplify_lfs(simplify_parameters &input_parameters, ma_data& madata); /////////////////////////// // Pass back the results in a safe way. std::copy(madata.mask.begin(), madata.mask.end(), mask); //memcpy(mask, &madata.mask[0], madata.mask.size() * sizeof(bool)); } <|endoftext|>
<commit_before>#include "blackhole/detail/sink/asynchronous.hpp" #include <cmath> #include <condition_variable> #include <mutex> namespace blackhole { inline namespace v1 { namespace experimental { namespace sink { namespace { static auto exp2(std::size_t factor) -> std::size_t { if (factor > 20) { throw std::invalid_argument("factor should fit in [0; 20] range"); } return static_cast<std::size_t>(std::exp2(factor)); } } // namespace class drop_overflow_policy_t : public overflow_policy_t { typedef overflow_policy_t::action_t action_t; public: /// Drops on overlow. virtual auto overflow() -> action_t { return action_t::drop; } /// Does nothing on wakeup. virtual auto wakeup() -> void {} }; class wait_overflow_policy_t : public overflow_policy_t { typedef overflow_policy_t::action_t action_t; mutable std::mutex mutex; std::condition_variable cv; public: virtual auto overflow() -> action_t { std::unique_lock<std::mutex> lock(mutex); cv.wait(lock); return action_t::retry; } virtual auto wakeup() -> void { cv.notify_one(); } }; asynchronous_t::asynchronous_t(std::unique_ptr<sink_t> wrapped, std::size_t factor) : queue(exp2(factor)), stopped(false), wrapped(std::move(wrapped)), overflow_policy(new wait_overflow_policy_t), thread(std::bind(&asynchronous_t::run, this)) {} asynchronous_t::~asynchronous_t() { stopped.store(true); thread.join(); } auto asynchronous_t::emit(const record_t& record, const string_view& message) -> void { if (stopped) { throw std::logic_error("queue is sealed"); } while (true) { const auto enqueued = queue.enqueue_with([&](value_type& value) { value = {recordbuf_t(record), message.to_string()}; }); if (enqueued) { // TODO: underflow_policy->wakeup(); return; } else { switch (overflow_policy->overflow()) { case overflow_policy_t::action_t::retry: continue; case overflow_policy_t::action_t::drop: return; } } } } auto asynchronous_t::run() -> void { while (true) { value_type result; const auto dequeued = queue.dequeue_with([&](value_type& value) { result = std::move(value); }); if (stopped && !dequeued) { return; } if (dequeued) { try { wrapped->emit(result.record.into_view(), result.message); overflow_policy->wakeup(); } catch (...) { throw; // TODO: exception_policy->process(std::current_exception()); [] } } else { ::usleep(1000); // TODO: underflow_policy->underflow(); [wait for enqueue, sleep]. } } } } // namespace sink } // namespace experimental } // namespace v1 } // namespace blackhole <commit_msg>refactor: drop logic error<commit_after>#include "blackhole/detail/sink/asynchronous.hpp" #include <cmath> #include <condition_variable> #include <mutex> namespace blackhole { inline namespace v1 { namespace experimental { namespace sink { namespace { static auto exp2(std::size_t factor) -> std::size_t { if (factor > 20) { throw std::invalid_argument("factor should fit in [0; 20] range"); } return static_cast<std::size_t>(std::exp2(factor)); } } // namespace class drop_overflow_policy_t : public overflow_policy_t { typedef overflow_policy_t::action_t action_t; public: /// Drops on overlow. virtual auto overflow() -> action_t { return action_t::drop; } /// Does nothing on wakeup. virtual auto wakeup() -> void {} }; class wait_overflow_policy_t : public overflow_policy_t { typedef overflow_policy_t::action_t action_t; mutable std::mutex mutex; std::condition_variable cv; public: virtual auto overflow() -> action_t { std::unique_lock<std::mutex> lock(mutex); cv.wait(lock); return action_t::retry; } virtual auto wakeup() -> void { cv.notify_one(); } }; asynchronous_t::asynchronous_t(std::unique_ptr<sink_t> wrapped, std::size_t factor) : queue(exp2(factor)), stopped(false), wrapped(std::move(wrapped)), overflow_policy(new wait_overflow_policy_t), thread(std::bind(&asynchronous_t::run, this)) {} asynchronous_t::~asynchronous_t() { stopped.store(true); thread.join(); } auto asynchronous_t::emit(const record_t& record, const string_view& message) -> void { while (true) { const auto enqueued = queue.enqueue_with([&](value_type& value) { value = {recordbuf_t(record), message.to_string()}; }); if (enqueued) { // TODO: underflow_policy->wakeup(); return; } else { switch (overflow_policy->overflow()) { case overflow_policy_t::action_t::retry: continue; case overflow_policy_t::action_t::drop: return; } } } } auto asynchronous_t::run() -> void { while (true) { value_type result; const auto dequeued = queue.dequeue_with([&](value_type& value) { result = std::move(value); }); if (stopped && !dequeued) { return; } if (dequeued) { try { wrapped->emit(result.record.into_view(), result.message); overflow_policy->wakeup(); } catch (...) { throw; // TODO: exception_policy->process(std::current_exception()); [] } } else { ::usleep(1000); // TODO: underflow_policy->underflow(); [wait for enqueue, sleep]. } } } } // namespace sink } // namespace experimental } // namespace v1 } // namespace blackhole <|endoftext|>
<commit_before>// Copyright (c) 2016 The Zcash developers // Original code from: https://gist.github.com/laanwj/0e689cfa37b52bcbbb44 /* To set up a new alert system ---------------------------- Create a new alert key pair: openssl ecparam -name secp256k1 -genkey -param_enc explicit -outform PEM -out data.pem Get the private key in hex: openssl ec -in data.pem -outform DER | tail -c 279 | xxd -p -c 279 Get the public key in hex: openssl ec -in data.pem -pubout -outform DER | tail -c 65 | xxd -p -c 65 Update the public keys found in chainparams.cpp. To send an alert message ------------------------ Copy the private keys into alertkeys.h. Modify the alert parameters and message found in this file. Build and run to send the alert (after 60 seconds): ./zcashd -printtoconsole -sendalert */ /* So you need to broadcast an alert... ... here's what to do: 1. Copy sendalert.cpp into your bitcoind build directory 2. Decrypt the alert keys copy the decrypted file as alertkeys.h into the src/ directory. 3. Modify the alert parameters in sendalert.cpp See the comments in the code for what does what. 4. Add sendalert.cpp to the src/Makefile.am so it gets built: libbitcoin_server_a_SOURCES = \ sendalert.cpp \ ... etc 5. Update init.cpp to launch the send alert thread. Define the thread function as external at the top of init.cpp: extern void ThreadSendAlert(); Add this call at the end of AppInit2: threadGroup.create_thread(boost::bind(ThreadSendAlert)); 6. build bitcoind, then run it with -printalert or -sendalert I usually run it like this: ./bitcoind -printtoconsole -sendalert One minute after starting up the alert will be broadcast. It is then flooded through the network until the nRelayUntil time, and will be active until nExpiration OR the alert is cancelled. If you screw up something, send another alert with nCancel set to cancel the bad alert. */ #include "main.h" #include "net.h" #include "alert.h" #include "init.h" #include "util.h" #include "utiltime.h" #include "key.h" #include "clientversion.h" #include "chainparams.h" #include "alertkeys.h" static const int64_t DAYS = 24 * 60 * 60; void ThreadSendAlert() { if (!mapArgs.count("-sendalert") && !mapArgs.count("-printalert")) return; MilliSleep(60*1000); // Wait a minute so we get connected // // Alerts are relayed around the network until nRelayUntil, flood // filling to every node. // After the relay time is past, new nodes are told about alerts // when they connect to peers, until either nExpiration or // the alert is cancelled by a newer alert. // Nodes never save alerts to disk, they are in-memory-only. // CAlert alert; alert.nRelayUntil = GetTime() + 15 * 60; alert.nExpiration = GetTime() + 365 * 60 * 60; alert.nID = 1040; // use https://en.bitcoin.it/wiki/Alerts to keep track of alert IDs alert.nCancel = 0; // cancels previous messages up to this ID number // These versions are protocol versions // 60002 : 0.7.* // 70001 : 0.8.* // 70002 : 0.9.* alert.nMinVer = 70002; alert.nMaxVer = 70002; // // main.cpp: // 1000 for Misc warnings like out of disk space and clock is wrong // 2000 for longer invalid proof-of-work chain // Higher numbers mean higher priority alert.nPriority = 5000; alert.strComment = ""; alert.strStatusBar = "URGENT: Upgrade required: see https://z.cash"; // Set specific client version/versions here. If setSubVer is empty, no filtering on subver is done: // alert.setSubVer.insert(std::string("/Satoshi:0.7.2/")); // Sign const CChainParams& chainparams = Params(); std::string networkID = chainparams.NetworkIDString(); bool fIsTestNet = networkID.compare("test") == 0; std::vector<unsigned char> vchTmp(ParseHex(fIsTestNet ? pszTestNetPrivKey : pszPrivKey)); CPrivKey vchPrivKey(vchTmp.begin(), vchTmp.end()); CDataStream sMsg(SER_NETWORK, CLIENT_VERSION); sMsg << *(CUnsignedAlert*)&alert; alert.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end()); CKey key; if (!key.SetPrivKey(vchPrivKey, false)) { printf("ThreadSendAlert() : key.SetPrivKey failed\n"); return; } if (!key.Sign(Hash(alert.vchMsg.begin(), alert.vchMsg.end()), alert.vchSig)) { printf("ThreadSendAlert() : key.Sign failed\n"); return; } // Test CDataStream sBuffer(SER_NETWORK, CLIENT_VERSION); sBuffer << alert; CAlert alert2; sBuffer >> alert2; if (!alert2.CheckSignature(chainparams.AlertKey())) { printf("ThreadSendAlert() : CheckSignature failed\n"); return; } assert(alert2.vchMsg == alert.vchMsg); assert(alert2.vchSig == alert.vchSig); alert.SetNull(); printf("\nThreadSendAlert:\n"); printf("hash=%s\n", alert2.GetHash().ToString().c_str()); printf("%s\n", alert2.ToString().c_str()); printf("vchMsg=%s\n", HexStr(alert2.vchMsg).c_str()); printf("vchSig=%s\n", HexStr(alert2.vchSig).c_str()); // Confirm if (!mapArgs.count("-sendalert")) return; while (vNodes.size() < 1 && !ShutdownRequested()) MilliSleep(500); if (ShutdownRequested()) return; #ifdef QT_GUI if (ThreadSafeMessageBox("Send alert?", "ThreadSendAlert", wxYES_NO | wxNO_DEFAULT) != wxYES) return; if (ThreadSafeMessageBox("Send alert, are you sure?", "ThreadSendAlert", wxYES_NO | wxNO_DEFAULT) != wxYES) { ThreadSafeMessageBox("Nothing sent", "ThreadSendAlert", wxOK); return; } #endif // Send printf("ThreadSendAlert() : Sending alert\n"); int nSent = 0; { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (alert2.RelayTo(pnode)) { printf("ThreadSendAlert() : Sent alert to %s\n", pnode->addr.ToString().c_str()); nSent++; } } } printf("ThreadSendAlert() : Alert sent to %d nodes\n", nSent); } <commit_msg>Disable QT alert message.<commit_after>// Copyright (c) 2016 The Zcash developers // Original code from: https://gist.github.com/laanwj/0e689cfa37b52bcbbb44 /* To set up a new alert system ---------------------------- Create a new alert key pair: openssl ecparam -name secp256k1 -genkey -param_enc explicit -outform PEM -out data.pem Get the private key in hex: openssl ec -in data.pem -outform DER | tail -c 279 | xxd -p -c 279 Get the public key in hex: openssl ec -in data.pem -pubout -outform DER | tail -c 65 | xxd -p -c 65 Update the public keys found in chainparams.cpp. To send an alert message ------------------------ Copy the private keys into alertkeys.h. Modify the alert parameters and message found in this file. Build and run to send the alert (after 60 seconds): ./zcashd -printtoconsole -sendalert */ /* So you need to broadcast an alert... ... here's what to do: 1. Copy sendalert.cpp into your bitcoind build directory 2. Decrypt the alert keys copy the decrypted file as alertkeys.h into the src/ directory. 3. Modify the alert parameters in sendalert.cpp See the comments in the code for what does what. 4. Add sendalert.cpp to the src/Makefile.am so it gets built: libbitcoin_server_a_SOURCES = \ sendalert.cpp \ ... etc 5. Update init.cpp to launch the send alert thread. Define the thread function as external at the top of init.cpp: extern void ThreadSendAlert(); Add this call at the end of AppInit2: threadGroup.create_thread(boost::bind(ThreadSendAlert)); 6. build bitcoind, then run it with -printalert or -sendalert I usually run it like this: ./bitcoind -printtoconsole -sendalert One minute after starting up the alert will be broadcast. It is then flooded through the network until the nRelayUntil time, and will be active until nExpiration OR the alert is cancelled. If you screw up something, send another alert with nCancel set to cancel the bad alert. */ #include "main.h" #include "net.h" #include "alert.h" #include "init.h" #include "util.h" #include "utiltime.h" #include "key.h" #include "clientversion.h" #include "chainparams.h" #include "alertkeys.h" static const int64_t DAYS = 24 * 60 * 60; void ThreadSendAlert() { if (!mapArgs.count("-sendalert") && !mapArgs.count("-printalert")) return; MilliSleep(60*1000); // Wait a minute so we get connected // // Alerts are relayed around the network until nRelayUntil, flood // filling to every node. // After the relay time is past, new nodes are told about alerts // when they connect to peers, until either nExpiration or // the alert is cancelled by a newer alert. // Nodes never save alerts to disk, they are in-memory-only. // CAlert alert; alert.nRelayUntil = GetTime() + 15 * 60; alert.nExpiration = GetTime() + 365 * 60 * 60; alert.nID = 1040; // use https://en.bitcoin.it/wiki/Alerts to keep track of alert IDs alert.nCancel = 0; // cancels previous messages up to this ID number // These versions are protocol versions // 60002 : 0.7.* // 70001 : 0.8.* // 70002 : 0.9.* alert.nMinVer = 70002; alert.nMaxVer = 70002; // // main.cpp: // 1000 for Misc warnings like out of disk space and clock is wrong // 2000 for longer invalid proof-of-work chain // Higher numbers mean higher priority alert.nPriority = 5000; alert.strComment = ""; alert.strStatusBar = "URGENT: Upgrade required: see https://z.cash"; // Set specific client version/versions here. If setSubVer is empty, no filtering on subver is done: // alert.setSubVer.insert(std::string("/Satoshi:0.7.2/")); // Sign const CChainParams& chainparams = Params(); std::string networkID = chainparams.NetworkIDString(); bool fIsTestNet = networkID.compare("test") == 0; std::vector<unsigned char> vchTmp(ParseHex(fIsTestNet ? pszTestNetPrivKey : pszPrivKey)); CPrivKey vchPrivKey(vchTmp.begin(), vchTmp.end()); CDataStream sMsg(SER_NETWORK, CLIENT_VERSION); sMsg << *(CUnsignedAlert*)&alert; alert.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end()); CKey key; if (!key.SetPrivKey(vchPrivKey, false)) { printf("ThreadSendAlert() : key.SetPrivKey failed\n"); return; } if (!key.Sign(Hash(alert.vchMsg.begin(), alert.vchMsg.end()), alert.vchSig)) { printf("ThreadSendAlert() : key.Sign failed\n"); return; } // Test CDataStream sBuffer(SER_NETWORK, CLIENT_VERSION); sBuffer << alert; CAlert alert2; sBuffer >> alert2; if (!alert2.CheckSignature(chainparams.AlertKey())) { printf("ThreadSendAlert() : CheckSignature failed\n"); return; } assert(alert2.vchMsg == alert.vchMsg); assert(alert2.vchSig == alert.vchSig); alert.SetNull(); printf("\nThreadSendAlert:\n"); printf("hash=%s\n", alert2.GetHash().ToString().c_str()); printf("%s\n", alert2.ToString().c_str()); printf("vchMsg=%s\n", HexStr(alert2.vchMsg).c_str()); printf("vchSig=%s\n", HexStr(alert2.vchSig).c_str()); // Confirm if (!mapArgs.count("-sendalert")) return; while (vNodes.size() < 1 && !ShutdownRequested()) MilliSleep(500); if (ShutdownRequested()) return; #if 0 #ifdef QT_GUI if (ThreadSafeMessageBox("Send alert?", "ThreadSendAlert", wxYES_NO | wxNO_DEFAULT) != wxYES) return; if (ThreadSafeMessageBox("Send alert, are you sure?", "ThreadSendAlert", wxYES_NO | wxNO_DEFAULT) != wxYES) { ThreadSafeMessageBox("Nothing sent", "ThreadSendAlert", wxOK); return; } #endif #endif // Send printf("ThreadSendAlert() : Sending alert\n"); int nSent = 0; { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (alert2.RelayTo(pnode)) { printf("ThreadSendAlert() : Sent alert to %s\n", pnode->addr.ToString().c_str()); nSent++; } } } printf("ThreadSendAlert() : Alert sent to %d nodes\n", nSent); } <|endoftext|>
<commit_before>#include <iostream> #include <cstdio> #include <algorithm> #include <queue> #include <map> #include <set> #include <stack> #include <cstring> #include <string> #include <vector> #include <iomanip> #include <cmath> #include <list> #include <bitset> using namespace std; #define ll long long #define lson l,mid,id<<1 #define rson mid+1,r,id<<1|1 typedef pair<int, int>pii; typedef pair<ll, ll>pll; typedef pair<double, double>pdd; const double eps = 1e-6; const ll LINF = 0x3f3f3f3f3f3f3f3fLL; const int INF = 0x3f3f3f3f; const double FINF = 1e18; #define x first #define y second #define REP(i,j,k) for(int i =(j);i<=(k);i++) #define REPD(i,j,k) for(int i =(j);i>=(k);i--) #define print(x) cout<<(x)<<endl; #define IOS ios::sync_with_stdio(0);cin.tie(0); void Init(){ return ; } void Solve(int t){ int n; scanf("%d",&n); int a=n*n; REPD(i,2051,3){ int b=i*i; int k1=sqrt(a+b); if(k1*k1+b==a&& k1>0){ print("%d %d %d\n",max(i,k1),min(i,k1)); } int k2=sqrt(a-b); if(k2*k2+b==a&& k2>0){ print("%d %d %d\n",max(i,k2),min(i,k2)); } int k3=sqrt(b-a); if(k3*k3+b==a&& k1>0){ print("%d %d %d\n",max(i,k3),min(i,k3)); } } if(t>1) printf("\n"); return ; } int main(){ freopen("uoj1079.in","r",stdin); int t; scanf("%d",&t); while(t--) Init(),Solve(t); return 0; }<commit_msg>update uoj1079<commit_after>#include <iostream> #include <cstdio> #include <algorithm> #include <queue> #include <map> #include <set> #include <stack> #include <cstring> #include <string> #include <vector> #include <iomanip> #include <cmath> #include <list> #include <bitset> using namespace std; #define ll long long #define lson l,mid,id<<1 #define rson mid+1,r,id<<1|1 typedef pair<int, int>pii; typedef pair<ll, ll>pll; typedef pair<double, double>pdd; const double eps = 1e-6; const ll LINF = 0x3f3f3f3f3f3f3f3fLL; const int INF = 0x3f3f3f3f; const double FINF = 1e18; #define x first #define y second #define REP(i,j,k) for(int i =(j);i<=(k);i++) #define REPD(i,j,k) for(int i =(j);i>=(k);i--) #define print(x) cout<<(x)<<endl; #define IOS ios::sync_with_stdio(0);cin.tie(0); void Init(){ return ; } void Solve(int t){ int n; scanf("%d",&n); int a=n*n; REPD(i,2051,3){ int b=i*i; int k1=sqrt(a+b); if(k1*k1+b==a&& k1>0){ printf("%d %d %d\n",max(i,k1),min(i,k1)); } int k2=sqrt(a-b); if(k2*k2+b==a&& k2>0){ printf("%d %d %d\n",max(i,k2),min(i,k2)); } int k3=sqrt(b-a); if(k3*k3+b==a&& k1>0){ printf("%d %d %d\n",max(i,k3),min(i,k3)); } } if(t>1) printf("\n"); return ; } int main(){ freopen("uoj1079.in","r",stdin); int t; scanf("%d",&t); while(t--) Init(),Solve(t); return 0; }<|endoftext|>
<commit_before>#include <iostream> #include <cstdio> #include <algorithm> #include <queue> #include <map> #include <set> #include <stack> #include <cstring> #include <string> #include <vector> #include <iomanip> #include <cmath> #include <list> #include <bitset> using namespace std; #define ll long long #define lson l,mid,id<<1 #define rson mid+1,r,id<<1|1 typedef pair<int, int>pii; typedef pair<ll, ll>pll; typedef pair<double, double>pdd; const double eps = 1e-6; const ll LINF = 0x3f3f3f3f3f3f3f3fLL; const int INF = 0x3f3f3f3f; const double FINF = 1e18; #define x first #define y second #define REP(i,j,k) for(int i =(j);i<=(k);i++) #define REPD(i,j,k) for(int i =(j);i>=(k);i--) #define print(x) cout<<(x)<<endl; #define IOS ios::sync_with_stdio(0);cin.tie(0); int dp[200005]; int q[200005]; int a[200005]; int g[200005]; int n; void Init(){ REP(i,1,n+1){scanf("%d",&(a[i]));g[i]=a[i]+i;} REP(i,n+1,n+n/2+1){a[i]=a[i-n];g[i]=a[i]+i;} return ; } void Solve(){ q[1]=1; int head=1,tail=1; for(int i=2;i<=n+n/2;i++) { while(i-q[head]>n/2)head++; /*因为q是递减队列,所以找到符合条件i-k<=n的排头,如果用链表的话就是把头一个个删掉*/ dp[i]=g[i]+a[q[head]]-q[head]; /*要选最大的就是队头*/ while(a[i]-i>=a[q[tail]]-q[tail]&&tail>=head)tail--; /*找位置插入*/ q[++tail]=i; } int ans=0; for(int i=2;i<=n+n/2;i++) ans=max(ans,dp[i]); pd(ans); return ; } int main(){ freopen("uoj8613.in","r",stdin); while(scanf("%d",&(n))&&n) Init(),Solve(); return 0; }<commit_msg>update uoj8613<commit_after>#include <iostream> #include <cstdio> #include <algorithm> #include <queue> #include <map> #include <set> #include <stack> #include <cstring> #include <string> #include <vector> #include <iomanip> #include <cmath> #include <list> #include <bitset> using namespace std; #define ll long long #define lson l,mid,id<<1 #define rson mid+1,r,id<<1|1 typedef pair<int, int>pii; typedef pair<ll, ll>pll; typedef pair<double, double>pdd; const double eps = 1e-6; const ll LINF = 0x3f3f3f3f3f3f3f3fLL; const int INF = 0x3f3f3f3f; const double FINF = 1e18; #define x first #define y second #define REP(i,j,k) for(int i =(j);i<=(k);i++) #define REPD(i,j,k) for(int i =(j);i>=(k);i--) #define print(x) cout<<(x)<<endl; #define IOS ios::sync_with_stdio(0);cin.tie(0); int dp[200005]; int q[200005]; int a[200005]; int g[200005]; int n; void Init(){ REP(i,1,n+1){scanf("%d",&(a[i]));g[i]=a[i]+i;} REP(i,n+1,n+n/2+1){a[i]=a[i-n];g[i]=a[i]+i;} return ; } void Solve(){ q[1]=1; int head=1,tail=1; for(int i=2;i<=n+n/2;i++) { while(i-q[head]>n/2)head++; dp[i]=g[i]+a[q[head]]-q[head]; while(a[i]-i>=a[q[tail]]-q[tail]&&tail>=head)tail--; q[++tail]=i; } int ans=0; for(int i=2;i<=n+n/2;i++) ans=max(ans,dp[i]); printf("%d",(ans)); return ; } int main(){ freopen("uoj8613.in","r",stdin); while(scanf("%d",&(n))&&n) Init(),Solve(); return 0; }<|endoftext|>
<commit_before>// Copyright (c) 2012 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 <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Fluttercoin"); // Client version number #define CLIENT_VERSION_SUFFIX "-beta" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "a" # define GIT_COMMIT_DATE "$Format:%cD" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <commit_msg>remove -beta from version<commit_after>// Copyright (c) 2012 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 <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Fluttercoin"); // Client version number #define CLIENT_VERSION_SUFFIX "" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "a" # define GIT_COMMIT_DATE "$Format:%cD" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <|endoftext|>
<commit_before>// spatial_tree.cpp // #include "common/common.h" #include "spatial_tree.h" #include "database.h" #include "page_info.h" #include "index_tree_t.h" namespace sdl { namespace db { spatial_tree::index_page::index_page(spatial_tree const * t, page_head const * h, size_t const i) : tree(t), head(h), slot(i) { SDL_ASSERT(tree && head); SDL_ASSERT(head->is_index()); SDL_ASSERT(head->data.pminlen == sizeof(spatial_tree_row)); SDL_ASSERT(slot <= slot_array::size(head)); SDL_ASSERT(slot_array::size(head)); } spatial_tree::spatial_tree(database * const p, page_head const * const h, shared_primary_key const & pk0) : this_db(p), cluster_root(h) { SDL_ASSERT(this_db && cluster_root); if (pk0 && pk0->is_index()) { SDL_ASSERT(1 == pk0->size()); //FIXME: current implementation SDL_ASSERT(pk0->first_type() == scalartype::t_bigint); //FIXME: current implementation A_STATIC_ASSERT_TYPE(impl::scalartype_to_key<scalartype::t_bigint>::type, int64); } else { throw_error<spatial_tree_error>("spatial_tree"); } SDL_ASSERT(is_str_empty(spatial_datapage::name())); SDL_ASSERT(find_page(min_cell())); SDL_ASSERT(find_page(max_cell())); } spatial_tree::datapage_access::iterator spatial_tree::datapage_access::begin() { page_head const * p = tree->min_page(); return iterator(this, std::move(p)); } spatial_tree::datapage_access::iterator spatial_tree::datapage_access::end() { return iterator(this, nullptr); } spatial_tree::unique_datapage spatial_tree::datapage_access::dereference(state_type const p) { SDL_ASSERT(p); return make_unique<spatial_datapage>(p); } void spatial_tree::datapage_access::load_next(state_type & p) { p = tree->this_db->load_next_head(p); } void spatial_tree::datapage_access::load_prev(state_type & p) { if (p) { SDL_ASSERT(p != tree->min_page()); SDL_ASSERT(p->data.prevPage); p = tree->this_db->load_prev_head(p); } else { p = tree->max_page(); } } page_head const * spatial_tree::load_leaf_page(bool const begin) const { page_head const * head = cluster_root; while (1) { SDL_ASSERT(head->data.pminlen == sizeof(spatial_tree_row)); const index_page_key page(head); const auto row = begin ? page.front() : page.back(); if (auto next = this_db->load_page_head(row->data.page)) { if (next->is_index()) { head = next; } else { SDL_ASSERT(next->is_data()); SDL_ASSERT(!begin || !head->data.prevPage); SDL_ASSERT(begin || !head->data.nextPage); SDL_ASSERT(!begin || !next->data.prevPage); SDL_ASSERT(begin || !next->data.nextPage); SDL_ASSERT(next->data.pminlen == sizeof(spatial_page_row)); return next; } } else { SDL_ASSERT(0); break; } } throw_error<spatial_tree_error>("bad index"); return nullptr; } page_head const * spatial_tree::min_page() const { if (!_min_page) { _min_page = load_leaf_page(true); } return _min_page; } page_head const * spatial_tree::max_page() const { if (!_max_page) { _max_page = load_leaf_page(false); } return _max_page; } spatial_page_row const * spatial_tree::min_page_row() const { if (auto const p = min_page()) { const spatial_datapage page(p); if (!page.empty()) { return page.front(); } } SDL_ASSERT(0); return{}; } spatial_page_row const * spatial_tree::max_page_row() const { if (auto const p = max_page()) { const spatial_datapage page(p); if (!page.empty()) { return page.back(); } } SDL_ASSERT(0); return{}; } spatial_cell spatial_tree::min_cell() const { if (auto const p = min_page_row()) { return p->data.cell_id; } SDL_ASSERT(0); return{}; } spatial_cell spatial_tree::max_cell() const { if (auto const p = max_page_row()) { return p->data.cell_id; } SDL_ASSERT(0); return{}; } size_t spatial_tree::index_page::find_slot(cell_ref cell_id) const { const index_page_key data(this->head); spatial_tree_row const * const null = head->data.prevPage ? nullptr : index_page_key(this->head).front(); size_t i = data.lower_bound([this, &cell_id, null](spatial_tree_row const * const x, size_t) { if (x == null) return true; return get_cell(x) < cell_id; }); SDL_ASSERT(i <= data.size()); if (i < data.size()) { if (i && (cell_id < row_cell(i))) { --i; } return i; } SDL_ASSERT(i); return i - 1; // last slot } pageFileID spatial_tree::find_page(cell_ref cell_id) const { SDL_ASSERT(cell_id); index_page p(this, cluster_root, 0); while (1) { auto const & id = p.row_page(p.find_slot(cell_id)); if (auto const head = this_db->load_page_head(id)) { if (head->is_index()) { p.head = head; p.slot = 0; continue; } if (head->is_data()) { SDL_ASSERT(id); return id; } } break; } SDL_ASSERT(0); return{}; } bool spatial_tree::is_front_intersect(page_head const * h, cell_ref cell_id) { SDL_ASSERT(h->is_data()); spatial_datapage data(h); if (!data.empty()) { return data.front()->data.cell_id.intersect(cell_id); } SDL_ASSERT(0); return false; } bool spatial_tree::is_back_intersect(page_head const * h, cell_ref cell_id) { SDL_ASSERT(h->is_data()); spatial_datapage data(h); if (!data.empty()) { return data.back()->data.cell_id.intersect(cell_id); } SDL_ASSERT(0); return false; } page_head const * spatial_tree::lower_bound(cell_ref cell_id) const { if (page_head const * h = this_db->load_page_head(find_page(cell_id))) { while (is_front_intersect(h, cell_id)) { if (page_head const * h2 = this_db->load_prev_head(h)) { if (is_back_intersect(h2, cell_id)) { h = h2; } else { break; } } else { break; } } SDL_ASSERT(!spatial_datapage(h).empty()); return h; } SDL_ASSERT(0); return nullptr; } recordID spatial_tree::load_prev_record(recordID const & pos) const { if (page_head const * h = this_db->load_page_head(pos.id)) { if (pos.slot) { SDL_ASSERT(pos.slot <= slot_array(h).size()); return recordID::init(h->data.pageId, pos.slot - 1); } if (h = this_db->load_prev_head(h)) { const spatial_datapage data(h); if (data) { return recordID::init(h->data.pageId, data.size() - 1); } SDL_ASSERT(0); } } return {}; } spatial_page_row const * spatial_tree::get_page_row(recordID const & pos) const { if (page_head const * const h = this_db->load_page_head(pos.id)) { SDL_ASSERT(pos.slot < slot_array(h).size()); return spatial_datapage(h)[pos.slot]; } SDL_ASSERT(0); return nullptr; } recordID spatial_tree::find(cell_ref cell_id) const { if (page_head const * const h = lower_bound(cell_id)) { const spatial_datapage data(h); if (data) { size_t const slot = data.lower_bound( [&cell_id](spatial_page_row const * const row, size_t) { return row->data.cell_id < cell_id; }); if (1) { // to be tested recordID result{}; recordID temp = recordID::init(h->data.pageId, slot); while (temp = load_prev_record(temp)) { if (intersect(get_page_row(temp), cell_id)) { result = temp; } else { if (result) return result; break; } } } if (slot == data.size()) { return {}; } return recordID::init(h->data.pageId, slot); } SDL_ASSERT(0); } return {}; } } // db } // sdl <commit_msg>fixed warnings<commit_after>// spatial_tree.cpp // #include "common/common.h" #include "spatial_tree.h" #include "database.h" #include "page_info.h" #include "index_tree_t.h" namespace sdl { namespace db { spatial_tree::index_page::index_page(spatial_tree const * t, page_head const * h, size_t const i) : tree(t), head(h), slot(i) { SDL_ASSERT(tree && head); SDL_ASSERT(head->is_index()); SDL_ASSERT(head->data.pminlen == sizeof(spatial_tree_row)); SDL_ASSERT(slot <= slot_array::size(head)); SDL_ASSERT(slot_array::size(head)); } spatial_tree::spatial_tree(database * const p, page_head const * const h, shared_primary_key const & pk0) : this_db(p), cluster_root(h) { SDL_ASSERT(this_db && cluster_root); if (pk0 && pk0->is_index()) { SDL_ASSERT(1 == pk0->size()); //FIXME: current implementation SDL_ASSERT(pk0->first_type() == scalartype::t_bigint); //FIXME: current implementation A_STATIC_ASSERT_TYPE(impl::scalartype_to_key<scalartype::t_bigint>::type, int64); } else { throw_error<spatial_tree_error>("spatial_tree"); } SDL_ASSERT(is_str_empty(spatial_datapage::name())); SDL_ASSERT(find_page(min_cell())); SDL_ASSERT(find_page(max_cell())); } spatial_tree::datapage_access::iterator spatial_tree::datapage_access::begin() { page_head const * p = tree->min_page(); return iterator(this, std::move(p)); } spatial_tree::datapage_access::iterator spatial_tree::datapage_access::end() { return iterator(this, nullptr); } spatial_tree::unique_datapage spatial_tree::datapage_access::dereference(state_type const p) { SDL_ASSERT(p); return make_unique<spatial_datapage>(p); } void spatial_tree::datapage_access::load_next(state_type & p) { p = tree->this_db->load_next_head(p); } void spatial_tree::datapage_access::load_prev(state_type & p) { if (p) { SDL_ASSERT(p != tree->min_page()); SDL_ASSERT(p->data.prevPage); p = tree->this_db->load_prev_head(p); } else { p = tree->max_page(); } } page_head const * spatial_tree::load_leaf_page(bool const begin) const { page_head const * head = cluster_root; while (1) { SDL_ASSERT(head->data.pminlen == sizeof(spatial_tree_row)); const index_page_key page(head); const auto row = begin ? page.front() : page.back(); if (auto next = this_db->load_page_head(row->data.page)) { if (next->is_index()) { head = next; } else { SDL_ASSERT(next->is_data()); SDL_ASSERT(!begin || !head->data.prevPage); SDL_ASSERT(begin || !head->data.nextPage); SDL_ASSERT(!begin || !next->data.prevPage); SDL_ASSERT(begin || !next->data.nextPage); SDL_ASSERT(next->data.pminlen == sizeof(spatial_page_row)); return next; } } else { SDL_ASSERT(0); break; } } throw_error<spatial_tree_error>("bad index"); return nullptr; } page_head const * spatial_tree::min_page() const { if (!_min_page) { _min_page = load_leaf_page(true); } return _min_page; } page_head const * spatial_tree::max_page() const { if (!_max_page) { _max_page = load_leaf_page(false); } return _max_page; } spatial_page_row const * spatial_tree::min_page_row() const { if (auto const p = min_page()) { const spatial_datapage page(p); if (!page.empty()) { return page.front(); } } SDL_ASSERT(0); return{}; } spatial_page_row const * spatial_tree::max_page_row() const { if (auto const p = max_page()) { const spatial_datapage page(p); if (!page.empty()) { return page.back(); } } SDL_ASSERT(0); return{}; } spatial_cell spatial_tree::min_cell() const { if (auto const p = min_page_row()) { return p->data.cell_id; } SDL_ASSERT(0); return{}; } spatial_cell spatial_tree::max_cell() const { if (auto const p = max_page_row()) { return p->data.cell_id; } SDL_ASSERT(0); return{}; } size_t spatial_tree::index_page::find_slot(cell_ref cell_id) const { const index_page_key data(this->head); spatial_tree_row const * const null = head->data.prevPage ? nullptr : index_page_key(this->head).front(); size_t i = data.lower_bound([this, &cell_id, null](spatial_tree_row const * const x, size_t) { if (x == null) return true; return get_cell(x) < cell_id; }); SDL_ASSERT(i <= data.size()); if (i < data.size()) { if (i && (cell_id < row_cell(i))) { --i; } return i; } SDL_ASSERT(i); return i - 1; // last slot } pageFileID spatial_tree::find_page(cell_ref cell_id) const { SDL_ASSERT(cell_id); index_page p(this, cluster_root, 0); while (1) { auto const & id = p.row_page(p.find_slot(cell_id)); if (auto const head = this_db->load_page_head(id)) { if (head->is_index()) { p.head = head; p.slot = 0; continue; } if (head->is_data()) { SDL_ASSERT(id); return id; } } break; } SDL_ASSERT(0); return{}; } bool spatial_tree::is_front_intersect(page_head const * h, cell_ref cell_id) { SDL_ASSERT(h->is_data()); spatial_datapage data(h); if (!data.empty()) { return data.front()->data.cell_id.intersect(cell_id); } SDL_ASSERT(0); return false; } bool spatial_tree::is_back_intersect(page_head const * h, cell_ref cell_id) { SDL_ASSERT(h->is_data()); spatial_datapage data(h); if (!data.empty()) { return data.back()->data.cell_id.intersect(cell_id); } SDL_ASSERT(0); return false; } page_head const * spatial_tree::lower_bound(cell_ref cell_id) const { if (page_head const * h = this_db->load_page_head(find_page(cell_id))) { while (is_front_intersect(h, cell_id)) { if (page_head const * h2 = this_db->load_prev_head(h)) { if (is_back_intersect(h2, cell_id)) { h = h2; } else { break; } } else { break; } } SDL_ASSERT(!spatial_datapage(h).empty()); return h; } SDL_ASSERT(0); return nullptr; } recordID spatial_tree::load_prev_record(recordID const & pos) const { if (page_head const * h = this_db->load_page_head(pos.id)) { if (pos.slot) { SDL_ASSERT(pos.slot <= slot_array(h).size()); return recordID::init(h->data.pageId, pos.slot - 1); } if (((h = this_db->load_prev_head(h)))) { const spatial_datapage data(h); if (data) { return recordID::init(h->data.pageId, data.size() - 1); } SDL_ASSERT(0); } } return {}; } spatial_page_row const * spatial_tree::get_page_row(recordID const & pos) const { if (page_head const * const h = this_db->load_page_head(pos.id)) { SDL_ASSERT(pos.slot < slot_array(h).size()); return spatial_datapage(h)[pos.slot]; } SDL_ASSERT(0); return nullptr; } recordID spatial_tree::find(cell_ref cell_id) const { if (page_head const * const h = lower_bound(cell_id)) { const spatial_datapage data(h); if (data) { size_t const slot = data.lower_bound( [&cell_id](spatial_page_row const * const row, size_t) { return row->data.cell_id < cell_id; }); if (1) { // to be tested recordID result{}; recordID temp = recordID::init(h->data.pageId, slot); while ((temp = load_prev_record(temp))) { if (intersect(get_page_row(temp), cell_id)) { result = temp; } else { if (result) return result; break; } } } if (slot == data.size()) { return {}; } return recordID::init(h->data.pageId, slot); } SDL_ASSERT(0); } return {}; } } // db } // sdl <|endoftext|>
<commit_before>// Copyright (c) 2012 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 <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. // Client version number #define CLIENT_VERSION_SUFFIX "" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "" # define GIT_COMMIT_DATE "14.04.2017" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <commit_msg>Scash-qt v.1.1<commit_after>// Copyright (c) 2012 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 <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Scash-qt v.1.1"); // Client version number #define CLIENT_VERSION_SUFFIX "" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "" # define GIT_COMMIT_DATE "14.04.2017" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <|endoftext|>
<commit_before>#ifndef DEDICATED_ONLY #include <boost/assign/list_inserter.hpp> using namespace boost::assign; #include <vector> #include <list> #include <AL/al.h> #include <boost/utility.hpp> #include "sfx.h" #include "sfxdriver.h" #include "sfxdriver_openal.h" #include "gusanos/gconsole.h" #include "CGameObject.h" #include "util/macros.h" #include "Debug.h" using namespace std; Sfx sfx; namespace { bool m_initialized = false; std::vector<Listener*> listeners; } void update_volume( int oldValue ) { notes<<"update_volume"<<endl; if (sfx) sfx.volumeChange(); } Sfx::Sfx():driver(0) { } Sfx::~Sfx() { if (driver) { delete driver; } } bool Sfx::init() { //notes<<"Sfx::init()"<<endl; driver = new SfxDriverOpenAL(); m_initialized = driver->init(); return m_initialized; } void Sfx::shutDown() { //notes<<"Sfx::shutDown()"<<endl; driver->shutDown(); } void Sfx::registerInConsole() { notes<<"Sfx::registerInConsole()"<<endl; if (m_initialized ) { driver->registerInConsole(); } } void Sfx::think() { driver->setListeners(listeners); driver->think(); } SfxDriver* Sfx::getDriver() { return driver; } void Sfx::clear() { if(driver) driver->clear(); } void Sfx::registerListener(Listener* l) { listeners.push_back(l); } void Sfx::removeListener(Listener* listener) { vector<Listener*>::iterator i; for ( i = listeners.begin(); i != listeners.end(); ++i ) { if ( listener == *i ) { listeners.erase(i); break; } } } void Sfx::volumeChange() { driver->volumeChange(); } Sfx::operator bool() { return m_initialized; } #endif <commit_msg>more security checks<commit_after>#ifndef DEDICATED_ONLY #include <boost/assign/list_inserter.hpp> using namespace boost::assign; #include <vector> #include <list> #include <AL/al.h> #include <boost/utility.hpp> #include "sfx.h" #include "sfxdriver.h" #include "sfxdriver_openal.h" #include "gusanos/gconsole.h" #include "CGameObject.h" #include "util/macros.h" #include "Debug.h" using namespace std; Sfx sfx; namespace { bool m_initialized = false; std::vector<Listener*> listeners; } void update_volume( int oldValue ) { notes<<"update_volume"<<endl; if (sfx) sfx.volumeChange(); } Sfx::Sfx():driver(0) { } Sfx::~Sfx() { if (driver) { delete driver; driver = NULL; m_initialized = false; } } bool Sfx::init() { //notes<<"Sfx::init()"<<endl; driver = new SfxDriverOpenAL(); m_initialized = driver->init(); return m_initialized; } void Sfx::shutDown() { if(driver) driver->shutDown(); m_initialized = false; } void Sfx::registerInConsole() { notes<<"Sfx::registerInConsole()"<<endl; if (driver && m_initialized) { driver->registerInConsole(); } } void Sfx::think() { if(driver) { driver->setListeners(listeners); driver->think(); } } SfxDriver* Sfx::getDriver() { return driver; } void Sfx::clear() { if(driver) driver->clear(); } void Sfx::registerListener(Listener* l) { listeners.push_back(l); } void Sfx::removeListener(Listener* listener) { vector<Listener*>::iterator i; for ( i = listeners.begin(); i != listeners.end(); ++i ) { if ( listener == *i ) { listeners.erase(i); break; } } } void Sfx::volumeChange() { if(driver) driver->volumeChange(); } Sfx::operator bool() { return m_initialized; } #endif <|endoftext|>
<commit_before>/* * Copyright 2018 Google, Inc. * * 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 copyright holders 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. * * Authors: Gabe Black */ #include "systemc/core/process.hh" #include "base/logging.hh" #include "systemc/core/event.hh" #include "systemc/core/scheduler.hh" #include "systemc/ext/core/sc_process_handle.hh" #include "systemc/ext/utils/sc_report_handler.hh" namespace sc_gem5 { SensitivityTimeout::SensitivityTimeout(Process *p, ::sc_core::sc_time t) : Sensitivity(p), timeoutEvent(this), time(t) { Tick when = scheduler.getCurTick() + time.value(); scheduler.schedule(&timeoutEvent, when); } SensitivityTimeout::~SensitivityTimeout() { if (timeoutEvent.scheduled()) scheduler.deschedule(&timeoutEvent); } void SensitivityTimeout::timeout() { scheduler.eventHappened(); notify(); } SensitivityEvent::SensitivityEvent( Process *p, const ::sc_core::sc_event *e) : Sensitivity(p), event(e) { Event::getFromScEvent(event)->addSensitivity(this); } SensitivityEvent::~SensitivityEvent() { Event::getFromScEvent(event)->delSensitivity(this); } SensitivityEventAndList::SensitivityEventAndList( Process *p, const ::sc_core::sc_event_and_list *list) : Sensitivity(p), list(list), count(0) { for (auto e: list->events) Event::getFromScEvent(e)->addSensitivity(this); } SensitivityEventAndList::~SensitivityEventAndList() { for (auto e: list->events) Event::getFromScEvent(e)->delSensitivity(this); } void SensitivityEventAndList::notifyWork(Event *e) { e->delSensitivity(this); count++; if (count == list->events.size()) process->satisfySensitivity(this); } SensitivityEventOrList::SensitivityEventOrList( Process *p, const ::sc_core::sc_event_or_list *list) : Sensitivity(p), list(list) { for (auto e: list->events) Event::getFromScEvent(e)->addSensitivity(this); } SensitivityEventOrList::~SensitivityEventOrList() { for (auto e: list->events) Event::getFromScEvent(e)->delSensitivity(this); } class UnwindExceptionReset : public ::sc_core::sc_unwind_exception { public: UnwindExceptionReset() { _isReset = true; } }; class UnwindExceptionKill : public ::sc_core::sc_unwind_exception { public: UnwindExceptionKill() {} }; template <typename T> struct BuiltinExceptionWrapper : public ExceptionWrapperBase { public: T t; void throw_it() override { throw t; } }; BuiltinExceptionWrapper<UnwindExceptionReset> resetException; BuiltinExceptionWrapper<UnwindExceptionKill> killException; void Process::forEachKid(const std::function<void(Process *)> &work) { for (auto &kid: get_child_objects()) { Process *p_kid = dynamic_cast<Process *>(kid); if (p_kid) work(p_kid); } } void Process::suspend(bool inc_kids) { if (inc_kids) forEachKid([](Process *p) { p->suspend(true); }); if (!_suspended) { _suspended = true; _suspendedReady = false; } if (procKind() != ::sc_core::SC_METHOD_PROC_ && scheduler.current() == this) { scheduler.yield(); } } void Process::resume(bool inc_kids) { if (inc_kids) forEachKid([](Process *p) { p->resume(true); }); if (_suspended) { _suspended = false; if (_suspendedReady) ready(); _suspendedReady = false; } } void Process::disable(bool inc_kids) { if (inc_kids) forEachKid([](Process *p) { p->disable(true); }); if (!::sc_core::sc_allow_process_control_corners && dynamic_cast<SensitivityTimeout *>(dynamicSensitivity)) { std::string message("attempt to disable a thread with timeout wait: "); message += name(); SC_REPORT_ERROR("Undefined process control interaction", message.c_str()); } _disabled = true; } void Process::enable(bool inc_kids) { if (inc_kids) forEachKid([](Process *p) { p->enable(true); }); _disabled = false; } void Process::kill(bool inc_kids) { // Propogate the kill to our children no matter what happens to us. if (inc_kids) forEachKid([](Process *p) { p->kill(true); }); // If we're in the middle of unwinding, ignore the kill request. if (_isUnwinding) return; // Update our state. terminate(); _isUnwinding = true; // Make sure this process isn't marked ready popListNode(); // Inject the kill exception into this process if it's started. if (!_needsStart) injectException(killException); _terminatedEvent.notify(); } void Process::reset(bool inc_kids) { // Propogate the reset to our children no matter what happens to us. if (inc_kids) forEachKid([](Process *p) { p->reset(true); }); // If we're in the middle of unwinding, ignore the reset request. if (_isUnwinding) return; if (_needsStart) { scheduler.runNow(this); } else { _isUnwinding = true; injectException(resetException); } _resetEvent.notify(); } void Process::throw_it(ExceptionWrapperBase &exc, bool inc_kids) { if (inc_kids) forEachKid([&exc](Process *p) { p->throw_it(exc, true); }); // Only inject an exception into threads that have started. if (!_needsStart) injectException(exc); } void Process::injectException(ExceptionWrapperBase &exc) { excWrapper = &exc; scheduler.runNow(this); }; void Process::syncResetOn(bool inc_kids) { if (inc_kids) forEachKid([](Process *p) { p->syncResetOn(true); }); _syncReset = true; } void Process::syncResetOff(bool inc_kids) { if (inc_kids) forEachKid([](Process *p) { p->syncResetOff(true); }); _syncReset = false; } void Process::dontInitialize() { scheduler.dontInitialize(this); } void Process::finalize() { for (auto &s: pendingStaticSensitivities) { s->finalize(staticSensitivities); delete s; s = nullptr; } pendingStaticSensitivities.clear(); }; void Process::run() { bool reset; do { reset = false; try { func->call(); } catch(const ::sc_core::sc_unwind_exception &exc) { reset = exc.is_reset(); _isUnwinding = false; } } while (reset); } void Process::addStatic(PendingSensitivity *s) { pendingStaticSensitivities.push_back(s); } void Process::setDynamic(Sensitivity *s) { delete dynamicSensitivity; dynamicSensitivity = s; } void Process::satisfySensitivity(Sensitivity *s) { // If there's a dynamic sensitivity and this wasn't it, ignore. if (dynamicSensitivity && dynamicSensitivity != s) return; setDynamic(nullptr); ready(); } void Process::ready() { if (disabled()) return; if (suspended()) _suspendedReady = true; else scheduler.ready(this); } void Process::lastReport(::sc_core::sc_report *report) { if (report) { _lastReport = std::unique_ptr<::sc_core::sc_report>( new ::sc_core::sc_report(*report)); } else { _lastReport = nullptr; } } ::sc_core::sc_report *Process::lastReport() const { return _lastReport.get(); } Process::Process(const char *name, ProcessFuncWrapper *func, bool _dynamic) : ::sc_core::sc_object(name), excWrapper(nullptr), func(func), _needsStart(true), _dynamic(_dynamic), _isUnwinding(false), _terminated(false), _suspended(false), _disabled(false), _syncReset(false), refCount(0), stackSize(::Fiber::DefaultStackSize), dynamicSensitivity(nullptr) { _newest = this; } void Process::terminate() { _terminated = true; _suspendedReady = false; _suspended = false; _syncReset = false; delete dynamicSensitivity; dynamicSensitivity = nullptr; for (auto s: staticSensitivities) delete s; staticSensitivities.clear(); } Process *Process::_newest; void throw_it_wrapper(Process *p, ExceptionWrapperBase &exc, bool inc_kids) { p->throw_it(exc, inc_kids); } } // namespace sc_gem5 <commit_msg>systemc: Ensure the terminated event is notified in all cases.<commit_after>/* * Copyright 2018 Google, Inc. * * 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 copyright holders 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. * * Authors: Gabe Black */ #include "systemc/core/process.hh" #include "base/logging.hh" #include "systemc/core/event.hh" #include "systemc/core/scheduler.hh" #include "systemc/ext/core/sc_process_handle.hh" #include "systemc/ext/utils/sc_report_handler.hh" namespace sc_gem5 { SensitivityTimeout::SensitivityTimeout(Process *p, ::sc_core::sc_time t) : Sensitivity(p), timeoutEvent(this), time(t) { Tick when = scheduler.getCurTick() + time.value(); scheduler.schedule(&timeoutEvent, when); } SensitivityTimeout::~SensitivityTimeout() { if (timeoutEvent.scheduled()) scheduler.deschedule(&timeoutEvent); } void SensitivityTimeout::timeout() { scheduler.eventHappened(); notify(); } SensitivityEvent::SensitivityEvent( Process *p, const ::sc_core::sc_event *e) : Sensitivity(p), event(e) { Event::getFromScEvent(event)->addSensitivity(this); } SensitivityEvent::~SensitivityEvent() { Event::getFromScEvent(event)->delSensitivity(this); } SensitivityEventAndList::SensitivityEventAndList( Process *p, const ::sc_core::sc_event_and_list *list) : Sensitivity(p), list(list), count(0) { for (auto e: list->events) Event::getFromScEvent(e)->addSensitivity(this); } SensitivityEventAndList::~SensitivityEventAndList() { for (auto e: list->events) Event::getFromScEvent(e)->delSensitivity(this); } void SensitivityEventAndList::notifyWork(Event *e) { e->delSensitivity(this); count++; if (count == list->events.size()) process->satisfySensitivity(this); } SensitivityEventOrList::SensitivityEventOrList( Process *p, const ::sc_core::sc_event_or_list *list) : Sensitivity(p), list(list) { for (auto e: list->events) Event::getFromScEvent(e)->addSensitivity(this); } SensitivityEventOrList::~SensitivityEventOrList() { for (auto e: list->events) Event::getFromScEvent(e)->delSensitivity(this); } class UnwindExceptionReset : public ::sc_core::sc_unwind_exception { public: UnwindExceptionReset() { _isReset = true; } }; class UnwindExceptionKill : public ::sc_core::sc_unwind_exception { public: UnwindExceptionKill() {} }; template <typename T> struct BuiltinExceptionWrapper : public ExceptionWrapperBase { public: T t; void throw_it() override { throw t; } }; BuiltinExceptionWrapper<UnwindExceptionReset> resetException; BuiltinExceptionWrapper<UnwindExceptionKill> killException; void Process::forEachKid(const std::function<void(Process *)> &work) { for (auto &kid: get_child_objects()) { Process *p_kid = dynamic_cast<Process *>(kid); if (p_kid) work(p_kid); } } void Process::suspend(bool inc_kids) { if (inc_kids) forEachKid([](Process *p) { p->suspend(true); }); if (!_suspended) { _suspended = true; _suspendedReady = false; } if (procKind() != ::sc_core::SC_METHOD_PROC_ && scheduler.current() == this) { scheduler.yield(); } } void Process::resume(bool inc_kids) { if (inc_kids) forEachKid([](Process *p) { p->resume(true); }); if (_suspended) { _suspended = false; if (_suspendedReady) ready(); _suspendedReady = false; } } void Process::disable(bool inc_kids) { if (inc_kids) forEachKid([](Process *p) { p->disable(true); }); if (!::sc_core::sc_allow_process_control_corners && dynamic_cast<SensitivityTimeout *>(dynamicSensitivity)) { std::string message("attempt to disable a thread with timeout wait: "); message += name(); SC_REPORT_ERROR("Undefined process control interaction", message.c_str()); } _disabled = true; } void Process::enable(bool inc_kids) { if (inc_kids) forEachKid([](Process *p) { p->enable(true); }); _disabled = false; } void Process::kill(bool inc_kids) { // Propogate the kill to our children no matter what happens to us. if (inc_kids) forEachKid([](Process *p) { p->kill(true); }); // If we're in the middle of unwinding, ignore the kill request. if (_isUnwinding) return; // Update our state. terminate(); _isUnwinding = true; // Make sure this process isn't marked ready popListNode(); // Inject the kill exception into this process if it's started. if (!_needsStart) injectException(killException); } void Process::reset(bool inc_kids) { // Propogate the reset to our children no matter what happens to us. if (inc_kids) forEachKid([](Process *p) { p->reset(true); }); // If we're in the middle of unwinding, ignore the reset request. if (_isUnwinding) return; if (_needsStart) { scheduler.runNow(this); } else { _isUnwinding = true; injectException(resetException); } _resetEvent.notify(); } void Process::throw_it(ExceptionWrapperBase &exc, bool inc_kids) { if (inc_kids) forEachKid([&exc](Process *p) { p->throw_it(exc, true); }); // Only inject an exception into threads that have started. if (!_needsStart) injectException(exc); } void Process::injectException(ExceptionWrapperBase &exc) { excWrapper = &exc; scheduler.runNow(this); }; void Process::syncResetOn(bool inc_kids) { if (inc_kids) forEachKid([](Process *p) { p->syncResetOn(true); }); _syncReset = true; } void Process::syncResetOff(bool inc_kids) { if (inc_kids) forEachKid([](Process *p) { p->syncResetOff(true); }); _syncReset = false; } void Process::dontInitialize() { scheduler.dontInitialize(this); } void Process::finalize() { for (auto &s: pendingStaticSensitivities) { s->finalize(staticSensitivities); delete s; s = nullptr; } pendingStaticSensitivities.clear(); }; void Process::run() { bool reset; do { reset = false; try { func->call(); } catch(const ::sc_core::sc_unwind_exception &exc) { reset = exc.is_reset(); _isUnwinding = false; } } while (reset); } void Process::addStatic(PendingSensitivity *s) { pendingStaticSensitivities.push_back(s); } void Process::setDynamic(Sensitivity *s) { delete dynamicSensitivity; dynamicSensitivity = s; } void Process::satisfySensitivity(Sensitivity *s) { // If there's a dynamic sensitivity and this wasn't it, ignore. if (dynamicSensitivity && dynamicSensitivity != s) return; setDynamic(nullptr); ready(); } void Process::ready() { if (disabled()) return; if (suspended()) _suspendedReady = true; else scheduler.ready(this); } void Process::lastReport(::sc_core::sc_report *report) { if (report) { _lastReport = std::unique_ptr<::sc_core::sc_report>( new ::sc_core::sc_report(*report)); } else { _lastReport = nullptr; } } ::sc_core::sc_report *Process::lastReport() const { return _lastReport.get(); } Process::Process(const char *name, ProcessFuncWrapper *func, bool _dynamic) : ::sc_core::sc_object(name), excWrapper(nullptr), func(func), _needsStart(true), _dynamic(_dynamic), _isUnwinding(false), _terminated(false), _suspended(false), _disabled(false), _syncReset(false), refCount(0), stackSize(::Fiber::DefaultStackSize), dynamicSensitivity(nullptr) { _newest = this; } void Process::terminate() { _terminated = true; _suspendedReady = false; _suspended = false; _syncReset = false; delete dynamicSensitivity; dynamicSensitivity = nullptr; for (auto s: staticSensitivities) delete s; staticSensitivities.clear(); _terminatedEvent.notify(); } Process *Process::_newest; void throw_it_wrapper(Process *p, ExceptionWrapperBase &exc, bool inc_kids) { p->throw_it(exc, inc_kids); } } // namespace sc_gem5 <|endoftext|>
<commit_before>// Copyright (c) 2012 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 <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Satoshi"); // Client version number #define CLIENT_VERSION_SUFFIX "-beta" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$ #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "$Format:%h$" # define GIT_COMMIT_DATE "$Format:%cD$" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <commit_msg>version management modification<commit_after>// Copyright (c) 2012 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 <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Satoshi"); // Client version number #define CLIENT_VERSION_SUFFIX "-beta" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested //#ifdef HAVE_BUILD_INFO //# include "build.h" //#endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$ //#ifdef GIT_ARCHIVE //# define GIT_COMMIT_ID "$Format:%h$" //# define GIT_COMMIT_DATE "$Format:%cD$" //#endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <|endoftext|>
<commit_before>#ifndef _OUROBOROS_BASE_HPP_ #define _OUROBOROS_BASE_HPP_ #include <string> #include <memory> namespace ouroboros { //Have this verify that our code generator is generating valid structures bool validateStructure(); class base_field { public: base_field( const std::string& aTitle, const std::string& aDescription); virtual ~base_field() = 0; std::string getTitle() const; std::string getDescription() const; void setTitle(const std::string& aTitle); void setDescription(const std::string& aDescription); private: std::string mTitle; std::string mDescription; }; class var_field : base_field { public: var_field( const std::string& aTitle, const std::string& aDescription, const std::string& aValue); virtual ~var_field() = 0; std::string getValue() const; private: std::string mValue; }; class group { public: group() = default; virtual ~group() = default; void add(std::unique_ptr<base_field>&& aField); std::unique_ptr<base_field>&& remove(); base_field *get(std::size_t aIndex) const; base_field *find(std::string aName) const; std::size_t getSize() const; }; class base_string : var_field { public: base_string( const std::string& aTitle, const std::string& aDescription, const std::string& aValue, const std::string& aPattern, std::size_t aLength, std::size_t aMinLength, std::size_t aMaxLength); std::string getPattern() const; std::size_t getLength() const; std::size_t getMinLength() const; std::size_t getMaxLength() const; void setPattern(const std::string& aPattern); void setLength(const std::size_t& aLength); void setMinLength(const std::size_t& aMinLength); void setMaxLength(const std::size_t& aMaxLength); private: std::string mPattern; std::size_t mLength; std::size_t mMinLength; std::size_t mMaxLength; }; class base_integer : var_field { public: base_integer( const std::string& aTitle, const std::string& aDescription, const std::string& aValue, std::size_t aMinInclusive, std::size_t aMaxInclusive, std::size_t aMinExclusive, std::size_t aMaxExclusive); std::size_t getMaxInclusive() const; std::size_t getMinInclusive() const; std::size_t getMaxExclusive() const; std::size_t getMinExclusive() const; void setMaxInclusive(const std::size_t& aMaxInclusive); void setMinInclusive(const std::size_t& aMinInclusive); void setMaxExclusive(const std::size_t& aMaxExclusive); void setMinExclusive(const std::size_t& aMinExclusive); private: std::size_t mMaxInclusive; std::size_t mMinInclusive; }; } #endif//_OUROBOROS_BASE_HPP_ <commit_msg>Fixed bug where classes weren't inheriting publicly.<commit_after>#ifndef _OUROBOROS_BASE_HPP_ #define _OUROBOROS_BASE_HPP_ #include <string> #include <memory> namespace ouroboros { //Have this verify that our code generator is generating valid structures bool validateStructure(); class base_field { public: base_field( const std::string& aTitle, const std::string& aDescription); virtual ~base_field() = 0; std::string getTitle() const; std::string getDescription() const; void setTitle(const std::string& aTitle); void setDescription(const std::string& aDescription); private: std::string mTitle; std::string mDescription; }; class var_field : public base_field { public: var_field( const std::string& aTitle, const std::string& aDescription, const std::string& aValue); virtual ~var_field() = 0; std::string getValue() const; private: std::string mValue; }; class group { public: group() = default; virtual ~group() = default; void add(std::unique_ptr<base_field>&& aField); std::unique_ptr<base_field>&& remove(); base_field *get(std::size_t aIndex) const; base_field *find(std::string aName) const; std::size_t getSize() const; }; class base_string : public var_field { public: base_string( const std::string& aTitle, const std::string& aDescription, const std::string& aValue, const std::string& aPattern, std::size_t aLength, std::size_t aMinLength, std::size_t aMaxLength); std::string getPattern() const; std::size_t getLength() const; std::size_t getMinLength() const; std::size_t getMaxLength() const; void setPattern(const std::string& aPattern); void setLength(const std::size_t& aLength); void setMinLength(const std::size_t& aMinLength); void setMaxLength(const std::size_t& aMaxLength); private: std::string mPattern; std::size_t mLength; std::size_t mMinLength; std::size_t mMaxLength; }; class base_integer : public var_field { public: base_integer( const std::string& aTitle, const std::string& aDescription, const std::string& aValue, std::size_t aMinInclusive, std::size_t aMaxInclusive, std::size_t aMinExclusive, std::size_t aMaxExclusive); std::size_t getMaxInclusive() const; std::size_t getMinInclusive() const; std::size_t getMaxExclusive() const; std::size_t getMinExclusive() const; void setMaxInclusive(const std::size_t& aMaxInclusive); void setMinInclusive(const std::size_t& aMinInclusive); void setMaxExclusive(const std::size_t& aMaxExclusive); void setMinExclusive(const std::size_t& aMinExclusive); private: std::size_t mMaxInclusive; std::size_t mMinInclusive; }; } #endif//_OUROBOROS_BASE_HPP_ <|endoftext|>
<commit_before>#include "version.hpp" // Get the git version macro from the build system #include "vg_git_version.hpp" // Do the same for the build environment info #include "vg_environment_version.hpp" #include <iostream> #include <sstream> namespace vg { using namespace std; // Define all the strings as the macros' values const string Version::VERSION = VG_GIT_VERSION; const string Version::COMPILER = VG_COMPILER_VERSION; const string Version::OS = VG_OS; const string Version::BUILD_USER = VG_BUILD_USER; const string Version::BUILD_HOST = VG_BUILD_HOST; // Keep the list of codenames. // Add new codenames here const unordered_map<string, string> Version::codenames = { {"v1.8.0", "Vallata"}, {"v1.9.0", "Miglionico"}, {"v1.10.0", "Rionero"}, {"v1.11.0", "Cairano"} // Add more codenames here }; string Version::get_version() { return VERSION; } string Version::get_release() { auto dash = VERSION.find('-'); if (dash == -1) { // Pure tag versions have no dash return VERSION; } else { // Otherwise it is tag-count-ghash and the tag describes the release return VERSION.substr(0, dash); } } string Version::get_codename() { auto release = get_release(); auto found = codenames.find(release); if (found == codenames.end()) { // No known codename for this release. // Return an empty string so we can just not show it. return ""; } else { // We have a known codename! return found->second; } } string Version::get_short() { stringstream s; s << VERSION; auto codename = get_codename(); if (!codename.empty()) { // Add the codename if we have one s << " \"" << codename << "\""; } return s.str(); } string Version::get_long() { stringstream s; s << "vg version " << get_short() << endl; s << "Compiled with " << COMPILER << " on " << OS << endl; s << "Built by " << BUILD_USER << "@" << BUILD_HOST; return s.str(); } } <commit_msg>Add a bunch of codenames<commit_after>#include "version.hpp" // Get the git version macro from the build system #include "vg_git_version.hpp" // Do the same for the build environment info #include "vg_environment_version.hpp" #include <iostream> #include <sstream> namespace vg { using namespace std; // Define all the strings as the macros' values const string Version::VERSION = VG_GIT_VERSION; const string Version::COMPILER = VG_COMPILER_VERSION; const string Version::OS = VG_OS; const string Version::BUILD_USER = VG_BUILD_USER; const string Version::BUILD_HOST = VG_BUILD_HOST; // Keep the list of codenames. // Add new codenames here const unordered_map<string, string> Version::codenames = { {"v1.8.0", "Vallata"}, {"v1.9.0", "Miglionico"}, {"v1.10.0", "Rionero"}, {"v1.11.0", "Cairano"}, {"v1.12.0", "Candida"}, {"v1.13.0", "Moschiano"}, {"v1.14.0", "Quadrelle"}, {"v1.15.0", "Tufo"}, {"v1.16.0", "Rotondi"}, {"v1.17.0", "Parolise"}, {"v1.18.0", "Zungoli"}, {"v1.19.0", "Tramutola"}, {"v1.20.0", "Ginestra"} // Add more codenames here }; string Version::get_version() { return VERSION; } string Version::get_release() { auto dash = VERSION.find('-'); if (dash == -1) { // Pure tag versions have no dash return VERSION; } else { // Otherwise it is tag-count-ghash and the tag describes the release return VERSION.substr(0, dash); } } string Version::get_codename() { auto release = get_release(); auto found = codenames.find(release); if (found == codenames.end()) { // No known codename for this release. // Return an empty string so we can just not show it. return ""; } else { // We have a known codename! return found->second; } } string Version::get_short() { stringstream s; s << VERSION; auto codename = get_codename(); if (!codename.empty()) { // Add the codename if we have one s << " \"" << codename << "\""; } return s.str(); } string Version::get_long() { stringstream s; s << "vg version " << get_short() << endl; s << "Compiled with " << COMPILER << " on " << OS << endl; s << "Built by " << BUILD_USER << "@" << BUILD_HOST; return s.str(); } } <|endoftext|>
<commit_before>//===------------------------ stdexcept.cpp -------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "stdexcept" #include "new" #include "string" #include <cstdlib> #include <cstring> #include <cstdint> #include <cstddef> #include "system_error" #ifndef __has_include #define __has_include(inc) 0 #endif #ifdef __APPLE__ #include <cxxabi.h> #elif defined(LIBCXXRT) || __has_include(<cxxabi.h>) #include <cxxabi.h> #endif // Note: optimize for size #if ! defined(_LIBCPP_MSVC) #pragma GCC visibility push(hidden) #endif namespace { class __libcpp_nmstr { private: const char* str_; typedef std::size_t unused_t; typedef std::ptrdiff_t count_t; static const std::ptrdiff_t offset = static_cast<std::ptrdiff_t>(2*sizeof(unused_t) + sizeof(count_t)); count_t& count() const _NOEXCEPT {return *const_cast<count_t *>(reinterpret_cast<const count_t *>(str_ - sizeof(count_t)));} public: explicit __libcpp_nmstr(const char* msg); __libcpp_nmstr(const __libcpp_nmstr& s) _NOEXCEPT; __libcpp_nmstr& operator=(const __libcpp_nmstr& s) _NOEXCEPT; ~__libcpp_nmstr(); const char* c_str() const _NOEXCEPT {return str_;} }; __libcpp_nmstr::__libcpp_nmstr(const char* msg) { std::size_t len = strlen(msg); str_ = new char[len + 1 + offset]; unused_t* c = reinterpret_cast<unused_t*>(const_cast<char *>(str_)); c[0] = c[1] = len; str_ += offset; count() = 0; std::memcpy(const_cast<char*>(c_str()), msg, len + 1); } inline __libcpp_nmstr::__libcpp_nmstr(const __libcpp_nmstr& s) _NOEXCEPT : str_(s.str_) { __sync_add_and_fetch(&count(), 1); } __libcpp_nmstr& __libcpp_nmstr::operator=(const __libcpp_nmstr& s) _NOEXCEPT { const char* p = str_; str_ = s.str_; __sync_add_and_fetch(&count(), 1); if (__sync_add_and_fetch((count_t*)(p-sizeof(count_t)), count_t(-1)) < 0) delete [] (p-offset); return *this; } inline __libcpp_nmstr::~__libcpp_nmstr() { if (__sync_add_and_fetch(&count(), count_t(-1)) < 0) delete [] (str_ - offset); } } #if ! defined(_LIBCPP_MSVC) #pragma GCC visibility pop #endif namespace std // purposefully not using versioning namespace { logic_error::logic_error(const string& msg) { __libcpp_nmstr *s = reinterpret_cast<__libcpp_nmstr *>(&__imp_); ::new(s) __libcpp_nmstr(msg.c_str()); } logic_error::logic_error(const char* msg) { __libcpp_nmstr *s = reinterpret_cast<__libcpp_nmstr *>(&__imp_); ::new(s) __libcpp_nmstr(msg); } logic_error::logic_error(const logic_error& le) _NOEXCEPT { __libcpp_nmstr *s = reinterpret_cast<__libcpp_nmstr *>(&__imp_); const __libcpp_nmstr *s2 = reinterpret_cast<const __libcpp_nmstr *>(&le.__imp_); ::new(s) __libcpp_nmstr(*s2); } logic_error& logic_error::operator=(const logic_error& le) _NOEXCEPT { __libcpp_nmstr *s1 = reinterpret_cast<__libcpp_nmstr *>(&__imp_); const __libcpp_nmstr *s2 = reinterpret_cast<const __libcpp_nmstr *>(&le.__imp_); *s1 = *s2; return *this; } #if !defined(_LIBCPPABI_VERSION) && !defined(LIBSTDCXX) logic_error::~logic_error() _NOEXCEPT { __libcpp_nmstr *s = reinterpret_cast<__libcpp_nmstr *>(&__imp_); s->~__libcpp_nmstr(); } const char* logic_error::what() const _NOEXCEPT { const __libcpp_nmstr *s = reinterpret_cast<const __libcpp_nmstr *>(&__imp_); return s->c_str(); } #endif runtime_error::runtime_error(const string& msg) { __libcpp_nmstr *s = reinterpret_cast<__libcpp_nmstr *>(&__imp_); ::new(s) __libcpp_nmstr(msg.c_str()); } runtime_error::runtime_error(const char* msg) { __libcpp_nmstr *s = reinterpret_cast<__libcpp_nmstr *>(&__imp_); ::new(s) __libcpp_nmstr(msg); } runtime_error::runtime_error(const runtime_error& le) _NOEXCEPT { __libcpp_nmstr *s = reinterpret_cast<__libcpp_nmstr *>(&__imp_); const __libcpp_nmstr *s2 = reinterpret_cast<const __libcpp_nmstr *>(&le.__imp_); ::new(s) __libcpp_nmstr(*s2); } runtime_error& runtime_error::operator=(const runtime_error& le) _NOEXCEPT { __libcpp_nmstr *s1 = reinterpret_cast<__libcpp_nmstr *>(&__imp_); const __libcpp_nmstr *s2 = reinterpret_cast<const __libcpp_nmstr *>(&le.__imp_); *s1 = *s2; return *this; } #if !defined(_LIBCPPABI_VERSION) && !defined(LIBSTDCXX) runtime_error::~runtime_error() _NOEXCEPT { __libcpp_nmstr *s = reinterpret_cast<__libcpp_nmstr *>(&__imp_); s->~__libcpp_nmstr(); } const char* runtime_error::what() const _NOEXCEPT { const __libcpp_nmstr *s = reinterpret_cast<const __libcpp_nmstr *>(&__imp_); return s->c_str(); } domain_error::~domain_error() _NOEXCEPT {} invalid_argument::~invalid_argument() _NOEXCEPT {} length_error::~length_error() _NOEXCEPT {} out_of_range::~out_of_range() _NOEXCEPT {} range_error::~range_error() _NOEXCEPT {} overflow_error::~overflow_error() _NOEXCEPT {} underflow_error::~underflow_error() _NOEXCEPT {} #endif } // std <commit_msg>Adjust build fix from r199494 to use C++ casts<commit_after>//===------------------------ stdexcept.cpp -------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "stdexcept" #include "new" #include "string" #include <cstdlib> #include <cstring> #include <cstdint> #include <cstddef> #include "system_error" #ifndef __has_include #define __has_include(inc) 0 #endif #ifdef __APPLE__ #include <cxxabi.h> #elif defined(LIBCXXRT) || __has_include(<cxxabi.h>) #include <cxxabi.h> #endif // Note: optimize for size #if ! defined(_LIBCPP_MSVC) #pragma GCC visibility push(hidden) #endif namespace { class __libcpp_nmstr { private: const char* str_; typedef std::size_t unused_t; typedef std::ptrdiff_t count_t; static const std::ptrdiff_t offset = static_cast<std::ptrdiff_t>(2*sizeof(unused_t) + sizeof(count_t)); count_t& count() const _NOEXCEPT {return *const_cast<count_t *>(reinterpret_cast<const count_t *>(str_ - sizeof(count_t)));} public: explicit __libcpp_nmstr(const char* msg); __libcpp_nmstr(const __libcpp_nmstr& s) _NOEXCEPT; __libcpp_nmstr& operator=(const __libcpp_nmstr& s) _NOEXCEPT; ~__libcpp_nmstr(); const char* c_str() const _NOEXCEPT {return str_;} }; __libcpp_nmstr::__libcpp_nmstr(const char* msg) { std::size_t len = strlen(msg); str_ = new char[len + 1 + offset]; unused_t* c = reinterpret_cast<unused_t*>(const_cast<char *>(str_)); c[0] = c[1] = len; str_ += offset; count() = 0; std::memcpy(const_cast<char*>(c_str()), msg, len + 1); } inline __libcpp_nmstr::__libcpp_nmstr(const __libcpp_nmstr& s) _NOEXCEPT : str_(s.str_) { __sync_add_and_fetch(&count(), 1); } __libcpp_nmstr& __libcpp_nmstr::operator=(const __libcpp_nmstr& s) _NOEXCEPT { const char* p = str_; str_ = s.str_; __sync_add_and_fetch(&count(), 1); if (__sync_add_and_fetch(reinterpret_cast<count_t*>(const_cast<char*>(p)-sizeof(count_t)), count_t(-1)) < 0) delete [] (p-offset); return *this; } inline __libcpp_nmstr::~__libcpp_nmstr() { if (__sync_add_and_fetch(&count(), count_t(-1)) < 0) delete [] (str_ - offset); } } #if ! defined(_LIBCPP_MSVC) #pragma GCC visibility pop #endif namespace std // purposefully not using versioning namespace { logic_error::logic_error(const string& msg) { __libcpp_nmstr *s = reinterpret_cast<__libcpp_nmstr *>(&__imp_); ::new(s) __libcpp_nmstr(msg.c_str()); } logic_error::logic_error(const char* msg) { __libcpp_nmstr *s = reinterpret_cast<__libcpp_nmstr *>(&__imp_); ::new(s) __libcpp_nmstr(msg); } logic_error::logic_error(const logic_error& le) _NOEXCEPT { __libcpp_nmstr *s = reinterpret_cast<__libcpp_nmstr *>(&__imp_); const __libcpp_nmstr *s2 = reinterpret_cast<const __libcpp_nmstr *>(&le.__imp_); ::new(s) __libcpp_nmstr(*s2); } logic_error& logic_error::operator=(const logic_error& le) _NOEXCEPT { __libcpp_nmstr *s1 = reinterpret_cast<__libcpp_nmstr *>(&__imp_); const __libcpp_nmstr *s2 = reinterpret_cast<const __libcpp_nmstr *>(&le.__imp_); *s1 = *s2; return *this; } #if !defined(_LIBCPPABI_VERSION) && !defined(LIBSTDCXX) logic_error::~logic_error() _NOEXCEPT { __libcpp_nmstr *s = reinterpret_cast<__libcpp_nmstr *>(&__imp_); s->~__libcpp_nmstr(); } const char* logic_error::what() const _NOEXCEPT { const __libcpp_nmstr *s = reinterpret_cast<const __libcpp_nmstr *>(&__imp_); return s->c_str(); } #endif runtime_error::runtime_error(const string& msg) { __libcpp_nmstr *s = reinterpret_cast<__libcpp_nmstr *>(&__imp_); ::new(s) __libcpp_nmstr(msg.c_str()); } runtime_error::runtime_error(const char* msg) { __libcpp_nmstr *s = reinterpret_cast<__libcpp_nmstr *>(&__imp_); ::new(s) __libcpp_nmstr(msg); } runtime_error::runtime_error(const runtime_error& le) _NOEXCEPT { __libcpp_nmstr *s = reinterpret_cast<__libcpp_nmstr *>(&__imp_); const __libcpp_nmstr *s2 = reinterpret_cast<const __libcpp_nmstr *>(&le.__imp_); ::new(s) __libcpp_nmstr(*s2); } runtime_error& runtime_error::operator=(const runtime_error& le) _NOEXCEPT { __libcpp_nmstr *s1 = reinterpret_cast<__libcpp_nmstr *>(&__imp_); const __libcpp_nmstr *s2 = reinterpret_cast<const __libcpp_nmstr *>(&le.__imp_); *s1 = *s2; return *this; } #if !defined(_LIBCPPABI_VERSION) && !defined(LIBSTDCXX) runtime_error::~runtime_error() _NOEXCEPT { __libcpp_nmstr *s = reinterpret_cast<__libcpp_nmstr *>(&__imp_); s->~__libcpp_nmstr(); } const char* runtime_error::what() const _NOEXCEPT { const __libcpp_nmstr *s = reinterpret_cast<const __libcpp_nmstr *>(&__imp_); return s->c_str(); } domain_error::~domain_error() _NOEXCEPT {} invalid_argument::~invalid_argument() _NOEXCEPT {} length_error::~length_error() _NOEXCEPT {} out_of_range::~out_of_range() _NOEXCEPT {} range_error::~range_error() _NOEXCEPT {} overflow_error::~overflow_error() _NOEXCEPT {} underflow_error::~underflow_error() _NOEXCEPT {} #endif } // std <|endoftext|>
<commit_before>// // ocr.cpp // license-plate-recognition // // Created by David Pearson on 10/22/14. // Copyright (c) 2014 David Pearson. All rights reserved. // #include <opencv2/opencv.hpp> #include <tesseract/baseapi.h> #include "ocr.h" using namespace cv; using namespace tesseract; char *get_plate_text(Mat *img_ptr) { // Dereference the image pointer Mat img = *img_ptr; // Chop off the top and bottom of the image to get a better look // at the license plate number // TODO: FIXME img = img(Rect(0, img.rows / 4, img.cols, img.rows / 2)); /*namedWindow("plate"); imshow("plate", img); waitKey();*/ // Perform thresholding to get a clean image for Tesseract threshold(img, img, 150, 255, CV_THRESH_BINARY); // Create and initialize a Tesseract API instance TessBaseAPI *t = new TessBaseAPI(); t->Init(NULL, "eng", OEM_DEFAULT); // Assum that there's only one block of text in the image // at this point t->SetPageSegMode(PSM_SINGLE_BLOCK); // Whitelist the characters that can actually show up in license // plates t->SetVariable("tessedit_char_whitelist", "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345789-"); // Load our image t->TesseractRect(img.data, 1, img.step1(), 0, 0, img.cols, img.rows); // Grab the text char *plate_text = t->GetUTF8Text(); printf("%s\n", plate_text); // Then dispose of the Tesseract API instance t->End(); // Return the plate text return plate_text; }<commit_msg>Improve region selection for OCR<commit_after>// // ocr.cpp // license-plate-recognition // // Created by David Pearson on 10/22/14. // Copyright (c) 2014 David Pearson. All rights reserved. // #include <opencv2/opencv.hpp> #include <tesseract/baseapi.h> #include "ocr.h" using namespace cv; using namespace tesseract; char *get_plate_text(Mat *img_ptr) { // Dereference the image pointer Mat img = *img_ptr; Mat gray = img.clone(); // Blur the image... Mat blurred(gray.cols, gray.rows, gray.type()); GaussianBlur(gray, blurred, Size(11, 11), 0, 0, BORDER_DEFAULT); // Before finding edges Mat edges_x(gray.rows, gray.cols, CV_8UC1); Mat edges(gray.rows, gray.cols, CV_8UC1); Sobel(gray, edges_x, CV_8U, 1, 0, 3, 1, 0, BORDER_DEFAULT); threshold(edges_x, edges_x, 100, 255, CV_THRESH_BINARY); Mat struct_elem = getStructuringElement(MORPH_RECT, Size(1, 5)); morphologyEx(edges_x, edges_x, MORPH_OPEN, struct_elem, Point(-1, -1), 1); int min = img.rows; int max = 0; int thresh = 10; for (int i = 0; i < img.rows; i++) { int count = 0; for (int j = 0; j < img.cols; j++) { int pixel = edges_x.at<uint8_t>(i, j, 0); if (pixel > 0) { count++; } } if (count >= thresh) { if (i < min) { min = i; } if (i > max) { max = i; } } } //printf("%d, %d\n", min, max); // Chop off the top and bottom of the image to get a better look // at the license plate number img = img(Rect(5, min, img.cols - 10, max - min)); /*namedWindow("plate"); imshow("plate", img); waitKey();*/ // Perform thresholding to get a clean image for Tesseract threshold(img, img, 150, 255, CV_THRESH_BINARY); // Create and initialize a Tesseract API instance TessBaseAPI *t = new TessBaseAPI(); t->Init(NULL, "eng", OEM_DEFAULT); // Assum that there's only one block of text in the image // at this point t->SetPageSegMode(PSM_SINGLE_BLOCK); // Whitelist the characters that can actually show up in license // plates t->SetVariable("tessedit_char_whitelist", "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345789-"); // Load our image t->TesseractRect(img.data, 1, img.step1(), 0, 0, img.cols, img.rows); // Grab the text char *plate_text = t->GetUTF8Text(); printf("%s\n", plate_text); // Then dispose of the Tesseract API instance t->End(); // Return the plate text return plate_text; }<|endoftext|>
<commit_before>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; MTL M; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read Secretfile // Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF Gals Secret; init_time_at(time,"# reading Secret file",t); Secret=read_Secretfile(F.Secretfile,F); printf("# Read %d galaxies from %s \n",Secret.size(),F.Secretfile.c_str()); print_time(time,"# ... took :"); std::vector<int> count(10); count=count_galaxies(Secret); printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n"); for(int i=0;i<8;i++){if(count[i]>0)printf (" type %d number %d \n",i, count[i]);} //read the three input fits files init_time_at(time,"# read target, SS, SF files",t); MTL Targ=read_MTLfile(F.Targfile,F,0,0); MTL SStars=read_MTLfile(F.SStarsfile,F,1,0); MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1); if(Targ.size() == 0) { std::cerr << "ERROR: No targets found in " << F.Targfile << std::endl; myexit(1); } print_time(time,"# ... took :"); //combine the three input files M=Targ; printf(" M size %d \n",M.size()); M.insert(M.end(),SStars.begin(),SStars.end()); printf(" M size %d \n",M.size()); M.insert(M.end(),SkyF.begin(),SkyF.end()); printf(" M size %d \n",M.size()); F.Ngal=M.size(); F.Ntarg=Secret.size(); //establish priority classes init_time_at(time,"# establish priority clasess",t); assign_priority_class(M); std::vector <int> count_class(M.priority_list.size(),0); for(int i;i<M.size();++i){ if(!M[i].SS&&!M[i].SF){ count_class[M[i].priority_class]+=1; } } for(int i;i<M.priority_list.size();++i){ printf(" class %d priority %d number %d\n",i,M.priority_list[i],count_class[i]); } print_time(time,"# ... took :"); // fiber positioners PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F); printf("computed neighbors\n"); std::cout.flush(); //P tiles in order specified by surveyFile Plates P = read_plate_centers(F); F.Nplate=P.size(); printf("# Read %d plates from %s and %d fibers from %s\n",F.Nplate,F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect galaxies at ",t); // For plates/fibers, collect available galaxies; done in parallel collect_galaxies_for_all(M,T,P,pp,F); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect available tile-fibers at",t); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //count number of galaxies in first pass and number not in first pass int inside=0; int outside=0; for(int g=0;g<FNtarg;++g){ Plist v=M[g].av_tfs; for(int i=0);i<v.size();++i){ if(v[i].f==0){ ++outside; break; } ++inside; } } printf ("inside = %d outisde = %d\n",inside,outside); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); Assignment A(M,F); print_time(t,"# Start assignment at : "); // Make a plan ---------------------------------------------------- // Plans whole survey without sky fibers, standard stars // assumes maximum number of observations needed for QSOs, LRGs simple_assign(M,P,pp,F,A); //check to see if there are tiles with no galaxies //need to keep mapping of old tile list to new tile list //and inverse map A.inv_order=initList(F.Nplate,-1); int inv_count=0; for (int j=0;j<F.Nplate ;++j){ bool not_done=true; for(int k=0;k<F.Nfiber && not_done;++k){ if(A.TF[j][k]!=-1){//fiber and therefore plate is used A.suborder.push_back(j);//suborder[jused] is jused-th used plate not_done=false; A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used //and otherwise the position of plate j in list of used plates inv_count++; } } } F.NUsedplate=A.suborder.size(); printf(" Plates actually used %d \n",F.NUsedplate); if(F.diagnose)diagnostic(M,Secret,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs // Smooth out distribution of free fibers, and increase the number of assignments for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly for (int i=0; i<1; i++) { improve(M,P,pp,F,A,0); redistribute_tf(M,P,pp,F,A,0); } print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); //try assigning SF and SS before real time assignment for (int jused=0;jused<F.NUsedplate;++jused){ int j=A.suborder[jused]; assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile assign_unused(j,M,P,pp,F,A); } if(F.diagnose)diagnostic(M,Secret,F,A); init_time_at(time,"# Begin real time assignment",t); //Execute plan, updating targets at intervals for(int i=0;i<F.pass_intervals.size();i++){ printf(" i=%d interval %d \n",i,F.pass_intervals[i]); } std::vector <int> update_intervals=F.pass_intervals; update_intervals.push_back(F.NUsedplate);//to end intervals at last plate for(int i=0;i<update_intervals.size();++i){ printf("i %d update_interval %d\n",i, update_intervals[i]); } for(int i=0;i<update_intervals.size()-1;++i){//go plate by used plate int starter=update_intervals[i]; printf("-- interval %d\n",i); for (int jused=starter; jused<update_intervals[i+1] && jused<A.suborder.size()-1; jused++) { if (0<=jused-F.Analysis) { update_plan_from_one_obs(jused,Secret,M,P,pp,F,A); } else printf("\n no update\n"); // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else } printf("-- redistribute %d\n",i); redistribute_tf(M,P,pp,F,A,starter); printf("-- improve %d\n",i); improve(M,P,pp,F,A,starter); printf("-- improve again %d\n",i); redistribute_tf(M,P,pp,F,A,starter); printf("-- diagnose %d\n",i); if(F.diagnose)diagnostic(M,Secret,F,A); } // check on SS and SF printf("-- Checking SS/SF\n"); List SS_hist=initList(11,0); List SF_hist=initList(41,0); for(int jused=0;jused<F.NUsedplate;++jused){ int j=A.suborder[jused]; for (int p=0;p<F.Npetal;++p){ int count_SS=0; int count_SF=0; for (int k=0;k<F.Nfbp;++k){ int kk=pp.fibers_of_sp[p][k]; int g=A.TF[j][kk]; if(g!=-1 && M[g].SS)count_SS++; if(g!=-1 && M[g].SF)count_SF++; } SS_hist[count_SS]++; SF_hist[count_SF]++; } } printf(" SS distribution \n"); for(int i=0;i<10;i++)printf("%8d",SS_hist[i]); printf("\n %8d \n",SS_hist[10]); printf(" SF distribution \n"); for(int i=0;i<10;i++)printf("%8d",SF_hist[i]); printf("\n"); for(int i=10;i<20;i++)printf("%8d",SF_hist[i]); printf("\n"); for(int i=20;i<30;i++)printf("%8d",SF_hist[i]); printf("\n"); for(int i=30;i<40;i++)printf("%8d",SF_hist[i]); printf("\n %8d \n",SF_hist[40]); // Results ------------------------------------------------------- if (F.PrintAscii){ for (int jused=0; jused<F.NUsedplate; jused++){ int j=A.suborder[jused]; write_FAtile_ascii(A.suborder[jused],F.outDir,M,P,pp,F,A); } } if (F.PrintFits) { for (int jused=0; jused<F.NUsedplate; jused++){ int j=A.suborder[jused]; fa_write(A.suborder[jused],F.outDir,M,P,pp,F,A); // Write outpu } } display_results("doc/figs/",Secret,M,P,pp,F,A,F.Nplate,true); if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane print_time(t,"# Finished !... in"); return(0); } <commit_msg>count galaxies in first pass<commit_after>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; MTL M; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read Secretfile // Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF Gals Secret; init_time_at(time,"# reading Secret file",t); Secret=read_Secretfile(F.Secretfile,F); printf("# Read %d galaxies from %s \n",Secret.size(),F.Secretfile.c_str()); print_time(time,"# ... took :"); std::vector<int> count(10); count=count_galaxies(Secret); printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n"); for(int i=0;i<8;i++){if(count[i]>0)printf (" type %d number %d \n",i, count[i]);} //read the three input fits files init_time_at(time,"# read target, SS, SF files",t); MTL Targ=read_MTLfile(F.Targfile,F,0,0); MTL SStars=read_MTLfile(F.SStarsfile,F,1,0); MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1); if(Targ.size() == 0) { std::cerr << "ERROR: No targets found in " << F.Targfile << std::endl; myexit(1); } print_time(time,"# ... took :"); //combine the three input files M=Targ; printf(" M size %d \n",M.size()); M.insert(M.end(),SStars.begin(),SStars.end()); printf(" M size %d \n",M.size()); M.insert(M.end(),SkyF.begin(),SkyF.end()); printf(" M size %d \n",M.size()); F.Ngal=M.size(); F.Ntarg=Secret.size(); //establish priority classes init_time_at(time,"# establish priority clasess",t); assign_priority_class(M); std::vector <int> count_class(M.priority_list.size(),0); for(int i;i<M.size();++i){ if(!M[i].SS&&!M[i].SF){ count_class[M[i].priority_class]+=1; } } for(int i;i<M.priority_list.size();++i){ printf(" class %d priority %d number %d\n",i,M.priority_list[i],count_class[i]); } print_time(time,"# ... took :"); // fiber positioners PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F); printf("computed neighbors\n"); std::cout.flush(); //P tiles in order specified by surveyFile Plates P = read_plate_centers(F); F.Nplate=P.size(); printf("# Read %d plates from %s and %d fibers from %s\n",F.Nplate,F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect galaxies at ",t); // For plates/fibers, collect available galaxies; done in parallel collect_galaxies_for_all(M,T,P,pp,F); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect available tile-fibers at",t); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //count number of galaxies in first pass and number not in first pass int inside=0; int outside=0; for(int g=0;g<F.Ntarg;++g){ Plist v=M[g].av_tfs; for(int i=0);i<v.size();++i){ if(v[i].f==0){ ++outside; break; } ++inside; } } printf ("inside = %d outisde = %d\n",inside,outside); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); Assignment A(M,F); print_time(t,"# Start assignment at : "); // Make a plan ---------------------------------------------------- // Plans whole survey without sky fibers, standard stars // assumes maximum number of observations needed for QSOs, LRGs simple_assign(M,P,pp,F,A); //check to see if there are tiles with no galaxies //need to keep mapping of old tile list to new tile list //and inverse map A.inv_order=initList(F.Nplate,-1); int inv_count=0; for (int j=0;j<F.Nplate ;++j){ bool not_done=true; for(int k=0;k<F.Nfiber && not_done;++k){ if(A.TF[j][k]!=-1){//fiber and therefore plate is used A.suborder.push_back(j);//suborder[jused] is jused-th used plate not_done=false; A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used //and otherwise the position of plate j in list of used plates inv_count++; } } } F.NUsedplate=A.suborder.size(); printf(" Plates actually used %d \n",F.NUsedplate); if(F.diagnose)diagnostic(M,Secret,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs // Smooth out distribution of free fibers, and increase the number of assignments for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly for (int i=0; i<1; i++) { improve(M,P,pp,F,A,0); redistribute_tf(M,P,pp,F,A,0); } print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); //try assigning SF and SS before real time assignment for (int jused=0;jused<F.NUsedplate;++jused){ int j=A.suborder[jused]; assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile assign_unused(j,M,P,pp,F,A); } if(F.diagnose)diagnostic(M,Secret,F,A); init_time_at(time,"# Begin real time assignment",t); //Execute plan, updating targets at intervals for(int i=0;i<F.pass_intervals.size();i++){ printf(" i=%d interval %d \n",i,F.pass_intervals[i]); } std::vector <int> update_intervals=F.pass_intervals; update_intervals.push_back(F.NUsedplate);//to end intervals at last plate for(int i=0;i<update_intervals.size();++i){ printf("i %d update_interval %d\n",i, update_intervals[i]); } for(int i=0;i<update_intervals.size()-1;++i){//go plate by used plate int starter=update_intervals[i]; printf("-- interval %d\n",i); for (int jused=starter; jused<update_intervals[i+1] && jused<A.suborder.size()-1; jused++) { if (0<=jused-F.Analysis) { update_plan_from_one_obs(jused,Secret,M,P,pp,F,A); } else printf("\n no update\n"); // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else } printf("-- redistribute %d\n",i); redistribute_tf(M,P,pp,F,A,starter); printf("-- improve %d\n",i); improve(M,P,pp,F,A,starter); printf("-- improve again %d\n",i); redistribute_tf(M,P,pp,F,A,starter); printf("-- diagnose %d\n",i); if(F.diagnose)diagnostic(M,Secret,F,A); } // check on SS and SF printf("-- Checking SS/SF\n"); List SS_hist=initList(11,0); List SF_hist=initList(41,0); for(int jused=0;jused<F.NUsedplate;++jused){ int j=A.suborder[jused]; for (int p=0;p<F.Npetal;++p){ int count_SS=0; int count_SF=0; for (int k=0;k<F.Nfbp;++k){ int kk=pp.fibers_of_sp[p][k]; int g=A.TF[j][kk]; if(g!=-1 && M[g].SS)count_SS++; if(g!=-1 && M[g].SF)count_SF++; } SS_hist[count_SS]++; SF_hist[count_SF]++; } } printf(" SS distribution \n"); for(int i=0;i<10;i++)printf("%8d",SS_hist[i]); printf("\n %8d \n",SS_hist[10]); printf(" SF distribution \n"); for(int i=0;i<10;i++)printf("%8d",SF_hist[i]); printf("\n"); for(int i=10;i<20;i++)printf("%8d",SF_hist[i]); printf("\n"); for(int i=20;i<30;i++)printf("%8d",SF_hist[i]); printf("\n"); for(int i=30;i<40;i++)printf("%8d",SF_hist[i]); printf("\n %8d \n",SF_hist[40]); // Results ------------------------------------------------------- if (F.PrintAscii){ for (int jused=0; jused<F.NUsedplate; jused++){ int j=A.suborder[jused]; write_FAtile_ascii(A.suborder[jused],F.outDir,M,P,pp,F,A); } } if (F.PrintFits) { for (int jused=0; jused<F.NUsedplate; jused++){ int j=A.suborder[jused]; fa_write(A.suborder[jused],F.outDir,M,P,pp,F,A); // Write outpu } } display_results("doc/figs/",Secret,M,P,pp,F,A,F.Nplate,true); if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane print_time(t,"# Finished !... in"); return(0); } <|endoftext|>
<commit_before>/* * Copyright © 2018 AperLambda <[email protected]> * * This file is part of λcommon. * * Licensed under the MIT license. For more information, * see the LICENSE file. */ #include "../../include/lambdacommon/system/fs.h" #include <lambdacommon/lstring.h> #include <stdexcept> #ifdef LAMBDA_WINDOWS #include <Windows.h> #define STAT_STRUCT _stati64 #define STAT_METHOD _stati64 #elif defined(LAMBDA_MAC_OSX) #include <errno.h> #else #include <unistd.h> #include <cstring> #include <climits> #define STAT_STRUCT stat #define STAT_METHOD stat #endif #include <sys/stat.h> namespace lambdacommon { namespace fs { std::wstring LAMBDACOMMON_API get_cwd_wstr() { #ifdef LAMBDA_WINDOWS wchar_t temp[MAX_PATH]; if (!_wgetcwd(temp, MAX_PATH)) throw std::runtime_error("fs.cpp(" + std::to_string(__LINE__ - 1) + ")@lambdacommon::fs::get_cwd_wstr(): Internal error \"" + std::to_string(GetLastError()) + "\""); return {temp}; #else return lstring::convert_string_to_wstring(get_cwd_str()); #endif } std::string LAMBDACOMMON_API get_cwd_str() { #ifdef LAMBDA_WINDOWS return lstring::convert_wstring_to_string(get_cwd_wstr()); #else char temp[PATH_MAX]; if (getcwd(temp, PATH_MAX) == nullptr) throw std::runtime_error("fs.cpp(" + std::to_string(__LINE__ - 1) + ")@lambdacommon::fs::get_cwd_str(): Internal error \"" + strerror(errno) + "\""); return {temp}; #endif } } }<commit_msg>:apple: Fixed missing getcwd() symbol.<commit_after>/* * Copyright © 2018 AperLambda <[email protected]> * * This file is part of λcommon. * * Licensed under the MIT license. For more information, * see the LICENSE file. */ #include "../../include/lambdacommon/system/fs.h" #include <lambdacommon/lstring.h> #include <stdexcept> #ifdef LAMBDA_WINDOWS #include <Windows.h> #define STAT_STRUCT _stati64 #define STAT_METHOD _stati64 #else #include <errno.h> #include <unistd.h> #include <cstring> #include <climits> #define STAT_STRUCT stat #define STAT_METHOD stat #endif #include <sys/stat.h> namespace lambdacommon { namespace fs { std::wstring LAMBDACOMMON_API get_cwd_wstr() { #ifdef LAMBDA_WINDOWS wchar_t temp[MAX_PATH]; if (!_wgetcwd(temp, MAX_PATH)) throw std::runtime_error("fs.cpp(" + std::to_string(__LINE__ - 1) + ")@lambdacommon::fs::get_cwd_wstr(): Internal error \"" + std::to_string(GetLastError()) + "\""); return {temp}; #else return lstring::convert_string_to_wstring(get_cwd_str()); #endif } std::string LAMBDACOMMON_API get_cwd_str() { #ifdef LAMBDA_WINDOWS return lstring::convert_wstring_to_string(get_cwd_wstr()); #else char temp[PATH_MAX]; if (getcwd(temp, PATH_MAX) == nullptr) throw std::runtime_error("fs.cpp(" + std::to_string(__LINE__ - 1) + ")@lambdacommon::fs::get_cwd_str(): Internal error \"" + strerror(errno) + "\""); return {temp}; #endif } } }<|endoftext|>
<commit_before>/** * \file * \brief Execute async task on application * * \author Uilian Ries <[email protected]> */ #include "task/task.hpp" #include <stdexcept> namespace smartaquarium { task::task(const std::string& _task_name, work _work, Poco::Logger& _logger) : Poco::Task(_task_name) , logger_(_logger) , work_(_work) { } void task::runTask() { } } // namespace smartaquarium <commit_msg>Fix task trigger<commit_after>/** * \file * \brief Execute async task on application * * \author Uilian Ries <[email protected]> */ #include "task/task.hpp" #include <stdexcept> namespace smartaquarium { task::task(const std::string& _task_name, work _work, Poco::Logger& _logger) : Poco::Task(_task_name) , logger_(_logger) , work_(_work) { } void task::runTask() { work_(); } } // namespace smartaquarium <|endoftext|>
<commit_before>/** * \file * \remark This file is part of VITA. * * \copyright Copyright (C) 2013-2015 EOS di Manlio Morini. * * \license * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/ */ #define MASTER_TEST_SET #define BOOST_TEST_MODULE Master Test Suite #include <boost/test/unit_test.hpp> constexpr double epsilon(0.00001); using namespace boost; #include "test/factory_fixture1.h" #include "test/factory_fixture2.h" #include "test/factory_fixture3.h" #include "test/factory_fixture4.h" #include "test/factory_fixture5.h" #include "test/evolution.cc" #include "test/evolution_selection.cc" #include "test/fitness.cc" #include "test/ga.cc" //#include "test_ga_perf.cc" #include "test/i_mep.cc" #include "test/i_ga.cc" #include "test/lambda.cc" #include "test/matrix.cc" #include "test/population.cc" #include "test/primitive_d.cc" #include "test/primitive_i.cc" #include "test/small_vector.cc" #include "test/src_constant.cc" #include "test/src_problem.cc" #include "test/summary.cc" #include "test/symbol_set.cc" #include "test/team.cc" #include "test/terminal.cc" #include "test/ttable.cc" #include "test/variant.cc" <commit_msg>[TEST] Unit test for variant class removed from tests<commit_after>/** * \file * \remark This file is part of VITA. * * \copyright Copyright (C) 2013-2015 EOS di Manlio Morini. * * \license * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/ */ #define MASTER_TEST_SET #define BOOST_TEST_MODULE Master Test Suite #include <boost/test/unit_test.hpp> constexpr double epsilon(0.00001); using namespace boost; #include "test/factory_fixture1.h" #include "test/factory_fixture2.h" #include "test/factory_fixture3.h" #include "test/factory_fixture4.h" #include "test/factory_fixture5.h" #include "test/evolution.cc" #include "test/evolution_selection.cc" #include "test/fitness.cc" #include "test/ga.cc" //#include "test_ga_perf.cc" #include "test/i_mep.cc" #include "test/i_ga.cc" #include "test/lambda.cc" #include "test/matrix.cc" #include "test/population.cc" #include "test/primitive_d.cc" #include "test/primitive_i.cc" #include "test/small_vector.cc" #include "test/src_constant.cc" #include "test/src_problem.cc" #include "test/summary.cc" #include "test/symbol_set.cc" #include "test/team.cc" #include "test/terminal.cc" #include "test/ttable.cc" //#include "test/variant.cc" <|endoftext|>
<commit_before>//============================================================================ // Name : pel.cpp // Author : Joe Selman // Version : //============================================================================ #include "PELConfig.h" #include <boost/program_options.hpp> #include <boost/tuple/tuple.hpp> namespace po = boost::program_options; #include <boost/foreach.hpp> #include <iostream> #include <cstdio> #include <string> #include <vector> #include <utility> #include <ctime> #include <map> #include <cstdlib> #include "pel.h" #include "logic/el_syntax.h" #include "logic/folparser.h" #include "logic/domain.h" #include "log.h" #include "logic/moves.h" #include "inference/maxwalksat.h" #include "logic/unit_prop.h" int main(int argc, char* argv[]) { try { // Declare the supported options. po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("version,v", "print version and exit") ("max", po::value<unsigned int>(), "maximum value an interval endpoint can take") ("min", po::value<unsigned int>(), "minimum value an interval endpoint can take") ("evalModel,e", "simply print the model weight of the facts file") ("prob,p", po::value<double>()->default_value(0.25), "probability of taking a random move") ("iterations,i", po::value<unsigned int>()->default_value(1000), "number of iterations before returning a model") ("output,o", po::value<std::string>(), "output model file") ("unitProp,u", "perform unit propagation only and exit") ("datafile,d", po::value<std::string>(), "log scores from maxwalksat to this file (csv form)") ; po::options_description hidden("Hidden options"); hidden.add_options() ("facts-file", po::value<std::string>(), "facts file") ("formula-file", po::value<std::string>(), "formula file") ; po::positional_options_description p; p.add("facts-file", 1); p.add("formula-file", 1); po::options_description cmdline_options; cmdline_options.add(desc).add(hidden); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(cmdline_options).positional(p).run(), vm); po::notify(vm); if (vm.count("version")) { std::cout << "pel version " << PEL_VERSION_MAJOR << "." << PEL_VERSION_MINOR << std::endl; return EXIT_SUCCESS; } if (vm.count("help") || !vm.count("facts-file") || !vm.count("formula-file")) { std::cout << "Usage: pel [OPTION]... FACT-FILE FORMULA-FILE" << std::endl; std::cout << desc << std::endl; return EXIT_FAILURE; } // setup our logging facilities FILE* debugFile = fopen("debug.log", "w"); if (!debugFile) std::cerr << "unable to open debug.log for logging - logging to stderr"; else FilePolicy::stream() = debugFile; FileLog::globalLogLevel() = LOG_DEBUG; LOG(LOG_INFO) << "Opened log file for new session"; // make sure we can open the output model file, if specified FILE* outputFile = NULL; if (vm.count("output")) { outputFile = fopen(vm["output"].as<std::string>().c_str(), "w"); if (!outputFile) { std::cerr << "unable to open output file \"" << vm["output"].as<std::string>() << "\" for writing." << std::endl; return EXIT_FAILURE; } } boost::shared_ptr<Domain> d = FOLParse::loadDomainFromFiles(vm["facts-file"].as<std::string>(), vm["formula-file"].as<std::string>()); if (vm.count("max") || vm.count("min")) { Interval maxInt = d->maxInterval(); if (vm.count("max")) maxInt.setFinish(vm["max"].as<unsigned int>()); if (vm.count("min")) maxInt.setStart(vm["min"].as<unsigned int>()); d->setMaxInterval(maxInt); } Model model = d->defaultModel(); LOG_PRINT(LOG_INFO) << "model size: " << model.size(); LOG(LOG_DEBUG) << "observation predicates: "; for(std::map<std::string, SISet>::const_iterator it = d->observedPredicates().begin(); it != d->observedPredicates().end(); it++) { LOG(LOG_DEBUG) << "\t" << it->first; } if (vm.count("evalModel")) { LOG(LOG_INFO) << "evaluating model..."; unsigned long sum = 0; // evaluate the weight of each formula in the domain for(Domain::formula_const_iterator it = d->formulas_begin(); it != d->formulas_end(); it++) { ELSentence formula = *it; //SISet satisfied = d->satisfied(*(formula.sentence()), model); SISet satisfied = formula.sentence()->dSatisfied(model, *d); unsigned long weight = d->score(formula, model); sum += weight; LOG_PRINT(LOG_INFO) << "formula: (" << formula.sentence()->toString() << ")"; LOG_PRINT(LOG_INFO) << "\tsatisfied @ " << satisfied.toString(); LOG_PRINT(LOG_INFO) << "\tscore contributed: " << weight; } LOG_PRINT(LOG_INFO) << "total score of model: " << sum; } else if (vm.count("unitProp")) { performUnitPropagation(*d); } else { double p = vm["prob"].as<double>(); unsigned int iterations = vm["iterations"].as<unsigned int>(); LOG(LOG_INFO) << "searching for a maximum-weight model, with p=" << p << " and iterations=" << iterations; Model defModel = d->defaultModel(); std::fstream datastream; if(vm.count("datafile")) { datastream.open(vm["datafile"].as<std::string>().c_str(), std::fstream::out); if (datastream.fail()) { LOG_PRINT(LOG_ERROR) << "unable to open file \"" << vm["datafile"].as<std::string>() << "\" for data file storage."; } } Model maxModel; if (datastream.is_open() && datastream.good()) { maxModel = maxWalkSat(*d, iterations, p, &defModel, &datastream); } else { maxModel = maxWalkSat(*d, iterations, p, &defModel, 0); } if (datastream.is_open()) datastream.close(); LOG_PRINT(LOG_INFO) << "Best model found: " << std::endl; LOG_PRINT(LOG_INFO) << maxModel.toString(); if (vm.count("output")) { // log it to the output file as well fprintf(outputFile, "# generated from fact file \"%s\" and formula file \"%s\"\n", vm["facts-file"].as<std::string>().c_str(), vm["formula-file"].as<std::string>().c_str()); std::string timeStr; { time_t rawtime; struct tm * timeinfo; time (&rawtime); timeinfo = localtime (&rawtime); timeStr = asctime(timeinfo); } fprintf(outputFile, "# generated on %s\n", timeStr.c_str()); fprintf(outputFile, "# run with %d iterations and %g chance of choosing a random move\n", iterations, p); fputs(maxModel.toString().c_str(), outputFile); } } // Should be good and close files? return EXIT_SUCCESS; } catch (std::exception& e) { std::cerr << "Exception : " << e.what() << std::endl; return EXIT_FAILURE; } catch (...) { std::cerr << "Unknown exception occurred" << std::endl; return EXIT_FAILURE; } } <commit_msg>extra space removed<commit_after>//============================================================================ // Name : pel.cpp // Author : Joe Selman // Version : //============================================================================ #include "PELConfig.h" #include <boost/program_options.hpp> #include <boost/tuple/tuple.hpp> namespace po = boost::program_options; #include <boost/foreach.hpp> #include <iostream> #include <cstdio> #include <string> #include <vector> #include <utility> #include <ctime> #include <map> #include <cstdlib> #include "pel.h" #include "logic/el_syntax.h" #include "logic/folparser.h" #include "logic/domain.h" #include "log.h" #include "logic/moves.h" #include "inference/maxwalksat.h" #include "logic/unit_prop.h" int main(int argc, char* argv[]) { try { // Declare the supported options. po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("version,v", "print version and exit") ("max", po::value<unsigned int>(), "maximum value an interval endpoint can take") ("min", po::value<unsigned int>(), "minimum value an interval endpoint can take") ("evalModel,e", "simply print the model weight of the facts file") ("prob,p", po::value<double>()->default_value(0.25), "probability of taking a random move") ("iterations,i", po::value<unsigned int>()->default_value(1000), "number of iterations before returning a model") ("output,o", po::value<std::string>(), "output model file") ("unitProp,u", "perform unit propagation only and exit") ("datafile,d", po::value<std::string>(), "log scores from maxwalksat to this file (csv form)") ; po::options_description hidden("Hidden options"); hidden.add_options() ("facts-file", po::value<std::string>(), "facts file") ("formula-file", po::value<std::string>(), "formula file") ; po::positional_options_description p; p.add("facts-file", 1); p.add("formula-file", 1); po::options_description cmdline_options; cmdline_options.add(desc).add(hidden); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(cmdline_options).positional(p).run(), vm); po::notify(vm); if (vm.count("version")) { std::cout << "pel version " << PEL_VERSION_MAJOR << "." << PEL_VERSION_MINOR << std::endl; return EXIT_SUCCESS; } if (vm.count("help") || !vm.count("facts-file") || !vm.count("formula-file")) { std::cout << "Usage: pel [OPTION]... FACT-FILE FORMULA-FILE" << std::endl; std::cout << desc << std::endl; return EXIT_FAILURE; } // setup our logging facilities FILE* debugFile = fopen("debug.log", "w"); if (!debugFile) std::cerr << "unable to open debug.log for logging - logging to stderr"; else FilePolicy::stream() = debugFile; FileLog::globalLogLevel() = LOG_DEBUG; LOG(LOG_INFO) << "Opened log file for new session"; // make sure we can open the output model file, if specified FILE* outputFile = NULL; if (vm.count("output")) { outputFile = fopen(vm["output"].as<std::string>().c_str(), "w"); if (!outputFile) { std::cerr << "unable to open output file \"" << vm["output"].as<std::string>() << "\" for writing." << std::endl; return EXIT_FAILURE; } } boost::shared_ptr<Domain> d = FOLParse::loadDomainFromFiles(vm["facts-file"].as<std::string>(), vm["formula-file"].as<std::string>()); if (vm.count("max") || vm.count("min")) { Interval maxInt = d->maxInterval(); if (vm.count("max")) maxInt.setFinish(vm["max"].as<unsigned int>()); if (vm.count("min")) maxInt.setStart(vm["min"].as<unsigned int>()); d->setMaxInterval(maxInt); } Model model = d->defaultModel(); LOG_PRINT(LOG_INFO) << "model size: " << model.size(); LOG(LOG_DEBUG) << "observation predicates: "; for(std::map<std::string, SISet>::const_iterator it = d->observedPredicates().begin(); it != d->observedPredicates().end(); it++) { LOG(LOG_DEBUG) << "\t" << it->first; } if (vm.count("evalModel")) { LOG(LOG_INFO) << "evaluating model..."; unsigned long sum = 0; // evaluate the weight of each formula in the domain for(Domain::formula_const_iterator it = d->formulas_begin(); it != d->formulas_end(); it++) { ELSentence formula = *it; //SISet satisfied = d->satisfied(*(formula.sentence()), model); SISet satisfied = formula.sentence()->dSatisfied(model, *d); unsigned long weight = d->score(formula, model); sum += weight; LOG_PRINT(LOG_INFO) << "formula: (" << formula.sentence()->toString() << ")"; LOG_PRINT(LOG_INFO) << "\tsatisfied @ " << satisfied.toString(); LOG_PRINT(LOG_INFO) << "\tscore contributed: " << weight; } LOG_PRINT(LOG_INFO) << "total score of model: " << sum; } else if (vm.count("unitProp")) { performUnitPropagation(*d); } else { double p = vm["prob"].as<double>(); unsigned int iterations = vm["iterations"].as<unsigned int>(); LOG(LOG_INFO) << "searching for a maximum-weight model, with p=" << p << " and iterations=" << iterations; Model defModel = d->defaultModel(); std::fstream datastream; if(vm.count("datafile")) { datastream.open(vm["datafile"].as<std::string>().c_str(), std::fstream::out); if (datastream.fail()) { LOG_PRINT(LOG_ERROR) << "unable to open file \"" << vm["datafile"].as<std::string>() << "\" for data file storage."; } } Model maxModel; if (datastream.is_open() && datastream.good()) { maxModel = maxWalkSat(*d, iterations, p, &defModel, &datastream); } else { maxModel = maxWalkSat(*d, iterations, p, &defModel, 0); } if (datastream.is_open()) datastream.close(); LOG_PRINT(LOG_INFO) << "Best model found: " << std::endl; LOG_PRINT(LOG_INFO) << maxModel.toString(); if (vm.count("output")) { // log it to the output file as well fprintf(outputFile, "# generated from fact file \"%s\" and formula file \"%s\"\n", vm["facts-file"].as<std::string>().c_str(), vm["formula-file"].as<std::string>().c_str()); std::string timeStr; { time_t rawtime; struct tm * timeinfo; time (&rawtime); timeinfo = localtime (&rawtime); timeStr = asctime(timeinfo); } fprintf(outputFile, "# generated on %s\n", timeStr.c_str()); fprintf(outputFile, "# run with %d iterations and %g chance of choosing a random move\n", iterations, p); fputs(maxModel.toString().c_str(), outputFile); } } // Should be good and close files? return EXIT_SUCCESS; } catch (std::exception& e) { std::cerr << "Exception : " << e.what() << std::endl; return EXIT_FAILURE; } catch (...) { std::cerr << "Unknown exception occurred" << std::endl; return EXIT_FAILURE; } } <|endoftext|>
<commit_before>#ifndef _PFA_HPP #define _PFA_HPP #include <armadillo> #include <map> static const double INV_SQRT_2PI = 0.3989422804014327; static const double INV_SQRT_2PI_LOG = -0.91893853320467267; inline double normal_pdf(double x, double m, double s) { double a = (x - m) / s; return INV_SQRT_2PI / s * std::exp(-0.5 * a * a); }; inline double normal_pdf_log(double x, double m, double s) { double a = (x - m) / s; return INV_SQRT_2PI_LOG - std::log(s) -0.5 * a * a; }; class PFA { public: PFA(double * cX, double * cF, double * cP, double * cQ, double * omega, double * cLout, int N, int J, int K, int C): // mat(aux_mem*, n_rows, n_cols, copy_aux_mem = true, strict = true) D(cX, N, J, false, true), F(cF, K, J, false, true), P(cP, K, K, false, true), q(cQ, C, false, true), omega(omega, C, false, true), L(cLout, N, K, false, true) { s = arma::vectorise(arma::stddev(D)); has_F_pair_coord = false; L.set_size(D.n_rows, F.n_rows); W.set_size(F.n_rows, F.n_rows); log_delta.set_size(D.n_rows, int((F.n_rows - 1) * F.n_rows / 2), q.n_elem); avg_delta.set_size(int((P.n_rows - 1) * P.n_rows / 2), q.n_elem); } ~PFA() {} void print(std::ostream& out, int info) { if (info == 0) { D.print(out, "Data Matrix:"); q.print(out, "Membership grids:"); s.print(out, "Estimated standard deviation of data columns (features):"); } if (info == 1) { F.print(out, "Factor Matrix:"); P.print(out, "Factor frequency Matrix:"); L.print(out, "Loading matrix:"); W.print(out, "E[L'L] matrix:"); omega.print(out, "Membership grid weights:"); } if (info == 2) { log_delta.print(out, "log(delta) tensor:"); avg_delta.print(out, "delta averaged over samples:"); } } void get_log_delta_given_nkq() { // this computes delta up to a normalizing constant // this results in a N by k1k2 by q tensor of loglik for (size_t qq = 0; qq < q.n_elem; qq++) { size_t col_cnt = 0; for (size_t k1 = 0; k1 < F.n_rows; k1++) { for (size_t k2 = 0; k2 < k1; k2++) { // given k1, k2 and q, density is a N-vector // in the end of the loop, the vector should populate a column of a slice of the tensor arma::vec Dn_llik = arma::zeros<arma::vec>(D.n_rows); for (size_t j = 0; j < D.n_cols; j++) { arma::vec density = D.col(j); double m = q.at(qq) * F.at(k2, j) + (1 - q.at(qq)) * F.at(k1, j); double sig = s.at(j); Dn_llik += density.transform( [=](double x) { return (normal_pdf_log(x, m, sig)); } ); } Dn_llik = Dn_llik + (std::log(P.at(k1, k2)) + std::log(omega.at(qq))); // populate the tensor log_delta.slice(qq).col(col_cnt) = Dn_llik; // set factor pair coordinates in the tensor if (!has_F_pair_coord) { F_pair_coord[std::make_pair(k1, k2)] = col_cnt; F_pair_coord[std::make_pair(k2, k1)] = col_cnt; } col_cnt++; } has_F_pair_coord = true; } } } double get_loglik_prop() { // log likelihood up to a normalizing constant return arma::accu(log_delta); } void update_weights() { // update P and omega // this results in a K1K2 by q matrix of avglik // which equals pi_k1k2 * omega_q arma::cube slice_rowsums = arma::sum(arma::exp(log_delta)); for (size_t qq = 0; qq < q.n_elem; qq++) { avg_delta.col(qq) = arma::vectorise(slice_rowsums.slice(qq)) / D.n_rows; } // sum over q grids arma::vec pik1k2 = arma::sum(avg_delta, 1); pik1k2 = pik1k2 / arma::sum(pik1k2); size_t col_cnt = 0; for (size_t k1 = 0; k1 < P.n_rows; k1++) { for (size_t k2 = 0; k2 < k1; k2++) { P.at(k1, k2) = pik1k2.at(col_cnt); col_cnt++; } } // sum over (k1, k2) omega = arma::vectorise(arma::sum(avg_delta)); omega = omega / arma::sum(omega); } void update_F() { // F, the K by J matrix, is to be updated here // Need to compute 2 matrices in order to solve F // The loading, L is N X K matrix; W = L'L is K X K matrix L.fill(0); for (size_t k = 0; k < F.n_rows; k++) { // I. First we compute the k-th column for E(L), the N X K matrix: // generate the proper input for 1 X K %*% K X N // where the 1 X K matrix is loadings Lk consisting of q or (1-q) // and the K X N matrix is the delta for a corresponding subset of a slice from delta // II. Then we compute the diagonal elements for E(W), the K X K matrix // Because we need to sum over all N and we have computed this before, // we can work with avg_delta (K1K2 X q) instead of log_delta the tensor // we need to loop over the q slices for (size_t qq = 0; qq < q.n_elem; qq++) { // I. ........................................ // create the left hand side Lk1, a 1 X K matrix double qi = q.at(qq); arma::mat Lk1(1, F.n_rows, arma::fill::zeros); for (size_t i = 0; i < F.n_rows; i++) { if (i < k) Lk1.at(0, i) = 1.0 - qi; if (i > k) Lk1.at(0, i) = qi; } // create the right hand side Lk2, a K X N matrix // from a slice of the tensor log_delta // where the rows are N's, the columns corresponds to // k1k2, k1k3, k2k3, k1k4, k2k4, k3k4, k1k5 ... along the lower triangle matrix P // use F_pair_coord to get proper index for data from the tensor arma::mat Lk2(D.n_rows, F.n_rows, arma::fill::zeros); for (size_t i = 0; i < F.n_rows; i++) { if (k != i) Lk2.col(i) = arma::exp(log_delta.slice(qq).col(F_pair_coord[std::make_pair(k, i)])); } // Update the k-th column of L L.col(k) += arma::vectorise(Lk1 * Lk2.t()); // II. ........................................ for (size_t i = 0; i < F.n_rows; i++) { if (i < k) Lk1.at(0, i) = (1.0 - qi) * (1.0 - qi); if (i > k) Lk1.at(0, i) = qi * qi; } arma::mat Lk3(F.n_rows, 1, arma::fill::zeros); for (size_t i = 0; i < F.n_rows; i++) { if (k != i) Lk3.at(i, 0) = D.n_rows * avg_delta.at(F_pair_coord[std::make_pair(k, i)], qq); } // Update E(W_kk) W.at(k, k) += arma::as_scalar(Lk1 * Lk3); } } // III. Now we compute off-diagonal elements for E(W), the K X K matrix // it involves on the LHS a vector of [q1(1-q1), q2(1-q2) ...] // and on the RHS for each pair of (k1, k2) the corresponding row from avg_delta arma::vec LHS = q.transform( [](double val) { return (val * (1.0 - val)); } ); for (size_t k1 = 0; k1 < F.n_rows; k1++) { for (size_t k2 = 0; k2 < k1; k2++) { arma::vec RHS = arma::vectorise(D.n_rows * avg_delta.row(F_pair_coord[std::make_pair(k1, k2)])); W.at(k1, k2) = arma::dot(LHS, RHS); W.at(k2, k1) = W.at(k1, k2); } } // IV. Finally we compute F F = arma::solve(W, L.t() * D); } private: arma::mat D; arma::mat F; arma::mat P; arma::vec q; arma::vec omega; arma::vec s; // N by K1K2 by q tensor arma::cube log_delta; // K1K2 by q matrix arma::mat avg_delta; std::map<std::pair<int,int>, int> F_pair_coord; bool has_F_pair_coord; arma::mat L; arma::mat W; }; #endif <commit_msg>Fix cordinates initialization of factor pairs<commit_after>#ifndef _PFA_HPP #define _PFA_HPP #include <armadillo> #include <map> static const double INV_SQRT_2PI = 0.3989422804014327; static const double INV_SQRT_2PI_LOG = -0.91893853320467267; inline double normal_pdf(double x, double m, double s) { double a = (x - m) / s; return INV_SQRT_2PI / s * std::exp(-0.5 * a * a); }; inline double normal_pdf_log(double x, double m, double s) { double a = (x - m) / s; return INV_SQRT_2PI_LOG - std::log(s) -0.5 * a * a; }; class PFA { public: PFA(double * cX, double * cF, double * cP, double * cQ, double * omega, double * cLout, int N, int J, int K, int C): // mat(aux_mem*, n_rows, n_cols, copy_aux_mem = true, strict = true) D(cX, N, J, false, true), F(cF, K, J, false, true), P(cP, K, K, false, true), q(cQ, C, false, true), omega(omega, C, false, true), L(cLout, N, K, false, true) { s = arma::vectorise(arma::stddev(D)); has_F_pair_coord = false; L.set_size(D.n_rows, F.n_rows); W.set_size(F.n_rows, F.n_rows); log_delta.set_size(D.n_rows, int((F.n_rows - 1) * F.n_rows / 2), q.n_elem); avg_delta.set_size(int((P.n_rows - 1) * P.n_rows / 2), q.n_elem); } ~PFA() {} void print(std::ostream& out, int info) { if (info == 0) { D.print(out, "Data Matrix:"); q.print(out, "Membership grids:"); s.print(out, "Estimated standard deviation of data columns (features):"); } if (info == 1) { F.print(out, "Factor Matrix:"); P.print(out, "Factor frequency Matrix:"); L.print(out, "Loading matrix:"); W.print(out, "E[L'L] matrix:"); omega.print(out, "Membership grid weights:"); } if (info == 2) { log_delta.print(out, "log(delta) tensor:"); avg_delta.print(out, "delta averaged over samples:"); } } void get_log_delta_given_nkq() { // this computes delta up to a normalizing constant // this results in a N by k1k2 by q tensor of loglik for (size_t qq = 0; qq < q.n_elem; qq++) { size_t col_cnt = 0; for (size_t k1 = 0; k1 < F.n_rows; k1++) { for (size_t k2 = 0; k2 < k1; k2++) { // given k1, k2 and q, density is a N-vector // in the end of the loop, the vector should populate a column of a slice of the tensor arma::vec Dn_llik = arma::zeros<arma::vec>(D.n_rows); for (size_t j = 0; j < D.n_cols; j++) { arma::vec density = D.col(j); double m = q.at(qq) * F.at(k2, j) + (1 - q.at(qq)) * F.at(k1, j); double sig = s.at(j); Dn_llik += density.transform( [=](double x) { return (normal_pdf_log(x, m, sig)); } ); } Dn_llik = Dn_llik + (std::log(P.at(k1, k2)) + std::log(omega.at(qq))); // populate the tensor log_delta.slice(qq).col(col_cnt) = Dn_llik; // set factor pair coordinates in the tensor if (!has_F_pair_coord) { F_pair_coord[std::make_pair(k1, k2)] = col_cnt; F_pair_coord[std::make_pair(k2, k1)] = col_cnt; } col_cnt++; } } has_F_pair_coord = true; } } double get_loglik_prop() { // log likelihood up to a normalizing constant return arma::accu(log_delta); } void update_weights() { // update P and omega // this results in a K1K2 by q matrix of avglik // which equals pi_k1k2 * omega_q arma::cube slice_rowsums = arma::sum(arma::exp(log_delta)); for (size_t qq = 0; qq < q.n_elem; qq++) { avg_delta.col(qq) = arma::vectorise(slice_rowsums.slice(qq)) / D.n_rows; } // sum over q grids arma::vec pik1k2 = arma::sum(avg_delta, 1); pik1k2 = pik1k2 / arma::sum(pik1k2); size_t col_cnt = 0; for (size_t k1 = 0; k1 < P.n_rows; k1++) { for (size_t k2 = 0; k2 < k1; k2++) { P.at(k1, k2) = pik1k2.at(col_cnt); col_cnt++; } } // sum over (k1, k2) omega = arma::vectorise(arma::sum(avg_delta)); omega = omega / arma::sum(omega); } void update_F() { // F, the K by J matrix, is to be updated here // Need to compute 2 matrices in order to solve F // The loading, L is N X K matrix; W = L'L is K X K matrix L.fill(0); for (size_t k = 0; k < F.n_rows; k++) { // I. First we compute the k-th column for E(L), the N X K matrix: // generate the proper input for 1 X K %*% K X N // where the 1 X K matrix is loadings Lk consisting of q or (1-q) // and the K X N matrix is the delta for a corresponding subset of a slice from delta // II. Then we compute the diagonal elements for E(W), the K X K matrix // Because we need to sum over all N and we have computed this before, // we can work with avg_delta (K1K2 X q) instead of log_delta the tensor // we need to loop over the q slices for (size_t qq = 0; qq < q.n_elem; qq++) { // I. ........................................ // create the left hand side Lk1, a 1 X K matrix double qi = q.at(qq); arma::mat Lk1(1, F.n_rows, arma::fill::zeros); for (size_t i = 0; i < F.n_rows; i++) { if (i < k) Lk1.at(0, i) = 1.0 - qi; if (i > k) Lk1.at(0, i) = qi; } // create the right hand side Lk2, a K X N matrix // from a slice of the tensor log_delta // where the rows are N's, the columns corresponds to // k1k2, k1k3, k2k3, k1k4, k2k4, k3k4, k1k5 ... along the lower triangle matrix P // use F_pair_coord to get proper index for data from the tensor arma::mat Lk2(D.n_rows, F.n_rows, arma::fill::zeros); for (size_t i = 0; i < F.n_rows; i++) { if (k != i) Lk2.col(i) = arma::exp(log_delta.slice(qq).col(F_pair_coord[std::make_pair(k, i)])); } // Update the k-th column of L L.col(k) += arma::vectorise(Lk1 * Lk2.t()); // II. ........................................ for (size_t i = 0; i < F.n_rows; i++) { if (i < k) Lk1.at(0, i) = (1.0 - qi) * (1.0 - qi); if (i > k) Lk1.at(0, i) = qi * qi; } arma::mat Lk3(F.n_rows, 1, arma::fill::zeros); for (size_t i = 0; i < F.n_rows; i++) { if (k != i) Lk3.at(i, 0) = D.n_rows * avg_delta.at(F_pair_coord[std::make_pair(k, i)], qq); } // Update E(W_kk) W.at(k, k) += arma::as_scalar(Lk1 * Lk3); } } // III. Now we compute off-diagonal elements for E(W), the K X K matrix // it involves on the LHS a vector of [q1(1-q1), q2(1-q2) ...] // and on the RHS for each pair of (k1, k2) the corresponding row from avg_delta arma::vec LHS = q.transform( [](double val) { return (val * (1.0 - val)); } ); for (size_t k1 = 0; k1 < F.n_rows; k1++) { for (size_t k2 = 0; k2 < k1; k2++) { arma::vec RHS = arma::vectorise(D.n_rows * avg_delta.row(F_pair_coord[std::make_pair(k1, k2)])); W.at(k1, k2) = arma::dot(LHS, RHS); W.at(k2, k1) = W.at(k1, k2); } } // IV. Finally we compute F F = arma::solve(W, L.t() * D); } private: arma::mat D; arma::mat F; arma::mat P; arma::vec q; arma::vec omega; arma::vec s; // N by K1K2 by q tensor arma::cube log_delta; // K1K2 by q matrix arma::mat avg_delta; std::map<std::pair<int,int>, int> F_pair_coord; bool has_F_pair_coord; arma::mat L; arma::mat W; }; #endif <|endoftext|>
<commit_before>/* Copyright (c) 2010, The Mineserver Project 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 The Mineserver Project 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 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. */ // // Mineserver trxlogger.cpp // #include <iostream> #include <fstream> #include <string> #include <time.h> #include <vector> #include "trxlogger.h" #include "logger.h" #include "config.h" TrxLogger::TrxLogger (std::string filename) { log_stream.open(filename.c_str(), std::fstream::in | std::fstream::out | std::fstream::binary ); if (!log_stream.is_open()) { LOG("Problem opening binary log!"); } } TrxLogger &TrxLogger::get() { static TrxLogger instance(Conf::get()->sValue("binlog")); return instance; } // Log action to binary log void TrxLogger::log(event_t event) { if(!log_stream.bad()) { event.timestamp = time (NULL); event.nsize = strlen(event.nick); log_stream.seekp(0, std::ios::end); log_stream.write((char *) &event.timestamp, sizeof(time_t)); log_stream.write((char *) &event.x, sizeof(int)); log_stream.write((char *) &event.y, sizeof(int)); log_stream.write((char *) &event.z, sizeof(int)); log_stream.write((char *) &event.otype, sizeof(uint8)); log_stream.write((char *) &event.ntype, sizeof(uint8)); log_stream.write((char *) &event.ometa, sizeof(uint8)); log_stream.write((char *) &event.nmeta, sizeof(uint8)); log_stream.write((char *) &event.nsize, sizeof(int)); log_stream.write((char *) &event.nick, event.nsize+1); } else { LOG("Binary log is bad!"); } } // Get logs based on nick and timestamp bool TrxLogger::getLogs(time_t t, std::string &nick, std::vector<event_t> *logs) { event_t event; log_stream.flush(); log_stream.seekg(0, std::ios::beg); while(this->getEvent(&event)) { if(event.timestamp > t && event.nick == nick.c_str()) { logs->push_back(event); } } return true; } // Get logs based on timestamp bool TrxLogger::getLogs(time_t t, std::vector<event_t> *logs) { event_t event; log_stream.flush(); log_stream.seekg(0, std::ios::beg); while(this->getEvent(&event)) { if(event.timestamp > t) { logs->push_back(event); } } return true; } // Get all logs bool TrxLogger::getLogs(std::vector<event_t> *logs) { event_t event; log_stream.flush(); log_stream.seekg(0, std::ios::beg); while(this->getEvent(&event)) { logs->push_back(event); } return true; } // Get event from log bool TrxLogger::getEvent(event_t *event) { if(!log_stream.eof()) { log_stream.read((char *) &event->timestamp, sizeof(time_t)); log_stream.read((char *) &event->x, sizeof(int)); log_stream.read((char *) &event->y, sizeof(int)); log_stream.read((char *) &event->z, sizeof(int)); log_stream.read((char *) &event->otype, sizeof(uint8)); log_stream.read((char *) &event->ntype, sizeof(uint8)); log_stream.read((char *) &event->ometa, sizeof(uint8)); log_stream.read((char *) &event->nmeta, sizeof(uint8)); log_stream.read((char *) &event->nsize, sizeof(int)); log_stream.read((char *) &event->nick, event->nsize+1); #ifdef _DEBUG printf("Time: %d\nx: %d\ny: %d\nz: %d\notype: %d\nntype: %d\nometa: %d\nnmeta %d\nnsize: %d\nnick: %s\n", event->timestamp, event->x, event->y, event->z, event->otype, event->ntype, event->ometa, event->nmeta, event->nsize, event->nick ); #endif return true; } return false; } TrxLogger::~TrxLogger() { log_stream.close(); } <commit_msg>rollback commands are all working!<commit_after>/* Copyright (c) 2010, The Mineserver Project 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 The Mineserver Project 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 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. */ // // Mineserver trxlogger.cpp // #include <iostream> #include <fstream> #include <string> #include <time.h> #include <vector> #include "trxlogger.h" #include "logger.h" #include "config.h" TrxLogger::TrxLogger (std::string filename) { log_stream.open(filename.c_str(), std::fstream::in | std::fstream::out | std::fstream::binary ); if (!log_stream.is_open()) { LOG("Problem opening binary log!"); } } TrxLogger &TrxLogger::get() { static TrxLogger instance(Conf::get()->sValue("binlog")); return instance; } // Log action to binary log void TrxLogger::log(event_t event) { if(!log_stream.bad()) { event.timestamp = time (NULL); event.nsize = strlen(event.nick); log_stream.seekp(0, std::ios::end); log_stream.write((char *) &event.timestamp, sizeof(time_t)); log_stream.write((char *) &event.x, sizeof(int)); log_stream.write((char *) &event.y, sizeof(int)); log_stream.write((char *) &event.z, sizeof(int)); log_stream.write((char *) &event.otype, sizeof(uint8)); log_stream.write((char *) &event.ntype, sizeof(uint8)); log_stream.write((char *) &event.ometa, sizeof(uint8)); log_stream.write((char *) &event.nmeta, sizeof(uint8)); log_stream.write((char *) &event.nsize, sizeof(int)); log_stream.write((char *) &event.nick, event.nsize+1); } else { LOG("WARNING: Binary log is bad!"); } } // Get logs based on nick and timestamp bool TrxLogger::getLogs(time_t t, std::string &nick, std::vector<event_t> *logs) { event_t event; log_stream.flush(); log_stream.seekg(0, std::ios::beg); while(this->getEvent(&event)) { if(event.timestamp > t && (strcmp(event.nick, nick.c_str()) == 0)) { logs->push_back(event); } } return true; } // Get logs based on timestamp bool TrxLogger::getLogs(time_t t, std::vector<event_t> *logs) { event_t event; log_stream.flush(); log_stream.seekg(0, std::ios::beg); while(this->getEvent(&event)) { if(event.timestamp > t) { logs->push_back(event); } } return true; } // Get all logs bool TrxLogger::getLogs(std::vector<event_t> *logs) { event_t event; log_stream.flush(); log_stream.seekg(0, std::ios::beg); while(this->getEvent(&event)) { logs->push_back(event); } return true; } // Get event from log bool TrxLogger::getEvent(event_t *event) { if(!log_stream.eof()) { log_stream.read((char *) &event->timestamp, sizeof(time_t)); log_stream.read((char *) &event->x, sizeof(int)); log_stream.read((char *) &event->y, sizeof(int)); log_stream.read((char *) &event->z, sizeof(int)); log_stream.read((char *) &event->otype, sizeof(uint8)); log_stream.read((char *) &event->ntype, sizeof(uint8)); log_stream.read((char *) &event->ometa, sizeof(uint8)); log_stream.read((char *) &event->nmeta, sizeof(uint8)); log_stream.read((char *) &event->nsize, sizeof(int)); log_stream.read((char *) &event->nick, event->nsize+1); #ifdef _DEBUG printf("Time: %d\nx: %d\ny: %d\nz: %d\notype: %d\nntype: %d\nometa: %d\nnmeta %d\nnsize: %d\nnick: %s\n", event->timestamp, event->x, event->y, event->z, event->otype, event->ntype, event->ometa, event->nmeta, event->nsize, event->nick ); #endif return true; } log_stream.clear(); return false; } TrxLogger::~TrxLogger() { log_stream.close(); } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 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 "pow.h" #include "arith_uint256.h" #include "chain.h" #include "primitives/block.h" #include "uint256.h" #include "util.h" unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params) { assert(pindexLast != nullptr); unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact(); // Only change once per difficulty adjustment interval if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval() != 0) { if (params.fPowAllowMinDifficultyBlocks) { // Special difficulty rule for testnet: // If the new block's timestamp is more than 2* 10 minutes // then allow mining of a min-difficulty block. if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2) return nProofOfWorkLimit; else { // Return the last non-special-min-difficulty-rules-block const CBlockIndex* pindex = pindexLast; while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit) pindex = pindex->pprev; return pindex->nBits; } } return pindexLast->nBits; } // Go back by what we want to be 14 days worth of blocks // Litecoin: This fixes an issue where a 51% attack can change difficulty at will. // Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz int blockstogoback = params.DifficultyAdjustmentInterval()-1; if ((pindexLast->nHeight+1) != params.DifficultyAdjustmentInterval()) blockstogoback = params.DifficultyAdjustmentInterval(); // Go back by what we want to be 14 days worth of blocks const CBlockIndex* pindexFirst = pindexLast; for (int i = 0; pindexFirst && i < blockstogoback; i++) pindexFirst = pindexFirst->pprev; assert(pindexFirst); return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params); } unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params) { if (params.fPowNoRetargeting) return pindexLast->nBits; // Limit adjustment step int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime; if (nActualTimespan < params.nPowTargetTimespan/4) nActualTimespan = params.nPowTargetTimespan/4; if (nActualTimespan > params.nPowTargetTimespan*4) nActualTimespan = params.nPowTargetTimespan*4; // Retarget arith_uint256 bnNew; arith_uint256 bnOld; bnNew.SetCompact(pindexLast->nBits); bnOld = bnNew; // Litecoin: intermediate uint256 can overflow by 1 bit bool fShift = bnNew.bits() > 235; if (fShift) bnNew >>= 1; bnNew *= nActualTimespan; bnNew /= params.nPowTargetTimespan; if (fShift) bnNew <<= 1; const arith_uint256 bnPowLimit = UintToArith256(params.powLimit); if (bnNew > bnPowLimit) bnNew = bnPowLimit; return bnNew.GetCompact(); } bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params) { bool fNegative; bool fOverflow; arith_uint256 bnTarget; bnTarget.SetCompact(nBits, &fNegative, &fOverflow); // Check range if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit)) return false; // Check proof of work matches claimed amount if (UintToArith256(hash) > bnTarget) return false; return true; } <commit_msg>Litecoin: Zeitgeist2 bool fshift bnNew.bits()<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 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 "pow.h" #include "arith_uint256.h" #include "chain.h" #include "primitives/block.h" #include "uint256.h" #include "util.h" unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params) { assert(pindexLast != nullptr); unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact(); // Only change once per difficulty adjustment interval if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval() != 0) { if (params.fPowAllowMinDifficultyBlocks) { // Special difficulty rule for testnet: // If the new block's timestamp is more than 2* 10 minutes // then allow mining of a min-difficulty block. if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2) return nProofOfWorkLimit; else { // Return the last non-special-min-difficulty-rules-block const CBlockIndex* pindex = pindexLast; while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit) pindex = pindex->pprev; return pindex->nBits; } } return pindexLast->nBits; } // Go back by what we want to be 14 days worth of blocks // Litecoin: This fixes an issue where a 51% attack can change difficulty at will. // Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz int blockstogoback = params.DifficultyAdjustmentInterval()-1; if ((pindexLast->nHeight+1) != params.DifficultyAdjustmentInterval()) blockstogoback = params.DifficultyAdjustmentInterval(); // Go back by what we want to be 14 days worth of blocks const CBlockIndex* pindexFirst = pindexLast; for (int i = 0; pindexFirst && i < blockstogoback; i++) pindexFirst = pindexFirst->pprev; assert(pindexFirst); return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params); } unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params) { if (params.fPowNoRetargeting) return pindexLast->nBits; // Limit adjustment step int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime; if (nActualTimespan < params.nPowTargetTimespan/4) nActualTimespan = params.nPowTargetTimespan/4; if (nActualTimespan > params.nPowTargetTimespan*4) nActualTimespan = params.nPowTargetTimespan*4; // Retarget arith_uint256 bnNew; arith_uint256 bnOld; bnNew.SetCompact(pindexLast->nBits); bnOld = bnNew; // Litecoin: intermediate uint256 can overflow by 1 bit const arith_uint256 bnPowLimit = UintToArith256(params.powLimit); bool fShift = bnNew.bits() > bnPowLimit.bits() - 1; if (fShift) bnNew >>= 1; bnNew *= nActualTimespan; bnNew /= params.nPowTargetTimespan; if (fShift) bnNew <<= 1; if (bnNew > bnPowLimit) bnNew = bnPowLimit; return bnNew.GetCompact(); } bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params) { bool fNegative; bool fOverflow; arith_uint256 bnTarget; bnTarget.SetCompact(nBits, &fNegative, &fOverflow); // Check range if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit)) return false; // Check proof of work matches claimed amount if (UintToArith256(hash) > bnTarget) return false; return true; } <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2013 Jolla Ltd. ** Contact: Aaron Kennedy <[email protected]> ** ** This file is part of lipstick. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QtCore/qmath.h> #include <QSGGeometryNode> #include <QSGSimpleMaterial> #include <QWaylandSurfaceItem> #include "lipstickcompositorwindow.h" #include "lipstickcompositor.h" #include "windowpixmapitem.h" namespace { class SurfaceTextureState { public: SurfaceTextureState() : m_texture(0), m_xScale(1), m_yScale(1) {} void setTexture(QSGTexture *texture) { m_texture = texture; } QSGTexture *texture() const { return m_texture; } void setXScale(float xScale) { m_xScale = xScale; } float xScale() const { return m_xScale; } void setYScale(float yScale) { m_yScale = yScale; } float yScale() const { return m_yScale; } private: QSGTexture *m_texture; float m_xScale; float m_yScale; }; class SurfaceTextureMaterial : public QSGSimpleMaterialShader<SurfaceTextureState> { QSG_DECLARE_SIMPLE_SHADER(SurfaceTextureMaterial, SurfaceTextureState) public: QList<QByteArray> attributes() const; void updateState(const SurfaceTextureState *newState, const SurfaceTextureState *oldState); protected: void initialize(); const char *vertexShader() const; const char *fragmentShader() const; private: int m_id_texScale; }; class SurfaceNode : public QObject, public QSGGeometryNode { Q_OBJECT public: SurfaceNode(); void setRect(const QRectF &); void setTextureProvider(QSGTextureProvider *); void setBlending(bool); void setRadius(qreal radius); void setXScale(qreal xScale); void setYScale(qreal yScale); private slots: void providerDestroyed(); void textureChanged(); private: void setTexture(QSGTexture *texture); void updateGeometry(); QSGSimpleMaterial<SurfaceTextureState> *m_material; QRectF m_rect; qreal m_radius; QSGTextureProvider *m_provider; QSGTexture *m_texture; QSGGeometry m_geometry; QRectF m_textureRect; }; QList<QByteArray> SurfaceTextureMaterial::attributes() const { QList<QByteArray> attributeList; attributeList << "qt_VertexPosition"; attributeList << "qt_VertexTexCoord"; return attributeList; } void SurfaceTextureMaterial::updateState(const SurfaceTextureState *newState, const SurfaceTextureState *) { if (newState->texture()) newState->texture()->bind(); program()->setUniformValue(m_id_texScale, newState->xScale(), newState->yScale()); } void SurfaceTextureMaterial::initialize() { QSGSimpleMaterialShader::initialize(); m_id_texScale = program()->uniformLocation("texScale"); } const char *SurfaceTextureMaterial::vertexShader() const { return "uniform highp mat4 qt_Matrix; \n" "attribute highp vec4 qt_VertexPosition; \n" "attribute highp vec2 qt_VertexTexCoord; \n" "varying highp vec2 qt_TexCoord; \n" "uniform highp vec2 texScale; \n" "void main() { \n" " qt_TexCoord = qt_VertexTexCoord * texScale; \n" " gl_Position = qt_Matrix * qt_VertexPosition; \n" "}"; } const char *SurfaceTextureMaterial::fragmentShader() const { return "varying highp vec2 qt_TexCoord; \n" "uniform sampler2D qt_Texture; \n" "uniform lowp float qt_Opacity; \n" "void main() { \n" " gl_FragColor = texture2D(qt_Texture, qt_TexCoord) * qt_Opacity; \n" "}"; } SurfaceNode::SurfaceNode() : m_material(0), m_radius(0), m_provider(0), m_texture(0), m_geometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 0) { setGeometry(&m_geometry); m_material = SurfaceTextureMaterial::createMaterial(); setMaterial(m_material); } void SurfaceNode::setRect(const QRectF &r) { if (m_rect == r) return; m_rect = r; updateGeometry(); } void SurfaceNode::setTextureProvider(QSGTextureProvider *p) { if (p == m_provider) return; if (m_provider) { QObject::disconnect(m_provider, SIGNAL(destroyed(QObject *)), this, SLOT(providerDestroyed())); QObject::disconnect(m_provider, SIGNAL(textureChanged()), this, SLOT(textureChanged())); m_provider = 0; } m_provider = p; QObject::connect(m_provider, SIGNAL(destroyed(QObject *)), this, SLOT(providerDestroyed())); QObject::connect(m_provider, SIGNAL(textureChanged()), this, SLOT(textureChanged())); setTexture(m_provider->texture()); } void SurfaceNode::updateGeometry() { if (m_texture) { QSize ts = m_texture->textureSize(); QRectF sourceRect(0, 0, ts.width(), ts.height()); QRectF textureRect = m_texture->convertToNormalizedSourceRect(sourceRect); if (m_radius) { float radius = qMin(float(qMin(m_rect.width(), m_rect.height()) * 0.5f), float(m_radius)); int segments = qBound(5, qCeil(radius * (M_PI / 6)), 18); float angle = 0.5f * float(M_PI) / segments; m_geometry.allocate((segments + 1) * 2 * 2); QSGGeometry::TexturedPoint2D *v = m_geometry.vertexDataAsTexturedPoint2D(); QSGGeometry::TexturedPoint2D *vlast = v + (segments + 1) * 2 * 2 - 2; float textureXRadius = radius * textureRect.width() / m_rect.width(); float textureYRadius = radius * textureRect.height() / m_rect.height(); float c = 1; float cosStep = qFastCos(angle); float s = 0; float sinStep = qFastSin(angle); for (int ii = 0; ii <= segments; ++ii) { float px = m_rect.left() + radius - radius * c; float tx = textureRect.left() + textureXRadius - textureXRadius * c; float px2 = m_rect.right() - radius + radius * c; float tx2 = textureRect.right() - textureXRadius + textureXRadius * c; float py = m_rect.top() + radius - radius * s; float ty = textureRect.top() + textureYRadius - textureYRadius * s; float py2 = m_rect.bottom() - radius + radius * s; float ty2 = textureRect.bottom() - textureYRadius + textureYRadius * s; v[0].x = px; v[0].y = py; v[0].tx = tx; v[0].ty = ty; v[1].x = px; v[1].y = py2; v[1].tx = tx; v[1].ty = ty2; vlast[0].x = px2; vlast[0].y = py; vlast[0].tx = tx2; vlast[0].ty = ty; vlast[1].x = px2; vlast[1].y = py2; vlast[1].tx = tx2; vlast[1].ty = ty2; v += 2; vlast -= 2; float t = c; c = c * cosStep - s * sinStep; s = s * cosStep + t * sinStep; } } else { m_geometry.allocate(4); QSGGeometry::updateTexturedRectGeometry(&m_geometry, m_rect, textureRect); } markDirty(DirtyGeometry); } } void SurfaceNode::setBlending(bool b) { m_material->setFlag(QSGMaterial::Blending, b); } void SurfaceNode::setRadius(qreal radius) { if (m_radius == radius) return; m_radius = radius; updateGeometry(); } void SurfaceNode::setTexture(QSGTexture *texture) { m_material->state()->setTexture(texture); QRectF tr; if (texture) tr = texture->convertToNormalizedSourceRect(QRect(QPoint(0,0), texture->textureSize())); bool ug = !m_texture || tr != m_textureRect; m_texture = texture; m_textureRect = tr; if (ug) updateGeometry(); markDirty(DirtyMaterial); } void SurfaceNode::setXScale(qreal xScale) { m_material->state()->setXScale(xScale); markDirty(DirtyMaterial); } void SurfaceNode::setYScale(qreal yScale) { m_material->state()->setYScale(yScale); markDirty(DirtyMaterial); } void SurfaceNode::textureChanged() { setTexture(m_provider->texture()); } void SurfaceNode::providerDestroyed() { m_provider = 0; setTexture(0); } } WindowPixmapItem::WindowPixmapItem() : m_item(0), m_shaderEffect(0), m_id(0), m_opaque(false), m_radius(0), m_xScale(1), m_yScale(1) { setFlag(ItemHasContents); } WindowPixmapItem::~WindowPixmapItem() { setWindowId(0); } int WindowPixmapItem::windowId() const { return m_id; } void WindowPixmapItem::setWindowId(int id) { if (m_id == id) return; if (m_item) { if (m_item->surface()) disconnect(m_item->surface(), SIGNAL(sizeChanged()), this, SIGNAL(windowSizeChanged())); m_item->imageRelease(); m_item = 0; } m_id = id; updateItem(); emit windowIdChanged(); } bool WindowPixmapItem::opaque() const { return m_opaque; } void WindowPixmapItem::setOpaque(bool o) { if (m_opaque == o) return; m_opaque = o; if (m_item) update(); emit opaqueChanged(); } qreal WindowPixmapItem::radius() const { return m_radius; } void WindowPixmapItem::setRadius(qreal r) { if (m_radius == r) return; m_radius = r; if (m_item) update(); emit radiusChanged(); } qreal WindowPixmapItem::xScale() const { return m_xScale; } void WindowPixmapItem::setXScale(qreal xScale) { if (m_xScale == xScale) return; m_xScale = xScale; if (m_item) update(); emit xScaleChanged(); } qreal WindowPixmapItem::yScale() const { return m_yScale; } void WindowPixmapItem::setYScale(qreal yScale) { if (m_yScale == yScale) return; m_yScale = yScale; if (m_item) update(); emit yScaleChanged(); } QSize WindowPixmapItem::windowSize() const { if (!m_item || !m_item->surface()) { return QSize(); } return m_item->surface()->size(); } void WindowPixmapItem::setWindowSize(const QSize &s) { if (!m_item || !m_item->surface()) { return; } m_item->surface()->requestSize(s); } QSGNode *WindowPixmapItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *) { SurfaceNode *node = static_cast<SurfaceNode *>(oldNode); if (m_item == 0) { delete node; return 0; } if (!node) node = new SurfaceNode; node->setTextureProvider(m_item->textureProvider()); node->setRect(QRectF(0, 0, width(), height())); node->setBlending(!m_opaque); node->setRadius(m_radius); node->setXScale(m_xScale); node->setYScale(m_yScale); return node; } void WindowPixmapItem::geometryChanged(const QRectF &n, const QRectF &o) { QQuickItem::geometryChanged(n, o); if (m_shaderEffect) m_shaderEffect->setSize(n.size()); } void WindowPixmapItem::updateItem() { LipstickCompositor *c = LipstickCompositor::instance(); Q_ASSERT(m_item == 0); if (c && m_id) { LipstickCompositorWindow *w = static_cast<LipstickCompositorWindow *>(c->windowForId(m_id)); if (!w) { delete m_shaderEffect; m_shaderEffect = 0; return; } else if (w->surface()) { m_item = w; delete m_shaderEffect; m_shaderEffect = 0; connect(m_item->surface(), SIGNAL(sizeChanged()), this, SIGNAL(windowSizeChanged())); } else { if (!m_shaderEffect) { m_shaderEffect = static_cast<QQuickItem *>(c->shaderEffectComponent()->create()); Q_ASSERT(m_shaderEffect); m_shaderEffect->setParentItem(this); m_shaderEffect->setSize(QSizeF(width(), height())); } m_shaderEffect->setProperty("window", qVariantFromValue((QObject *)w)); } w->imageAddref(); update(); } } #include "windowpixmapitem.moc" <commit_msg>[lipstick] Check if the new window size is different<commit_after>/*************************************************************************** ** ** Copyright (C) 2013 Jolla Ltd. ** Contact: Aaron Kennedy <[email protected]> ** ** This file is part of lipstick. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QtCore/qmath.h> #include <QSGGeometryNode> #include <QSGSimpleMaterial> #include <QWaylandSurfaceItem> #include "lipstickcompositorwindow.h" #include "lipstickcompositor.h" #include "windowpixmapitem.h" namespace { class SurfaceTextureState { public: SurfaceTextureState() : m_texture(0), m_xScale(1), m_yScale(1) {} void setTexture(QSGTexture *texture) { m_texture = texture; } QSGTexture *texture() const { return m_texture; } void setXScale(float xScale) { m_xScale = xScale; } float xScale() const { return m_xScale; } void setYScale(float yScale) { m_yScale = yScale; } float yScale() const { return m_yScale; } private: QSGTexture *m_texture; float m_xScale; float m_yScale; }; class SurfaceTextureMaterial : public QSGSimpleMaterialShader<SurfaceTextureState> { QSG_DECLARE_SIMPLE_SHADER(SurfaceTextureMaterial, SurfaceTextureState) public: QList<QByteArray> attributes() const; void updateState(const SurfaceTextureState *newState, const SurfaceTextureState *oldState); protected: void initialize(); const char *vertexShader() const; const char *fragmentShader() const; private: int m_id_texScale; }; class SurfaceNode : public QObject, public QSGGeometryNode { Q_OBJECT public: SurfaceNode(); void setRect(const QRectF &); void setTextureProvider(QSGTextureProvider *); void setBlending(bool); void setRadius(qreal radius); void setXScale(qreal xScale); void setYScale(qreal yScale); private slots: void providerDestroyed(); void textureChanged(); private: void setTexture(QSGTexture *texture); void updateGeometry(); QSGSimpleMaterial<SurfaceTextureState> *m_material; QRectF m_rect; qreal m_radius; QSGTextureProvider *m_provider; QSGTexture *m_texture; QSGGeometry m_geometry; QRectF m_textureRect; }; QList<QByteArray> SurfaceTextureMaterial::attributes() const { QList<QByteArray> attributeList; attributeList << "qt_VertexPosition"; attributeList << "qt_VertexTexCoord"; return attributeList; } void SurfaceTextureMaterial::updateState(const SurfaceTextureState *newState, const SurfaceTextureState *) { if (newState->texture()) newState->texture()->bind(); program()->setUniformValue(m_id_texScale, newState->xScale(), newState->yScale()); } void SurfaceTextureMaterial::initialize() { QSGSimpleMaterialShader::initialize(); m_id_texScale = program()->uniformLocation("texScale"); } const char *SurfaceTextureMaterial::vertexShader() const { return "uniform highp mat4 qt_Matrix; \n" "attribute highp vec4 qt_VertexPosition; \n" "attribute highp vec2 qt_VertexTexCoord; \n" "varying highp vec2 qt_TexCoord; \n" "uniform highp vec2 texScale; \n" "void main() { \n" " qt_TexCoord = qt_VertexTexCoord * texScale; \n" " gl_Position = qt_Matrix * qt_VertexPosition; \n" "}"; } const char *SurfaceTextureMaterial::fragmentShader() const { return "varying highp vec2 qt_TexCoord; \n" "uniform sampler2D qt_Texture; \n" "uniform lowp float qt_Opacity; \n" "void main() { \n" " gl_FragColor = texture2D(qt_Texture, qt_TexCoord) * qt_Opacity; \n" "}"; } SurfaceNode::SurfaceNode() : m_material(0), m_radius(0), m_provider(0), m_texture(0), m_geometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 0) { setGeometry(&m_geometry); m_material = SurfaceTextureMaterial::createMaterial(); setMaterial(m_material); } void SurfaceNode::setRect(const QRectF &r) { if (m_rect == r) return; m_rect = r; updateGeometry(); } void SurfaceNode::setTextureProvider(QSGTextureProvider *p) { if (p == m_provider) return; if (m_provider) { QObject::disconnect(m_provider, SIGNAL(destroyed(QObject *)), this, SLOT(providerDestroyed())); QObject::disconnect(m_provider, SIGNAL(textureChanged()), this, SLOT(textureChanged())); m_provider = 0; } m_provider = p; QObject::connect(m_provider, SIGNAL(destroyed(QObject *)), this, SLOT(providerDestroyed())); QObject::connect(m_provider, SIGNAL(textureChanged()), this, SLOT(textureChanged())); setTexture(m_provider->texture()); } void SurfaceNode::updateGeometry() { if (m_texture) { QSize ts = m_texture->textureSize(); QRectF sourceRect(0, 0, ts.width(), ts.height()); QRectF textureRect = m_texture->convertToNormalizedSourceRect(sourceRect); if (m_radius) { float radius = qMin(float(qMin(m_rect.width(), m_rect.height()) * 0.5f), float(m_radius)); int segments = qBound(5, qCeil(radius * (M_PI / 6)), 18); float angle = 0.5f * float(M_PI) / segments; m_geometry.allocate((segments + 1) * 2 * 2); QSGGeometry::TexturedPoint2D *v = m_geometry.vertexDataAsTexturedPoint2D(); QSGGeometry::TexturedPoint2D *vlast = v + (segments + 1) * 2 * 2 - 2; float textureXRadius = radius * textureRect.width() / m_rect.width(); float textureYRadius = radius * textureRect.height() / m_rect.height(); float c = 1; float cosStep = qFastCos(angle); float s = 0; float sinStep = qFastSin(angle); for (int ii = 0; ii <= segments; ++ii) { float px = m_rect.left() + radius - radius * c; float tx = textureRect.left() + textureXRadius - textureXRadius * c; float px2 = m_rect.right() - radius + radius * c; float tx2 = textureRect.right() - textureXRadius + textureXRadius * c; float py = m_rect.top() + radius - radius * s; float ty = textureRect.top() + textureYRadius - textureYRadius * s; float py2 = m_rect.bottom() - radius + radius * s; float ty2 = textureRect.bottom() - textureYRadius + textureYRadius * s; v[0].x = px; v[0].y = py; v[0].tx = tx; v[0].ty = ty; v[1].x = px; v[1].y = py2; v[1].tx = tx; v[1].ty = ty2; vlast[0].x = px2; vlast[0].y = py; vlast[0].tx = tx2; vlast[0].ty = ty; vlast[1].x = px2; vlast[1].y = py2; vlast[1].tx = tx2; vlast[1].ty = ty2; v += 2; vlast -= 2; float t = c; c = c * cosStep - s * sinStep; s = s * cosStep + t * sinStep; } } else { m_geometry.allocate(4); QSGGeometry::updateTexturedRectGeometry(&m_geometry, m_rect, textureRect); } markDirty(DirtyGeometry); } } void SurfaceNode::setBlending(bool b) { m_material->setFlag(QSGMaterial::Blending, b); } void SurfaceNode::setRadius(qreal radius) { if (m_radius == radius) return; m_radius = radius; updateGeometry(); } void SurfaceNode::setTexture(QSGTexture *texture) { m_material->state()->setTexture(texture); QRectF tr; if (texture) tr = texture->convertToNormalizedSourceRect(QRect(QPoint(0,0), texture->textureSize())); bool ug = !m_texture || tr != m_textureRect; m_texture = texture; m_textureRect = tr; if (ug) updateGeometry(); markDirty(DirtyMaterial); } void SurfaceNode::setXScale(qreal xScale) { m_material->state()->setXScale(xScale); markDirty(DirtyMaterial); } void SurfaceNode::setYScale(qreal yScale) { m_material->state()->setYScale(yScale); markDirty(DirtyMaterial); } void SurfaceNode::textureChanged() { setTexture(m_provider->texture()); } void SurfaceNode::providerDestroyed() { m_provider = 0; setTexture(0); } } WindowPixmapItem::WindowPixmapItem() : m_item(0), m_shaderEffect(0), m_id(0), m_opaque(false), m_radius(0), m_xScale(1), m_yScale(1) { setFlag(ItemHasContents); } WindowPixmapItem::~WindowPixmapItem() { setWindowId(0); } int WindowPixmapItem::windowId() const { return m_id; } void WindowPixmapItem::setWindowId(int id) { if (m_id == id) return; QSize oldSize = windowSize(); if (m_item) { if (m_item->surface()) disconnect(m_item->surface(), SIGNAL(sizeChanged()), this, SIGNAL(windowSizeChanged())); m_item->imageRelease(); m_item = 0; } m_id = id; updateItem(); emit windowIdChanged(); if (windowSize() != oldSize) emit windowSizeChanged(); } bool WindowPixmapItem::opaque() const { return m_opaque; } void WindowPixmapItem::setOpaque(bool o) { if (m_opaque == o) return; m_opaque = o; if (m_item) update(); emit opaqueChanged(); } qreal WindowPixmapItem::radius() const { return m_radius; } void WindowPixmapItem::setRadius(qreal r) { if (m_radius == r) return; m_radius = r; if (m_item) update(); emit radiusChanged(); } qreal WindowPixmapItem::xScale() const { return m_xScale; } void WindowPixmapItem::setXScale(qreal xScale) { if (m_xScale == xScale) return; m_xScale = xScale; if (m_item) update(); emit xScaleChanged(); } qreal WindowPixmapItem::yScale() const { return m_yScale; } void WindowPixmapItem::setYScale(qreal yScale) { if (m_yScale == yScale) return; m_yScale = yScale; if (m_item) update(); emit yScaleChanged(); } QSize WindowPixmapItem::windowSize() const { if (!m_item || !m_item->surface()) { return QSize(); } return m_item->surface()->size(); } void WindowPixmapItem::setWindowSize(const QSize &s) { if (!m_item || !m_item->surface()) { return; } m_item->surface()->requestSize(s); } QSGNode *WindowPixmapItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *) { SurfaceNode *node = static_cast<SurfaceNode *>(oldNode); if (m_item == 0) { delete node; return 0; } if (!node) node = new SurfaceNode; node->setTextureProvider(m_item->textureProvider()); node->setRect(QRectF(0, 0, width(), height())); node->setBlending(!m_opaque); node->setRadius(m_radius); node->setXScale(m_xScale); node->setYScale(m_yScale); return node; } void WindowPixmapItem::geometryChanged(const QRectF &n, const QRectF &o) { QQuickItem::geometryChanged(n, o); if (m_shaderEffect) m_shaderEffect->setSize(n.size()); } void WindowPixmapItem::updateItem() { LipstickCompositor *c = LipstickCompositor::instance(); Q_ASSERT(m_item == 0); if (c && m_id) { LipstickCompositorWindow *w = static_cast<LipstickCompositorWindow *>(c->windowForId(m_id)); if (!w) { delete m_shaderEffect; m_shaderEffect = 0; return; } else if (w->surface()) { m_item = w; delete m_shaderEffect; m_shaderEffect = 0; connect(m_item->surface(), SIGNAL(sizeChanged()), this, SIGNAL(windowSizeChanged())); } else { if (!m_shaderEffect) { m_shaderEffect = static_cast<QQuickItem *>(c->shaderEffectComponent()->create()); Q_ASSERT(m_shaderEffect); m_shaderEffect->setParentItem(this); m_shaderEffect->setSize(QSizeF(width(), height())); } m_shaderEffect->setProperty("window", qVariantFromValue((QObject *)w)); } w->imageAddref(); update(); } } #include "windowpixmapitem.moc" <|endoftext|>
<commit_before>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_file_agent.h" #include "condor_file_local.h" #include "condor_debug.h" #include "condor_error.h" #include "condor_syscall_mode.h" #define KB 1024 #define TRANSFER_BLOCK_SIZE (32*KB) static char buffer[TRANSFER_BLOCK_SIZE]; CondorFileAgent::CondorFileAgent( CondorFile *file ) { original = file; url = NULL; local_url = NULL; } CondorFileAgent::~CondorFileAgent() { delete original; free( url ); free( local_url ); } int CondorFileAgent::open( const char *url_in, int flags, int mode ) { int pos=0, chunk=0, result=0; int local_flags; char *junk = (char *)malloc(strlen(url_in)+1); char *sub_url = (char *)malloc(strlen(url_in)+1); char local_filename[_POSIX_PATH_MAX]; free( url ); url = strdup( url_in ); /* linux glibc 2.1 and presumeably 2.0 had a bug where the range didn't work with 8bit numbers */ #if defined(LINUX) && (defined(GLIBC20) || defined(GLIBC21)) sscanf( url, "%[^:]:%[\x1-\x7F]",junk,sub_url ); #else sscanf( url, "%[^:]:%[\x1-\xFF]",junk,sub_url ); #endif free( junk ); // First, fudge the flags. Even if the file is opened // write-only, we must open it read/write to get the // original data. // We need not worry especially about O_CREAT and O_TRUNC // because these will be applied at the original open, // and their effects will be preserved through pull_data(). if( flags&O_WRONLY ) { flags = flags&~O_WRONLY; flags = flags|O_RDWR; } // The local copy is created anew, opened read/write. local_flags = O_RDWR|O_CREAT|O_TRUNC; // O_APPEND is a little tricky. In this case, it is applied // to both the original and the copy, but the data must not // be pulled. if( flags&O_APPEND ){ local_flags = local_flags|O_APPEND; } // Open the original file. result = original->open(sub_url,flags,mode); free( sub_url ); if(result<0) return -1; // Choose where to store the file. // Notice that tmpnam() may do funny syscalls to make sure that // the name is not in use. So, it must be done in local mode. // Eventually, this should be in a Condor spool directory. int scm = SetSyscalls(SYS_LOCAL|SYS_UNMAPPED); tmpnam(local_filename); SetSyscalls(scm); free( local_url ); local_url = (char *)malloc(strlen(local_filename) + 7); sprintf(local_url,"local:%s",local_filename); // Open the local copy, with a private mode. local_copy = new CondorFileLocal; result = local_copy->open(local_url,local_flags,0700); if(result<0) _condor_error_retry("Couldn't create temporary file '%s'!",local_url); // Now, delete the file right away. // If we get into trouble and can't clean up properly, // the file system will free it for us. scm = SetSyscalls(SYS_LOCAL|SYS_UNMAPPED); unlink( local_filename ); SetSyscalls(scm); // If the file has not been opened for append, // then yank all of the data in. dprintf(D_ALWAYS,"CondorFileAgent: Copying %s into %s\n",original->get_url(),local_copy->get_url()); if( !(flags&O_APPEND) ){ do { chunk = original->read(pos,buffer,TRANSFER_BLOCK_SIZE); if(chunk<0) _condor_error_retry("CondorFileAgent: Couldn't read from '%s'",original->get_url()); result = local_copy->write(pos,buffer,chunk); if(result<0) _condor_error_retry("CondorFileAgent: Couldn't write to '%s'",local_url); pos += chunk; } while(chunk==TRANSFER_BLOCK_SIZE); } // Return success! return 1; } int CondorFileAgent::close() { int pos=0, chunk=0, result=0; // If the original file was opened for writing, then // push the local copy back out. if the original file // was opened append-only, then the data is simply appended // by the operating system at the other end. if( original->is_writeable() ) { dprintf(D_ALWAYS,"CondorFileAgent: Copying %s back into %s\n",local_copy->get_url(),original->get_url()); original->ftruncate(local_copy->get_size()); do { chunk = local_copy->read(pos,buffer,TRANSFER_BLOCK_SIZE); if(chunk<0) _condor_error_retry("CondorFileAgent: Couldn't read from '%s'",local_url); result = original->write(pos,buffer,chunk); if(result<0) _condor_error_retry("CondorFileAgent: Couldn't write to '%s'",original->get_url()); pos += chunk; } while(chunk==TRANSFER_BLOCK_SIZE); } // Close the original file. This must happen before the // local copy is closed, so that any failure can be reported // before the local copy is lost. result = original->close(); if(result<0) return result; // Finally, close and delete the local copy. // There is nothing reasonable we can do if the local close fails. result = local_copy->close(); delete local_copy; return 0; } int CondorFileAgent::read( int offset, char *data, int length ) { if( is_readable() ) { return local_copy->read( offset, data, length ); } else { errno = EINVAL; return -1; } } int CondorFileAgent::write( int offset, char *data, int length ) { if( is_writeable() ) { return local_copy->write( offset,data, length ); } else { errno = EINVAL; return -1; } } int CondorFileAgent::fcntl( int cmd, int arg ) { return local_copy->fcntl(cmd,arg); } int CondorFileAgent::ioctl( int cmd, long arg ) { return local_copy->ioctl(cmd,arg); } int CondorFileAgent::ftruncate( size_t length ) { return local_copy->ftruncate( length ); } int CondorFileAgent::fsync() { return local_copy->fsync(); } int CondorFileAgent::flush() { return local_copy->flush(); } int CondorFileAgent::fstat(struct stat *buf) { struct stat local; int ret, ret2; ret = original->fstat(buf); if (ret != 0){ return ret; } ret2 = local_copy->fstat(&local); if (ret2 != 0){ return ret2; } buf->st_size = local.st_size; buf->st_atime = local.st_atime; buf->st_mtime = local.st_mtime; return ret2; } int CondorFileAgent::is_readable() { return original->is_readable(); } int CondorFileAgent::is_writeable() { return original->is_writeable(); } int CondorFileAgent::is_seekable() { return 1; } int CondorFileAgent::get_size() { return local_copy->get_size(); } char const * CondorFileAgent::get_url() { return url ? url : ""; } int CondorFileAgent::get_unmapped_fd() { return local_copy->get_unmapped_fd(); } int CondorFileAgent::is_file_local() { return 1; } <commit_msg>+ Fixed CID 1208, uninit_ctor on the local_copy member variable.<commit_after>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_file_agent.h" #include "condor_file_local.h" #include "condor_debug.h" #include "condor_error.h" #include "condor_syscall_mode.h" #define KB 1024 #define TRANSFER_BLOCK_SIZE (32*KB) static char buffer[TRANSFER_BLOCK_SIZE]; CondorFileAgent::CondorFileAgent( CondorFile *file ) { original = file; url = NULL; local_url = NULL; local_copy = NULL; } CondorFileAgent::~CondorFileAgent() { delete original; free( url ); free( local_url ); } int CondorFileAgent::open( const char *url_in, int flags, int mode ) { int pos=0, chunk=0, result=0; int local_flags; char *junk = (char *)malloc(strlen(url_in)+1); char *sub_url = (char *)malloc(strlen(url_in)+1); char local_filename[_POSIX_PATH_MAX]; free( url ); url = strdup( url_in ); /* linux glibc 2.1 and presumeably 2.0 had a bug where the range didn't work with 8bit numbers */ #if defined(LINUX) && (defined(GLIBC20) || defined(GLIBC21)) sscanf( url, "%[^:]:%[\x1-\x7F]",junk,sub_url ); #else sscanf( url, "%[^:]:%[\x1-\xFF]",junk,sub_url ); #endif free( junk ); // First, fudge the flags. Even if the file is opened // write-only, we must open it read/write to get the // original data. // We need not worry especially about O_CREAT and O_TRUNC // because these will be applied at the original open, // and their effects will be preserved through pull_data(). if( flags&O_WRONLY ) { flags = flags&~O_WRONLY; flags = flags|O_RDWR; } // The local copy is created anew, opened read/write. local_flags = O_RDWR|O_CREAT|O_TRUNC; // O_APPEND is a little tricky. In this case, it is applied // to both the original and the copy, but the data must not // be pulled. if( flags&O_APPEND ){ local_flags = local_flags|O_APPEND; } // Open the original file. result = original->open(sub_url,flags,mode); free( sub_url ); if(result<0) return -1; // Choose where to store the file. // Notice that tmpnam() may do funny syscalls to make sure that // the name is not in use. So, it must be done in local mode. // Eventually, this should be in a Condor spool directory. int scm = SetSyscalls(SYS_LOCAL|SYS_UNMAPPED); tmpnam(local_filename); SetSyscalls(scm); free( local_url ); local_url = (char *)malloc(strlen(local_filename) + 7); sprintf(local_url,"local:%s",local_filename); // Open the local copy, with a private mode. local_copy = new CondorFileLocal; result = local_copy->open(local_url,local_flags,0700); if(result<0) _condor_error_retry("Couldn't create temporary file '%s'!",local_url); // Now, delete the file right away. // If we get into trouble and can't clean up properly, // the file system will free it for us. scm = SetSyscalls(SYS_LOCAL|SYS_UNMAPPED); unlink( local_filename ); SetSyscalls(scm); // If the file has not been opened for append, // then yank all of the data in. dprintf(D_ALWAYS,"CondorFileAgent: Copying %s into %s\n",original->get_url(),local_copy->get_url()); if( !(flags&O_APPEND) ){ do { chunk = original->read(pos,buffer,TRANSFER_BLOCK_SIZE); if(chunk<0) _condor_error_retry("CondorFileAgent: Couldn't read from '%s'",original->get_url()); result = local_copy->write(pos,buffer,chunk); if(result<0) _condor_error_retry("CondorFileAgent: Couldn't write to '%s'",local_url); pos += chunk; } while(chunk==TRANSFER_BLOCK_SIZE); } // Return success! return 1; } int CondorFileAgent::close() { int pos=0, chunk=0, result=0; // If the original file was opened for writing, then // push the local copy back out. if the original file // was opened append-only, then the data is simply appended // by the operating system at the other end. if( original->is_writeable() ) { dprintf(D_ALWAYS,"CondorFileAgent: Copying %s back into %s\n",local_copy->get_url(),original->get_url()); original->ftruncate(local_copy->get_size()); do { chunk = local_copy->read(pos,buffer,TRANSFER_BLOCK_SIZE); if(chunk<0) _condor_error_retry("CondorFileAgent: Couldn't read from '%s'",local_url); result = original->write(pos,buffer,chunk); if(result<0) _condor_error_retry("CondorFileAgent: Couldn't write to '%s'",original->get_url()); pos += chunk; } while(chunk==TRANSFER_BLOCK_SIZE); } // Close the original file. This must happen before the // local copy is closed, so that any failure can be reported // before the local copy is lost. result = original->close(); if(result<0) return result; // Finally, close and delete the local copy. // There is nothing reasonable we can do if the local close fails. result = local_copy->close(); delete local_copy; return 0; } int CondorFileAgent::read( int offset, char *data, int length ) { if( is_readable() ) { return local_copy->read( offset, data, length ); } else { errno = EINVAL; return -1; } } int CondorFileAgent::write( int offset, char *data, int length ) { if( is_writeable() ) { return local_copy->write( offset,data, length ); } else { errno = EINVAL; return -1; } } int CondorFileAgent::fcntl( int cmd, int arg ) { return local_copy->fcntl(cmd,arg); } int CondorFileAgent::ioctl( int cmd, long arg ) { return local_copy->ioctl(cmd,arg); } int CondorFileAgent::ftruncate( size_t length ) { return local_copy->ftruncate( length ); } int CondorFileAgent::fsync() { return local_copy->fsync(); } int CondorFileAgent::flush() { return local_copy->flush(); } int CondorFileAgent::fstat(struct stat *buf) { struct stat local; int ret, ret2; ret = original->fstat(buf); if (ret != 0){ return ret; } ret2 = local_copy->fstat(&local); if (ret2 != 0){ return ret2; } buf->st_size = local.st_size; buf->st_atime = local.st_atime; buf->st_mtime = local.st_mtime; return ret2; } int CondorFileAgent::is_readable() { return original->is_readable(); } int CondorFileAgent::is_writeable() { return original->is_writeable(); } int CondorFileAgent::is_seekable() { return 1; } int CondorFileAgent::get_size() { return local_copy->get_size(); } char const * CondorFileAgent::get_url() { return url ? url : ""; } int CondorFileAgent::get_unmapped_fd() { return local_copy->get_unmapped_fd(); } int CondorFileAgent::is_file_local() { return 1; } <|endoftext|>
<commit_before>#ifndef TOML11_REGION_H #define TOML11_REGION_H #include "exception.hpp" #include <memory> #include <algorithm> #include <initializer_list> #include <iterator> #include <iostream> namespace toml { namespace detail { // helper function to avoid std::string(0, 'c') template<typename Iterator> std::string make_string(Iterator first, Iterator last) { if(first == last) {return "";} return std::string(first, last); } inline std::string make_string(std::size_t len, char c) { if(len == 0) {return "";} return std::string(len, c); } // location in a container, normally in a file content. // shared_ptr points the resource that the iter points. // it can be used not only for resource handling, but also error message. template<typename Container> struct location { static_assert(std::is_same<char, typename Container::value_type>::value,""); using const_iterator = typename Container::const_iterator; using source_ptr = std::shared_ptr<const Container>; location(std::string name, Container cont) : source_(std::make_shared<Container>(std::move(cont))), source_name_(std::move(name)), iter_(source_->cbegin()) {} location(const location&) = default; location(location&&) = default; location& operator=(const location&) = default; location& operator=(location&&) = default; ~location() = default; const_iterator& iter() noexcept {return iter_;} const_iterator iter() const noexcept {return iter_;} const_iterator begin() const noexcept {return source_->cbegin();} const_iterator end() const noexcept {return source_->cend();} source_ptr const& source() const& noexcept {return source_;} source_ptr&& source() && noexcept {return std::move(source_);} std::string const& name() const noexcept {return source_name_;} private: source_ptr source_; std::string source_name_; const_iterator iter_; }; // region in a container, normally in a file content. // shared_ptr points the resource that the iter points. // combinators returns this. // it will be used to generate better error messages. struct region_base { region_base() = default; virtual ~region_base() = default; region_base(const region_base&) = default; region_base(region_base&& ) = default; region_base& operator=(const region_base&) = default; region_base& operator=(region_base&& ) = default; virtual bool is_ok() const noexcept {return false;} virtual std::string str() const {return std::string("unknown region");} virtual std::string name() const {return std::string("unknown file");} virtual std::string line() const {return std::string("unknown line");} virtual std::string line_num() const {return std::string("?");} virtual std::size_t before() const noexcept {return 0;} virtual std::size_t size() const noexcept {return 0;} virtual std::size_t after() const noexcept {return 0;} }; template<typename Container> struct region final : public region_base { static_assert(std::is_same<char, typename Container::value_type>::value,""); using const_iterator = typename Container::const_iterator; using source_ptr = std::shared_ptr<const Container>; // delete default constructor. source_ never be null. region() = delete; region(const location<Container>& loc) : source_(loc.source()), source_name_(loc.name()), first_(loc.iter()), last_(loc.iter()) {} region(location<Container>&& loc) : source_(loc.source()), source_name_(loc.name()), first_(loc.iter()), last_(loc.iter()) {} region(const location<Container>& loc, const_iterator f, const_iterator l) : source_(loc.source()), source_name_(loc.name()), first_(f), last_(l) {} region(location<Container>&& loc, const_iterator f, const_iterator l) : source_(loc.source()), source_name_(loc.name()), first_(f), last_(l) {} region(const region&) = default; region(region&&) = default; region& operator=(const region&) = default; region& operator=(region&&) = default; ~region() = default; region& operator+=(const region& other) { if(this->begin() != other.begin() || this->end() != other.end() || this->last_ != other.first_) { throw internal_error("invalid region concatenation"); } this->last_ = other.last_; return *this; } bool is_ok() const noexcept override {return static_cast<bool>(source_);} std::string str() const override {return make_string(first_, last_);} std::string line() const override { return make_string(this->line_begin(), this->line_end()); } std::string line_num() const override { return std::to_string(1 + std::count(this->begin(), this->first(), '\n')); } std::size_t size() const noexcept override { return std::distance(first_, last_); } std::size_t before() const noexcept override { return std::distance(this->line_begin(), this->first()); } std::size_t after() const noexcept override { return std::distance(this->last(), this->line_end()); } const_iterator line_begin() const noexcept { using reverse_iterator = std::reverse_iterator<const_iterator>; return std::find(reverse_iterator(this->first()), reverse_iterator(this->begin()), '\n').base(); } const_iterator line_end() const noexcept { return std::find(this->last(), this->end(), '\n'); } const_iterator begin() const noexcept {return source_->cbegin();} const_iterator end() const noexcept {return source_->cend();} const_iterator first() const noexcept {return first_;} const_iterator last() const noexcept {return last_;} source_ptr const& source() const& noexcept {return source_;} source_ptr&& source() && noexcept {return std::move(source_);} std::string name() const override {return source_name_;} private: source_ptr source_; std::string source_name_; const_iterator first_, last_; }; // to show a better error message. inline std::string format_underline(const std::string& message, const region_base& reg, const std::string& comment_for_underline) { const auto line = reg.line(); const auto line_number = reg.line_num(); std::string retval; retval += message; retval += "\n --> "; retval += reg.name(); retval += "\n "; retval += line_number; retval += " | "; retval += line; retval += '\n'; retval += make_string(line_number.size() + 1, ' '); retval += " | "; retval += make_string(reg.before(), ' '); retval += make_string(reg.size(), '~'); retval += ' '; retval += comment_for_underline; return retval; } // to show a better error message. template<typename Container> std::string format_underline(const std::string& message, const location<Container>& loc, const std::string& comment_for_underline, std::initializer_list<std::string> helps = {}) { using const_iterator = typename location<Container>::const_iterator; using reverse_iterator = std::reverse_iterator<const_iterator>; const auto line_begin = std::find(reverse_iterator(loc.iter()), reverse_iterator(loc.begin()), '\n').base(); const auto line_end = std::find(loc.iter(), loc.end(), '\n'); const auto line_number = std::to_string( 1 + std::count(loc.begin(), loc.iter(), '\n')); std::string retval; retval += message; retval += "\n --> "; retval += loc.name(); retval += "\n "; retval += line_number; retval += " | "; retval += make_string(line_begin, line_end); retval += '\n'; retval += make_string(line_number.size() + 1, ' '); retval += " | "; retval += make_string(std::distance(line_begin, loc.iter()),' '); retval += '^'; retval += make_string(std::distance(loc.iter(), line_end), '-'); retval += ' '; retval += comment_for_underline; if(helps.size() != 0) { retval += '\n'; retval += make_string(line_number.size() + 1, ' '); retval += " | "; for(const auto help : helps) { retval += "\nHint: "; retval += help; } } return retval; } } // detail } // toml #endif// TOML11_REGION_H <commit_msg>consider LF in the range when writing error msg<commit_after>#ifndef TOML11_REGION_H #define TOML11_REGION_H #include "exception.hpp" #include <memory> #include <algorithm> #include <initializer_list> #include <iterator> #include <iostream> namespace toml { namespace detail { // helper function to avoid std::string(0, 'c') template<typename Iterator> std::string make_string(Iterator first, Iterator last) { if(first == last) {return "";} return std::string(first, last); } inline std::string make_string(std::size_t len, char c) { if(len == 0) {return "";} return std::string(len, c); } // location in a container, normally in a file content. // shared_ptr points the resource that the iter points. // it can be used not only for resource handling, but also error message. template<typename Container> struct location { static_assert(std::is_same<char, typename Container::value_type>::value,""); using const_iterator = typename Container::const_iterator; using source_ptr = std::shared_ptr<const Container>; location(std::string name, Container cont) : source_(std::make_shared<Container>(std::move(cont))), source_name_(std::move(name)), iter_(source_->cbegin()) {} location(const location&) = default; location(location&&) = default; location& operator=(const location&) = default; location& operator=(location&&) = default; ~location() = default; const_iterator& iter() noexcept {return iter_;} const_iterator iter() const noexcept {return iter_;} const_iterator begin() const noexcept {return source_->cbegin();} const_iterator end() const noexcept {return source_->cend();} source_ptr const& source() const& noexcept {return source_;} source_ptr&& source() && noexcept {return std::move(source_);} std::string const& name() const noexcept {return source_name_;} private: source_ptr source_; std::string source_name_; const_iterator iter_; }; // region in a container, normally in a file content. // shared_ptr points the resource that the iter points. // combinators returns this. // it will be used to generate better error messages. struct region_base { region_base() = default; virtual ~region_base() = default; region_base(const region_base&) = default; region_base(region_base&& ) = default; region_base& operator=(const region_base&) = default; region_base& operator=(region_base&& ) = default; virtual bool is_ok() const noexcept {return false;} virtual std::string str() const {return std::string("unknown region");} virtual std::string name() const {return std::string("unknown file");} virtual std::string line() const {return std::string("unknown line");} virtual std::string line_num() const {return std::string("?");} virtual std::size_t before() const noexcept {return 0;} virtual std::size_t size() const noexcept {return 0;} virtual std::size_t after() const noexcept {return 0;} }; template<typename Container> struct region final : public region_base { static_assert(std::is_same<char, typename Container::value_type>::value,""); using const_iterator = typename Container::const_iterator; using source_ptr = std::shared_ptr<const Container>; // delete default constructor. source_ never be null. region() = delete; region(const location<Container>& loc) : source_(loc.source()), source_name_(loc.name()), first_(loc.iter()), last_(loc.iter()) {} region(location<Container>&& loc) : source_(loc.source()), source_name_(loc.name()), first_(loc.iter()), last_(loc.iter()) {} region(const location<Container>& loc, const_iterator f, const_iterator l) : source_(loc.source()), source_name_(loc.name()), first_(f), last_(l) {} region(location<Container>&& loc, const_iterator f, const_iterator l) : source_(loc.source()), source_name_(loc.name()), first_(f), last_(l) {} region(const region&) = default; region(region&&) = default; region& operator=(const region&) = default; region& operator=(region&&) = default; ~region() = default; region& operator+=(const region& other) { if(this->begin() != other.begin() || this->end() != other.end() || this->last_ != other.first_) { throw internal_error("invalid region concatenation"); } this->last_ = other.last_; return *this; } bool is_ok() const noexcept override {return static_cast<bool>(source_);} std::string str() const override {return make_string(first_, last_);} std::string line() const override { if(this->contain_newline()) { return make_string(this->line_begin(), std::find(this->line_begin(), this->last(), '\n')); } return make_string(this->line_begin(), this->line_end()); } std::string line_num() const override { return std::to_string(1 + std::count(this->begin(), this->first(), '\n')); } std::size_t size() const noexcept override { return std::distance(first_, last_); } std::size_t before() const noexcept override { return std::distance(this->line_begin(), this->first()); } std::size_t after() const noexcept override { return std::distance(this->last(), this->line_end()); } bool contain_newline() const noexcept { return std::find(this->first(), this->last(), '\n') != this->last(); } const_iterator line_begin() const noexcept { using reverse_iterator = std::reverse_iterator<const_iterator>; return std::find(reverse_iterator(this->first()), reverse_iterator(this->begin()), '\n').base(); } const_iterator line_end() const noexcept { return std::find(this->last(), this->end(), '\n'); } const_iterator begin() const noexcept {return source_->cbegin();} const_iterator end() const noexcept {return source_->cend();} const_iterator first() const noexcept {return first_;} const_iterator last() const noexcept {return last_;} source_ptr const& source() const& noexcept {return source_;} source_ptr&& source() && noexcept {return std::move(source_);} std::string name() const override {return source_name_;} private: source_ptr source_; std::string source_name_; const_iterator first_, last_; }; // to show a better error message. inline std::string format_underline(const std::string& message, const region_base& reg, const std::string& comment_for_underline) { const auto line = reg.line(); const auto line_number = reg.line_num(); std::string retval; retval += message; retval += "\n --> "; retval += reg.name(); retval += "\n "; retval += line_number; retval += " | "; retval += line; retval += '\n'; retval += make_string(line_number.size() + 1, ' '); retval += " | "; retval += make_string(reg.before(), ' '); retval += make_string(reg.size(), '~'); retval += ' '; retval += comment_for_underline; return retval; } // to show a better error message. template<typename Container> std::string format_underline(const std::string& message, const location<Container>& loc, const std::string& comment_for_underline, std::initializer_list<std::string> helps = {}) { using const_iterator = typename location<Container>::const_iterator; using reverse_iterator = std::reverse_iterator<const_iterator>; const auto line_begin = std::find(reverse_iterator(loc.iter()), reverse_iterator(loc.begin()), '\n').base(); const auto line_end = std::find(loc.iter(), loc.end(), '\n'); const auto line_number = std::to_string( 1 + std::count(loc.begin(), loc.iter(), '\n')); std::string retval; retval += message; retval += "\n --> "; retval += loc.name(); retval += "\n "; retval += line_number; retval += " | "; retval += make_string(line_begin, line_end); retval += '\n'; retval += make_string(line_number.size() + 1, ' '); retval += " | "; retval += make_string(std::distance(line_begin, loc.iter()),' '); retval += '^'; retval += make_string(std::distance(loc.iter(), line_end), '-'); retval += ' '; retval += comment_for_underline; if(helps.size() != 0) { retval += '\n'; retval += make_string(line_number.size() + 1, ' '); retval += " | "; for(const auto help : helps) { retval += "\nHint: "; retval += help; } } return retval; } } // detail } // toml #endif// TOML11_REGION_H <|endoftext|>
<commit_before>// ------------------------------------------------------------------------- // @FileName : NFCNPCRefreshModule.cpp // @Author : LvSheng.Huang // @Date : 2013-10-17 // @Module : NFCNPCRefreshModule // ------------------------------------------------------------------------- #include "NFCNPCRefreshModule.h" bool NFCNPCRefreshModule::Init() { return true; } bool NFCNPCRefreshModule::Shut() { return true; } bool NFCNPCRefreshModule::Execute() { return true; } bool NFCNPCRefreshModule::AfterInit() { m_pScheduleModule = pPluginManager->FindModule<NFIScheduleModule>(); m_pEventModule = pPluginManager->FindModule<NFIEventModule>(); m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>(); m_pSceneProcessModule = pPluginManager->FindModule<NFISceneProcessModule>(); m_pElementModule = pPluginManager->FindModule<NFIElementModule>(); m_pPackModule = pPluginManager->FindModule<NFIPackModule>(); m_pLogModule = pPluginManager->FindModule<NFILogModule>(); m_pLevelModule = pPluginManager->FindModule<NFILevelModule>(); m_pHeroPropertyModule = pPluginManager->FindModule<NFIHeroPropertyModule>(); m_pKernelModule->AddClassCallBack(NFrame::NPC::ThisName(), this, &NFCNPCRefreshModule::OnObjectClassEvent); return true; } int NFCNPCRefreshModule::OnObjectClassEvent( const NFGUID& self, const std::string& strClassName, const CLASS_OBJECT_EVENT eClassEvent, const NFIDataList& var ) { NF_SHARE_PTR<NFIObject> pSelf = m_pKernelModule->GetObject(self); if (nullptr == pSelf) { return 1; } if (strClassName == NFrame::NPC::ThisName()) { if ( CLASS_OBJECT_EVENT::COE_CREATE_LOADDATA == eClassEvent ) { const std::string& strConfigIndex = m_pKernelModule->GetPropertyString(self, NFrame::NPC::ConfigID()); const std::string& strPropertyID = m_pElementModule->GetPropertyString(strConfigIndex, NFrame::NPC::EffectData()); const int nNPCType = m_pElementModule->GetPropertyInt(strConfigIndex, NFrame::NPC::NPCType()); NF_SHARE_PTR<NFIPropertyManager> pSelfPropertyManager = pSelf->GetPropertyManager(); if (nNPCType == NFMsg::ENPCType::ENPCTYPE_HERO) { //hero NFGUID xMasterID = m_pKernelModule->GetPropertyObject(self, NFrame::NPC::MasterID()); NF_SHARE_PTR<NFIRecord> pHeroPropertyRecord = m_pKernelModule->FindRecord(xMasterID, NFrame::Player::R_HeroPropertyValue()); if (pHeroPropertyRecord) { NFCDataList xHeroPropertyList; if (m_pHeroPropertyModule->CalHeroAllProperty(xMasterID, self, xHeroPropertyList)) { for (int i = 0; i < pHeroPropertyRecord->GetCols(); ++i) { const std::string& strColTag = pHeroPropertyRecord->GetColTag(i); const int nValue = xHeroPropertyList.Int(i); pSelfPropertyManager->SetPropertyInt(strColTag, nValue); } } } } } else if ( CLASS_OBJECT_EVENT::COE_CREATE_HASDATA == eClassEvent ) { const std::string& strConfigID = m_pKernelModule->GetPropertyString(self, NFrame::NPC::ConfigID()); int nHPMax = m_pElementModule->GetPropertyInt(strConfigID, NFrame::NPC::MAXHP()); m_pKernelModule->SetPropertyInt(self, NFrame::NPC::HP(), nHPMax); m_pKernelModule->AddPropertyCallBack( self, NFrame::NPC::HP(), this, &NFCNPCRefreshModule::OnObjectHPEvent ); m_pEventModule->AddEventCallBack( self, NFED_ON_OBJECT_BE_KILLED, this, &NFCNPCRefreshModule::OnObjectBeKilled ); } } return 0; } int NFCNPCRefreshModule::OnObjectHPEvent( const NFGUID& self, const std::string& strPropertyName, const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar) { if ( newVar.GetInt() <= 0 ) { NFGUID identAttacker = m_pKernelModule->GetPropertyObject( self, NFrame::NPC::LastAttacker()); if (!identAttacker.IsNull()) { m_pEventModule->DoEvent( self, NFED_ON_OBJECT_BE_KILLED, NFCDataList() << identAttacker ); m_pScheduleModule->AddSchedule( self, "OnDeadDestroyHeart", this, &NFCNPCRefreshModule::OnDeadDestroyHeart, 5.0f, 1 ); } } return 0; } int NFCNPCRefreshModule::OnDeadDestroyHeart( const NFGUID& self, const std::string& strHeartBeat, const float fTime, const int nCount) { //and create new object const std::string& strClassName = m_pKernelModule->GetPropertyString( self, NFrame::NPC::ClassName()); const std::string& strSeedID = m_pKernelModule->GetPropertyString( self, NFrame::NPC::SeedID()); const std::string& strConfigID = m_pKernelModule->GetPropertyString( self, NFrame::NPC::ConfigID()); int nSceneID = m_pKernelModule->GetPropertyInt( self, NFrame::NPC::SceneID()); int nGroupID = m_pKernelModule->GetPropertyInt( self, NFrame::NPC::GroupID()); //m_pSceneProcessModule->ClearAll( nSceneID, nGroupID, strSeendID ); float fSeedX = m_pKernelModule->GetPropertyFloat( self, NFrame::NPC::X()); float fSeedY = m_pKernelModule->GetPropertyFloat( self, NFrame::NPC::Y()); float fSeedZ = m_pKernelModule->GetPropertyFloat( self, NFrame::NPC::Z()); m_pKernelModule->DestroyObject( self ); NFCDataList arg; arg << NFrame::NPC::X() << fSeedX; arg << NFrame::NPC::Y() << fSeedY; arg << NFrame::NPC::Z() << fSeedZ; arg << NFrame::NPC::SeedID() << strSeedID; m_pKernelModule->CreateObject( NFGUID(), nSceneID, nGroupID, strClassName, strConfigID, arg ); return 0; } int NFCNPCRefreshModule::OnObjectBeKilled( const NFGUID& self, const NFEventDefine nEventID, const NFIDataList& var ) { if ( var.GetCount() == 1 && var.Type( 0 ) == TDATA_OBJECT ) { NFGUID identKiller = var.Object( 0 ); if ( m_pKernelModule->GetObject( identKiller ) ) { const int nExp = m_pKernelModule->GetPropertyInt( self, NFrame::Player::EXP() ); m_pLevelModule->AddExp( identKiller, nExp); m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, identKiller, "Add Exp for kill monster", nExp); } else { m_pLogModule->LogObject(NFILogModule::NLL_ERROR_NORMAL, identKiller, "There is no object", __FUNCTION__, __LINE__); } } return 0; }<commit_msg>fixed for effectdata when create a npc<commit_after>// ------------------------------------------------------------------------- // @FileName : NFCNPCRefreshModule.cpp // @Author : LvSheng.Huang // @Date : 2013-10-17 // @Module : NFCNPCRefreshModule // ------------------------------------------------------------------------- #include "NFCNPCRefreshModule.h" bool NFCNPCRefreshModule::Init() { return true; } bool NFCNPCRefreshModule::Shut() { return true; } bool NFCNPCRefreshModule::Execute() { return true; } bool NFCNPCRefreshModule::AfterInit() { m_pScheduleModule = pPluginManager->FindModule<NFIScheduleModule>(); m_pEventModule = pPluginManager->FindModule<NFIEventModule>(); m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>(); m_pSceneProcessModule = pPluginManager->FindModule<NFISceneProcessModule>(); m_pElementModule = pPluginManager->FindModule<NFIElementModule>(); m_pPackModule = pPluginManager->FindModule<NFIPackModule>(); m_pLogModule = pPluginManager->FindModule<NFILogModule>(); m_pLevelModule = pPluginManager->FindModule<NFILevelModule>(); m_pHeroPropertyModule = pPluginManager->FindModule<NFIHeroPropertyModule>(); m_pKernelModule->AddClassCallBack(NFrame::NPC::ThisName(), this, &NFCNPCRefreshModule::OnObjectClassEvent); return true; } int NFCNPCRefreshModule::OnObjectClassEvent( const NFGUID& self, const std::string& strClassName, const CLASS_OBJECT_EVENT eClassEvent, const NFIDataList& var ) { NF_SHARE_PTR<NFIObject> pSelf = m_pKernelModule->GetObject(self); if (nullptr == pSelf) { return 1; } if (strClassName == NFrame::NPC::ThisName()) { if ( CLASS_OBJECT_EVENT::COE_CREATE_LOADDATA == eClassEvent ) { const std::string& strConfigIndex = m_pKernelModule->GetPropertyString(self, NFrame::NPC::ConfigID()); const std::string& strEffectPropertyID = m_pElementModule->GetPropertyString(strConfigIndex, NFrame::NPC::EffectData()); const int nNPCType = m_pElementModule->GetPropertyInt(strConfigIndex, NFrame::NPC::NPCType()); NF_SHARE_PTR<NFIPropertyManager> pSelfPropertyManager = pSelf->GetPropertyManager(); if (nNPCType == NFMsg::ENPCType::ENPCTYPE_HERO) { //hero NFGUID xMasterID = m_pKernelModule->GetPropertyObject(self, NFrame::NPC::MasterID()); NF_SHARE_PTR<NFIRecord> pHeroPropertyRecord = m_pKernelModule->FindRecord(xMasterID, NFrame::Player::R_HeroPropertyValue()); if (pHeroPropertyRecord) { NFCDataList xHeroPropertyList; if (m_pHeroPropertyModule->CalHeroAllProperty(xMasterID, self, xHeroPropertyList)) { for (int i = 0; i < pHeroPropertyRecord->GetCols(); ++i) { const std::string& strColTag = pHeroPropertyRecord->GetColTag(i); const int nValue = xHeroPropertyList.Int(i); pSelfPropertyManager->SetPropertyInt(strColTag, nValue); } } } } else { //normal npc NF_SHARE_PTR<NFIPropertyManager> pConfigPropertyManager = m_pElementModule->GetPropertyManager(strEffectPropertyID); if (pConfigPropertyManager) { std::string strProperName; for (NFIProperty* pProperty = pConfigPropertyManager->FirstNude(strProperName); pProperty != NULL; pProperty = pConfigPropertyManager->NextNude(strProperName)) { if (pSelfPropertyManager && strProperName != NFrame::NPC::ID() && pProperty->Changed()) { pSelfPropertyManager->SetProperty(pProperty->GetKey(), pProperty->GetValue()); } } } } } else if ( CLASS_OBJECT_EVENT::COE_CREATE_HASDATA == eClassEvent ) { const std::string& strConfigID = m_pKernelModule->GetPropertyString(self, NFrame::NPC::ConfigID()); int nHPMax = m_pElementModule->GetPropertyInt(strConfigID, NFrame::NPC::MAXHP()); m_pKernelModule->SetPropertyInt(self, NFrame::NPC::HP(), nHPMax); m_pKernelModule->AddPropertyCallBack( self, NFrame::NPC::HP(), this, &NFCNPCRefreshModule::OnObjectHPEvent ); m_pEventModule->AddEventCallBack( self, NFED_ON_OBJECT_BE_KILLED, this, &NFCNPCRefreshModule::OnObjectBeKilled ); } } return 0; } int NFCNPCRefreshModule::OnObjectHPEvent( const NFGUID& self, const std::string& strPropertyName, const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar) { if ( newVar.GetInt() <= 0 ) { NFGUID identAttacker = m_pKernelModule->GetPropertyObject( self, NFrame::NPC::LastAttacker()); if (!identAttacker.IsNull()) { m_pEventModule->DoEvent( self, NFED_ON_OBJECT_BE_KILLED, NFCDataList() << identAttacker ); m_pScheduleModule->AddSchedule( self, "OnDeadDestroyHeart", this, &NFCNPCRefreshModule::OnDeadDestroyHeart, 5.0f, 1 ); } } return 0; } int NFCNPCRefreshModule::OnDeadDestroyHeart( const NFGUID& self, const std::string& strHeartBeat, const float fTime, const int nCount) { //and create new object const std::string& strClassName = m_pKernelModule->GetPropertyString( self, NFrame::NPC::ClassName()); const std::string& strSeedID = m_pKernelModule->GetPropertyString( self, NFrame::NPC::SeedID()); const std::string& strConfigID = m_pKernelModule->GetPropertyString( self, NFrame::NPC::ConfigID()); int nSceneID = m_pKernelModule->GetPropertyInt( self, NFrame::NPC::SceneID()); int nGroupID = m_pKernelModule->GetPropertyInt( self, NFrame::NPC::GroupID()); //m_pSceneProcessModule->ClearAll( nSceneID, nGroupID, strSeendID ); float fSeedX = m_pKernelModule->GetPropertyFloat( self, NFrame::NPC::X()); float fSeedY = m_pKernelModule->GetPropertyFloat( self, NFrame::NPC::Y()); float fSeedZ = m_pKernelModule->GetPropertyFloat( self, NFrame::NPC::Z()); m_pKernelModule->DestroyObject( self ); NFCDataList arg; arg << NFrame::NPC::X() << fSeedX; arg << NFrame::NPC::Y() << fSeedY; arg << NFrame::NPC::Z() << fSeedZ; arg << NFrame::NPC::SeedID() << strSeedID; m_pKernelModule->CreateObject( NFGUID(), nSceneID, nGroupID, strClassName, strConfigID, arg ); return 0; } int NFCNPCRefreshModule::OnObjectBeKilled( const NFGUID& self, const NFEventDefine nEventID, const NFIDataList& var ) { if ( var.GetCount() == 1 && var.Type( 0 ) == TDATA_OBJECT ) { NFGUID identKiller = var.Object( 0 ); if ( m_pKernelModule->GetObject( identKiller ) ) { const int nExp = m_pKernelModule->GetPropertyInt( self, NFrame::Player::EXP() ); m_pLevelModule->AddExp( identKiller, nExp); m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, identKiller, "Add Exp for kill monster", nExp); } else { m_pLogModule->LogObject(NFILogModule::NLL_ERROR_NORMAL, identKiller, "There is no object", __FUNCTION__, __LINE__); } } return 0; }<|endoftext|>
<commit_before>// -*- c-basic-offset: 2; related-file-name: "element.h" -*- /* * @(#)$Id$ * * Modified from the Click Element base class by Eddie Kohler * statistics: Robert Morris * P2 version: Timothy Roscoe * * Copyright (c) 1999-2000 Massachusetts Institute of Technology * Copyright (c) 2004 Regents of the University of California * Copyright (c) 2004 Intel Corporation * * 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, subject to the conditions * listed in the Click LICENSE file. These conditions include: you must * preserve this copyright notice, and you cannot mention the copyright * holders in advertising related to the Software without their permission. * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This * notice is a summary of the Click LICENSE file; the license in that file is * legally binding. * * This file is distributed under the terms in the attached INTEL-LICENSE file. * If you do not find these files, copies can be found by writing to: * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, * Berkeley, CA, 94704. Attention: Intel License Inquiry. * * DESCRIPTION: Base class for P2 elements * * Note to P2 hackers: much has been removed from the original Click * class. Much of that may well find its way back in, but for now * let's put stuff back in when we understand why we need it. That * way we'll all develop a better understanding of why Click (and P2) * are the way they are. * * An element may be in one of two states: CONFIGURATION and RUNNING. * During configuration, the element maintains data about its ports * (including personalities, flow codes, etc.) that faciliate with * static analysis of the big picture of the forwarding engine. Since * all those data aare not useful once the element is up and running, we * only keep them during configuration and discard them thereafter. */ #include "element.h" // Some basic element types const char * const Element::PUSH_TO_PULL = "h/l"; const char * const Element::PULL_TO_PUSH = "l/h"; // A basic flow code const char * const Element::COMPLETE_FLOW = "x/x"; int Element::nelements_allocated = 0; int Element::elementCounter = 0; #if P2_STATS >= 2 # define ELEMENT_CTOR_STATS _calls(0), _self_cycles(0), _child_cycles(0), #else # define ELEMENT_CTOR_STATS #endif Element::Element() : ELEMENT_CTOR_STATS _inputs(0), _outputs(0), _ninputs(0), _noutputs(0) { nelements_allocated++; _ID = elementCounter++; } Element::Element(int ninputs, int noutputs) : ELEMENT_CTOR_STATS _inputs(0), _outputs(0), _ninputs(0), _noutputs(0) { set_nports(ninputs, noutputs); nelements_allocated++; _ID = elementCounter++; } Element::~Element() { nelements_allocated--; if (_inputs) delete[] _inputs; if (_outputs) delete[] _outputs; } // INPUTS AND OUTPUTS void Element::set_nports(int new_ninputs, int new_noutputs) { // exit on bad counts, or if already initialized // XXX initialized flag for element if (new_ninputs < 0 || new_noutputs < 0) return; // create new port arrays Port *new_inputs = new Port[new_ninputs]; if (!new_inputs) // out of memory -- return return; Port *new_outputs = new Port[new_noutputs]; if (!new_outputs) { // out of memory -- return delete[] new_inputs; return; } // install information if (_inputs) delete[] _inputs; if (_outputs) delete[] _outputs; _inputs = new_inputs; _outputs = new_outputs; _ninputs = new_ninputs; _noutputs = new_noutputs; } void Element::set_ninputs(int count) { set_nports(count, _noutputs); } void Element::set_noutputs(int count) { set_nports(_ninputs, count); } bool Element::ports_frozen() const { assert(0); // Deal with freezing without port0 return false; } int Element::connect_input(int i, Element *f, int port) { if (i >= 0 && i < ninputs() && _inputs[i].allowed()) { _inputs[i] = Port(this, f, port); return 0; } else return -1; } int Element::connect_output(int o, Element *f, int port) { if (o >= 0 && o < noutputs() && _outputs[o].allowed()) { _outputs[o] = Port(this, f, port); return 0; } else return -1; } // PUSH OR PULL PROCESSING const char * Element::processing() const { return "a/a"; } const char *Element::flow_code() const { return COMPLETE_FLOW; } const char *Element::flags() const { return ""; } #if P2_STATS >= 1 static str read_icounts_handler(Element *f, void *) { strbuf sa; for (int i = 0; i < f->ninputs(); i++) if (f->input(i).allowed() || P2_STATS >= 2) sa << f->input(i).ntuples() << "\n"; else sa << "??\n"; return sa.take_string(); } static str read_ocounts_handler(Element *f, void *) { strbuf sa; for (int i = 0; i < f->noutputs(); i++) if (f->output(i).allowed() || P2_STATS >= 2) sa << f->output(i).ntuples() << "\n"; else sa << "??\n"; return sa.take_string(); } #endif /* P2_STATS >= 1 */ #if P2_STATS >= 2 /* * cycles: * # of calls to this element (push or pull). * cycles spent in this element and elements it pulls or pushes. * cycles spent in the elements this one pulls and pushes. */ static str read_cycles_handler(Element *f, void *) { return(str(f->_calls) + "\n" + str(f->_self_cycles) + "\n" + str(f->_child_cycles) + "\n"); } #endif // RUNNING int Element::push(int port, TupleRef p, cbv cb) { p = simple_action(p); if (p) return output(0).push(p,cb); return 1; } TuplePtr Element::pull(int port, cbv cb) { TuplePtr p = input(0).pull(cb); if (p) p = simple_action(p); return p; } TupleRef Element::simple_action(TupleRef p) { return p; } REMOVABLE_INLINE const Element::Port & Element::input(int i) const { assert(i >= 0 && i < ninputs()); return _inputs[i]; } REMOVABLE_INLINE const Element::Port & Element::output(int o) const { assert(o >= 0 && o < noutputs()); return _outputs[o]; } //////////////////////////////////////////////////////////// // Element::Port REMOVABLE_INLINE int Element::Port::push(TupleRef p, cbv cb) const { // If I am not connected, I shouldn't be pushed. assert(_e); #if P2_STATS >= 1 _tuples++; #endif int returnValue; #if P2_STATS >= 2 _e->input(_port)._tuples++; uint64_t c0 = click_get_cycles(); #endif // P2_STATS >= 2 returnValue = _e->push(_port, p, cb); #if P2_STATS >= 2 uint64_t c1 = click_get_cycles(); uint64_t x = c1 - c0; _e->_calls += 1; _e->_self_cycles += x; _owner->_child_cycles += x; #endif return returnValue; } REMOVABLE_INLINE TuplePtr Element::Port::pull(cbv cb) const { // If I am not connected, I shouldn't be pulled. assert(_e); #if P2_STATS >= 2 _e->output(_port)._tuples++; uint64_t c0 = click_get_cycles(); #endif TuplePtr p = _e->pull(_port, cb); #if P2_STATS >= 2 uint64_t c1 = click_get_cycles(); uint64_t x = c1 - c0; _e->_calls += 1; _e->_self_cycles += x; _owner->_child_cycles += x; #endif #if P2_STATS >= 1 if (p) _tuples++; #endif return p; } /** Construct a detached free port */ REMOVABLE_INLINE Element::Port::Port() : _e(0), _port(NOT_INITIALIZED), _cb(cbv_null) PORT_CTOR_INIT(0) { } /** Construct an attached port */ REMOVABLE_INLINE Element::Port::Port(Element *owner, Element *e, int p) : _e(e), _port(p), _cb(cbv_null) PORT_CTOR_INIT(owner) { (void) owner; } int Element::initialize() { return 0; } bool Element::run_task() { // This should never be run assert(0); return false; } <commit_msg>Inputs and outputs are now locally allocated vectors of references Now references point to allocated reference counted ports<commit_after>// -*- c-basic-offset: 2; related-file-name: "element.h" -*- /* * @(#)$Id$ * * Modified from the Click Element base class by Eddie Kohler * statistics: Robert Morris * P2 version: Timothy Roscoe * * Copyright (c) 1999-2000 Massachusetts Institute of Technology * Copyright (c) 2004 Regents of the University of California * Copyright (c) 2004 Intel Corporation * * 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, subject to the conditions * listed in the Click LICENSE file. These conditions include: you must * preserve this copyright notice, and you cannot mention the copyright * holders in advertising related to the Software without their permission. * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This * notice is a summary of the Click LICENSE file; the license in that file is * legally binding. * * This file is distributed under the terms in the attached INTEL-LICENSE file. * If you do not find these files, copies can be found by writing to: * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, * Berkeley, CA, 94704. Attention: Intel License Inquiry. * * DESCRIPTION: Base class for P2 elements * * Note to P2 hackers: much has been removed from the original Click * class. Much of that may well find its way back in, but for now * let's put stuff back in when we understand why we need it. That * way we'll all develop a better understanding of why Click (and P2) * are the way they are. * * An element may be in one of two states: CONFIGURATION and RUNNING. * During configuration, the element maintains data about its ports * (including personalities, flow codes, etc.) that faciliate with * static analysis of the big picture of the forwarding engine. Since * all those data aare not useful once the element is up and running, we * only keep them during configuration and discard them thereafter. */ #include "element.h" // Some basic element types const char * const Element::PUSH_TO_PULL = "h/l"; const char * const Element::PULL_TO_PUSH = "l/h"; // A basic flow code const char * const Element::COMPLETE_FLOW = "x/x"; int Element::nelements_allocated = 0; int Element::elementCounter = 0; #if P2_STATS >= 2 # define ELEMENT_CTOR_STATS _calls(0), _self_cycles(0), _child_cycles(0), #else # define ELEMENT_CTOR_STATS #endif Element::Element() : ELEMENT_CTOR_STATS _ninputs(0), _noutputs(0) { nelements_allocated++; _ID = elementCounter++; } Element::Element(int ninputs, int noutputs) : ELEMENT_CTOR_STATS _ninputs(0), _noutputs(0) { set_nports(ninputs, noutputs); nelements_allocated++; _ID = elementCounter++; } Element::~Element() { nelements_allocated--; } // INPUTS AND OUTPUTS void Element::set_nports(int new_ninputs, int new_noutputs) { // exit on bad counts, or if already initialized // XXX initialized flag for element if (new_ninputs < 0 || new_noutputs < 0) return; // Enlarge port arrays if necessary _inputs.setsize(new_ninputs); _ninputs = new_ninputs; for (int i = 0; i < new_ninputs; i++) { _inputs[i] = New refcounted< Port >(); } _outputs.setsize(new_noutputs); _noutputs = new_noutputs; for (int i = 0; i < new_noutputs; i++) { _outputs[i] = New refcounted< Port >(); } } void Element::set_ninputs(int count) { set_nports(count, _noutputs); } void Element::set_noutputs(int count) { set_nports(_ninputs, count); } bool Element::ports_frozen() const { assert(0); // Deal with freezing without port0 return false; } int Element::connect_input(int i, Element *f, int port) { if (i >= 0 && i < ninputs() && input(i)->allowed()) { _inputs[i] = New refcounted< Port >(this, f, port); return 0; } else return -1; } int Element::connect_output(int o, Element *f, int port) { if (o >= 0 && o < noutputs() && output(o)->allowed()) { _outputs[o] = New refcounted< Port >(this, f, port); return 0; } else return -1; } // PUSH OR PULL PROCESSING const char * Element::processing() const { return "a/a"; } const char *Element::flow_code() const { return COMPLETE_FLOW; } const char *Element::flags() const { return ""; } #if P2_STATS >= 1 static str read_icounts_handler(Element *f, void *) { strbuf sa; for (int i = 0; i < f->ninputs(); i++) if (f->input(i).allowed() || P2_STATS >= 2) sa << f->input(i).ntuples() << "\n"; else sa << "??\n"; return sa.take_string(); } static str read_ocounts_handler(Element *f, void *) { strbuf sa; for (int i = 0; i < f->noutputs(); i++) if (f->output(i).allowed() || P2_STATS >= 2) sa << f->output(i).ntuples() << "\n"; else sa << "??\n"; return sa.take_string(); } #endif /* P2_STATS >= 1 */ #if P2_STATS >= 2 /* * cycles: * # of calls to this element (push or pull). * cycles spent in this element and elements it pulls or pushes. * cycles spent in the elements this one pulls and pushes. */ static str read_cycles_handler(Element *f, void *) { return(str(f->_calls) + "\n" + str(f->_self_cycles) + "\n" + str(f->_child_cycles) + "\n"); } #endif // RUNNING int Element::push(int port, TupleRef p, cbv cb) { p = simple_action(p); if (p) return output(0)->push(p,cb); return 1; } TuplePtr Element::pull(int port, cbv cb) { TuplePtr p = input(0)->pull(cb); if (p) p = simple_action(p); return p; } TupleRef Element::simple_action(TupleRef p) { return p; } REMOVABLE_INLINE const Element::PortRef Element::input(int i) const { assert(i >= 0 && i < ninputs()); return _inputs[i]; } REMOVABLE_INLINE const Element::PortRef Element::output(int o) const { assert(o >= 0 && o < noutputs()); return _outputs[o]; } //////////////////////////////////////////////////////////// // Element::Port REMOVABLE_INLINE int Element::Port::push(TupleRef p, cbv cb) const { // If I am not connected, I shouldn't be pushed. assert(_e); #if P2_STATS >= 1 _tuples++; #endif int returnValue; #if P2_STATS >= 2 _e->input(_port)._tuples++; uint64_t c0 = click_get_cycles(); #endif // P2_STATS >= 2 returnValue = _e->push(_port, p, cb); #if P2_STATS >= 2 uint64_t c1 = click_get_cycles(); uint64_t x = c1 - c0; _e->_calls += 1; _e->_self_cycles += x; _owner->_child_cycles += x; #endif return returnValue; } REMOVABLE_INLINE TuplePtr Element::Port::pull(cbv cb) const { // If I am not connected, I shouldn't be pulled. assert(_e); #if P2_STATS >= 2 _e->output(_port)._tuples++; uint64_t c0 = click_get_cycles(); #endif TuplePtr p = _e->pull(_port, cb); #if P2_STATS >= 2 uint64_t c1 = click_get_cycles(); uint64_t x = c1 - c0; _e->_calls += 1; _e->_self_cycles += x; _owner->_child_cycles += x; #endif #if P2_STATS >= 1 if (p) _tuples++; #endif return p; } /** Construct a detached free port */ REMOVABLE_INLINE Element::Port::Port() : _e(0), _port(NOT_INITIALIZED), _cb(cbv_null) PORT_CTOR_INIT(0) { } /** Construct an attached port */ REMOVABLE_INLINE Element::Port::Port(Element *owner, Element *e, int p) : _e(e), _port(p), _cb(cbv_null) PORT_CTOR_INIT(owner) { (void) owner; } int Element::initialize() { return 0; } bool Element::run_task() { // This should never be run assert(0); return false; } <|endoftext|>
<commit_before>#include <native/UriTemplate.hpp> #include <native/UriTemplateFormat.hpp> #include <native/UriTemplateValue.hpp> #include <gtest/gtest.h> using namespace native; namespace { void initGlobalFormats() { static bool initiated = false; if(initiated) { return; } initiated = true; UriTemplateFormat::AddGlobalFormat("formatName1", "(?:[A-Z0-9\\-]{2}|[A-Z]{3})"); UriTemplateFormat::AddGlobalFormat("FormatName2", "[0-9]{1,4}[A-Z]?"); UriTemplateFormat::AddGlobalFormat("FormatName3", "[0-9]{2}[A-Z]{3}[0-9]{2}"); UriTemplateFormat::AddGlobalFormat("FormatComplex", "{format1:formatName1}_{number:FormatName2}/{date:FormatName3}"); UriTemplateFormat::AddGlobalFormat("FormatName6", "[A-Z]{3}"); UriTemplateFormat::AddGlobalFormat("FormatName4", "{complex:FormatComplex}/someText/{format5:FormatName6}"); } void checkUriTemplate( const std::string pattern, const std::string matchPattern, const std::string extractionPattern) { EXPECT_NO_THROW(const UriTemplate uriTemplate(pattern)); const std::string matchPatternWithEndAnchor(matchPattern+"$"); const std::string extractionPatternWithEndAnchor(extractionPattern+"$"); const UriTemplate uriTemplate(pattern); EXPECT_STREQ(uriTemplate.getTemplate().c_str(), pattern.c_str()); EXPECT_STREQ(uriTemplate.getPattern().c_str(), matchPatternWithEndAnchor.c_str()); EXPECT_STREQ(uriTemplate.getPattern(false, false).c_str(), matchPattern.c_str()); EXPECT_STREQ(uriTemplate.getPattern(true).c_str(), extractionPatternWithEndAnchor.c_str()); EXPECT_STREQ(uriTemplate.getPattern(true, false).c_str(), extractionPattern.c_str()); } } /* namespace */ TEST(UriTemplateTest, SimpleText) { checkUriTemplate("simpleText", "simpleText", "simpleText"); } TEST(UriTemplateTest, SimpleRegExp) { checkUriTemplate("simpleText[A-Z]+", "simpleText[A-Z]+", "simpleText[A-Z]+"); } TEST(UriTemplateTest, NoneCapturingRegExp) { checkUriTemplate("simpleText(?:[A-Z]+)", "simpleText(?:[A-Z]+)", "simpleText(?:[A-Z]+)"); } TEST(UriTemplateTest, ExceptionOnCapturingRegExp) { EXPECT_ANY_THROW(const UriTemplate uriTemplate("simpleText([A-Z]+)")); } TEST(UriTemplateTest, UriTemplate) { initGlobalFormats(); checkUriTemplate("someText{par1:formatName1}", "someText(?:[A-Z0-9\\-]{2}|[A-Z]{3})", "someText((?:[A-Z0-9\\-]{2}|[A-Z]{3}))"); } TEST(UriTemplateTest, UriTemplate2) { initGlobalFormats(); checkUriTemplate( "someText/{par1:FormatName4}", "someText/(?:[A-Z0-9\\-]{2}|[A-Z]{3})_[0-9]{1,4}[A-Z]?/[0-9]{2}[A-Z]{3}[0-9]{2}/someText/[A-Z]{3}", "someText/((((?:[A-Z0-9\\-]{2}|[A-Z]{3}))_([0-9]{1,4}[A-Z]?)/([0-9]{2}[A-Z]{3}[0-9]{2}))/someText/([A-Z]{3}))"); } TEST(UriTemplateTest, NoFormatNames) { initGlobalFormats(); const UriTemplate uriTemplate("someText"); EXPECT_EQ(int(uriTemplate.getFormatNames().size()), 0); UriTemplateValue extractedValues; EXPECT_NO_THROW(uriTemplate.extract(extractedValues, "someText")); EXPECT_EQ(int(extractedValues.size()), 0); } TEST(UriTemplateTest, ExtractedValueSimple) { initGlobalFormats(); const UriTemplate uriTemplate("someText/{par1:formatName1}"); EXPECT_EQ(int(uriTemplate.getFormatNames().size()), 1); UriTemplateValue extractedValues; EXPECT_EQ(uriTemplate.extract(extractedValues, "someText/AB"), true); EXPECT_EQ(int(extractedValues.size()), 1); EXPECT_STREQ(extractedValues["par1"].getString().c_str(), "AB"); EXPECT_EQ(int(extractedValues["par1"].size()), 0); } TEST(UriTemplateTest, ExtractNotMatchIfExistsUnmatchedPreffix) { initGlobalFormats(); const UriTemplate uriTemplate("someText/{par1:formatName1}"); EXPECT_EQ(int(uriTemplate.getFormatNames().size()), 1); UriTemplateValue extractedValues; EXPECT_EQ(uriTemplate.extract(extractedValues, "1someText/AB"), false); } TEST(UriTemplateTest, ExtractNotMatchIfExistsUnmatchedSuffix) { initGlobalFormats(); const UriTemplate uriTemplate("someText/{par1:formatName1}"); EXPECT_EQ(int(uriTemplate.getFormatNames().size()), 1); UriTemplateValue extractedValues; EXPECT_EQ(uriTemplate.extract(extractedValues, "someText/AB2"), false); } TEST(UriTemplateTest, ExceptionOnDuplicateParameterName) { initGlobalFormats(); EXPECT_ANY_THROW(const UriTemplate uriTemplate("someText/{par1:formatName1}/{par1:FormatComplex}")); } TEST(UriTemplateTest, ExtractedValuesComplex) { initGlobalFormats(); const UriTemplate uriTemplate("someText/{someText:FormatName4}/longUri/{format1:formatName1}"); EXPECT_EQ(int(uriTemplate.getFormatNames().size()), 2); UriTemplateValue extractedValues; EXPECT_EQ(uriTemplate.extract(extractedValues, "someText/AC_1234/01JAN15/someText/ABC/longUri/AB"), true); EXPECT_EQ(int(extractedValues.size()), 2); EXPECT_STREQ(extractedValues["someText"].getString().c_str(), "AC_1234/01JAN15/someText/ABC"); EXPECT_EQ(int(extractedValues["someText"].size()), 2); EXPECT_STREQ(extractedValues["someText"]["complex"].getString().c_str(), "AC_1234/01JAN15"); EXPECT_EQ(int(extractedValues["someText"]["complex"].size()), 3); EXPECT_STREQ(extractedValues["someText"]["complex"]["format1"].getString().c_str(), "AC"); EXPECT_STREQ(extractedValues["someText"]["complex"]["number"].getString().c_str(), "1234"); EXPECT_STREQ(extractedValues["someText"]["complex"]["date"].getString().c_str(), "01JAN15"); EXPECT_STREQ(extractedValues["someText"]["format5"].getString().c_str(), "ABC"); EXPECT_EQ(int(extractedValues["someText"]["format5"].size()), 0); EXPECT_STREQ(extractedValues["format1"].getString().c_str(), "AB"); EXPECT_EQ(int(extractedValues["format1"].size()), 0); } <commit_msg>uriTemplate: more tests<commit_after>#include <native/UriTemplate.hpp> #include <native/UriTemplateFormat.hpp> #include <native/UriTemplateValue.hpp> #include <gtest/gtest.h> using namespace native; namespace { void initGlobalFormats() { static bool initiated = false; if(initiated) { return; } initiated = true; UriTemplateFormat::AddGlobalFormat("formatName1", "(?:[A-Z0-9\\-]{2}|[A-Z]{3})"); UriTemplateFormat::AddGlobalFormat("FormatName2", "[0-9]{1,4}[A-Z]?"); UriTemplateFormat::AddGlobalFormat("FormatName3", "[0-9]{2}[A-Z]{3}[0-9]{2}"); UriTemplateFormat::AddGlobalFormat("FormatComplex", "{format1:formatName1}_{number:FormatName2}/{date:FormatName3}"); UriTemplateFormat::AddGlobalFormat("FormatName6", "[A-Z]{3}"); UriTemplateFormat::AddGlobalFormat("FormatName4", "{complex:FormatComplex}/someText/{format5:FormatName6}"); } void checkUriTemplate( const std::string pattern, const std::string matchPattern, const std::string extractionPattern) { EXPECT_NO_THROW(const UriTemplate uriTemplate(pattern)); const std::string matchPatternWithEndAnchor(matchPattern+"$"); const std::string extractionPatternWithEndAnchor(extractionPattern+"$"); const UriTemplate uriTemplate(pattern); EXPECT_STREQ(uriTemplate.getTemplate().c_str(), pattern.c_str()); EXPECT_STREQ(uriTemplate.getPattern().c_str(), matchPatternWithEndAnchor.c_str()); EXPECT_STREQ(uriTemplate.getPattern(false, false).c_str(), matchPattern.c_str()); EXPECT_STREQ(uriTemplate.getPattern(true).c_str(), extractionPatternWithEndAnchor.c_str()); EXPECT_STREQ(uriTemplate.getPattern(true, false).c_str(), extractionPattern.c_str()); } } /* namespace */ TEST(UriTemplateTest, SimpleText) { checkUriTemplate("simpleText", "simpleText", "simpleText"); } TEST(UriTemplateTest, SimpleRegExp) { checkUriTemplate("simpleText[A-Z]+", "simpleText[A-Z]+", "simpleText[A-Z]+"); } TEST(UriTemplateTest, NoneCapturingRegExp) { checkUriTemplate("simpleText(?:[A-Z]+)", "simpleText(?:[A-Z]+)", "simpleText(?:[A-Z]+)"); } TEST(UriTemplateTest, ExceptionOnCapturingRegExp) { EXPECT_ANY_THROW(const UriTemplate uriTemplate("simpleText([A-Z]+)")); } TEST(UriTemplateTest, UriTemplate) { initGlobalFormats(); checkUriTemplate("someText{par1:formatName1}", "someText(?:[A-Z0-9\\-]{2}|[A-Z]{3})", "someText((?:[A-Z0-9\\-]{2}|[A-Z]{3}))"); } TEST(UriTemplateTest, UriTemplate2) { initGlobalFormats(); checkUriTemplate( "someText/{par1:FormatName4}", "someText/(?:[A-Z0-9\\-]{2}|[A-Z]{3})_[0-9]{1,4}[A-Z]?/[0-9]{2}[A-Z]{3}[0-9]{2}/someText/[A-Z]{3}", "someText/((((?:[A-Z0-9\\-]{2}|[A-Z]{3}))_([0-9]{1,4}[A-Z]?)/([0-9]{2}[A-Z]{3}[0-9]{2}))/someText/([A-Z]{3}))"); } TEST(UriTemplateTest, NoFormatNames) { initGlobalFormats(); const UriTemplate uriTemplate("someText"); EXPECT_EQ(int(uriTemplate.getFormatNames().size()), 0); UriTemplateValue extractedValues; EXPECT_NO_THROW(uriTemplate.extract(extractedValues, "someText")); EXPECT_EQ(int(extractedValues.size()), 0); } TEST(UriTemplateTest, ExtractedValueSimple) { initGlobalFormats(); const UriTemplate uriTemplate("someText/{par1:formatName1}"); EXPECT_EQ(int(uriTemplate.getFormatNames().size()), 1); UriTemplateValue extractedValues; EXPECT_EQ(uriTemplate.extract(extractedValues, "someText/AB"), true); EXPECT_EQ(int(extractedValues.size()), 1); EXPECT_STREQ(extractedValues["par1"].getString().c_str(), "AB"); EXPECT_EQ(int(extractedValues["par1"].size()), 0); } TEST(UriTemplateTest, ExtractNotMatchIfExistsUnmatchedPreffix) { initGlobalFormats(); const UriTemplate uriTemplate("someText/{par1:formatName1}"); EXPECT_EQ(int(uriTemplate.getFormatNames().size()), 1); UriTemplateValue extractedValues; EXPECT_EQ(uriTemplate.extract(extractedValues, "1someText/AB"), false); } TEST(UriTemplateTest, ExtractNotMatchIfExistsUnmatchedSuffix) { initGlobalFormats(); const UriTemplate uriTemplate("someText/{par1:formatName1}"); EXPECT_EQ(int(uriTemplate.getFormatNames().size()), 1); UriTemplateValue extractedValues; EXPECT_EQ(uriTemplate.extract(extractedValues, "someText/AB2"), false); } TEST(UriTemplateTest, ExtractMatchIfExistsUnmatchedSuffixExplicitly) { initGlobalFormats(); const UriTemplate uriTemplate("someText/{par1:formatName1}"); EXPECT_EQ(int(uriTemplate.getFormatNames().size()), 1); UriTemplateValue extractedValues; EXPECT_EQ(uriTemplate.extract(extractedValues, "someText/AB2", false), true); } TEST(UriTemplateTest, ExceptionOnDuplicateParameterName) { initGlobalFormats(); EXPECT_ANY_THROW(const UriTemplate uriTemplate("someText/{par1:formatName1}/{par1:FormatComplex}")); } TEST(UriTemplateTest, ExtractedValuesComplex) { initGlobalFormats(); const UriTemplate uriTemplate("someText/{someText:FormatName4}/longUri/{format1:formatName1}"); EXPECT_EQ(int(uriTemplate.getFormatNames().size()), 2); UriTemplateValue extractedValues; EXPECT_EQ(uriTemplate.extract(extractedValues, "someText/AC_1234/01JAN15/someText/ABC/longUri/AB"), true); EXPECT_EQ(int(extractedValues.size()), 2); EXPECT_STREQ(extractedValues["someText"].getString().c_str(), "AC_1234/01JAN15/someText/ABC"); EXPECT_EQ(int(extractedValues["someText"].size()), 2); EXPECT_STREQ(extractedValues["someText"]["complex"].getString().c_str(), "AC_1234/01JAN15"); EXPECT_EQ(int(extractedValues["someText"]["complex"].size()), 3); EXPECT_STREQ(extractedValues["someText"]["complex"]["format1"].getString().c_str(), "AC"); EXPECT_STREQ(extractedValues["someText"]["complex"]["number"].getString().c_str(), "1234"); EXPECT_STREQ(extractedValues["someText"]["complex"]["date"].getString().c_str(), "01JAN15"); EXPECT_STREQ(extractedValues["someText"]["format5"].getString().c_str(), "ABC"); EXPECT_EQ(int(extractedValues["someText"]["format5"].size()), 0); EXPECT_STREQ(extractedValues["format1"].getString().c_str(), "AB"); EXPECT_EQ(int(extractedValues["format1"].size()), 0); } <|endoftext|>
<commit_before>// Copyright 2013 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 "ui/app_list/app_list_switches.h" #include "base/command_line.h" namespace app_list { namespace switches { // If set, the app info context menu item is not available in the app list UI. const char kDisableAppInfo[] = "disable-app-list-app-info"; // Disables syncing of the app list independent of extensions. const char kDisableSyncAppList[] = "disable-sync-app-list"; // If set, the voice search is disabled in app list UI. const char kDisableVoiceSearch[] = "disable-app-list-voice-search"; // If set, the app list will be centered and wide instead of tall. const char kEnableCenteredAppList[] = "enable-centered-app-list"; // If set, the experimental app list will be used. Implies // --enable-centered-app-list. const char kEnableExperimentalAppList[] = "enable-experimental-app-list"; // Enables syncing of the app list independent of extensions. const char kEnableSyncAppList[] = "enable-sync-app-list"; bool IsAppListSyncEnabled() { #if defined(TOOLKIT_VIEWS) return !CommandLine::ForCurrentProcess()->HasSwitch(kDisableSyncAppList); #else return CommandLine::ForCurrentProcess()->HasSwitch(kEnableSyncAppList); #endif } bool IsFolderUIEnabled() { #if !defined(TOOLKIT_VIEWS) return false; // Folder UI not implemented for Cocoa. #endif // Folder UI is available only when AppList sync is enabled, and should // not be disabled separately. return IsAppListSyncEnabled(); } bool IsVoiceSearchEnabled() { // Speech recognition in AppList is only for ChromeOS right now. #if defined(OS_CHROMEOS) return !CommandLine::ForCurrentProcess()->HasSwitch(kDisableVoiceSearch); #else return false; #endif } bool IsAppInfoEnabled() { return !CommandLine::ForCurrentProcess()->HasSwitch(kDisableAppInfo); } bool IsExperimentalAppListEnabled() { return CommandLine::ForCurrentProcess()->HasSwitch( kEnableExperimentalAppList); } bool IsCenteredAppListEnabled() { return CommandLine::ForCurrentProcess()->HasSwitch(kEnableCenteredAppList) || IsExperimentalAppListEnabled(); } } // namespace switches } // namespace app_list <commit_msg>Only allow ShowAppInfoFlow on Ash and Views platforms<commit_after>// Copyright 2013 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 "ui/app_list/app_list_switches.h" #include "base/command_line.h" namespace app_list { namespace switches { // If set, the app info context menu item is not available in the app list UI. const char kDisableAppInfo[] = "disable-app-list-app-info"; // Disables syncing of the app list independent of extensions. const char kDisableSyncAppList[] = "disable-sync-app-list"; // If set, the voice search is disabled in app list UI. const char kDisableVoiceSearch[] = "disable-app-list-voice-search"; // If set, the app list will be centered and wide instead of tall. const char kEnableCenteredAppList[] = "enable-centered-app-list"; // If set, the experimental app list will be used. Implies // --enable-centered-app-list. const char kEnableExperimentalAppList[] = "enable-experimental-app-list"; // Enables syncing of the app list independent of extensions. const char kEnableSyncAppList[] = "enable-sync-app-list"; bool IsAppListSyncEnabled() { #if defined(TOOLKIT_VIEWS) return !CommandLine::ForCurrentProcess()->HasSwitch(kDisableSyncAppList); #else return CommandLine::ForCurrentProcess()->HasSwitch(kEnableSyncAppList); #endif } bool IsFolderUIEnabled() { #if !defined(TOOLKIT_VIEWS) return false; // Folder UI not implemented for Cocoa. #endif // Folder UI is available only when AppList sync is enabled, and should // not be disabled separately. return IsAppListSyncEnabled(); } bool IsVoiceSearchEnabled() { // Speech recognition in AppList is only for ChromeOS right now. #if defined(OS_CHROMEOS) return !CommandLine::ForCurrentProcess()->HasSwitch(kDisableVoiceSearch); #else return false; #endif } bool IsAppInfoEnabled() { #if defined(TOOLKIT_VIEWS) return !CommandLine::ForCurrentProcess()->HasSwitch(kDisableAppInfo); #else return false; #endif } bool IsExperimentalAppListEnabled() { return CommandLine::ForCurrentProcess()->HasSwitch( kEnableExperimentalAppList); } bool IsCenteredAppListEnabled() { return CommandLine::ForCurrentProcess()->HasSwitch(kEnableCenteredAppList) || IsExperimentalAppListEnabled(); } } // namespace switches } // namespace app_list <|endoftext|>
<commit_before>#include "task/task.hh" task::Task::Task(unsigned task_id, int16_t fun_id, std::vector<int64_t>& params) : id(task_id) , is_complete(false) , fun_id(fun_id) , params(params) {} <commit_msg>Adding task.cc<commit_after>#include "task.hh" task::Task::Task(unsigned task_id, int16_t fun_id, std::vector<int64_t>& params) : id(task_id) , is_complete(false) , fun_id(fun_id) , params(params) {} <|endoftext|>
<commit_before>// coding: utf-8 // ---------------------------------------------------------------------------- /* * Copyright (c) 2015, Christian Menard * 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 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 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 XPCC__PCA9685_HPP #define XPCC__PCA9685_HPP #include <xpcc/architecture/interface/i2c_device.hpp> namespace xpcc { namespace pca9685 { enum Register { REG_MODE1 = 0x00, REG_MODE2 = 0x01, REG_SUBADR1 = 0x02, REG_SUBADR2 = 0x03, REG_SUBADR3 = 0x04, REG_ALLCALLADR = 0x05, REG_LED0_ON_L = 0x06, REG_LED0_ON_H = 0x07, REG_LED0_OFF_L = 0x08, REG_LED0_OFF_H = 0x09, REG_LED1_ON_L = 0x0a, REG_LED1_ON_H = 0x0b, REG_LED1_OFF_L = 0x0c, REG_LED1_OFF_H = 0x0d, REG_LED2_ON_L = 0x0e, REG_LED2_ON_H = 0x0f, REG_LED2_OFF_L = 0x10, REG_LED2_OFF_H = 0x11, REG_LED3_ON_L = 0x12, REG_LED3_ON_H = 0x13, REG_LED3_OFF_L = 0x14, REG_LED3_OFF_H = 0x15, REG_LED4_ON_L = 0x16, REG_LED4_ON_H = 0x17, REG_LED4_OFF_L = 0x18, REG_LED4_OFF_H = 0x19, REG_LED5_ON_L = 0x1a, REG_LED5_ON_H = 0x1b, REG_LED5_OFF_L = 0x1c, REG_LED5_OFF_H = 0x1d, REG_LED6_ON_L = 0x1e, REG_LED6_ON_H = 0x1f, REG_LED6_OFF_L = 0x20, REG_LED6_OFF_H = 0x21, REG_LED7_ON_L = 0x22, REG_LED7_ON_H = 0x23, REG_LED7_OFF_L = 0x24, REG_LED7_OFF_H = 0x25, REG_LED8_ON_L = 0x26, REG_LED8_ON_H = 0x27, REG_LED8_OFF_L = 0x28, REG_LED8_OFF_H = 0x29, REG_LED9_ON_L = 0x2a, REG_LED9_ON_H = 0x2b, REG_LED9_OFF_L = 0x2c, REG_LED9_OFF_H = 0x2d, REG_LED10_ON_L = 0x2e, REG_LED10_ON_H = 0x2f, REG_LED10_OFF_L = 0x30, REG_LED10_OFF_H = 0x31, REG_LED11_ON_L = 0x32, REG_LED11_ON_H = 0x33, REG_LED11_OFF_L = 0x34, REG_LED11_OFF_H = 0x35, REG_LED12_ON_L = 0x36, REG_LED12_ON_H = 0x37, REG_LED12_OFF_L = 0x38, REG_LED12_OFF_H = 0x39, REG_LED13_ON_L = 0x3a, REG_LED13_ON_H = 0x3b, REG_LED13_OFF_L = 0x3c, REG_LED13_OFF_H = 0x3d, REG_LED14_ON_L = 0x3e, REG_LED14_ON_H = 0x3f, REG_LED14_OFF_L = 0x40, REG_LED14_OFF_H = 0x41, REG_LED15_ON_L = 0x42, REG_LED15_ON_H = 0x43, REG_LED15_OFF_L = 0x44, REG_LED15_OFF_H = 0x45, /* * 0x46 - 0xf9 reserved for future use */ REG_ALL_LED_ON_L = 0xfa, REG_ALL_LED_ON_H = 0xfb, REG_ALL_LED_OFF_L = 0xfc, REG_ALL_LED_OFF_H = 0xfd, REG_PRE_SCALE = 0xfe, REG_TestMode = 0xfe, }; enum Mode1 { MODE1_RESTART = 0x80, MODE1_EXTCLK = 0x40, MODE1_AI = 0x20, MODE1_SLEEP = 0x10, MODE1_SUB1 = 0x08, MODE1_SUB2 = 0x04, MODE1_SUB3 = 0x02, MODE1_ALLCALL = 0x01, }; enum Mode2 { MODE2_INVRT = 0x10, MODE2_OCH = 0x08, MODE2_OUTDRV = 0x04, MODE2_OUTNE1 = 0x02, MODE2_OUTNE0 = 0x01, }; } /** * PCA9685 16-channel, 12-bit PWM LED controller, I2C-bus * * This class allows for basic (and for most use cases sufficient) control * of a PCA9685. It implements initialization (setting of MODE1 and MODE2 * registers), writing values for single channels, and writing a value for * all channels. * * This driver has the following limitations: * - no register read access * - no arbitrary register write access * - no address reconfiguration * - registers LED*_ON_* are fixed at 0 * * @tparam I2cMaster I2C interface * * @author Christian Menard * @ingroup driver_pwm */ template<typename I2cMaster> class Pca9685 : public xpcc::I2cDevice< I2cMaster, 1, I2cWriteAdapter > { uint8_t buffer[3]; public: /** * Constructor. * * @param address I2C address */ Pca9685(uint8_t address); /** * Initialize the device. * * Note: The bit AI (Auto Increment) in MODE2 register will always be * set as it is essential for correct operation of this driver. * * @param mode1 value to be written to MODE1 register * @param mode2 value to be written to MODE2 register */ xpcc::co::Result<bool> initialize(uint8_t mode1 = 0, uint8_t mode2 = 0); /** * Set the 12-bit PWM value of a single channel. * * Checks if the specified channel is valid (return false otherwise) * and masks out the upper 4 bits of value to ensure that always a * 12-bit value is written. * * @param channel one of the 16 channels (0-15) * @param value 12-bit PWM value to be written */ xpcc::co::Result<bool> setChannel(uint8_t channel, uint16_t value); /** * Set all 16 12-bit PWM channels to the same value. * * The upper 4 bits of value are masked out to ensure that always a * 12-bit value is written. * * @param value 12-bit PWM value to be written */ xpcc::co::Result<bool> setAllChannels(uint16_t value); }; } #include "pca9685_impl.hpp" #endif // XPCC__PCA9685_HPP <commit_msg>Driver: PCA9685: Indentation as per coding convention.<commit_after>// coding: utf-8 // ---------------------------------------------------------------------------- /* * Copyright (c) 2015, Christian Menard * 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 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 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 XPCC__PCA9685_HPP #define XPCC__PCA9685_HPP #include <xpcc/architecture/interface/i2c_device.hpp> namespace xpcc { namespace pca9685 { enum Register { REG_MODE1 = 0x00, REG_MODE2 = 0x01, REG_SUBADR1 = 0x02, REG_SUBADR2 = 0x03, REG_SUBADR3 = 0x04, REG_ALLCALLADR = 0x05, REG_LED0_ON_L = 0x06, REG_LED0_ON_H = 0x07, REG_LED0_OFF_L = 0x08, REG_LED0_OFF_H = 0x09, REG_LED1_ON_L = 0x0a, REG_LED1_ON_H = 0x0b, REG_LED1_OFF_L = 0x0c, REG_LED1_OFF_H = 0x0d, REG_LED2_ON_L = 0x0e, REG_LED2_ON_H = 0x0f, REG_LED2_OFF_L = 0x10, REG_LED2_OFF_H = 0x11, REG_LED3_ON_L = 0x12, REG_LED3_ON_H = 0x13, REG_LED3_OFF_L = 0x14, REG_LED3_OFF_H = 0x15, REG_LED4_ON_L = 0x16, REG_LED4_ON_H = 0x17, REG_LED4_OFF_L = 0x18, REG_LED4_OFF_H = 0x19, REG_LED5_ON_L = 0x1a, REG_LED5_ON_H = 0x1b, REG_LED5_OFF_L = 0x1c, REG_LED5_OFF_H = 0x1d, REG_LED6_ON_L = 0x1e, REG_LED6_ON_H = 0x1f, REG_LED6_OFF_L = 0x20, REG_LED6_OFF_H = 0x21, REG_LED7_ON_L = 0x22, REG_LED7_ON_H = 0x23, REG_LED7_OFF_L = 0x24, REG_LED7_OFF_H = 0x25, REG_LED8_ON_L = 0x26, REG_LED8_ON_H = 0x27, REG_LED8_OFF_L = 0x28, REG_LED8_OFF_H = 0x29, REG_LED9_ON_L = 0x2a, REG_LED9_ON_H = 0x2b, REG_LED9_OFF_L = 0x2c, REG_LED9_OFF_H = 0x2d, REG_LED10_ON_L = 0x2e, REG_LED10_ON_H = 0x2f, REG_LED10_OFF_L = 0x30, REG_LED10_OFF_H = 0x31, REG_LED11_ON_L = 0x32, REG_LED11_ON_H = 0x33, REG_LED11_OFF_L = 0x34, REG_LED11_OFF_H = 0x35, REG_LED12_ON_L = 0x36, REG_LED12_ON_H = 0x37, REG_LED12_OFF_L = 0x38, REG_LED12_OFF_H = 0x39, REG_LED13_ON_L = 0x3a, REG_LED13_ON_H = 0x3b, REG_LED13_OFF_L = 0x3c, REG_LED13_OFF_H = 0x3d, REG_LED14_ON_L = 0x3e, REG_LED14_ON_H = 0x3f, REG_LED14_OFF_L = 0x40, REG_LED14_OFF_H = 0x41, REG_LED15_ON_L = 0x42, REG_LED15_ON_H = 0x43, REG_LED15_OFF_L = 0x44, REG_LED15_OFF_H = 0x45, /* * 0x46 - 0xf9 reserved for future use */ REG_ALL_LED_ON_L = 0xfa, REG_ALL_LED_ON_H = 0xfb, REG_ALL_LED_OFF_L = 0xfc, REG_ALL_LED_OFF_H = 0xfd, REG_PRE_SCALE = 0xfe, REG_TestMode = 0xfe, }; enum Mode1 { MODE1_RESTART = 0x80, MODE1_EXTCLK = 0x40, MODE1_AI = 0x20, MODE1_SLEEP = 0x10, MODE1_SUB1 = 0x08, MODE1_SUB2 = 0x04, MODE1_SUB3 = 0x02, MODE1_ALLCALL = 0x01, }; enum Mode2 { MODE2_INVRT = 0x10, MODE2_OCH = 0x08, MODE2_OUTDRV = 0x04, MODE2_OUTNE1 = 0x02, MODE2_OUTNE0 = 0x01, }; } // namespace pca9685 /** * PCA9685 16-channel, 12-bit PWM LED controller, I2C-bus * * This class allows for basic (and for most use cases sufficient) control * of a PCA9685. It implements initialization (setting of MODE1 and MODE2 * registers), writing values for single channels, and writing a value for * all channels. * * This driver has the following limitations: * - no register read access * - no arbitrary register write access * - no address reconfiguration * - registers LED*_ON_* are fixed at 0 * * @tparam I2cMaster I2C interface * * @author Christian Menard * @ingroup driver_pwm */ template<typename I2cMaster> class Pca9685 : public xpcc::I2cDevice< I2cMaster, 1, I2cWriteAdapter > { uint8_t buffer[3]; public: /** * Constructor. * * @param address I2C address */ Pca9685(uint8_t address); /** * Initialize the device. * * Note: The bit AI (Auto Increment) in MODE2 register will always be * set as it is essential for correct operation of this driver. * * @param mode1 value to be written to MODE1 register * @param mode2 value to be written to MODE2 register */ xpcc::co::Result<bool> initialize(uint8_t mode1 = 0, uint8_t mode2 = 0); /** * Set the 12-bit PWM value of a single channel. * * Checks if the specified channel is valid (return false otherwise) * and masks out the upper 4 bits of value to ensure that always a * 12-bit value is written. * * @param channel one of the 16 channels (0-15) * @param value 12-bit PWM value to be written */ xpcc::co::Result<bool> setChannel(uint8_t channel, uint16_t value); /** * Set all 16 12-bit PWM channels to the same value. * * The upper 4 bits of value are masked out to ensure that always a * 12-bit value is written. * * @param value 12-bit PWM value to be written */ xpcc::co::Result<bool> setAllChannels(uint16_t value); }; } // namespace xpcc #include "pca9685_impl.hpp" #endif // XPCC__PCA9685_HPP <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2015 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include "test.hpp" #include "caf/all.hpp" using namespace caf; namespace { std::atomic<size_t> s_ctors; std::atomic<size_t> s_dtors; } // namespace <anonymous> class worker : public event_based_actor { public: worker(); ~worker(); behavior make_behavior() override; }; worker::worker() { ++s_ctors; } worker::~worker() { ++s_dtors; } behavior worker::make_behavior() { return { [](int x, int y) { return x + y; } }; } actor spawn_worker() { return spawn<worker>(); } void test_actor_pool() { scoped_actor self; auto w = actor_pool::make(5, spawn_worker, actor_pool::round_robin{}); self->monitor(w); self->send(w, sys_atom::value, put_atom::value, spawn_worker()); std::vector<actor_addr> workers; for (int i = 0; i < 6; ++i) { self->sync_send(w, i, i).await( [&](int res) { CAF_CHECK_EQUAL(res, i + i); auto sender = self->current_sender(); self->monitor(sender); workers.push_back(sender); } ); } CAF_CHECK(workers.size() == 6); CAF_CHECK(std::unique(workers.begin(), workers.end()) == workers.end()); auto is_invalid = [](const actor_addr& addr) { return addr == invalid_actor_addr; }; CAF_CHECK(std::none_of(workers.begin(), workers.end(), is_invalid)); self->sync_send(w, sys_atom::value, get_atom::value).await( [&](std::vector<actor>& ws) { std::sort(workers.begin(), workers.end()); std::sort(ws.begin(), ws.end()); CAF_CHECK(workers.size() == ws.size() && std::equal(workers.begin(), workers.end(), ws.begin())); } ); anon_send_exit(workers.back(), exit_reason::user_shutdown); self->receive( after(std::chrono::milliseconds(25)) >> [] { // wait some time to give the pool time to remove the failed worker } ); self->receive( [&](const down_msg& dm) { CAF_CHECK(dm.source == workers.back()); workers.pop_back(); // check whether actor pool removed failed worker self->sync_send(w, sys_atom::value, get_atom::value).await( [&](std::vector<actor>& ws) { std::sort(ws.begin(), ws.end()); CAF_CHECK(workers.size() == ws.size() && std::equal(workers.begin(), workers.end(), ws.begin())); } ); }, after(std::chrono::milliseconds(250)) >> [] { CAF_PRINTERR("didn't receive a down message"); } ); CAF_CHECKPOINT(); self->send_exit(w, exit_reason::user_shutdown); for (int i = 0; i < 6; ++i) { self->receive( [&](const down_msg& dm) { auto last = workers.end(); auto src = dm.source; CAF_CHECK(src != invalid_actor_addr); auto pos = std::find(workers.begin(), last, src); CAF_CHECK(pos != last || src == w); if (pos != last) { workers.erase(pos); } }, after(std::chrono::milliseconds(250)) >> [] { CAF_PRINTERR("didn't receive a down message"); } ); } } void test_broadcast_actor_pool() { scoped_actor self; auto spawn5 = []() { return actor_pool::make(5, spawn_worker, actor_pool::broadcast{}); }; auto w = actor_pool::make(5, spawn5, actor_pool::broadcast{}); self->send(w, 1, 2); std::vector<int> results; int i = 0; self->receive_for(i, 25)( [&](int res) { results.push_back(res); }, after(std::chrono::milliseconds(250)) >> [] { CAF_PRINTERR("didn't receive a result"); } ); CAF_CHECK_EQUAL(results.size(), 25); CAF_CHECK(std::all_of(results.begin(), results.end(), [](int res) { return res == 3; })); self->send_exit(w, exit_reason::user_shutdown); self->await_all_other_actors_done(); } void test_random_actor_pool() { scoped_actor self; auto w = actor_pool::make(5, spawn_worker, actor_pool::random{}); for (int i = 0; i < 5; ++i) { self->sync_send(w, 1, 2).await( [&](int res) { CAF_CHECK_EQUAL(res, 3); }, after(std::chrono::milliseconds(250)) >> [] { CAF_PRINTERR("didn't receive a down message"); } ); } self->send_exit(w, exit_reason::user_shutdown); self->await_all_other_actors_done(); } void test_split_join_actor_pool() { CAF_CHECKPOINT(); auto spawn_split_worker = [] { return spawn<lazy_init>([]() -> behavior { return { [](size_t pos, std::vector<int> xs) { return xs[pos]; } }; }); }; auto split_fun = [](std::vector<std::pair<actor, message>>& xs, message& y) { for (size_t i = 0; i < xs.size(); ++i) { xs[i].second = make_message(i) + y; } }; auto join_fun = [](int& res, message& msg) { msg.apply([&](int x) { res += x; }); }; scoped_actor self; auto w = actor_pool::make(5, spawn_split_worker, actor_pool::split_join<int>(join_fun, split_fun)); self->sync_send(w, std::vector<int>{1, 2, 3, 4, 5}).await( [&](int res) { CAF_CHECK_EQUAL(res, 15); } ); self->sync_send(w, std::vector<int>{6, 7, 8, 9, 10}).await( [&](int res) { CAF_CHECK_EQUAL(res, 40); } ); self->send_exit(w, exit_reason::user_shutdown); self->await_all_other_actors_done(); } int main() { CAF_TEST(test_actor_pool); test_actor_pool(); test_broadcast_actor_pool(); test_random_actor_pool(); test_split_join_actor_pool(); await_all_actors_done(); shutdown(); CAF_CHECK_EQUAL(s_dtors.load(), s_ctors.load()); return CAF_TEST_RESULT(); } <commit_msg>Properly announce types in actor pool test<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2015 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include "test.hpp" #include "caf/all.hpp" using namespace caf; namespace { std::atomic<size_t> s_ctors; std::atomic<size_t> s_dtors; } // namespace <anonymous> class worker : public event_based_actor { public: worker(); ~worker(); behavior make_behavior() override; }; worker::worker() { ++s_ctors; } worker::~worker() { ++s_dtors; } behavior worker::make_behavior() { return { [](int x, int y) { return x + y; } }; } actor spawn_worker() { return spawn<worker>(); } void test_actor_pool() { scoped_actor self; auto w = actor_pool::make(5, spawn_worker, actor_pool::round_robin{}); self->monitor(w); self->send(w, sys_atom::value, put_atom::value, spawn_worker()); std::vector<actor_addr> workers; for (int i = 0; i < 6; ++i) { self->sync_send(w, i, i).await( [&](int res) { CAF_CHECK_EQUAL(res, i + i); auto sender = self->current_sender(); self->monitor(sender); workers.push_back(sender); } ); } CAF_CHECK(workers.size() == 6); CAF_CHECK(std::unique(workers.begin(), workers.end()) == workers.end()); auto is_invalid = [](const actor_addr& addr) { return addr == invalid_actor_addr; }; CAF_CHECK(std::none_of(workers.begin(), workers.end(), is_invalid)); self->sync_send(w, sys_atom::value, get_atom::value).await( [&](std::vector<actor>& ws) { std::sort(workers.begin(), workers.end()); std::sort(ws.begin(), ws.end()); CAF_CHECK(workers.size() == ws.size() && std::equal(workers.begin(), workers.end(), ws.begin())); } ); anon_send_exit(workers.back(), exit_reason::user_shutdown); self->receive( after(std::chrono::milliseconds(25)) >> [] { // wait some time to give the pool time to remove the failed worker } ); self->receive( [&](const down_msg& dm) { CAF_CHECK(dm.source == workers.back()); workers.pop_back(); // check whether actor pool removed failed worker self->sync_send(w, sys_atom::value, get_atom::value).await( [&](std::vector<actor>& ws) { std::sort(ws.begin(), ws.end()); CAF_CHECK(workers.size() == ws.size() && std::equal(workers.begin(), workers.end(), ws.begin())); } ); }, after(std::chrono::milliseconds(250)) >> [] { CAF_PRINTERR("didn't receive a down message"); } ); CAF_CHECKPOINT(); self->send_exit(w, exit_reason::user_shutdown); for (int i = 0; i < 6; ++i) { self->receive( [&](const down_msg& dm) { auto last = workers.end(); auto src = dm.source; CAF_CHECK(src != invalid_actor_addr); auto pos = std::find(workers.begin(), last, src); CAF_CHECK(pos != last || src == w); if (pos != last) { workers.erase(pos); } }, after(std::chrono::milliseconds(250)) >> [] { CAF_PRINTERR("didn't receive a down message"); } ); } } void test_broadcast_actor_pool() { scoped_actor self; auto spawn5 = []() { return actor_pool::make(5, spawn_worker, actor_pool::broadcast{}); }; auto w = actor_pool::make(5, spawn5, actor_pool::broadcast{}); self->send(w, 1, 2); std::vector<int> results; int i = 0; self->receive_for(i, 25)( [&](int res) { results.push_back(res); }, after(std::chrono::milliseconds(250)) >> [] { CAF_PRINTERR("didn't receive a result"); } ); CAF_CHECK_EQUAL(results.size(), 25); CAF_CHECK(std::all_of(results.begin(), results.end(), [](int res) { return res == 3; })); self->send_exit(w, exit_reason::user_shutdown); self->await_all_other_actors_done(); } void test_random_actor_pool() { scoped_actor self; auto w = actor_pool::make(5, spawn_worker, actor_pool::random{}); for (int i = 0; i < 5; ++i) { self->sync_send(w, 1, 2).await( [&](int res) { CAF_CHECK_EQUAL(res, 3); }, after(std::chrono::milliseconds(250)) >> [] { CAF_PRINTERR("didn't receive a down message"); } ); } self->send_exit(w, exit_reason::user_shutdown); self->await_all_other_actors_done(); } void test_split_join_actor_pool() { CAF_CHECKPOINT(); auto spawn_split_worker = [] { return spawn<lazy_init>([]() -> behavior { return { [](size_t pos, std::vector<int> xs) { return xs[pos]; } }; }); }; auto split_fun = [](std::vector<std::pair<actor, message>>& xs, message& y) { for (size_t i = 0; i < xs.size(); ++i) { xs[i].second = make_message(i) + y; } }; auto join_fun = [](int& res, message& msg) { msg.apply([&](int x) { res += x; }); }; scoped_actor self; auto w = actor_pool::make(5, spawn_split_worker, actor_pool::split_join<int>(join_fun, split_fun)); self->sync_send(w, std::vector<int>{1, 2, 3, 4, 5}).await( [&](int res) { CAF_CHECK_EQUAL(res, 15); } ); self->sync_send(w, std::vector<int>{6, 7, 8, 9, 10}).await( [&](int res) { CAF_CHECK_EQUAL(res, 40); } ); self->send_exit(w, exit_reason::user_shutdown); self->await_all_other_actors_done(); } int main() { announce<std::vector<int>>("vector<int>"); CAF_TEST(test_actor_pool); test_actor_pool(); test_broadcast_actor_pool(); test_random_actor_pool(); test_split_join_actor_pool(); await_all_actors_done(); shutdown(); CAF_CHECK_EQUAL(s_dtors.load(), s_ctors.load()); return CAF_TEST_RESULT(); } <|endoftext|>
<commit_before>#include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkImageRegionIterator.h" #include "itkRGBPixel.h" #include "itkRGBAPixel.h" #include "itkRedColormapFunctor.h" #include "itkGreenColormapFunctor.h" #include "itkBlueColormapFunctor.h" #include "itkGreyColormapFunctor.h" #include "itkHotColormapFunctor.h" #include "itkCoolColormapFunctor.h" #include "itkSpringColormapFunctor.h" #include "itkSummerColormapFunctor.h" #include "itkAutumnColormapFunctor.h" #include "itkWinterColormapFunctor.h" #include "itkCopperColormapFunctor.h" #include "itkHSVColormapFunctor.h" #include "itkJetColormapFunctor.h" #include "itkCustomColormapFunctor.h" #include "itkOverUnderColormapFunctor.h" #include "itkScalarToRGBColormapImageFilter.h" #include <fstream.h> #include <sstream> #include <string> template <unsigned int ImageDimension> int ConvertScalarImageToRGB( int argc, char *argv[] ) { typedef unsigned int PixelType; // typedef itk::RGBPixel<unsigned char> RGBPixelType; typedef itk::RGBAPixel<unsigned char> RGBPixelType; typedef float RealType; typedef itk::Image<PixelType, ImageDimension> ImageType; typedef itk::Image<float, ImageDimension> RealImageType; typedef itk::Image<RGBPixelType, ImageDimension> RGBImageType; typedef itk::ImageFileReader<RealImageType> ReaderType; typename ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[2] ); reader->Update(); typedef itk::Image<unsigned char, ImageDimension> MaskImageType; typename MaskImageType::Pointer maskImage = MaskImageType::New(); typedef itk::ImageFileReader<MaskImageType> MaskReaderType; typename MaskReaderType::Pointer maskreader = MaskReaderType::New(); maskreader->SetFileName( argv[4] ); try { maskreader->Update(); maskImage = maskreader->GetOutput(); } catch(...) { maskImage = NULL; }; std::string colormapString( argv[5] ); typedef itk::ScalarToRGBColormapImageFilter<RealImageType, RGBImageType> RGBFilterType; typename RGBFilterType::Pointer rgbfilter = RGBFilterType::New(); rgbfilter->SetInput( reader->GetOutput() ); if ( colormapString == "red" ) { rgbfilter->SetColormap( RGBFilterType::Red ); } else if ( colormapString == "green" ) { rgbfilter->SetColormap( RGBFilterType::Green ); } else if ( colormapString == "blue" ) { rgbfilter->SetColormap( RGBFilterType::Blue ); } else if ( colormapString == "grey" ) { rgbfilter->SetColormap( RGBFilterType::Grey ); } else if ( colormapString == "cool" ) { rgbfilter->SetColormap( RGBFilterType::Cool ); } else if ( colormapString == "hot" ) { rgbfilter->SetColormap( RGBFilterType::Hot ); } else if ( colormapString == "spring" ) { rgbfilter->SetColormap( RGBFilterType::Spring ); } else if ( colormapString == "autumn" ) { rgbfilter->SetColormap( RGBFilterType::Autumn ); } else if ( colormapString == "winter" ) { rgbfilter->SetColormap( RGBFilterType::Winter ); } else if ( colormapString == "copper" ) { rgbfilter->SetColormap( RGBFilterType::Copper ); } else if ( colormapString == "summer" ) { rgbfilter->SetColormap( RGBFilterType::Summer ); } else if ( colormapString == "jet" ) { // rgbfilter->SetColormap( RGBFilterType::Jet ); typedef itk::Functor::JetColormapFunctor<typename RealImageType::PixelType, typename RGBImageType::PixelType> ColormapType; typename ColormapType::Pointer colormap = ColormapType::New(); rgbfilter->SetColormap( colormap ); } else if ( colormapString == "hsv" ) { // rgbfilter->SetColormap( RGBFilterType::HSV ); typedef itk::Functor::HSVColormapFunctor<typename RealImageType::PixelType, typename RGBImageType::PixelType> ColormapType; typename ColormapType::Pointer colormap = ColormapType::New(); rgbfilter->SetColormap( colormap ); } else if ( colormapString == "overunder" ) { rgbfilter->SetColormap( RGBFilterType::OverUnder ); } else if ( colormapString == "custom" ) { typedef itk::Functor::CustomColormapFunctor<typename RealImageType::PixelType, typename RGBImageType::PixelType> ColormapType; typename ColormapType::Pointer colormap = ColormapType::New(); ifstream str( argv[6] ); std::string line; // Get red values { std::getline( str, line ); std::istringstream iss( line ); float value; typename ColormapType::ChannelType channel; while ( iss >> value ) { channel.push_back( value ); } colormap->SetRedChannel( channel ); } // Get green values { std::getline( str, line ); std::istringstream iss( line ); float value; typename ColormapType::ChannelType channel; while ( iss >> value ) { channel.push_back( value ); } colormap->SetGreenChannel( channel ); } // Get blue values { std::getline( str, line ); std::istringstream iss( line ); float value; typename ColormapType::ChannelType channel; while ( iss >> value ) { channel.push_back( value ); } colormap->SetBlueChannel( channel ); } rgbfilter->SetColormap( colormap ); } if( maskImage ) { RealType maskMinimumValue = itk::NumericTraits<RealType>::max(); RealType maskMaximumValue = itk::NumericTraits<RealType>::NonpositiveMin(); itk::ImageRegionIterator<MaskImageType> ItM( maskImage, maskImage->GetLargestPossibleRegion() ); itk::ImageRegionIterator<RealImageType> ItS( reader->GetOutput(), reader->GetOutput()->GetLargestPossibleRegion() ); for( ItM.GoToBegin(), ItS.GoToBegin(); !ItM.IsAtEnd(); ++ItM, ++ItS ) { if( ItM.Get() != 0 ) { if( maskMinimumValue >= ItS.Get() ) { maskMinimumValue = ItS.Get(); } if( maskMaximumValue <= ItS.Get() ) { maskMaximumValue = ItS.Get(); } } } rgbfilter->SetUseInputImageExtremaForScaling( false ); rgbfilter->GetColormap()->SetMinimumInputValue( maskMinimumValue ); rgbfilter->GetColormap()->SetMaximumInputValue( maskMaximumValue ); } rgbfilter->GetColormap()->SetMinimumRGBComponentValue( ( argc > 9 ) ? static_cast< typename RGBPixelType::ComponentType>( atof( argv[9] ) ) : 0 ); rgbfilter->GetColormap()->SetMaximumRGBComponentValue( ( argc > 10 ) ? static_cast< typename RGBPixelType::ComponentType>( atof( argv[10] ) ) : 255 ); if( argc > 8 ) { rgbfilter->SetUseInputImageExtremaForScaling( false ); rgbfilter->GetColormap()->SetMinimumInputValue( static_cast<RealType>( atof( argv[7] ) ) ); rgbfilter->GetColormap()->SetMaximumInputValue( static_cast<RealType>( atof( argv[8] ) ) ); } try { rgbfilter->Update(); } catch (...) { return EXIT_FAILURE; } if( maskImage ) { itk::ImageRegionIterator<MaskImageType> ItM( maskImage, maskImage->GetLargestPossibleRegion() ); itk::ImageRegionIterator<RGBImageType> ItC( rgbfilter->GetOutput(), rgbfilter->GetOutput()->GetLargestPossibleRegion() ); itk::ImageRegionIterator<RealImageType> ItS( reader->GetOutput(), reader->GetOutput()->GetLargestPossibleRegion() ); ItM.GoToBegin(); ItC.GoToBegin(); ItS.GoToBegin(); while( !ItM.IsAtEnd() ) { if( ItM.Get() == 0 ) { RGBPixelType rgbpixel; // RealType minimumValue = rgbfilter->GetColormap()->GetMinimumInputValue(); // RealType maximumValue = rgbfilter->GetColormap()->GetMaximumInputValue(); // // RealType minimumRGBValue // = rgbfilter->GetColormap()->GetMinimumRGBComponentValue(); // RealType maximumRGBValue // = rgbfilter->GetColormap()->GetMaximumRGBComponentValue(); // // RealType ratio = ( ItS.Get() - minimumValue ) / ( maximumValue - minimumValue ); // // rgbpixel.Fill( ratio * ( maximumRGBValue - minimumRGBValue ) // + minimumRGBValue ); rgbpixel.Fill( 0.0 ); ItC.Set( rgbpixel ); } ++ItM; ++ItC; ++ItS; } } typedef itk::ImageFileWriter<RGBImageType> WriterType; typename WriterType::Pointer writer = WriterType::New(); writer->SetInput( rgbfilter->GetOutput() ); writer->SetFileName( argv[3] ); writer->Update(); return 0; } int main( int argc, char *argv[] ) { if ( argc < 6 ) { std::cout << "Usage: " << argv[0] << " imageDimension inputImage outputImage " << "mask colormap [customColormapFile] [minimumInput] [maximumInput] " << "[minimumRGBOutput] [maximumRGBOutput]" << std::endl; std::cout << " Possible colormaps: grey, red, green, blue, copper, jet, hsv, "; std::cout << "spring, summer, autumn, winter, hot, cool, overunder, custom" << std::endl; exit( 1 ); } switch( atoi( argv[1] ) ) { case 2: ConvertScalarImageToRGB<2>( argc, argv ); break; case 3: ConvertScalarImageToRGB<3>( argc, argv ); break; default: std::cerr << "Unsupported dimension" << std::endl; exit( EXIT_FAILURE ); } } <commit_msg> rmv fstream <commit_after>#include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkImageRegionIterator.h" #include "itkRGBPixel.h" #include "itkRGBAPixel.h" #include "itkRedColormapFunctor.h" #include "itkGreenColormapFunctor.h" #include "itkBlueColormapFunctor.h" #include "itkGreyColormapFunctor.h" #include "itkHotColormapFunctor.h" #include "itkCoolColormapFunctor.h" #include "itkSpringColormapFunctor.h" #include "itkSummerColormapFunctor.h" #include "itkAutumnColormapFunctor.h" #include "itkWinterColormapFunctor.h" #include "itkCopperColormapFunctor.h" #include "itkHSVColormapFunctor.h" #include "itkJetColormapFunctor.h" #include "itkCustomColormapFunctor.h" #include "itkOverUnderColormapFunctor.h" #include "itkScalarToRGBColormapImageFilter.h" template <unsigned int ImageDimension> int ConvertScalarImageToRGB( int argc, char *argv[] ) { typedef unsigned int PixelType; // typedef itk::RGBPixel<unsigned char> RGBPixelType; typedef itk::RGBAPixel<unsigned char> RGBPixelType; typedef float RealType; typedef itk::Image<PixelType, ImageDimension> ImageType; typedef itk::Image<float, ImageDimension> RealImageType; typedef itk::Image<RGBPixelType, ImageDimension> RGBImageType; typedef itk::ImageFileReader<RealImageType> ReaderType; typename ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[2] ); reader->Update(); typedef itk::Image<unsigned char, ImageDimension> MaskImageType; typename MaskImageType::Pointer maskImage = MaskImageType::New(); typedef itk::ImageFileReader<MaskImageType> MaskReaderType; typename MaskReaderType::Pointer maskreader = MaskReaderType::New(); maskreader->SetFileName( argv[4] ); try { maskreader->Update(); maskImage = maskreader->GetOutput(); } catch(...) { maskImage = NULL; }; std::string colormapString( argv[5] ); typedef itk::ScalarToRGBColormapImageFilter<RealImageType, RGBImageType> RGBFilterType; typename RGBFilterType::Pointer rgbfilter = RGBFilterType::New(); rgbfilter->SetInput( reader->GetOutput() ); if ( colormapString == "red" ) { rgbfilter->SetColormap( RGBFilterType::Red ); } else if ( colormapString == "green" ) { rgbfilter->SetColormap( RGBFilterType::Green ); } else if ( colormapString == "blue" ) { rgbfilter->SetColormap( RGBFilterType::Blue ); } else if ( colormapString == "grey" ) { rgbfilter->SetColormap( RGBFilterType::Grey ); } else if ( colormapString == "cool" ) { rgbfilter->SetColormap( RGBFilterType::Cool ); } else if ( colormapString == "hot" ) { rgbfilter->SetColormap( RGBFilterType::Hot ); } else if ( colormapString == "spring" ) { rgbfilter->SetColormap( RGBFilterType::Spring ); } else if ( colormapString == "autumn" ) { rgbfilter->SetColormap( RGBFilterType::Autumn ); } else if ( colormapString == "winter" ) { rgbfilter->SetColormap( RGBFilterType::Winter ); } else if ( colormapString == "copper" ) { rgbfilter->SetColormap( RGBFilterType::Copper ); } else if ( colormapString == "summer" ) { rgbfilter->SetColormap( RGBFilterType::Summer ); } else if ( colormapString == "jet" ) { // rgbfilter->SetColormap( RGBFilterType::Jet ); typedef itk::Functor::JetColormapFunctor<typename RealImageType::PixelType, typename RGBImageType::PixelType> ColormapType; typename ColormapType::Pointer colormap = ColormapType::New(); rgbfilter->SetColormap( colormap ); } else if ( colormapString == "hsv" ) { // rgbfilter->SetColormap( RGBFilterType::HSV ); typedef itk::Functor::HSVColormapFunctor<typename RealImageType::PixelType, typename RGBImageType::PixelType> ColormapType; typename ColormapType::Pointer colormap = ColormapType::New(); rgbfilter->SetColormap( colormap ); } else if ( colormapString == "overunder" ) { rgbfilter->SetColormap( RGBFilterType::OverUnder ); } else if ( colormapString == "custom" ) { typedef itk::Functor::CustomColormapFunctor<typename RealImageType::PixelType, typename RGBImageType::PixelType> ColormapType; typename ColormapType::Pointer colormap = ColormapType::New(); ifstream str( argv[6] ); std::string line; // Get red values { std::getline( str, line ); std::istringstream iss( line ); float value; typename ColormapType::ChannelType channel; while ( iss >> value ) { channel.push_back( value ); } colormap->SetRedChannel( channel ); } // Get green values { std::getline( str, line ); std::istringstream iss( line ); float value; typename ColormapType::ChannelType channel; while ( iss >> value ) { channel.push_back( value ); } colormap->SetGreenChannel( channel ); } // Get blue values { std::getline( str, line ); std::istringstream iss( line ); float value; typename ColormapType::ChannelType channel; while ( iss >> value ) { channel.push_back( value ); } colormap->SetBlueChannel( channel ); } rgbfilter->SetColormap( colormap ); } if( maskImage ) { RealType maskMinimumValue = itk::NumericTraits<RealType>::max(); RealType maskMaximumValue = itk::NumericTraits<RealType>::NonpositiveMin(); itk::ImageRegionIterator<MaskImageType> ItM( maskImage, maskImage->GetLargestPossibleRegion() ); itk::ImageRegionIterator<RealImageType> ItS( reader->GetOutput(), reader->GetOutput()->GetLargestPossibleRegion() ); for( ItM.GoToBegin(), ItS.GoToBegin(); !ItM.IsAtEnd(); ++ItM, ++ItS ) { if( ItM.Get() != 0 ) { if( maskMinimumValue >= ItS.Get() ) { maskMinimumValue = ItS.Get(); } if( maskMaximumValue <= ItS.Get() ) { maskMaximumValue = ItS.Get(); } } } rgbfilter->SetUseInputImageExtremaForScaling( false ); rgbfilter->GetColormap()->SetMinimumInputValue( maskMinimumValue ); rgbfilter->GetColormap()->SetMaximumInputValue( maskMaximumValue ); } rgbfilter->GetColormap()->SetMinimumRGBComponentValue( ( argc > 9 ) ? static_cast< typename RGBPixelType::ComponentType>( atof( argv[9] ) ) : 0 ); rgbfilter->GetColormap()->SetMaximumRGBComponentValue( ( argc > 10 ) ? static_cast< typename RGBPixelType::ComponentType>( atof( argv[10] ) ) : 255 ); if( argc > 8 ) { rgbfilter->SetUseInputImageExtremaForScaling( false ); rgbfilter->GetColormap()->SetMinimumInputValue( static_cast<RealType>( atof( argv[7] ) ) ); rgbfilter->GetColormap()->SetMaximumInputValue( static_cast<RealType>( atof( argv[8] ) ) ); } try { rgbfilter->Update(); } catch (...) { return EXIT_FAILURE; } if( maskImage ) { itk::ImageRegionIterator<MaskImageType> ItM( maskImage, maskImage->GetLargestPossibleRegion() ); itk::ImageRegionIterator<RGBImageType> ItC( rgbfilter->GetOutput(), rgbfilter->GetOutput()->GetLargestPossibleRegion() ); itk::ImageRegionIterator<RealImageType> ItS( reader->GetOutput(), reader->GetOutput()->GetLargestPossibleRegion() ); ItM.GoToBegin(); ItC.GoToBegin(); ItS.GoToBegin(); while( !ItM.IsAtEnd() ) { if( ItM.Get() == 0 ) { RGBPixelType rgbpixel; // RealType minimumValue = rgbfilter->GetColormap()->GetMinimumInputValue(); // RealType maximumValue = rgbfilter->GetColormap()->GetMaximumInputValue(); // // RealType minimumRGBValue // = rgbfilter->GetColormap()->GetMinimumRGBComponentValue(); // RealType maximumRGBValue // = rgbfilter->GetColormap()->GetMaximumRGBComponentValue(); // // RealType ratio = ( ItS.Get() - minimumValue ) / ( maximumValue - minimumValue ); // // rgbpixel.Fill( ratio * ( maximumRGBValue - minimumRGBValue ) // + minimumRGBValue ); rgbpixel.Fill( 0.0 ); ItC.Set( rgbpixel ); } ++ItM; ++ItC; ++ItS; } } typedef itk::ImageFileWriter<RGBImageType> WriterType; typename WriterType::Pointer writer = WriterType::New(); writer->SetInput( rgbfilter->GetOutput() ); writer->SetFileName( argv[3] ); writer->Update(); return 0; } int main( int argc, char *argv[] ) { if ( argc < 6 ) { std::cout << "Usage: " << argv[0] << " imageDimension inputImage outputImage " << "mask colormap [customColormapFile] [minimumInput] [maximumInput] " << "[minimumRGBOutput] [maximumRGBOutput]" << std::endl; std::cout << " Possible colormaps: grey, red, green, blue, copper, jet, hsv, "; std::cout << "spring, summer, autumn, winter, hot, cool, overunder, custom" << std::endl; exit( 1 ); } switch( atoi( argv[1] ) ) { case 2: ConvertScalarImageToRGB<2>( argc, argv ); break; case 3: ConvertScalarImageToRGB<3>( argc, argv ); break; default: std::cerr << "Unsupported dimension" << std::endl; exit( EXIT_FAILURE ); } } <|endoftext|>
<commit_before><commit_msg>There are instances where the URLRequestAutomationJob::Kill() function can get called after Cleanup, which results in the AutomationResourceMessageFilter member getting destroyed and a subsequent crash.<commit_after><|endoftext|>