blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 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
115 values
content
stringlengths
3
10.4M
authors
sequencelengths
1
1
author_id
stringlengths
0
158
ef0806fd66b5bc0165caf9b004ad73016739dc06
baa82ab14c5532f5984bd8afff31f376c1477f5f
/6.41.cpp
007640c3136cf7a4acaa92173530468209defa42
[]
no_license
AnthonyM2456/Tarea-Ccomp2-1.1-02-05-20
6f16481858c087642ae4dc3c8ec2ee53c8f02af4
65c5410daf60f073938fd0485ffe615d3a8fa0dd
refs/heads/master
2022-06-20T04:27:01.458115
2020-05-04T22:25:58
2020-05-04T22:25:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
388
cpp
#include "iostream" using namespace std; int gcd(int x, int y){ if(x < y){ return gcd(y,x); } else{ if(y == 0){ return x; } else{ return gcd(y, int(x%y)); } } } int main(){ int x, y; cout << "ingresar el primer valor: "; cin >> x; cout << "ingresar el segundo valor: "; cin >> y; cout << "El MCD es: " << gcd(x,y); return 0; }
00687173615e188c8f978c8dabed210e04ab0502
2aa0d8fc8e03f23293a1416242dbe9588e9892a9
/OCLODE_efficient/main.cpp
34008be203a9b5d5420a9f2f68974d6e5d4e7887
[]
no_license
weiyangedward/co-expression-network-clustering
9a1badaf7e121d6eb88734906d4bf80d077b614d
87d5174aaf81c73a7ac13b294d70b9bc1d2b4d8c
refs/heads/master
2021-01-16T20:40:46.719785
2016-05-28T23:12:35
2016-05-28T23:12:35
52,640,132
0
0
null
null
null
null
UTF-8
C++
false
false
4,822
cpp
//#include "cs-grn.h" //#include "ReadInputs.h" #include "Clustering.h" #include "SpeciesNetwork.h" #include "Orthology.h" using namespace std; int main (int argc, char * const argv[]) { if (argc < 7) { printf("usage: %s " "<num_clusters> " "<num_trials> " "<coupling_constant> " "<orth_file> " "<num_species> " "<spc1nw> " "<spc2nw> ... " "-s:string <start_clustering_file> " "-t:double <max_temp> " "-n <clustering with noise cluster> \n", argv[0]); exit(1); } clock_t begin = clock(); /*============ read files and parameters ============*/ int argbase = 1; // count for argv int num_clusters = atoi(argv[argbase++]); // num clusters num_clusters +=1; // add one more cluster: 'noise cluster 0' int num_trials = atoi(argv[argbase++]); // number of trials double coupling_constant = atof(argv[argbase++]); // coupling_constant char *orth_file = argv[argbase++]; // ortholog files int num_species = atoi(argv[argbase++]); // number of species /* init species co-expression network */ SpeciesNetwork **species_network = new SpeciesNetwork*[num_species]; for (int i=0; i<num_species; i++) { char *spe_network_file = argv[argbase++]; // species_network[i] = read_network_file(spc); // init network for a species species_network[i] = new SpeciesNetwork(spe_network_file); } /* read parameters: startclusfn '-s' and max_temp '-t', noise_cluster '-n', weight for noise term '-lambda' */ char startclusfn[1024]; startclusfn[0] = 0; double max_temp = -1; bool has_noise_cluster = false; double lambda = 1.0; while (argbase < argc) { // ground-truth clutering if (!strcmp(argv[argbase], "-s")) { argbase++; strcpy(startclusfn, argv[argbase++]); continue; } // starting tempreture if (!strcmp(argv[argbase], "-t")) { argbase++; max_temp = atof(argv[argbase++]); continue; } // has noise cluster if (!strcmp(argv[argbase], "-n")) { argbase++; has_noise_cluster = true; continue; } } // create ortholog obj using (ortholog file, network arr, number of spe) // Orthology *orth = read_orthology_file(orth_file, species_network, num_species); /* init orthologous */ Orthology *orthology = new Orthology(orth_file, species_network, num_species); /*======= clustering ==========*/ // create arr of size num_trials for clustering obj Clustering **clustering = new Clustering *[num_trials]; for (int i=0; i<num_trials; i++) { // init clustering for a trial clustering[i] = new Clustering(species_network, num_species, orthology, num_clusters, coupling_constant, has_noise_cluster); // use ground-truth clustering label as start point if (startclusfn[0]!=0) { fprintf(stderr,"Using seed clustering file %s\n",startclusfn); clustering[i]->pre_set(startclusfn, orthology, species_network); } // if starting tempreture used, set max_temp if (max_temp >= 0) clustering[i]->set_max_temp(max_temp); // simulated annealing to find parameters with best cost clustering[i]->learn_ground_state(species_network, orthology); } /*==== go through all trails, and record the best cost ====*/ double best_cost = 0.0; int best_trial = -1; for (int i=0; i<num_trials; i++) { if (clustering[i]->best_total_cost < best_cost) // cost is negative { best_trial = i; best_cost = clustering[i]->best_total_cost; } } /*====== print best clustering found =======*/ printf("Best clustering, with cost %g is:\n", best_cost); clustering[best_trial]->Print(species_network); /*====== print running time =========*/ clock_t end = clock(); double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; fprintf(stderr,"Total time: %f s\n",elapsed_secs); /* free memory */ for (int i=0; i<num_trials; i++) { delete clustering[i]; } delete[] clustering; for (int i=0; i<num_species; i++) { delete species_network[i]; } delete[] species_network; delete orthology; return 0; }
3a6921a219ec1315967753aaa186da56949a7a0d
1778667bd78b5814b5950e244da4b0ec85752aca
/src/main.h
016de7d159ccb334212587099673e0cb14696507
[ "MIT" ]
permissive
iGotSpots/PrimeChain
4abcf6d54d7d01ab1a40b6840f17c5d1b30a3d49
c40789a9725483ed4e330ba329d4e2b5ad2d0e3e
refs/heads/master
2021-01-18T23:11:58.025697
2016-06-20T17:16:20
2016-06-20T17:16:23
61,455,040
2
1
null
2016-06-20T11:10:38
2016-06-18T22:30:47
C++
UTF-8
C++
false
false
50,658
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2013 The PrimeChain developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_MAIN_H #define BITCOIN_MAIN_H #include "bignum.h" #include "net.h" #include "script.h" #ifdef WIN32 #include <io.h> /* for _commit */ #endif #include <list> class CWallet; class CBlock; class CBlockIndex; class CKeyItem; class CReserveKey; class COutPoint; class CAddress; class CInv; class CRequestTracker; class CNode; static const unsigned int MAX_BLOCK_SIZE = 1000000; static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2; static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50; static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100; static const int LAST_POW_BLOCK = 1000; static const int64 MIN_TX_FEE = 10000; static const int64 MIN_RELAY_TX_FEE = MIN_TX_FEE; static const int64 MAX_MONEY = 2000000000 * COIN; static const int64 MAX_MINT_PROOF_OF_WORK = 1000000000000 * COIN; static const int64 MIN_TXOUT_AMOUNT = MIN_TX_FEE; inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); } static const int COINBASE_MATURITY_PPC = 60; static const int LOCKTIME_THRESHOLD = 500000000; static const int STAKE_START_TIME = 1408636800; static const int STAKE_TARGET_SPACING = 180; static const int STAKE_MIN_AGE = 60 * 60; static const int STAKE_MAX_AGE = 60 * 60 * 24 * 366; #ifdef USE_UPNP static const int fHaveUPnP = true; #else static const int fHaveUPnP = false; #endif static const uint256 hashGenesisBlockOfficial("0x000000007ddfa2ee658c1fef6e56e397e33b484e72bc3a2a460118fcc7ed2393"); static const uint256 hashGenesisBlockTestNet("0x00000001f757bb737f6596503e17cd17b0658ce630cc727c0cca81aec47c9f06"); static const int64 nMaxClockDrift = 2 * 60 * 60; // two hours extern CScript COINBASE_FLAGS; extern CCriticalSection cs_main; extern std::map<uint256, CBlockIndex*> mapBlockIndex; extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen; extern uint256 hashGenesisBlock; extern unsigned int nStakeMinAge; extern int nCoinbaseMaturity; extern CBlockIndex* pindexGenesisBlock; extern int nBestHeight; extern CBigNum bnBestChainTrust; extern CBigNum bnBestInvalidTrust; extern uint256 hashBestChain; extern CBlockIndex* pindexBest; extern unsigned int nTransactionsUpdated; extern uint64 nLastBlockTx; extern uint64 nLastBlockSize; extern int64 nLastCoinStakeSearchInterval; extern const std::string strMessageMagic; extern double dHashesPerSec; extern int64 nHPSTimerStart; extern int64 nTimeBestReceived; extern CCriticalSection cs_setpwalletRegistered; extern std::set<CWallet*> setpwalletRegistered; extern std::map<uint256, CBlock*> mapOrphanBlocks; // Settings extern int64 nTransactionFee; class CReserveKey; class CTxDB; class CTxIndex; void RegisterWallet(CWallet* pwalletIn); void UnregisterWallet(CWallet* pwalletIn); void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true); bool ProcessBlock(CNode* pfrom, CBlock* pblock); bool CheckDiskSpace(uint64 nAdditionalBytes=0); FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb"); FILE* AppendBlockFile(unsigned int& nFileRet); bool LoadBlockIndex(bool fAllowNew=true); void PrintBlockTree(); bool ProcessMessages(CNode* pfrom); bool SendMessages(CNode* pto, bool fSendTrickle); void GenerateBitcoins(bool fGenerate, CWallet* pwallet); CBlock* CreateNewBlock(CReserveKey& reservekey, CWallet* pwallet, bool fProofOfStake=false); void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce); void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1); bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey); bool CheckProofOfWork(uint256 hash, unsigned int nBits); int64 GetProofOfWorkReward(unsigned int nBits); int64 GetProofOfStakeReward(int64 nCoinAge, int nHeight); unsigned int ComputeMinWork(unsigned int nBase, int64 nTime); int GetNumBlocksOfPeers(); bool IsInitialBlockDownload(); std::string GetWarnings(std::string strFor); uint256 WantedByOrphan(const CBlock* pblockOrphan); const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake); void BitcoinMiner(CWallet *pwallet, bool fProofOfStake); bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock); double GetBlockDifficulty(const CBlockIndex* blockindex = NULL); bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut); /** Position on disk for a particular transaction. */ class CDiskTxPos { public: unsigned int nFile; unsigned int nBlockPos; unsigned int nTxPos; CDiskTxPos() { SetNull(); } CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn) { nFile = nFileIn; nBlockPos = nBlockPosIn; nTxPos = nTxPosIn; } IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); ) void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; } bool IsNull() const { return (nFile == -1); } friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b) { return (a.nFile == b.nFile && a.nBlockPos == b.nBlockPos && a.nTxPos == b.nTxPos); } friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b) { return !(a == b); } std::string ToString() const { if (IsNull()) return "null"; else return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos); } void print() const { printf("%s", ToString().c_str()); } }; /** An inpoint - a combination of a transaction and an index n into its vin */ class CInPoint { public: CTransaction* ptx; unsigned int n; CInPoint() { SetNull(); } CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; } void SetNull() { ptx = NULL; n = -1; } bool IsNull() const { return (ptx == NULL && n == -1); } }; /** An outpoint - a combination of a transaction hash and an index n into its vout */ class COutPoint { public: uint256 hash; unsigned int n; COutPoint() { SetNull(); } COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; } IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); ) void SetNull() { hash = 0; n = -1; } bool IsNull() const { return (hash == 0 && n == -1); } friend bool operator<(const COutPoint& a, const COutPoint& b) { return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n)); } friend bool operator==(const COutPoint& a, const COutPoint& b) { return (a.hash == b.hash && a.n == b.n); } friend bool operator!=(const COutPoint& a, const COutPoint& b) { return !(a == b); } std::string ToString() const { return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n); } void print() const { printf("%s\n", ToString().c_str()); } }; /** An input of a transaction. It contains the location of the previous * transaction's output that it claims and a signature that matches the * output's public key. */ class CTxIn { public: COutPoint prevout; CScript scriptSig; unsigned int nSequence; CTxIn() { nSequence = std::numeric_limits<unsigned int>::max(); } explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max()) { prevout = prevoutIn; scriptSig = scriptSigIn; nSequence = nSequenceIn; } CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max()) { prevout = COutPoint(hashPrevTx, nOut); scriptSig = scriptSigIn; nSequence = nSequenceIn; } IMPLEMENT_SERIALIZE ( READWRITE(prevout); READWRITE(scriptSig); READWRITE(nSequence); ) bool IsFinal() const { return (nSequence == std::numeric_limits<unsigned int>::max()); } friend bool operator==(const CTxIn& a, const CTxIn& b) { return (a.prevout == b.prevout && a.scriptSig == b.scriptSig && a.nSequence == b.nSequence); } friend bool operator!=(const CTxIn& a, const CTxIn& b) { return !(a == b); } std::string ToStringShort() const { return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n); } std::string ToString() const { std::string str; str += "CTxIn("; str += prevout.ToString(); if (prevout.IsNull()) str += strprintf(", coinbase %s", HexStr(scriptSig).c_str()); else str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str()); if (nSequence != std::numeric_limits<unsigned int>::max()) str += strprintf(", nSequence=%u", nSequence); str += ")"; return str; } void print() const { printf("%s\n", ToString().c_str()); } }; /** An output of a transaction. It contains the public key that the next input * must be able to sign with to claim it. */ class CTxOut { public: int64 nValue; CScript scriptPubKey; CTxOut() { SetNull(); } CTxOut(int64 nValueIn, CScript scriptPubKeyIn) { nValue = nValueIn; scriptPubKey = scriptPubKeyIn; } IMPLEMENT_SERIALIZE ( READWRITE(nValue); READWRITE(scriptPubKey); ) void SetNull() { nValue = -1; scriptPubKey.clear(); } bool IsNull() { return (nValue == -1); } void SetEmpty() { nValue = 0; scriptPubKey.clear(); } bool IsEmpty() const { return (nValue == 0 && scriptPubKey.empty()); } uint256 GetHash() const { return SerializeHash(*this); } friend bool operator==(const CTxOut& a, const CTxOut& b) { return (a.nValue == b.nValue && a.scriptPubKey == b.scriptPubKey); } friend bool operator!=(const CTxOut& a, const CTxOut& b) { return !(a == b); } std::string ToStringShort() const { return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str()); } std::string ToString() const { if (IsEmpty()) return "CTxOut(empty)"; if (scriptPubKey.size() < 6) return "CTxOut(error)"; return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str()); } void print() const { printf("%s\n", ToString().c_str()); } }; enum GetMinFee_mode { GMF_BLOCK, GMF_RELAY, GMF_SEND, }; typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx; /** The basic transaction that is broadcasted on the network and contained in * blocks. A transaction can contain multiple inputs and outputs. */ class CTransaction { public: int nVersion; unsigned int nTime; std::vector<CTxIn> vin; std::vector<CTxOut> vout; unsigned int nLockTime; // Denial-of-service detection: mutable int nDoS; bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; } CTransaction() { SetNull(); } IMPLEMENT_SERIALIZE ( READWRITE(this->nVersion); nVersion = this->nVersion; READWRITE(nTime); READWRITE(vin); READWRITE(vout); READWRITE(nLockTime); ) void SetNull() { nVersion = 1; nTime = GetAdjustedTime(); vin.clear(); vout.clear(); nLockTime = 0; nDoS = 0; // Denial-of-service prevention } bool IsNull() const { return (vin.empty() && vout.empty()); } uint256 GetHash() const { return SerializeHash(*this); } bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const { // Time based nLockTime implemented in 0.1.6 if (nLockTime == 0) return true; if (nBlockHeight == 0) nBlockHeight = nBestHeight; if (nBlockTime == 0) nBlockTime = GetAdjustedTime(); if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime)) return true; BOOST_FOREACH(const CTxIn& txin, vin) if (!txin.IsFinal()) return false; return true; } bool IsNewerThan(const CTransaction& old) const { if (vin.size() != old.vin.size()) return false; for (unsigned int i = 0; i < vin.size(); i++) if (vin[i].prevout != old.vin[i].prevout) return false; bool fNewer = false; unsigned int nLowest = std::numeric_limits<unsigned int>::max(); for (unsigned int i = 0; i < vin.size(); i++) { if (vin[i].nSequence != old.vin[i].nSequence) { if (vin[i].nSequence <= nLowest) { fNewer = false; nLowest = vin[i].nSequence; } if (old.vin[i].nSequence < nLowest) { fNewer = true; nLowest = old.vin[i].nSequence; } } } return fNewer; } bool IsCoinBase() const { return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1); } bool IsCoinStake() const { // PrimeChain: the coin stake transaction is marked with the first output empty return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty()); } /** Check for standard transaction types @return True if all outputs (scriptPubKeys) use only standard transaction forms */ bool IsStandard() const; /** Check for standard transaction types @param[in] mapInputs Map of previous transactions that have outputs we're spending @return True if all inputs (scriptSigs) use only standard transaction forms @see CTransaction::FetchInputs */ bool AreInputsStandard(const MapPrevTx& mapInputs) const; /** Count ECDSA signature operations the old-fashioned (pre-0.6) way @return number of sigops this transaction's outputs will produce when spent @see CTransaction::FetchInputs */ unsigned int GetLegacySigOpCount() const; /** Count ECDSA signature operations in pay-to-script-hash inputs. @param[in] mapInputs Map of previous transactions that have outputs we're spending @return maximum number of sigops required to validate this transaction's inputs @see CTransaction::FetchInputs */ unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const; /** Amount of bitcoins spent by this transaction. @return sum of all outputs (note: does not include fees) */ int64 GetValueOut() const { int64 nValueOut = 0; BOOST_FOREACH(const CTxOut& txout, vout) { nValueOut += txout.nValue; if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut)) throw std::runtime_error("CTransaction::GetValueOut() : value out of range"); } return nValueOut; } /** Amount of bitcoins coming in to this transaction Note that lightweight clients may not know anything besides the hash of previous transactions, so may not be able to calculate this. @param[in] mapInputs Map of previous transactions that have outputs we're spending @return Sum of value of all inputs (scriptSigs) @see CTransaction::FetchInputs */ int64 GetValueIn(const MapPrevTx& mapInputs) const; static bool AllowFree(double dPriority) { // Large (in bytes) low-priority (new, small-coin) transactions // need a fee. return dPriority > COIN * 144 / 250; } int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK, unsigned int nBytes=0) const; bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL) { CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION); if (!filein) return error("CTransaction::ReadFromDisk() : OpenBlockFile failed"); // Read transaction if (fseek(filein, pos.nTxPos, SEEK_SET) != 0) return error("CTransaction::ReadFromDisk() : fseek failed"); try { filein >> *this; } catch (std::exception &e) { return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__); } // Return file pointer if (pfileRet) { if (fseek(filein, pos.nTxPos, SEEK_SET) != 0) return error("CTransaction::ReadFromDisk() : second fseek failed"); *pfileRet = filein.release(); } return true; } friend bool operator==(const CTransaction& a, const CTransaction& b) { return (a.nVersion == b.nVersion && a.nTime == b.nTime && a.vin == b.vin && a.vout == b.vout && a.nLockTime == b.nLockTime); } friend bool operator!=(const CTransaction& a, const CTransaction& b) { return !(a == b); } std::string ToStringShort() const { std::string str; str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user")); return str; } std::string ToString() const { std::string str; str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction"); str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n", GetHash().ToString().substr(0,10).c_str(), nTime, nVersion, vin.size(), vout.size(), nLockTime); for (unsigned int i = 0; i < vin.size(); i++) str += " " + vin[i].ToString() + "\n"; for (unsigned int i = 0; i < vout.size(); i++) str += " " + vout[i].ToString() + "\n"; return str; } void print() const { printf("%s", ToString().c_str()); } bool ReadFromDisk(CTxDB& txdb, const uint256& hash, CTxIndex& txindexRet); bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet); bool ReadFromDisk(CTxDB& txdb, COutPoint prevout); bool ReadFromDisk(COutPoint prevout); bool DisconnectInputs(CTxDB& txdb); /** Fetch from memory and/or disk. inputsRet keys are transaction hashes. @param[in] txdb Transaction database @param[in] mapTestPool List of pending changes to the transaction index database @param[in] fBlock True if being called to add a new best-block to the chain @param[in] fMiner True if being called by CreateNewBlock @param[out] inputsRet Pointers to this transaction's inputs @param[out] fInvalid returns true if transaction is invalid @return Returns true if all inputs are in txdb or mapTestPool */ bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool, bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid); /** Sanity check previous transactions, then, if all checks succeed, mark them as spent by this transaction. @param[in] inputs Previous transactions (from FetchInputs) @param[out] mapTestPool Keeps track of inputs that need to be updated on disk @param[in] posThisTx Position of this transaction on disk @param[in] pindexBlock @param[in] fBlock true if called from ConnectBlock @param[in] fMiner true if called from CreateNewBlock @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions @return Returns true if all checks succeed */ bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs, std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx, const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true); bool ClientConnectInputs(); bool CheckTransaction() const; bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL); bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const; // PrimeChain: get transaction coin age protected: const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const; }; /** A transaction with a merkle branch linking it to the block chain. */ class CMerkleTx : public CTransaction { public: uint256 hashBlock; std::vector<uint256> vMerkleBranch; int nIndex; // memory only mutable bool fMerkleVerified; CMerkleTx() { Init(); } CMerkleTx(const CTransaction& txIn) : CTransaction(txIn) { Init(); } void Init() { hashBlock = 0; nIndex = -1; fMerkleVerified = false; } IMPLEMENT_SERIALIZE ( nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action); nVersion = this->nVersion; READWRITE(hashBlock); READWRITE(vMerkleBranch); READWRITE(nIndex); ) int SetMerkleBranch(const CBlock* pblock=NULL); int GetDepthInMainChain(CBlockIndex* &pindexRet) const; int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); } bool IsInMainChain() const { return GetDepthInMainChain() > 0; } int GetBlocksToMaturity() const; bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true); bool AcceptToMemoryPool(); }; /** A txdb record that contains the disk location of a transaction and the * locations of transactions that spend its outputs. vSpent is really only * used as a flag, but having the location is very helpful for debugging. */ class CTxIndex { public: CDiskTxPos pos; std::vector<CDiskTxPos> vSpent; CTxIndex() { SetNull(); } CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs) { pos = posIn; vSpent.resize(nOutputs); } IMPLEMENT_SERIALIZE ( if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(pos); READWRITE(vSpent); ) void SetNull() { pos.SetNull(); vSpent.clear(); } bool IsNull() { return pos.IsNull(); } friend bool operator==(const CTxIndex& a, const CTxIndex& b) { return (a.pos == b.pos && a.vSpent == b.vSpent); } friend bool operator!=(const CTxIndex& a, const CTxIndex& b) { return !(a == b); } int GetDepthInMainChain() const; }; /** Nodes collect new transactions into a block, hash them into a hash tree, * and scan through nonce values to make the block's hash satisfy proof-of-work * requirements. When they solve the proof-of-work, they broadcast the block * to everyone and the block is added to the block chain. The first transaction * in the block is a special one that creates a new coin owned by the creator * of the block. * * Blocks are appended to blk0001.dat files on disk. Their location on disk * is indexed by CBlockIndex objects in memory. */ class CBlock { public: // header int nVersion; uint256 hashPrevBlock; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; // network and disk std::vector<CTransaction> vtx; // PrimeChain: block signature - signed by coin base txout[0]'s owner std::vector<unsigned char> vchBlockSig; // memory only mutable std::vector<uint256> vMerkleTree; // Denial-of-service detection: mutable int nDoS; bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; } CBlock() { SetNull(); } IMPLEMENT_SERIALIZE ( READWRITE(this->nVersion); nVersion = this->nVersion; READWRITE(hashPrevBlock); READWRITE(hashMerkleRoot); READWRITE(nTime); READWRITE(nBits); READWRITE(nNonce); // ConnectBlock depends on vtx following header to generate CDiskTxPos if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY))) { READWRITE(vtx); READWRITE(vchBlockSig); } else if (fRead) { const_cast<CBlock*>(this)->vtx.clear(); const_cast<CBlock*>(this)->vchBlockSig.clear(); } ) void SetNull() { nVersion = 1; hashPrevBlock = 0; hashMerkleRoot = 0; nTime = 0; nBits = 0; nNonce = 0; vtx.clear(); vchBlockSig.clear(); vMerkleTree.clear(); nDoS = 0; } bool IsNull() const { return (nBits == 0); } uint256 GetHash() const { return Hash(BEGIN(nVersion), END(nNonce)); } int64 GetBlockTime() const { return (int64)nTime; } void UpdateTime(const CBlockIndex* pindexPrev); // PrimeChain: two types of block: proof-of-work or proof-of-stake bool IsProofOfStake() const { return (vtx.size() > 1 && vtx[1].IsCoinStake()); } bool IsProofOfWork() const { return !IsProofOfStake(); } std::pair<COutPoint, unsigned int> GetProofOfStake() const { return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0); } // PrimeChain: get max transaction timestamp int64 GetMaxTransactionTime() const { int64 maxTransactionTime = 0; BOOST_FOREACH(const CTransaction& tx, vtx) maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime); return maxTransactionTime; } uint256 BuildMerkleTree() const { vMerkleTree.clear(); BOOST_FOREACH(const CTransaction& tx, vtx) vMerkleTree.push_back(tx.GetHash()); int j = 0; for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) { for (int i = 0; i < nSize; i += 2) { int i2 = std::min(i+1, nSize-1); vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]), BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2]))); } j += nSize; } return (vMerkleTree.empty() ? 0 : vMerkleTree.back()); } std::vector<uint256> GetMerkleBranch(int nIndex) const { if (vMerkleTree.empty()) BuildMerkleTree(); std::vector<uint256> vMerkleBranch; int j = 0; for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) { int i = std::min(nIndex^1, nSize-1); vMerkleBranch.push_back(vMerkleTree[j+i]); nIndex >>= 1; j += nSize; } return vMerkleBranch; } static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex) { if (nIndex == -1) return 0; BOOST_FOREACH(const uint256& otherside, vMerkleBranch) { if (nIndex & 1) hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash)); else hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside)); nIndex >>= 1; } return hash; } bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet) { // Open history file to append CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION); if (!fileout) return error("CBlock::WriteToDisk() : AppendBlockFile failed"); // Write index header unsigned char pchMessageStart[4]; GetMessageStart(pchMessageStart, true); unsigned int nSize = fileout.GetSerializeSize(*this); fileout << FLATDATA(pchMessageStart) << nSize; // Write block long fileOutPos = ftell(fileout); if (fileOutPos < 0) return error("CBlock::WriteToDisk() : ftell failed"); nBlockPosRet = fileOutPos; fileout << *this; // Flush stdio buffers and commit to disk before returning fflush(fileout); if (!IsInitialBlockDownload() || (nBestHeight+1) % 50000 == 0) { #ifdef WIN32 _commit(_fileno(fileout)); #else fsync(fileno(fileout)); #endif } return true; } bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true) { SetNull(); // Open history file to read CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION); if (!filein) return error("CBlock::ReadFromDisk() : OpenBlockFile failed"); if (!fReadTransactions) filein.nType |= SER_BLOCKHEADERONLY; // Read block try { filein >> *this; } catch (std::exception &e) { return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__); } // Check the header if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits)) return error("CBlock::ReadFromDisk() : errors in block header"); return true; } void print() const { printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d, vchBlockSig=%s)\n", GetHash().ToString().substr(0,20).c_str(), nVersion, hashPrevBlock.ToString().substr(0,20).c_str(), hashMerkleRoot.ToString().substr(0,10).c_str(), nTime, nBits, nNonce, vtx.size(), HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str()); for (unsigned int i = 0; i < vtx.size(); i++) { printf(" "); vtx[i].print(); } printf(" vMerkleTree: "); for (unsigned int i = 0; i < vMerkleTree.size(); i++) printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str()); printf("\n"); } bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex); bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex); bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true); bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew); bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos); bool CheckBlock() const; bool AcceptBlock(); bool GetCoinAge(uint64& nCoinAge) const; // PrimeChain: calculate total coin age spent in block bool SignBlock(const CKeyStore& keystore); bool CheckBlockSignature() const; unsigned int GetStakeEntropyBit() const; // PrimeChain: entropy bit for stake modifier if chosen by modifier private: bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew); }; /** The block chain is a tree shaped structure starting with the * genesis block at the root, with each block potentially having multiple * candidates to be the next block. pprev and pnext link a path through the * main/longest chain. A blockindex may have multiple pprev pointing back * to it, but pnext will only point forward to the longest branch, or will * be null if the block is not part of the longest chain. */ class CBlockIndex { public: const uint256* phashBlock; CBlockIndex* pprev; CBlockIndex* pnext; unsigned int nFile; unsigned int nBlockPos; CBigNum bnChainTrust; // PrimeChain: trust score of block chain int nHeight; int64 nMint; int64 nMoneySupply; unsigned int nFlags; // PrimeChain: block index flags enum { BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier }; uint64 nStakeModifier; // hash modifier for proof-of-stake unsigned int nStakeModifierChecksum; // checksum of index; in-memeory only // proof-of-stake specific fields COutPoint prevoutStake; unsigned int nStakeTime; uint256 hashProofOfStake; // block header int nVersion; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; CBlockIndex() { phashBlock = NULL; pprev = NULL; pnext = NULL; nFile = 0; nBlockPos = 0; nHeight = 0; bnChainTrust = 0; nMint = 0; nMoneySupply = 0; nFlags = 0; nStakeModifier = 0; nStakeModifierChecksum = 0; hashProofOfStake = 0; prevoutStake.SetNull(); nStakeTime = 0; nVersion = 0; hashMerkleRoot = 0; nTime = 0; nBits = 0; nNonce = 0; } CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block) { phashBlock = NULL; pprev = NULL; pnext = NULL; nFile = nFileIn; nBlockPos = nBlockPosIn; nHeight = 0; bnChainTrust = 0; nMint = 0; nMoneySupply = 0; nFlags = 0; nStakeModifier = 0; nStakeModifierChecksum = 0; hashProofOfStake = 0; if (block.IsProofOfStake()) { SetProofOfStake(); prevoutStake = block.vtx[1].vin[0].prevout; nStakeTime = block.vtx[1].nTime; } else { prevoutStake.SetNull(); nStakeTime = 0; } nVersion = block.nVersion; hashMerkleRoot = block.hashMerkleRoot; nTime = block.nTime; nBits = block.nBits; nNonce = block.nNonce; } CBlock GetBlockHeader() const { CBlock block; block.nVersion = nVersion; if (pprev) block.hashPrevBlock = pprev->GetBlockHash(); block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; return block; } uint256 GetBlockHash() const { return *phashBlock; } int64 GetBlockTime() const { return (int64)nTime; } /** * Duplicate from bitcoinrpc that originaly define this method. * May require some cleanup since this method should be available both for rpc * and qt clients. */ double GetBlockDifficulty() const { int nShift = (nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } CBigNum GetBlockTrust() const { CBigNum bnTarget; bnTarget.SetCompact(nBits); if (bnTarget <= 0) return 0; return (IsProofOfStake()? (CBigNum(1)<<256) / (bnTarget+1) : 1); } bool IsInMainChain() const { return (pnext || this == pindexBest); } bool CheckIndex() const { return IsProofOfWork() ? CheckProofOfWork(GetBlockHash(), nBits) : true; } bool EraseBlockFromDisk() { // Open history file CAutoFile fileout = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb+"), SER_DISK, CLIENT_VERSION); if (!fileout) return false; // Overwrite with empty null block CBlock block; block.SetNull(); fileout << block; return true; } enum { nMedianTimeSpan=11 }; int64 GetMedianTimePast() const { int64 pmedian[nMedianTimeSpan]; int64* pbegin = &pmedian[nMedianTimeSpan]; int64* pend = &pmedian[nMedianTimeSpan]; const CBlockIndex* pindex = this; for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev) *(--pbegin) = pindex->GetBlockTime(); std::sort(pbegin, pend); return pbegin[(pend - pbegin)/2]; } int64 GetMedianTime() const { const CBlockIndex* pindex = this; for (int i = 0; i < nMedianTimeSpan/2; i++) { if (!pindex->pnext) return GetBlockTime(); pindex = pindex->pnext; } return pindex->GetMedianTimePast(); } bool IsProofOfWork() const { return !(nFlags & BLOCK_PROOF_OF_STAKE); } bool IsProofOfStake() const { return (nFlags & BLOCK_PROOF_OF_STAKE); } void SetProofOfStake() { nFlags |= BLOCK_PROOF_OF_STAKE; } unsigned int GetStakeEntropyBit() const { return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1); } bool SetStakeEntropyBit(unsigned int nEntropyBit) { if (nEntropyBit > 1) return false; nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0); return true; } bool GeneratedStakeModifier() const { return (nFlags & BLOCK_STAKE_MODIFIER); } void SetStakeModifier(uint64 nModifier, bool fGeneratedStakeModifier) { nStakeModifier = nModifier; if (fGeneratedStakeModifier) nFlags |= BLOCK_STAKE_MODIFIER; } std::string ToString() const { return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, nMint=%s, nMoneySupply=%s, nFlags=(%s)(%d)(%s), nStakeModifier=%016"PRI64x", nStakeModifierChecksum=%08x, hashProofOfStake=%s, prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)", pprev, pnext, nFile, nBlockPos, nHeight, FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(), GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW", nStakeModifier, nStakeModifierChecksum, hashProofOfStake.ToString().c_str(), prevoutStake.ToString().c_str(), nStakeTime, hashMerkleRoot.ToString().substr(0,10).c_str(), GetBlockHash().ToString().substr(0,20).c_str()); } void print() const { printf("%s\n", ToString().c_str()); } }; /** Used to marshal pointers into hashes for db storage. */ class CDiskBlockIndex : public CBlockIndex { public: uint256 hashPrev; uint256 hashNext; CDiskBlockIndex() { hashPrev = 0; hashNext = 0; } explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) { hashPrev = (pprev ? pprev->GetBlockHash() : 0); hashNext = (pnext ? pnext->GetBlockHash() : 0); } IMPLEMENT_SERIALIZE ( if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(hashNext); READWRITE(nFile); READWRITE(nBlockPos); READWRITE(nHeight); READWRITE(nMint); READWRITE(nMoneySupply); READWRITE(nFlags); READWRITE(nStakeModifier); if (IsProofOfStake()) { READWRITE(prevoutStake); READWRITE(nStakeTime); READWRITE(hashProofOfStake); } else if (fRead) { const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull(); const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0; const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0; } // block header READWRITE(this->nVersion); READWRITE(hashPrev); READWRITE(hashMerkleRoot); READWRITE(nTime); READWRITE(nBits); READWRITE(nNonce); ) uint256 GetBlockHash() const { CBlock block; block.nVersion = nVersion; block.hashPrevBlock = hashPrev; block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; return block.GetHash(); } std::string ToString() const { std::string str = "CDiskBlockIndex("; str += CBlockIndex::ToString(); str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)", GetBlockHash().ToString().c_str(), hashPrev.ToString().substr(0,20).c_str(), hashNext.ToString().substr(0,20).c_str()); return str; } void print() const { printf("%s\n", ToString().c_str()); } }; /** Describes a place in the block chain to another node such that if the * other node doesn't have the same branch, it can find a recent common trunk. * The further back it is, the further before the fork it may be. */ class CBlockLocator { protected: std::vector<uint256> vHave; public: CBlockLocator() { } explicit CBlockLocator(const CBlockIndex* pindex) { Set(pindex); } explicit CBlockLocator(uint256 hashBlock) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end()) Set((*mi).second); } CBlockLocator(const std::vector<uint256>& vHaveIn) { vHave = vHaveIn; } IMPLEMENT_SERIALIZE ( if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(vHave); ) void SetNull() { vHave.clear(); } bool IsNull() { return vHave.empty(); } void Set(const CBlockIndex* pindex) { vHave.clear(); int nStep = 1; while (pindex) { vHave.push_back(pindex->GetBlockHash()); // Exponentially larger steps back for (int i = 0; pindex && i < nStep; i++) pindex = pindex->pprev; if (vHave.size() > 10) nStep *= 2; } vHave.push_back(hashGenesisBlock); } int GetDistanceBack() { // Retrace how far back it was in the sender's branch int nDistance = 0; int nStep = 1; BOOST_FOREACH(const uint256& hash, vHave) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) return nDistance; } nDistance += nStep; if (nDistance > 10) nStep *= 2; } return nDistance; } CBlockIndex* GetBlockIndex() { // Find the first block the caller has in the main chain BOOST_FOREACH(const uint256& hash, vHave) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) return pindex; } } return pindexGenesisBlock; } uint256 GetBlockHash() { // Find the first block the caller has in the main chain BOOST_FOREACH(const uint256& hash, vHave) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) return hash; } } return hashGenesisBlock; } int GetHeight() { CBlockIndex* pindex = GetBlockIndex(); if (!pindex) return 0; return pindex->nHeight; } }; /** Alerts are for notifying old versions if they become too obsolete and * need to upgrade. The message is displayed in the status bar. * Alert messages are broadcast as a vector of signed data. Unserializing may * not read the entire buffer if the alert is for a newer version, but older * versions can still relay the original data. */ class CUnsignedAlert { public: int nVersion; int64 nRelayUntil; // when newer nodes stop relaying to newer nodes int64 nExpiration; int nID; int nCancel; std::set<int> setCancel; int nMinVer; // lowest version inclusive int nMaxVer; // highest version inclusive std::set<std::string> setSubVer; // empty matches all int nPriority; // Actions std::string strComment; std::string strStatusBar; std::string strReserved; IMPLEMENT_SERIALIZE ( READWRITE(this->nVersion); nVersion = this->nVersion; READWRITE(nRelayUntil); READWRITE(nExpiration); READWRITE(nID); READWRITE(nCancel); READWRITE(setCancel); READWRITE(nMinVer); READWRITE(nMaxVer); READWRITE(setSubVer); READWRITE(nPriority); READWRITE(strComment); READWRITE(strStatusBar); READWRITE(strReserved); ) void SetNull() { nVersion = 1; nRelayUntil = 0; nExpiration = 0; nID = 0; nCancel = 0; setCancel.clear(); nMinVer = 0; nMaxVer = 0; setSubVer.clear(); nPriority = 0; strComment.clear(); strStatusBar.clear(); strReserved.clear(); } std::string ToString() const { std::string strSetCancel; BOOST_FOREACH(int n, setCancel) strSetCancel += strprintf("%d ", n); std::string strSetSubVer; BOOST_FOREACH(std::string str, setSubVer) strSetSubVer += "\"" + str + "\" "; return strprintf( "CAlert(\n" " nVersion = %d\n" " nRelayUntil = %"PRI64d"\n" " nExpiration = %"PRI64d"\n" " nID = %d\n" " nCancel = %d\n" " setCancel = %s\n" " nMinVer = %d\n" " nMaxVer = %d\n" " setSubVer = %s\n" " nPriority = %d\n" " strComment = \"%s\"\n" " strStatusBar = \"%s\"\n" ")\n", nVersion, nRelayUntil, nExpiration, nID, nCancel, strSetCancel.c_str(), nMinVer, nMaxVer, strSetSubVer.c_str(), nPriority, strComment.c_str(), strStatusBar.c_str()); } void print() const { printf("%s", ToString().c_str()); } }; /** An alert is a combination of a serialized CUnsignedAlert and a signature. */ class CAlert : public CUnsignedAlert { public: std::vector<unsigned char> vchMsg; std::vector<unsigned char> vchSig; CAlert() { SetNull(); } IMPLEMENT_SERIALIZE ( READWRITE(vchMsg); READWRITE(vchSig); ) void SetNull() { CUnsignedAlert::SetNull(); vchMsg.clear(); vchSig.clear(); } bool IsNull() const { return (nExpiration == 0); } uint256 GetHash() const { return SerializeHash(*this); } bool IsInEffect() const { return (GetAdjustedTime() < nExpiration); } bool Cancels(const CAlert& alert) const { if (!IsInEffect()) return false; // this was a no-op before 31403 return (alert.nID <= nCancel || setCancel.count(alert.nID)); } bool AppliesTo(int nVersion, std::string strSubVerIn) const { // TODO: rework for client-version-embedded-in-strSubVer ? return (IsInEffect() && nMinVer <= nVersion && nVersion <= nMaxVer && (setSubVer.empty() || setSubVer.count(strSubVerIn))); } bool AppliesToMe() const { return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>())); } bool RelayTo(CNode* pnode) const { if (!IsInEffect()) return false; // returns true if wasn't already contained in the set if (pnode->setKnown.insert(GetHash()).second) { if (AppliesTo(pnode->nVersion, pnode->strSubVer) || AppliesToMe() || GetAdjustedTime() < nRelayUntil) { pnode->PushMessage("alert", *this); return true; } } return false; } bool CheckSignature() { CKey key; if (!key.SetPubKey(ParseHex("04a0a849dd49b113d3179a332dd77715c43be4d0076e2f19e66de23dd707e56630f792f298dfd209bf042bb3561f4af6983f3d81e439737ab0bf7f898fecd21aab"))) return error("CAlert::CheckSignature() : SetPubKey failed"); if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig)) return error("CAlert::CheckSignature() : verify signature failed"); // Now unserialize the data CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION); sMsg >> *(CUnsignedAlert*)this; return true; } bool ProcessAlert(); }; class CTxMemPool { public: mutable CCriticalSection cs; std::map<uint256, CTransaction> mapTx; std::map<COutPoint, CInPoint> mapNextTx; bool accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs, bool* pfMissingInputs); bool addUnchecked(CTransaction &tx); bool remove(CTransaction &tx); void queryHashes(std::vector<uint256>& vtxid); unsigned long size() { LOCK(cs); return mapTx.size(); } bool exists(uint256 hash) { return (mapTx.count(hash) != 0); } CTransaction& lookup(uint256 hash) { return mapTx[hash]; } }; extern CTxMemPool mempool; #endif
2558d201f245c924696b0104b3eb79dc693c60cf
f14626611951a4f11a84cd71f5a2161cd144a53a
/Client/GameClient/ClientApp/Skills/SkillAI.cpp
d8aeed89d6633470c0c28b7db80c96f82b9df8d0
[]
no_license
Deadmanovi4/mmo-resourse
045616f9be76f3b9cd4a39605accd2afa8099297
1c310e15147ae775a59626aa5b5587c6895014de
refs/heads/master
2021-05-29T06:14:28.650762
2015-06-18T01:16:43
2015-06-18T01:16:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,361
cpp
#include "StdAfx.h" #include "SkillAI.h" #include "SkillXml.h" #include "NormalCloseInAttackAI.h" #include "RushAttackAI.h" #include "NormalLongDistanceAttackAI.h" #include "RandomSummonAI.h" #include "FixSummonAI.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif CSkillAI::CSkillAI(void) { } CSkillAI::~CSkillAI() { } void CSkillAI::AI() { } bool CSkillAI::Display() { return true; } bool CSkillAI::StepBeginAI(vector<long> vecType, vector<CGUID> vecID) { return true; } bool CSkillAI::StepRunAI(vector<long> vecType, vector<CGUID> vecID) { return true; } bool CSkillAI::StepEndAI() { return true; } CSkillAI* CSkillAI::CreateSkillAI(CSkillXml* pSkill, long lAI) { CSkillAI* pSkillAI = NULL; switch(lAI) { case 0: pSkillAI = new NormalCloseInAttackAI(pSkill); break; case 1: pSkillAI = new CRushAttackAI(pSkill); break; case 2: pSkillAI = new CNormalLongDistanceAttackAI(pSkill,CNormalLongDistanceAttackAI::FLY_TRACK); break; case 3: pSkillAI = new CRandomSummonAI(pSkill); break; case 4: pSkillAI = new CFixSummonAI(pSkill); break; case 5: pSkillAI = new CNormalLongDistanceAttackAI(pSkill,CNormalLongDistanceAttackAI::FLY_LOCK_LINE); break; default: pSkillAI = NULL; break; } return pSkillAI; }
295fa67ee93835a8710151f93f19c900487f28f3
4023bf31636e4ce892531440f660377964460b8f
/cpp/log/cms_verifier.h
ffbab79660d0ebc2e2d8201149ef4c1a47673df8
[ "Apache-2.0" ]
permissive
rutsky/certificate-transparency
c1e363ec9623161ab543ab9aafac2815c4017415
043d2309160f23be7a6a431132bce63d5853b4b9
refs/heads/master
2021-01-18T08:12:36.911349
2015-11-03T18:24:21
2015-11-03T18:24:21
45,531,176
1
0
null
2015-11-04T10:17:51
2015-11-04T10:17:51
null
UTF-8
C++
false
false
3,359
h
/* -*- mode: c++; indent-tabs-mode: nil -*- */ #ifndef CMS_VERIFIER_H #define CMS_VERIFIER_H #include <memory> #include <openssl/asn1.h> #include <openssl/bio.h> #include <openssl/cms.h> #include "base/macros.h" #include "log/cert.h" #include "util/openssl_util.h" // for LOG_OPENSSL_ERRORS #include "util/status.h" namespace cert_trans { class CmsVerifier { public: CmsVerifier() = default; virtual ~CmsVerifier() = default; // NOTE: CMS related API is provisional and may evolve over the near // future. Public API does not refer to OpenSSL CMS data objects to // allow for future use with alternate S/MIME implementations providing // CMS functionality. // Checks that a CMS_ContentInfo has a signer that matches a specified // certificate. Does not verify the signature or check the payload. virtual util::StatusOr<bool> IsCmsSignedByCert(BIO* cms_bio_in, const Cert& cert) const; // Checks that a CMS_ContentInfo has a signer that matches a specified // certificate. Does not verify the signature or check the payload. virtual util::StatusOr<bool> IsCmsSignedByCert(const std::string& cms_object, const Cert* cert) const; // Unpacks a CMS signed data object that is assumed to contain a certificate // Does not do any checks on signatures or cert validity at this point, // the caller must do these separately. Returns a new Cert object built from // the unpacked data, which will only be valid if we successfully unpacked // the CMS blob. virtual Cert* UnpackCmsSignedCertificate(const std::string& cms_object); // Unpacks a CMS signed data object that is assumed to contain a certificate // If the CMS signature verifies as being signed by the supplied Cert // then we return a corresponding new Cert object built from the unpacked // data. If it cannot be loaded as a certificate or fails CMS signing check // then an unloaded empty Cert object is returned. // The caller owns the returned certificate and must free the input bio. // NOTE: Certificate validity checks must be done separately. This // only checks that the CMS signature is validly made by the supplied // certificate. virtual Cert* UnpackCmsSignedCertificate(BIO* cms_bio_in, const Cert& verify_cert); private: // Verifies that data from a DER BIO is signed by a given certificate. // and writes the unwrapped content to another BIO. NULL can be passed for // cms_bio_out if the caller just wishes to verify the signature. Does // not free either BIO. Does not do any checks on the content of the // CMS message or validate that the CMS signature is trusted to root. util::Status UnpackCmsDerBio(BIO* cms_bio_in, const Cert& certChain, BIO* cms_bio_out); // Writes the unwrapped content from a CMS object to another BIO. Does // not free either BIO. Does not do any checks on the content of the // CMS message or validate that the CMS signature is trusted to root. // The unpacked data may not be a valid X.509 cert. The caller must // apply any additional checks necessary. util::Status UnpackCmsDerBio(BIO* cms_bio_in, BIO* cms_bio_out); DISALLOW_COPY_AND_ASSIGN(CmsVerifier); }; } // namespace cert_trans #endif
6832b771a135badfe746bde285006cca38d81302
8567438779e6af0754620a25d379c348e4cd5a5d
/content/renderer/media_recorder/video_track_recorder.h
895523d696eaf7e2f1d364762e7df8c8b45209f0
[ "BSD-3-Clause" ]
permissive
thngkaiyuan/chromium
c389ac4b50ccba28ee077cbf6115c41b547955ae
dab56a4a71f87f64ecc0044e97b4a8f247787a68
refs/heads/master
2022-11-10T02:50:29.326119
2017-04-08T12:28:57
2017-04-08T12:28:57
84,073,924
0
1
BSD-3-Clause
2022-10-25T19:47:15
2017-03-06T13:04:15
null
UTF-8
C++
false
false
3,587
h
// Copyright 2015 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. #ifndef CONTENT_RENDERER_MEDIA_RECORDER_VIDEO_TRACK_RECORDER_H_ #define CONTENT_RENDERER_MEDIA_RECORDER_VIDEO_TRACK_RECORDER_H_ #include <memory> #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_checker.h" #include "content/public/common/features.h" #include "content/public/renderer/media_stream_video_sink.h" #include "media/muxers/webm_muxer.h" #include "third_party/WebKit/public/platform/WebMediaStreamTrack.h" namespace media { class VideoFrame; } // namespace media namespace video_track_recorder { const int kVEAEncoderMinResolutionWidth = 640; const int kVEAEncoderMinResolutionHeight = 480; } // namespace video_track_recorder namespace content { // VideoTrackRecorder is a MediaStreamVideoSink that encodes the video frames // received from a Stream Video Track. This class is constructed and used on a // single thread, namely the main Render thread. This mirrors the other // MediaStreamVideo* classes that are constructed/configured on Main Render // thread but that pass frames on Render IO thread. It has an internal Encoder // with its own threading subtleties, see the implementation file. class CONTENT_EXPORT VideoTrackRecorder : NON_EXPORTED_BASE(public MediaStreamVideoSink) { public: // Do not change the order of codecs; add new ones right before LAST. enum class CodecId { VP8, VP9, #if BUILDFLAG(RTC_USE_H264) H264, #endif LAST }; class Encoder; using OnEncodedVideoCB = base::Callback<void(const media::WebmMuxer::VideoParameters& params, std::unique_ptr<std::string> encoded_data, base::TimeTicks capture_timestamp, bool is_key_frame)>; static CodecId GetPreferredCodecId(); VideoTrackRecorder(CodecId codec, const blink::WebMediaStreamTrack& track, const OnEncodedVideoCB& on_encoded_video_cb, int32_t bits_per_second); ~VideoTrackRecorder() override; void Pause(); void Resume(); void OnVideoFrameForTesting(const scoped_refptr<media::VideoFrame>& frame, base::TimeTicks capture_time); private: friend class VideoTrackRecorderTest; void InitializeEncoder(CodecId codec, const OnEncodedVideoCB& on_encoded_video_callback, int32_t bits_per_second, const scoped_refptr<media::VideoFrame>& frame, base::TimeTicks capture_time); // Used to check that we are destroyed on the same thread we were created. base::ThreadChecker main_render_thread_checker_; // We need to hold on to the Blink track to remove ourselves on dtor. blink::WebMediaStreamTrack track_; // Inner class to encode using whichever codec is configured. scoped_refptr<Encoder> encoder_; base::Callback<void(const scoped_refptr<media::VideoFrame>& frame, base::TimeTicks capture_time)> initialize_encoder_callback_; // Used to track the paused state during the initialization process. bool paused_before_init_; base::WeakPtrFactory<VideoTrackRecorder> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(VideoTrackRecorder); }; } // namespace content #endif // CONTENT_RENDERER_MEDIA_RECORDER_VIDEO_TRACK_RECORDER_H_
9262933ba5b7a106c0c9ca9b05639c481d4f8f9e
de9ac40cb8c7509c0372f96eec23f243349bedb1
/plugins/samplesource/airspy/airspygui.h
aca2de1e093425865210d1d87cd62554fabf5e44
[]
no_license
gaspar1987/sdrangel
260709c43cf8a9abbfe1c1cd0b9ad566abe1d767
e37c90c8d0ff246573380a0a3187579fe231ce63
refs/heads/master
2021-07-22T04:53:53.994410
2018-07-21T20:28:35
2018-07-21T20:28:35
143,798,261
3
0
null
2021-07-04T09:36:10
2018-08-07T00:35:17
C
UTF-8
C++
false
false
3,656
h
/////////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2015 Edouard Griffiths, F4EXB // // // // This program is free software; you can redistribute it and/or modify // // it under the terms of the GNU General Public License as published by // // the Free Software Foundation as version 3 of the License, or // // // // This program is distributed in the hope that it will be useful, // // but WITHOUT ANY WARRANTY; without even the implied warranty of // // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // // GNU General Public License V3 for more details. // // // // You should have received a copy of the GNU General Public License // // along with this program. If not, see <http://www.gnu.org/licenses/>. // /////////////////////////////////////////////////////////////////////////////////// #ifndef INCLUDE_AIRSPYGUI_H #define INCLUDE_AIRSPYGUI_H #include <plugin/plugininstancegui.h> #include <QTimer> #include <QWidget> #include "util/messagequeue.h" #include "airspyinput.h" class DeviceUISet; namespace Ui { class AirspyGui; class AirspySampleRates; } class AirspyGui : public QWidget, public PluginInstanceGUI { Q_OBJECT public: explicit AirspyGui(DeviceUISet *deviceUISet, QWidget* parent = 0); virtual ~AirspyGui(); virtual void destroy(); void setName(const QString& name); QString getName() const; void resetToDefaults(); virtual qint64 getCenterFrequency() const; virtual void setCenterFrequency(qint64 centerFrequency); QByteArray serialize() const; bool deserialize(const QByteArray& data); virtual MessageQueue* getInputMessageQueue() { return &m_inputMessageQueue; } virtual bool handleMessage(const Message& message); uint32_t getDevSampleRate(unsigned int index); int getDevSampleRateIndex(uint32_t sampleRate); private: Ui::AirspyGui* ui; DeviceUISet* m_deviceUISet; bool m_doApplySettings; bool m_forceSettings; AirspySettings m_settings; QTimer m_updateTimer; QTimer m_statusTimer; std::vector<uint32_t> m_rates; DeviceSampleSource* m_sampleSource; int m_sampleRate; quint64 m_deviceCenterFrequency; //!< Center frequency in device int m_lastEngineState; MessageQueue m_inputMessageQueue; void blockApplySettings(bool block) { m_doApplySettings = !block; } void displaySettings(); void displaySampleRates(); void sendSettings(); void updateSampleRateAndFrequency(); void updateFrequencyLimits(); private slots: void on_centerFrequency_changed(quint64 value); void on_LOppm_valueChanged(int value); void on_dcOffset_toggled(bool checked); void on_iqImbalance_toggled(bool checked); void on_sampleRate_currentIndexChanged(int index); void on_biasT_stateChanged(int state); void on_decim_currentIndexChanged(int index); void on_fcPos_currentIndexChanged(int index); void on_lna_valueChanged(int value); void on_mix_valueChanged(int value); void on_vga_valueChanged(int value); void on_lnaAGC_stateChanged(int state); void on_mixAGC_stateChanged(int state); void on_startStop_toggled(bool checked); void on_record_toggled(bool checked); void on_transverter_clicked(); void updateHardware(); void updateStatus(); void handleInputMessages(); }; #endif // INCLUDE_AIRSPYGUI_H
35d4434ab28bdb66ace94a9ea18f2589b24d9972
c93e0155fc42550af82485da58e0c70c816f329e
/Chapter 5 - Mathematics/Ad-Hoc/1- The Simpler Ones/10469.cpp
8146dfaba46602e3388710adb41294ecdf7035c7
[]
no_license
Rubix982/Personal-UVA-Solutions
f3ecc1885fbfebf9a1f20d574605187abeecab2a
fc5c2f178976bcd77fc54e037f75ff7a2503a965
refs/heads/master
2020-12-02T21:45:32.023877
2020-02-14T16:20:37
2020-02-14T16:20:37
231,129,540
1
1
null
null
null
null
UTF-8
C++
false
false
56
cpp
// To Carry Or Not To Carry, super simple if you use xor
19318e3456e18a1cfc3bcbdeb8af92a4dd5252f1
1806eaae69f944683e308348714efc4c470bb95c
/tools/KPFGen/src/fx.c
a95d471d75f2d70d4e03306ddfba3973fe97e050
[]
no_license
ayaz345/TurokEX
09b929f69918ffef9c45d6142fe7888e96d409d9
90589b4bd3c35e79ea42572e4c89dc335c5cfbfe
refs/heads/master
2023-07-10T20:56:47.643435
2014-06-20T01:59:44
2014-06-20T01:59:44
650,764,618
0
0
null
null
null
null
UTF-8
C++
false
false
24,403
c
// Emacs style mode select -*- C++ -*- //----------------------------------------------------------------------------- // // Copyright(C) 2012 Samuel Villarreal // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA // 02111-1307, USA. // //----------------------------------------------------------------------------- #include "types.h" #include "common.h" #include "rnc.h" #include "pak.h" #include "decoders.h" extern short texindexes[2000]; extern const char *sndfxnames[]; char *GetActionName(int id, float arg0); static byte *fxdata; #define CHUNK_DIRECTORY_VFX 20 #define CHUNK_VFX_CHUNKSIZE 0 #define CHUNK_VFX_DATA 4 #define CHUNK_VFX_INDEXES 8 #define CHUNK_VFX_EVENTS 12 #define CHUNK_VFX_INDEX_COUNT 4 #define CHUNK_VFX_DATA_OFFSETS 4 #define CHUNK_VFX_DATA_START 8 #define CHUNK_EVENTS_COUNT 4 #define CHUNK_EVENTS_START 8 #define FXF_FADEOUT 0x00001 #define FXF_UNKNOWN2 0x00002 #define FXF_STOPANIMONHIT 0x00004 #define FXF_FLOOROFFSET 0x00008 #define FXF_UNKNOWN5 0x00010 #define FXF_ADDOFFSET 0x00020 #define FXF_UNKNOWN7 0x00040 #define FXF_ACTORINSTANCE 0x00080 #define FXF_MIRROR 0x00100 #define FXF_UNKNOWN10 0x00200 #define FXF_UNKNOWN11 0x00400 #define FXF_UNKNOWN12 0x00800 #define FXF_SCALELERP 0x01000 #define FXF_UNKNOWN14 0x02000 #define FXF_DEPTHBUFFER 0x04000 #define FXF_UNKNOWN15 0x08000 #define FXF_UNKNOWN16 0x10000 #define FXF_DESTROYONWATER 0x20000 #define FXF_PROJECTILE 0x40000 #define FXF_LENSFLARES 0x80000 #define FXF_LOCALAXIS 0x100000 #define FXF_UNKNOWN21 0x200000 #define FXF_UNKNOWN22 0x400000 #define FXF_STICKONTARGET 0x800000 #define FXF_NODIRECTION 0x1000000 #define FXF_BLOOD 0x2000000 #define FXF_UNKNOWN26 0x4000000 #define FXF_UNKNOWN27 0x8000000 static int curfx = 0; typedef struct { short hitplane; short hitwater; short onhitmetal; short onhitstone; short onhitflesh; short onhitmonster; short onhitalien; short onhitlava; short onhitslime; short onhitforcefield; short onexpire; short active; short onexpirewater; short activewater; } fxbehavior_t; typedef struct { float f[14]; fxbehavior_t b_fx; fxbehavior_t b_action; fxbehavior_t b_sound; } fxevent_t; static float CoerceFloat(__int16 val) { union { int i; float f; } coerce_u; coerce_u.i = (val << 16); return coerce_u.f; } void FX_GetName(int index, char *name) { if(index == -1) { sprintf(name, "none"); return; } switch(index) { case 1: sprintf(name, "fx/projectile_arrow.kfx"); break; case 2: sprintf(name, "fx/projectile_bullet.kfx"); break; case 3: sprintf(name, "fx/projectile_shell.kfx"); break; case 4: sprintf(name, "fx/projectile_grenade.kfx"); break; case 5: sprintf(name, "fx/projectile_tekshot.kfx"); break; case 6: sprintf(name, "fx/projectile_fusionshot.kfx"); break; case 7: sprintf(name, "fx/bulletshell.kfx"); break; case 8: sprintf(name, "fx/shotshell.kfx"); break; case 9: sprintf(name, "fx/blood_gush1.kfx"); break; case 12: sprintf(name, "fx/projectile_grenade_explosion.kfx"); break; case 14: sprintf(name, "fx/impact_water_splash01.kfx"); break; case 16: sprintf(name, "fx/projectile_acid.kfx"); break; case 17: sprintf(name, "fx/projectile_trex_fire.kfx"); break; case 18: sprintf(name, "fx/projectile_redbubbles.kfx"); break; case 21: sprintf(name, "fx/projectile_greenblob.kfx"); break; case 22: sprintf(name, "fx/projectile_shockwave.kfx"); break; case 23: sprintf(name, "fx/projectile_shaman.kfx"); break; case 26: sprintf(name, "fx/projectile_enemy_bullet.kfx"); break; case 27: sprintf(name, "fx/projectile_enemy_tekshot.kfx"); break; case 28: sprintf(name, "fx/steppuff1.kfx"); break; case 29: sprintf(name, "fx/steppuff2.kfx"); break; case 30: sprintf(name, "fx/muzzle_rifle.kfx"); break; case 32: sprintf(name, "fx/muzzle_grenade_launcher.kfx"); break; case 38: sprintf(name, "fx/muzzle_pistol.kfx"); break; case 39: sprintf(name, "fx/muzzle_shotgun.kfx"); break; case 43: sprintf(name, "fx/projectile_flame.kfx"); break; case 44: sprintf(name, "fx/projectile_trex_laser_fire.kfx"); break; case 49: sprintf(name, "fx/projectile_enemy_shell.kfx"); break; case 50: sprintf(name, "fx/projectile_scatter_blast.kfx"); break; case 52: sprintf(name, "fx/blood_death.kfx"); break; case 54: sprintf(name, "fx/sparks_damage.kfx"); break; case 57: sprintf(name, "fx/blood_splatter1.kfx"); break; case 81: sprintf(name, "fx/ambience_green_fountain.kfx"); break; case 84: sprintf(name, "fx/ambience_waterfall_steam.kfx"); break; case 91: sprintf(name, "fx/projectile_rocket_explosion.kfx"); break; case 92: sprintf(name, "fx/projectile_rocket_smoketrail.kfx"); break; case 101: sprintf(name, "fx/projectile_pulseshot_impact.kfx"); break; case 108: sprintf(name, "fx/ambience_underwater_bubbles.kfx"); break; case 116: sprintf(name, "fx/projectile_rocket.kfx"); break; case 117: sprintf(name, "fx/projectile_particleshot_1.kfx"); break; case 120: sprintf(name, "fx/projectile_pulseshot.kfx"); break; case 121: sprintf(name, "fx/impact_bubbles.kfx"); break; case 127: sprintf(name, "fx/projectile_greenblob_trail.kfx"); break; case 128: sprintf(name, "fx/projectile_greenblob_explode.kfx"); break; case 132: sprintf(name, "fx/projectile_tekarrow_explode.kfx"); break; case 166: sprintf(name, "fx/ambience_bubbles01.kfx"); break; case 186: sprintf(name, "fx/projectile_grenade_explosion_water.kfx"); break; case 189: sprintf(name, "fx/impact_water_splash02.kfx"); break; case 192: sprintf(name, "fx/bubble_trail01.kfx"); break; case 193: sprintf(name, "fx/projectile_shellexp.kfx"); break; case 194: sprintf(name, "fx/projectile_tekarrow.kfx"); break; case 196: sprintf(name, "fx/shotshellexp.kfx"); break; case 198: sprintf(name, "fx/projectile_particleshot_2.kfx"); break; case 199: sprintf(name, "fx/projectile_particleshot_3.kfx"); break; case 200: sprintf(name, "fx/projectile_particleshot_4.kfx"); break; case 201: sprintf(name, "fx/projectile_particleshot_5.kfx"); break; case 229: sprintf(name, "fx/projectile_hummer_bullet_1.kfx"); break; case 230: sprintf(name, "fx/projectile_trex_rockets.kfx"); break; case 254: sprintf(name, "fx/blood_spurt1.kfx"); break; case 255: sprintf(name, "fx/projectile_pulseshot_trail.kfx"); break; case 264: sprintf(name, "fx/projectile_enemy_pulseshot.kfx"); break; case 285: sprintf(name, "fx/ambience_tall_fire1.kfx"); break; case 286: sprintf(name, "fx/ambience_tall_fire2.kfx"); break; case 303: sprintf(name, "fx/projectile_minibullet.kfx"); break; case 306: sprintf(name, "fx/pickup_powerup.kfx"); break; case 309: sprintf(name, "fx/electric_spaz.kfx"); break; case 310: sprintf(name, "fx/projectile_chronoblast.kfx"); break; case 333: sprintf(name, "fx/ambience_waterfall_bubbles.kfx"); break; case 344: sprintf(name, "fx/pickup_key_sparkles.kfx"); break; case 359: sprintf(name, "fx/ambience_thunderstorm.kfx"); break; case 362: sprintf(name, "fx/hummer_explosion.kfx"); break; case 374: sprintf(name, "fx/animal_death_flash.kfx"); break; default: sprintf(name, "fx/fx_%03d.kfx", index); break; } } static char *FX_GetDamageClass(int id, float arg0) { static char damageClass[128]; int iArg0 = (int)arg0; strcpy(damageClass, va("defs/damage.def@damageClass_%03d_%i", id, iArg0)); return damageClass; } static dboolean FX_CanDamage(fxevent_t *fxevent) { return (fxevent->b_action.onhitalien != -1 || fxevent->b_action.onhitflesh != -1 || fxevent->b_action.onhitforcefield != -1 || fxevent->b_action.onhitlava != -1 || fxevent->b_action.onhitmetal != -1 || fxevent->b_action.onhitmonster != -1 || fxevent->b_action.onhitslime != -1 || fxevent->b_action.onhitstone != -1); } static void FX_WriteEvents(fxevent_t *fxevent, const char *eventName, short fxEvent, short soundEvent, short actionEvent, short actionSlot) { char name[256]; if(fxEvent != -1 || soundEvent != -1 || actionEvent != -1) { Com_Strcat(" %s\n", eventName); Com_Strcat(" {\n"); if(fxEvent != -1) { FX_GetName(fxEvent, name); Com_Strcat(" fx = \"%s\"\n", name); } if(soundEvent != -1) { Com_Strcat(" sound = \"sounds/shaders/%s.ksnd\"\n", sndfxnames[soundEvent]); } if(actionEvent != -1) { float evf; evf = fxevent->f[actionSlot]; //Com_Strcat(" action = { \"%s\" %f }\n", //GetActionName(actionEvent, evf), evf); Com_Strcat(" damageDef = \"%s\"\n", FX_GetDamageClass(actionEvent, evf)); } Com_Strcat(" }\n"); } } static void FX_PrintFlag(const char *flagName, const int flags, const int bit) { if(flags & bit) Com_Strcat(" %s = 1\n", flagName); } static void FX_PrintInt(const char *name, short val) { if(val != 0) Com_Strcat(" %s = %i\n", name, val); } static void FX_PrintFloat(const char *name, short val) { float f = CoerceFloat(val); if(f != 0) Com_Strcat(" %s = %f\n", name, f); } static void FX_PrintVector(const char *name, short *val) { if(curfx == 255 && !strcmp(name, "offset")) { // stupid view offset hack for projectile_pulseshot_trail Com_Strcat(" %s = { 0.0 0.0 6.375 }\n", name); } else { float f1 = CoerceFloat(val[0]); float f2 = CoerceFloat(val[1]); float f3 = CoerceFloat(val[2]); // another stupid hack if(curfx == 310 && !strcmp(name, "offset")) { f1 = -f1; } if(f1 != 0 || f2 != 0 || f3 != 0) Com_Strcat(" %s = { %f %f %f }\n", name, f1, f2, f3); } } void FX_StoreParticleEffects(void) { byte *tmp; byte *indexes; byte *data; byte *events; int count; int size; int i; int j; char name[256]; fxevent_t *fxevents; tmp = Com_GetCartData(cartfile, CHUNK_DIRECTORY_VFX, &size); fxdata = RNC_ParseFile(tmp, size, 0); indexes = Com_GetCartData(fxdata, CHUNK_VFX_INDEXES, 0); count = Com_GetCartOffset(indexes, CHUNK_VFX_INDEX_COUNT, 0); data = Com_GetCartData(fxdata, CHUNK_VFX_DATA, 0); events = Com_GetCartData(fxdata, CHUNK_VFX_EVENTS, 0); fxevents = (fxevent_t*)(events + 8); PK_AddFolder("fx/"); //StoreExternalFile("fx/muzzle_pistol.kfx", "fx/muzzle_pistol.kfx"); //StoreExternalFile("fx/muzzle_rifle.kfx", "fx/muzzle_rifle.kfx"); //StoreExternalFile("fx/muzzle_shotgun.kfx", "fx/muzzle_shotgun.kfx"); for(i = 0, j = 0; i < count; i++) { int start; int end; if(DC_LookupParticleFX(data + CHUNK_VFX_DATA_START, *((int*)data + 1), i, &start, &end)) { Com_StrcatClear(); Com_SetDataProgress(1); curfx = i; Com_Strcat("fx[%i] =\n{\n", (end-start)+1); while(start <= end) { byte *fxchunk; short *vfx; int flags; int k; fxevent_t *fxevent; fxchunk = Com_GetCartData(fxdata, CHUNK_VFX_DATA_START, 0); vfx = (short*)((fxchunk + 8) + 104 * start); fxevent = &fxevents[vfx[0]]; flags = vfx[2] | (vfx[3] << 16); Com_Strcat(" {\n"); FX_PrintFlag("bFadeout", flags, FXF_FADEOUT); FX_PrintFlag("bStopAnimOnImpact", flags, FXF_STOPANIMONHIT); FX_PrintFlag("bOffsetFromFloor", flags, FXF_FLOOROFFSET); FX_PrintFlag("bTextureWrapMirror", flags, FXF_MIRROR); FX_PrintFlag("bDepthBuffer", flags, FXF_DEPTHBUFFER); FX_PrintFlag("bActorInstance", flags, FXF_ACTORINSTANCE); FX_PrintFlag("bScaleLerp", flags, FXF_SCALELERP); FX_PrintFlag("bLensFlares", flags, FXF_LENSFLARES); FX_PrintFlag("bBlood", flags, FXF_BLOOD); FX_PrintFlag("bAddOffset", flags, FXF_ADDOFFSET); FX_PrintFlag("bNoDirection", flags, FXF_NODIRECTION); FX_PrintFlag("bLocalAxis", flags, FXF_LOCALAXIS); FX_PrintFlag("bProjectile", flags, FXF_PROJECTILE); FX_PrintFlag("bDestroyOnWaterSurface", flags, FXF_DESTROYONWATER); if(FX_CanDamage(fxevent)) Com_Strcat(" bLinkArea = 1\n"); FX_PrintFloat("mass", vfx[4]); FX_PrintFloat("translation_global_randomscale", vfx[5]); FX_PrintVector("translation_randomscale", &vfx[6]); FX_PrintVector("translation", &vfx[9]); FX_PrintFloat("gravity", vfx[12]); FX_PrintFloat("gravity_randomscale", vfx[13]); FX_PrintFloat("friction", vfx[14]); FX_PrintFloat("animFriction", vfx[15]); FX_PrintFloat("scale", vfx[18]); FX_PrintFloat("scale_randomscale", vfx[19]); FX_PrintFloat("scale_dest", vfx[20]); FX_PrintFloat("scale_dest_randomscale", vfx[21]); FX_PrintFloat("forward_speed", vfx[22]); FX_PrintFloat("forward_speed_randomscale", vfx[23]); FX_PrintVector("offset_random", &vfx[24]); FX_PrintFloat("rotation_offset", vfx[27]); FX_PrintFloat("rotation_offset_randomscale", vfx[28]); FX_PrintFloat("rotation_speed", vfx[29]); FX_PrintFloat("rotation_speed_randomscale", vfx[30]); FX_PrintFloat("screen_offset_x", vfx[31]); FX_PrintFloat("screen_offset_y", vfx[32]); FX_PrintVector("offset", &vfx[33]); Com_Strcat(" shader = \"defs/shaders.def@worldfx\"\n"); if(flags & FXF_LENSFLARES) Com_Strcat(" lensFlares = \"lensflares/turoklens.klf\"\n"); Com_Strcat(" textures[%i] =\n", texindexes[vfx[36]]); Com_Strcat(" {\n"); for(k = 0; k < texindexes[vfx[36]]; k++) Com_Strcat(" \"textures/tex%04d_%02d.tga\"\n", vfx[36], k); Com_Strcat(" }\n"); FX_PrintInt("instances", vfx[37]); FX_PrintInt("instances_randomscale", vfx[38]); FX_PrintInt("lifetime", vfx[39]); FX_PrintInt("lifetime_randomscale", vfx[40]); FX_PrintInt("restart", vfx[41]); FX_PrintInt("animspeed", vfx[42] & 0xff); Com_Strcat(" color1 = [%i %i %i]\n", (vfx[44] >> 8) & 0xff, vfx[45] & 0xff, (vfx[45] >> 8) & 0xff); Com_Strcat(" color2 = [%i %i %i]\n", vfx[46] & 0xff, (vfx[46] >> 8) & 0xff, vfx[47] & 0xff); FX_PrintInt("color1_randomscale", (vfx[47] >> 8) & 0xff); FX_PrintInt("color2_randomscale", (vfx[48] >> 8) & 0xff); FX_PrintInt("saturation_randomscale", vfx[48] & 0xff); FX_PrintInt("fadein_time", (vfx[50] >> 8) & 0xff); FX_PrintInt("fadeout_time", vfx[51]); switch((vfx[42] >> 8) & 0xff) { case 0: Com_Strcat(" ontouch = default\n"); break; case 1: Com_Strcat(" ontouch = destroy\n"); break; case 2: Com_Strcat(" ontouch = reflect\n"); break; case 3: Com_Strcat(" onplane = bounce\n"); break; default: Com_Strcat(" // ontouch = unknown_%i\n", (vfx[42] >> 8) & 0xff); break; } switch((vfx[43] >> 8) & 0xff) { case 0: Com_Strcat(" onplane = default\n"); break; case 1: Com_Strcat(" onplane = destroy\n"); break; case 2: Com_Strcat(" onplane = reflect\n"); break; case 3: Com_Strcat(" onplane = bounce\n"); break; default: Com_Strcat(" // onplane = unknown_%i\n", (vfx[43] >> 8) & 0xff); break; } if((vfx[50] & 0xff) == 3) Com_Strcat(" drawtype = hidden\n"); else { switch(vfx[44] & 0xff) { case 0: Com_Strcat(" drawtype = default\n"); break; case 1: Com_Strcat(" drawtype = flat\n"); break; case 2: Com_Strcat(" drawtype = decal\n"); break; case 4: Com_Strcat(" drawtype = surface\n"); break; case 5: Com_Strcat(" drawtype = billboard\n"); break; default: Com_Strcat(" // drawtype = unknown_%i\n", vfx[44] & 0xff); break; } } switch((vfx[49] >> 8) & 0xff) { case 0: Com_Strcat(" animtype = default\n"); break; case 1: Com_Strcat(" animtype = onetime\n"); break; case 2: Com_Strcat(" animtype = loop\n"); break; case 3: Com_Strcat(" animtype = sinwave\n"); break; case 4: Com_Strcat(" animtype = drawsingleframe\n"); break; default: Com_Strcat(" // animtype = unknown_%i\n", (vfx[49] >> 8) & 0xff); break; } // fxevent ## 11 appears to be blank, so we'll just // take advantage of that if(vfx[0] != 11) { Com_Strcat(" onImpact\n"); Com_Strcat(" {\n"); FX_WriteEvents(fxevent, "[0]", fxevent->b_fx.hitplane, fxevent->b_sound.hitplane, fxevent->b_action.hitplane, 0); FX_WriteEvents(fxevent, "[2]", fxevent->b_fx.onhitmetal, fxevent->b_sound.onhitmetal, fxevent->b_action.onhitmetal, 2); FX_WriteEvents(fxevent, "[3]", fxevent->b_fx.onhitstone, fxevent->b_sound.onhitstone, fxevent->b_action.onhitstone, 3); FX_WriteEvents(fxevent, "[4]", fxevent->b_fx.onhitflesh, fxevent->b_sound.onhitflesh, fxevent->b_action.onhitflesh, 4); FX_WriteEvents(fxevent, "[5]", fxevent->b_fx.onhitmonster, fxevent->b_sound.onhitmonster, fxevent->b_action.onhitmonster, 5); FX_WriteEvents(fxevent, "[6]", fxevent->b_fx.onhitalien, fxevent->b_sound.onhitalien, fxevent->b_action.onhitalien, 6); FX_WriteEvents(fxevent, "[7]", fxevent->b_fx.onhitlava, fxevent->b_sound.onhitlava, fxevent->b_action.onhitlava, 7); FX_WriteEvents(fxevent, "[8]", fxevent->b_fx.onhitslime, fxevent->b_sound.onhitslime, fxevent->b_action.onhitslime, 8); FX_WriteEvents(fxevent, "[9]", fxevent->b_fx.onhitforcefield, fxevent->b_sound.onhitforcefield, fxevent->b_action.onhitforcefield, 9); Com_Strcat(" }\n"); } FX_WriteEvents(fxevent, "onTick", fxevent->b_fx.active, fxevent->b_sound.active, fxevent->b_action.active, 11); FX_WriteEvents(fxevent, "onExpire", fxevent->b_fx.onexpire, fxevent->b_sound.onexpire, fxevent->b_action.onexpire, 10); FX_WriteEvents(fxevent, "onWaterImpact", fxevent->b_fx.hitwater, fxevent->b_sound.hitwater, fxevent->b_action.hitwater, 1); FX_WriteEvents(fxevent, "onWaterTick", fxevent->b_fx.activewater, fxevent->b_sound.activewater, fxevent->b_action.activewater, 13); FX_WriteEvents(fxevent, "onWaterExpire", fxevent->b_fx.onexpirewater, fxevent->b_sound.onexpirewater, fxevent->b_action.onexpirewater, 12); Com_Strcat(" }\n"); start++; } Com_Strcat("}\n"); FX_GetName(i, name); Com_StrcatAddToFile(name); j++; } } Com_Free(&fxdata); }
758bc5c3a7354aae2d93ad4180ab0f49441702fa
5a60d60fca2c2b8b44d602aca7016afb625bc628
/aws-cpp-sdk-sesv2/include/aws/sesv2/model/GetConfigurationSetEventDestinationsResult.h
57385fc5c2b3b061b81081b67ae98b8fe28a284d
[ "Apache-2.0", "MIT", "JSON" ]
permissive
yuatpocketgems/aws-sdk-cpp
afaa0bb91b75082b63236cfc0126225c12771ed0
a0dcbc69c6000577ff0e8171de998ccdc2159c88
refs/heads/master
2023-01-23T10:03:50.077672
2023-01-04T22:42:53
2023-01-04T22:42:53
134,497,260
0
1
null
2018-05-23T01:47:14
2018-05-23T01:47:14
null
UTF-8
C++
false
false
3,332
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/sesv2/SESV2_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/sesv2/model/EventDestination.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace SESV2 { namespace Model { /** * <p>Information about an event destination for a configuration set.</p><p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/sesv2-2019-09-27/GetConfigurationSetEventDestinationsResponse">AWS * API Reference</a></p> */ class GetConfigurationSetEventDestinationsResult { public: AWS_SESV2_API GetConfigurationSetEventDestinationsResult(); AWS_SESV2_API GetConfigurationSetEventDestinationsResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); AWS_SESV2_API GetConfigurationSetEventDestinationsResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p>An array that includes all of the events destinations that have been * configured for the configuration set.</p> */ inline const Aws::Vector<EventDestination>& GetEventDestinations() const{ return m_eventDestinations; } /** * <p>An array that includes all of the events destinations that have been * configured for the configuration set.</p> */ inline void SetEventDestinations(const Aws::Vector<EventDestination>& value) { m_eventDestinations = value; } /** * <p>An array that includes all of the events destinations that have been * configured for the configuration set.</p> */ inline void SetEventDestinations(Aws::Vector<EventDestination>&& value) { m_eventDestinations = std::move(value); } /** * <p>An array that includes all of the events destinations that have been * configured for the configuration set.</p> */ inline GetConfigurationSetEventDestinationsResult& WithEventDestinations(const Aws::Vector<EventDestination>& value) { SetEventDestinations(value); return *this;} /** * <p>An array that includes all of the events destinations that have been * configured for the configuration set.</p> */ inline GetConfigurationSetEventDestinationsResult& WithEventDestinations(Aws::Vector<EventDestination>&& value) { SetEventDestinations(std::move(value)); return *this;} /** * <p>An array that includes all of the events destinations that have been * configured for the configuration set.</p> */ inline GetConfigurationSetEventDestinationsResult& AddEventDestinations(const EventDestination& value) { m_eventDestinations.push_back(value); return *this; } /** * <p>An array that includes all of the events destinations that have been * configured for the configuration set.</p> */ inline GetConfigurationSetEventDestinationsResult& AddEventDestinations(EventDestination&& value) { m_eventDestinations.push_back(std::move(value)); return *this; } private: Aws::Vector<EventDestination> m_eventDestinations; }; } // namespace Model } // namespace SESV2 } // namespace Aws
f8ae862433ad2b6ad929003cf7edfda349ec38d2
1d0097e25c983c764be6871c4e9d19acd83c9a6d
/llvm-3.2.src/lib/Target/MBlaze/MBlazeInstrInfo.cpp
b5025fc8ee6c845903f40daee4febdc31634f521
[ "LicenseRef-scancode-unknown-license-reference", "NCSA" ]
permissive
smowton/llpe
16a695782bebbeadfd1abed770d0928e464edb39
8905aeda642c5d7e5cd3fb757c3e9897b62d0028
refs/heads/master
2022-03-11T23:08:18.465994
2020-09-16T07:49:12
2020-09-16T07:49:12
1,102,256
50
10
NOASSERTION
2020-09-16T07:49:13
2010-11-22T12:52:25
C++
UTF-8
C++
false
false
11,254
cpp
//===-- MBlazeInstrInfo.cpp - MBlaze Instruction Information --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains the MBlaze implementation of the TargetInstrInfo class. // //===----------------------------------------------------------------------===// #include "MBlazeInstrInfo.h" #include "MBlazeTargetMachine.h" #include "MBlazeMachineFunction.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/ScoreboardHazardRecognizer.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/ADT/STLExtras.h" #define GET_INSTRINFO_CTOR #include "MBlazeGenInstrInfo.inc" using namespace llvm; MBlazeInstrInfo::MBlazeInstrInfo(MBlazeTargetMachine &tm) : MBlazeGenInstrInfo(MBlaze::ADJCALLSTACKDOWN, MBlaze::ADJCALLSTACKUP), TM(tm), RI(*TM.getSubtargetImpl(), *this) {} static bool isZeroImm(const MachineOperand &op) { return op.isImm() && op.getImm() == 0; } /// isLoadFromStackSlot - If the specified machine instruction is a direct /// load from a stack slot, return the virtual or physical register number of /// the destination along with the FrameIndex of the loaded stack slot. If /// not, return 0. This predicate must return 0 if the instruction has /// any side effects other than loading from the stack slot. unsigned MBlazeInstrInfo:: isLoadFromStackSlot(const MachineInstr *MI, int &FrameIndex) const { if (MI->getOpcode() == MBlaze::LWI) { if ((MI->getOperand(1).isFI()) && // is a stack slot (MI->getOperand(2).isImm()) && // the imm is zero (isZeroImm(MI->getOperand(2)))) { FrameIndex = MI->getOperand(1).getIndex(); return MI->getOperand(0).getReg(); } } return 0; } /// isStoreToStackSlot - If the specified machine instruction is a direct /// store to a stack slot, return the virtual or physical register number of /// the source reg along with the FrameIndex of the loaded stack slot. If /// not, return 0. This predicate must return 0 if the instruction has /// any side effects other than storing to the stack slot. unsigned MBlazeInstrInfo:: isStoreToStackSlot(const MachineInstr *MI, int &FrameIndex) const { if (MI->getOpcode() == MBlaze::SWI) { if ((MI->getOperand(1).isFI()) && // is a stack slot (MI->getOperand(2).isImm()) && // the imm is zero (isZeroImm(MI->getOperand(2)))) { FrameIndex = MI->getOperand(1).getIndex(); return MI->getOperand(0).getReg(); } } return 0; } /// insertNoop - If data hazard condition is found insert the target nop /// instruction. void MBlazeInstrInfo:: insertNoop(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const { DebugLoc DL; BuildMI(MBB, MI, DL, get(MBlaze::NOP)); } void MBlazeInstrInfo:: copyPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, DebugLoc DL, unsigned DestReg, unsigned SrcReg, bool KillSrc) const { llvm::BuildMI(MBB, I, DL, get(MBlaze::ADDK), DestReg) .addReg(SrcReg, getKillRegState(KillSrc)).addReg(MBlaze::R0); } void MBlazeInstrInfo:: storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, unsigned SrcReg, bool isKill, int FI, const TargetRegisterClass *RC, const TargetRegisterInfo *TRI) const { DebugLoc DL; BuildMI(MBB, I, DL, get(MBlaze::SWI)).addReg(SrcReg,getKillRegState(isKill)) .addFrameIndex(FI).addImm(0); //.addFrameIndex(FI); } void MBlazeInstrInfo:: loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, unsigned DestReg, int FI, const TargetRegisterClass *RC, const TargetRegisterInfo *TRI) const { DebugLoc DL; BuildMI(MBB, I, DL, get(MBlaze::LWI), DestReg) .addFrameIndex(FI).addImm(0); //.addFrameIndex(FI); } //===----------------------------------------------------------------------===// // Branch Analysis //===----------------------------------------------------------------------===// bool MBlazeInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl<MachineOperand> &Cond, bool AllowModify) const { // If the block has no terminators, it just falls into the block after it. MachineBasicBlock::iterator I = MBB.end(); if (I == MBB.begin()) return false; --I; while (I->isDebugValue()) { if (I == MBB.begin()) return false; --I; } if (!isUnpredicatedTerminator(I)) return false; // Get the last instruction in the block. MachineInstr *LastInst = I; // If there is only one terminator instruction, process it. unsigned LastOpc = LastInst->getOpcode(); if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) { if (MBlaze::isUncondBranchOpcode(LastOpc)) { TBB = LastInst->getOperand(0).getMBB(); return false; } if (MBlaze::isCondBranchOpcode(LastOpc)) { // Block ends with fall-through condbranch. TBB = LastInst->getOperand(1).getMBB(); Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode())); Cond.push_back(LastInst->getOperand(0)); return false; } // Otherwise, don't know what this is. return true; } // Get the instruction before it if it's a terminator. MachineInstr *SecondLastInst = I; // If there are three terminators, we don't know what sort of block this is. if (SecondLastInst && I != MBB.begin() && isUnpredicatedTerminator(--I)) return true; // If the block ends with something like BEQID then BRID, handle it. if (MBlaze::isCondBranchOpcode(SecondLastInst->getOpcode()) && MBlaze::isUncondBranchOpcode(LastInst->getOpcode())) { TBB = SecondLastInst->getOperand(1).getMBB(); Cond.push_back(MachineOperand::CreateImm(SecondLastInst->getOpcode())); Cond.push_back(SecondLastInst->getOperand(0)); FBB = LastInst->getOperand(0).getMBB(); return false; } // If the block ends with two unconditional branches, handle it. // The second one is not executed, so remove it. if (MBlaze::isUncondBranchOpcode(SecondLastInst->getOpcode()) && MBlaze::isUncondBranchOpcode(LastInst->getOpcode())) { TBB = SecondLastInst->getOperand(0).getMBB(); I = LastInst; if (AllowModify) I->eraseFromParent(); return false; } // Otherwise, can't handle this. return true; } unsigned MBlazeInstrInfo:: InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, const SmallVectorImpl<MachineOperand> &Cond, DebugLoc DL) const { // Shouldn't be a fall through. assert(TBB && "InsertBranch must not be told to insert a fallthrough"); assert((Cond.size() == 2 || Cond.size() == 0) && "MBlaze branch conditions have two components!"); unsigned Opc = MBlaze::BRID; if (!Cond.empty()) Opc = (unsigned)Cond[0].getImm(); if (FBB == 0) { if (Cond.empty()) // Unconditional branch BuildMI(&MBB, DL, get(Opc)).addMBB(TBB); else // Conditional branch BuildMI(&MBB, DL, get(Opc)).addReg(Cond[1].getReg()).addMBB(TBB); return 1; } BuildMI(&MBB, DL, get(Opc)).addReg(Cond[1].getReg()).addMBB(TBB); BuildMI(&MBB, DL, get(MBlaze::BRID)).addMBB(FBB); return 2; } unsigned MBlazeInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const { MachineBasicBlock::iterator I = MBB.end(); if (I == MBB.begin()) return 0; --I; while (I->isDebugValue()) { if (I == MBB.begin()) return 0; --I; } if (!MBlaze::isUncondBranchOpcode(I->getOpcode()) && !MBlaze::isCondBranchOpcode(I->getOpcode())) return 0; // Remove the branch. I->eraseFromParent(); I = MBB.end(); if (I == MBB.begin()) return 1; --I; if (!MBlaze::isCondBranchOpcode(I->getOpcode())) return 1; // Remove the branch. I->eraseFromParent(); return 2; } bool MBlazeInstrInfo::ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const { assert(Cond.size() == 2 && "Invalid MBlaze branch opcode!"); switch (Cond[0].getImm()) { default: return true; case MBlaze::BEQ: Cond[0].setImm(MBlaze::BNE); return false; case MBlaze::BNE: Cond[0].setImm(MBlaze::BEQ); return false; case MBlaze::BGT: Cond[0].setImm(MBlaze::BLE); return false; case MBlaze::BGE: Cond[0].setImm(MBlaze::BLT); return false; case MBlaze::BLT: Cond[0].setImm(MBlaze::BGE); return false; case MBlaze::BLE: Cond[0].setImm(MBlaze::BGT); return false; case MBlaze::BEQI: Cond[0].setImm(MBlaze::BNEI); return false; case MBlaze::BNEI: Cond[0].setImm(MBlaze::BEQI); return false; case MBlaze::BGTI: Cond[0].setImm(MBlaze::BLEI); return false; case MBlaze::BGEI: Cond[0].setImm(MBlaze::BLTI); return false; case MBlaze::BLTI: Cond[0].setImm(MBlaze::BGEI); return false; case MBlaze::BLEI: Cond[0].setImm(MBlaze::BGTI); return false; case MBlaze::BEQD: Cond[0].setImm(MBlaze::BNED); return false; case MBlaze::BNED: Cond[0].setImm(MBlaze::BEQD); return false; case MBlaze::BGTD: Cond[0].setImm(MBlaze::BLED); return false; case MBlaze::BGED: Cond[0].setImm(MBlaze::BLTD); return false; case MBlaze::BLTD: Cond[0].setImm(MBlaze::BGED); return false; case MBlaze::BLED: Cond[0].setImm(MBlaze::BGTD); return false; case MBlaze::BEQID: Cond[0].setImm(MBlaze::BNEID); return false; case MBlaze::BNEID: Cond[0].setImm(MBlaze::BEQID); return false; case MBlaze::BGTID: Cond[0].setImm(MBlaze::BLEID); return false; case MBlaze::BGEID: Cond[0].setImm(MBlaze::BLTID); return false; case MBlaze::BLTID: Cond[0].setImm(MBlaze::BGEID); return false; case MBlaze::BLEID: Cond[0].setImm(MBlaze::BGTID); return false; } } /// getGlobalBaseReg - Return a virtual register initialized with the /// the global base register value. Output instructions required to /// initialize the register in the function entry block, if necessary. /// unsigned MBlazeInstrInfo::getGlobalBaseReg(MachineFunction *MF) const { MBlazeFunctionInfo *MBlazeFI = MF->getInfo<MBlazeFunctionInfo>(); unsigned GlobalBaseReg = MBlazeFI->getGlobalBaseReg(); if (GlobalBaseReg != 0) return GlobalBaseReg; // Insert the set of GlobalBaseReg into the first MBB of the function MachineBasicBlock &FirstMBB = MF->front(); MachineBasicBlock::iterator MBBI = FirstMBB.begin(); MachineRegisterInfo &RegInfo = MF->getRegInfo(); const TargetInstrInfo *TII = MF->getTarget().getInstrInfo(); GlobalBaseReg = RegInfo.createVirtualRegister(&MBlaze::GPRRegClass); BuildMI(FirstMBB, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), GlobalBaseReg).addReg(MBlaze::R20); RegInfo.addLiveIn(MBlaze::R20); MBlazeFI->setGlobalBaseReg(GlobalBaseReg); return GlobalBaseReg; }
be36c7f402a0f6a4e1a95eee0614e1688beef058
51e2e702104e2420a9621e085a8dea4edc5c7299
/Templates/SoundTemplate.cpp
e11cc5f55899d3f3c225cb14e24e4643aa56b536
[ "MIT" ]
permissive
lockathan/centerspace
ade06d865ccdd8292307c65a96a792bea7562e4c
74f04b2d5bf31b64924e31d5759a24651484120c
refs/heads/main
2023-07-13T02:54:36.785667
2021-08-16T06:35:58
2021-08-16T06:35:58
392,587,714
1
0
null
null
null
null
UTF-8
C++
false
false
459
cpp
#include <Templates/SoundTemplate.h> #include <string> #include <hash_map> SoundTemplate::SoundTemplate() : Template(), mFileName(""), mLoop(false) { } SoundTemplate::~SoundTemplate() { } std::string& SoundTemplate::getFileName() { return mFileName; } void SoundTemplate::setFileName(const std::string& fileName) { mFileName = fileName; } bool SoundTemplate::loop() { return mLoop; } void SoundTemplate::setLoop(bool loop) { mLoop = loop; }
9fa3d9d6ed30150ec7d4c304df5aefc09ab2f978
88ae8695987ada722184307301e221e1ba3cc2fa
/chrome/browser/ui/views/payments/secure_payment_confirmation_dialog_view.h
95d034f604e64a76fd3e40ce153ea7e5c1425271
[ "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
4,000
h
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_VIEWS_PAYMENTS_SECURE_PAYMENT_CONFIRMATION_DIALOG_VIEW_H_ #define CHROME_BROWSER_UI_VIEWS_PAYMENTS_SECURE_PAYMENT_CONFIRMATION_DIALOG_VIEW_H_ #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "components/payments/content/secure_payment_confirmation_view.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/views/controls/button/button.h" #include "ui/views/window/dialog_delegate.h" namespace views { class StyledLabel; } namespace payments { class PaymentUIObserver; // Draws the user interface in the secure payment confirmation flow. Owned by // the SecurePaymentConfirmationController. class SecurePaymentConfirmationDialogView : public SecurePaymentConfirmationView, public views::DialogDelegateView { public: METADATA_HEADER(SecurePaymentConfirmationDialogView); class ObserverForTest { public: virtual void OnDialogClosed() = 0; virtual void OnConfirmButtonPressed() = 0; virtual void OnCancelButtonPressed() = 0; virtual void OnOptOutClicked() = 0; }; // IDs that identify a view within the secure payment confirmation dialog. // Used to validate views in browsertests. enum class DialogViewID : int { VIEW_ID_NONE = 0, HEADER_ICON, PROGRESS_BAR, TITLE, MERCHANT_LABEL, MERCHANT_VALUE, INSTRUMENT_LABEL, INSTRUMENT_VALUE, INSTRUMENT_ICON, TOTAL_LABEL, TOTAL_VALUE }; explicit SecurePaymentConfirmationDialogView( base::WeakPtr<ObserverForTest> observer_for_test, const base::WeakPtr<PaymentUIObserver> ui_observer_for_test); ~SecurePaymentConfirmationDialogView() override; // SecurePaymentConfirmationView: void ShowDialog(content::WebContents* web_contents, base::WeakPtr<SecurePaymentConfirmationModel> model, VerifyCallback verify_callback, CancelCallback cancel_callback, OptOutCallback opt_out_callback) override; void OnModelUpdated() override; void HideDialog() override; bool ClickOptOutForTesting() override; // views::DialogDelegate: bool ShouldShowCloseButton() const override; bool Accept() override; base::WeakPtr<SecurePaymentConfirmationDialogView> GetWeakPtr(); private: void OnDialogAccepted(); void OnDialogCancelled(); void OnDialogClosed(); void OnOptOutClicked(); void InitChildViews(); std::unique_ptr<views::View> CreateHeaderView(); std::unique_ptr<views::View> CreateBodyView(); std::unique_ptr<views::View> CreateRows(); std::unique_ptr<views::View> CreateRowView( const std::u16string& label, DialogViewID label_id, const std::u16string& value, DialogViewID value_id, const SkBitmap* icon = nullptr, DialogViewID icon_id = DialogViewID::VIEW_ID_NONE); void UpdateLabelView(DialogViewID id, const std::u16string& text); base::WeakPtr<ObserverForTest> observer_for_test_; const base::WeakPtr<PaymentUIObserver> ui_observer_for_test_; VerifyCallback verify_callback_; CancelCallback cancel_callback_; OptOutCallback opt_out_callback_; // Cache the instrument icon pointer so we don't needlessly update it in // OnModelUpdated(). raw_ptr<const SkBitmap, DanglingUntriaged> instrument_icon_ = nullptr; // Cache the instrument icon generation ID to check if the instrument_icon_ // has changed pixels. uint32_t instrument_icon_generation_id_ = 0; // The opt-out view stored in the dialog footnote. This is always created in // InitChildViews, but is only marked visible if opt-out was requested. raw_ptr<views::StyledLabel> opt_out_view_ = nullptr; base::WeakPtrFactory<SecurePaymentConfirmationDialogView> weak_ptr_factory_{ this}; }; } // namespace payments #endif // CHROME_BROWSER_UI_VIEWS_PAYMENTS_SECURE_PAYMENT_CONFIRMATION_DIALOG_VIEW_H_
1713fd33dfa046be191999b512425a5d336843db
d96333ca6eb18677c2579c1114fb047cc799bf13
/atcoder_test.cpp
faac7f4f525a10b60cde24ceb052b20e92242d6a
[]
no_license
zaburo-ch/icpc_practice
e8fe735857689f685ea86435346963731f5dcd18
fc275c0d0a0b8feba786059fa1f571563d8e432e
refs/heads/master
2021-01-19T05:03:31.891988
2015-06-28T17:39:00
2015-06-28T17:39:00
21,899,426
0
0
null
null
null
null
UTF-8
C++
false
false
362
cpp
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <vector> #include <string> #include <queue> #include <map> #include <algorithm> #include <set> #define INF 10000000 using namespace std; typedef pair<int,int> P; int main(){ int a,b,c; string s; cin >> a >> b >> c >> s; cout << a+b+c << " " << s << endl; return 0; }
ae44de7ab0e86aee512ffe24210403c0bec8ace6
583e614741a633a427e80e68db1a62698d3607d1
/CISP 360/Chapter 13/Pracicing/Rectangle.h
780829e24d55a25651914d9fa115fe729b028b60
[]
no_license
Justin-Singh125125/CISP-360
c7f9e06fd25bbe1d28d211da2c9f8695bc26a9f5
754de232a958d7b5a699374a3965e49fa69a1abe
refs/heads/master
2020-04-08T14:34:02.294634
2018-11-28T04:17:26
2018-11-28T04:17:26
159,442,525
1
0
null
null
null
null
UTF-8
C++
false
false
381
h
#ifndef RECTANGLE_H #define RECTANGLE_H class Rectangle { private: double width; double length; public: //a constructor Rectangle(double,double); void setWidth(double); void setLength(double); double getWidth() const {return width;} double getLength() const {return length;} double getArea() const { return (length * width);} }; #endif
a757b1ce54f381eb42b5f54a3c7b1431744d6344
0d70a382034757292519af69e2ba71a0f06f0135
/libraries/Communications/ControlMessage.h
e85d772bd6eccd7df70837d73124bf4197e3cb03
[]
no_license
grossadamm/victoria
4e89a17ad29f37a93676fe7ccc9b868dca8b5152
c0c6d07cd87ba74f8005e84fce3065701b071c5b
refs/heads/master
2021-01-15T15:26:35.338605
2016-08-17T03:56:40
2016-08-17T03:56:40
44,703,926
0
0
null
null
null
null
UTF-8
C++
false
false
431
h
#ifndef ControlMessage_h #define ControlMessage_h #include "Arduino.h" #include "Command.h" class ControlMessage { public: ControlMessage(char message[32]); ~ControlMessage(); Command getCommand(); bool commandsAvailable(); private: void setNextEndIndex(); char _message[32]; char *_messageContinues; Command _currentCommand; int _startIndex; int _endIndex; bool _first; }; #endif
18e31ff22aed4475beed8d8f476181465c8b9965
37b53d11b252b5b1b827a2f4d50e154ed56b6a50
/samples/LuaScript/LuaConsole/ConsoleCfg.cpp
e64d64034b753d1681b6a7b87aa4ec82a58e7365
[]
no_license
johndpope/orbiter-sdk
070232d667bf1eb7aceae2e14df068f424e86090
8f0f45583ed43d7f0df2ef6ddd837fe7c2ef17f8
refs/heads/master
2020-05-16T22:50:51.303970
2019-03-25T16:43:55
2019-03-25T16:43:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,175
cpp
#include "ConsoleCfg.h" #include "resource.h" ConsoleConfig *ConsoleConfig::cc = 0; const char *ConsoleConfig::cfgfile = "Modules\\Console.cfg"; ConsoleConfig::ConsoleConfig (HINSTANCE hDLL): LaunchpadItem () { hModule = hDLL; SetDefault (); ReadConfig (); } char *ConsoleConfig::Name () { return "Console Configuration"; } char *ConsoleConfig::Description () { static char *desc = "Customize the appearance and behaviour of the inline Lua Console.\r\n\r\nThe console allows to run scripts during a simulation session."; return desc; bool clbkOpen (HWND hLaunchpad); } bool ConsoleConfig::clbkOpen (HWND hLaunchpad) { cc = this; // keep a global pointer to be used by the message handlers (ugly) return OpenDialog (hModule, hLaunchpad, IDD_CONFIG, DlgProc); } int ConsoleConfig::clbkWriteConfig () { FILEHANDLE hFile = oapiOpenFile (cfgfile, FILE_OUT, CONFIG); if (!hFile) return 1; oapiWriteItem_int (hFile, "FSIZE", fontsize); oapiCloseFile (hFile, FILE_OUT); return 0; } void ConsoleConfig::InitDialog (HWND hDlg) { char cbuf[256]; sprintf (cbuf, "%d", fontsize); SetWindowText (GetDlgItem (hDlg, IDC_FONTSIZE), cbuf); } void ConsoleConfig::CloseDialog (HWND hDlg) { EndDialog (hDlg, 0); } void ConsoleConfig::SetDefault () { fontsize = 14; } bool ConsoleConfig::ReadConfig () { int d; FILEHANDLE hFile = oapiOpenFile (cfgfile, FILE_IN, CONFIG); if (!hFile) { MessageBeep (-1); return false; } if (oapiReadItem_int (hFile, "FSIZE", d)) fontsize = (DWORD)d; oapiCloseFile (hFile, FILE_IN); return true; } void ConsoleConfig::Apply (HWND hDlg) { char cbuf[256]; DWORD d; GetWindowText (GetDlgItem (hDlg, IDC_FONTSIZE), cbuf, 256); if (sscanf (cbuf, "%d", &d) == 1) fontsize = d; } BOOL CALLBACK ConsoleConfig::DlgProc (HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_INITDIALOG: cc->InitDialog (hDlg); break; case WM_COMMAND: switch (LOWORD (wParam)) { case IDOK: cc->Apply (hDlg); // fall through case IDCANCEL: cc->CloseDialog (hDlg); return 0; } break; } return 0; }
146843976cafe67fa1244924721aeb232849e88d
c5208b483726e8dd8ef8e75cfc31f4739421bccc
/StRoot/StEvent/StRichMCPixel.h
6625cc483519ab22b2bd04213154aa09c3605661
[]
no_license
jdbrice/StStgc
85cc17cf444a087f71b41d9115ab7983e1bdded9
76b0b0847f7a220944e896c177d8a0203d60ac84
refs/heads/master
2020-06-18T19:33:02.459977
2019-07-24T19:36:22
2019-07-24T19:36:22
196,420,514
0
0
null
null
null
null
UTF-8
C++
false
false
2,361
h
/*! * \class StRichMCPixel * \author Brian Lasiuk, May 2000 * * MC pixel contains the raw pixel info but also * */ /*************************************************************************** * * $Id: StRichMCPixel.h,v 1.1 2018/11/14 16:49:05 akio Exp $ * * Author: Brian Lasiuk, May 2000 *************************************************************************** * * Description: * MC pixel contains the raw pixel info but also * *************************************************************************** * * $Log: StRichMCPixel.h,v $ * Revision 1.1 2018/11/14 16:49:05 akio * FCS codes in offline/upgrade/akio * * Revision 2.3 2002/02/22 22:56:49 jeromel * Doxygen basic documentation in all header files. None of this is required * for QM production. * * Revision 2.2 2001/04/05 04:00:40 ullrich * Replaced all (U)Long_t by (U)Int_t and all redundant ROOT typedefs. * * Revision 2.1 2000/05/22 21:44:44 ullrich * Initial Revision * **************************************************************************/ #ifndef StRichMCPixel_hh #define StRichMCPixel_hh #include "StRichPixel.h" #include "StRichMCInfo.h" #include "StContainers.h" class StRichMCPixel : public StRichPixel { public: StRichMCPixel(); StRichMCPixel(unsigned int packedData); StRichMCPixel(unsigned int packedData, const StSPtrVecRichMCInfo&); // StRichMCPixel(const StRichMCPixel&); use default // StRichMCPixel& operator=(const StRichMCPixel&); use default ~StRichMCPixel(); int operator==(const StRichMCPixel&) const; int operator!=(const StRichMCPixel&) const; unsigned short contributions() const; void addInfo(const StRichMCInfo*); void setInfo(const StSPtrVecRichMCInfo&); const StSPtrVecRichMCInfo& getMCInfo() const; StSPtrVecRichMCInfo& getMCInfo(); protected: StSPtrVecRichMCInfo mInfo; ClassDef(StRichMCPixel,1) }; inline unsigned short StRichMCPixel::contributions() const { return mInfo.size(); } inline void StRichMCPixel::addInfo(const StRichMCInfo* p) { mInfo.push_back(p);} inline void StRichMCPixel::setInfo(const StSPtrVecRichMCInfo& p) { mInfo = p;} inline const StSPtrVecRichMCInfo& StRichMCPixel::getMCInfo() const {return mInfo;} inline StSPtrVecRichMCInfo& StRichMCPixel::getMCInfo() { return mInfo;} #endif
2db453fd4f2ed7e5551341fdd871a8d714b58d29
100ed6b0576bd357010ebaa5f48a90cd9195ca2f
/examples/guess/submissions/run_time_error/guess_rte_after_correct.cc
74216638a7e551c7cc232f113fffb32dab635211
[ "MIT" ]
permissive
Kattis/problemtools
f4f1bc3c0cfcfaf8daf167c27bc2aef4f04c6584
307d417056e8dc8581db96572e945868e0559454
refs/heads/develop
2023-08-16T12:40:43.474950
2023-06-25T21:43:53
2023-06-25T21:43:53
22,494,980
95
76
MIT
2023-08-02T23:28:22
2014-08-01T04:16:09
Python
UTF-8
C++
false
false
364
cc
#include <cstdio> #include <cstring> int main(void) { int lo = 1, hi = 1000; while (true) { int m = (lo+hi)/2; printf("%d\n", m); fflush(stdout); char res[1000]; scanf("%s", res); if (!strcmp(res, "correct")) break; if (!strcmp(res, "lower")) hi = m-1; else lo = m+1; } return 42; }
3769f6b04f37da81f80ae7d10807c84b49ea4840
68a76eb015df500ab93125396cf351dff1e53356
/Codeforces/236A.cpp
479676e152ac648b538c90340d73abc4180aff14
[]
no_license
deepakn97/Competitive-Programming
a84999c0755a187a55a0bb2f384c216e7ee4bf15
aae415839c6d823daba5cd830935bf3350de895e
refs/heads/master
2021-10-04T08:00:59.867642
2018-12-03T15:37:32
2018-12-03T15:37:32
81,475,571
0
0
null
null
null
null
UTF-8
C++
false
false
379
cpp
#include <iostream> #include <string> #include <set> using namespace std; int main() { string s; cin >> s; int l = s.size(); set<char> dis; for(int i = 0 ; i < l; i++) dis.insert(s[i]); int number = dis.size(); if(number%2 != 0) cout << "IGNORE HIM!" << endl; else cout << "CHAT WITH HER!" << endl; }
753c1e1834c6898279a7a5a8786abdac42f390fe
0c7ca9dc4fd5d77b536f6b9e8db7ec7759f3618f
/Homework05/Animals/Animals/Animal.h
52fc49ae6003ff99d912cbbba813539f8e83735c
[]
no_license
prog1261-2020/homework-MidnightCodeboy
20db2d814551a2375cd05c59b209611bc7406382
dd5aae96ef629ca2c782ade0cdb53280f2ca7b60
refs/heads/master
2020-12-10T13:07:17.215719
2020-03-26T03:29:40
2020-03-26T03:29:40
233,602,906
0
0
null
null
null
null
UTF-8
C++
false
false
1,443
h
#pragma once /** * @file Animal.h * * @author Joseph Roy-Plommer * @version <1.0> * @date 2020-02-08 * * @section Academic Integrity * I certify that this work is solely my own and complies with * NBCC Academic Integrity Policy (policy 1111) * * @section DESCRIPTION * Represents an Animal. * * @section LICENSE * <any necessary attributions> * * Copyright 2019 * Permission to use, copy, modify, and/or distribute this software for * any purpose with or without fee is hereby granted, provided that the * above copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include <string> class Animal { public: Animal(); Animal(const std::string& name, const std::string& type, const std::string& sound); const std::string& getName() const; const std::string& getType() const; const std::string& getSound() const; void speak(); protected: std::string name; std::string type; std::string sound; };
7b68c5c3e0ef57777e693aa7f6852e855861b88b
391638cf1cabe716c05bbc0afd434f9c0873bddb
/program6/program6.cpp
8edc6699f9defcf56fd8cbe597cd962dd6b4003d
[]
no_license
Anxiaolu/Cpp_Learning
f78a2c12637b387214612349264c78a72b1bc3c1
4c86a7511fdbbd14d8057d5b9e53c7186c5523db
refs/heads/master
2021-01-19T08:51:30.337888
2017-04-10T05:58:48
2017-04-10T05:58:48
87,689,108
0
0
null
null
null
null
UTF-8
C++
false
false
1,351
cpp
#include<iostream> #include<string> using namespace std; class Teacher { public: Teacher(string nam,int ag,string se, string add,string T,string t){ name = nam; Age = ag; sex = se; Address = add; Tel = T; title = t; }; ~Teacher(){}; void display(){ cout<<"name:"<<name<<endl; cout<<"Age:"<<Age<<endl; cout<<"sex:"<<sex<<endl; cout<<"Address:"<<Address<<endl; cout<<"Tel:"<<Tel<<endl; cout<<"title:"<<title<<endl; }; private: string name; int Age; string sex; string Address; string Tel; string title; }; class Cadre { public: Cadre(string nam,int ag,string se, string add,string T,string p){ name1 = nam; Age1 = ag; sex1 = se; Address1 = add; Tel1 = T; post = p; }; ~Cadre(){}; string getPost(){return post;}; protected: string name1; int Age1; string sex1; string Address1; string Tel1; string post; }; class Tea_cad:public Teacher,public Cadre { public: Tea_cad(string nam,int ag,string se, string add,string T,string t,string p,int w): Teacher(nam,ag,se,add,T,t),Cadre(nam,ag,se,add,T,p),wage(w){}; ~Tea_cad(){}; int getWage(){return wage;}; private: int wage; }; int main(int argc, char const *argv[]) { Tea_cad tc("lsadi",10,"nan","Address","15616","Teacher","",20); Teacher *t; t = &tc; t->display(); Cadre *c; c = &tc; cout<<c->getPost()<<tc.getWage()<<endl; return 0; }
5639efd50efb18a147c53540ed610023d680c894
dc5ff438d66e64050ad253da01820a2f03389f7c
/srm-624-div-2/BuildingHeightsEasy.cpp
c07a240c2695810fee6acc4885dd9effa35ec789
[]
no_license
maqin/SRM
7d9a45ec4262b6f105203f3b7063028af045d5c3
c7a1e08e54e5e4551e841814669e3b32262d16b1
refs/heads/master
2021-01-22T03:06:20.067586
2015-05-10T00:48:41
2015-05-10T00:48:41
21,329,896
0
0
null
null
null
null
UTF-8
C++
false
false
985
cpp
#include<iostream> #include<vector> #include<algorithm> #include<limits.h> using namespace std; class BuildingHeightsEasy{ public: int minimum(int M, vector<int> heights){ if(M<=1) return 0; sort(heights.begin(),heights.end()); int same = 1; int res = INT_MAX; for(int i = 1; i<heights.size(); i++){ if(heights[i]==heights[i-1]) same ++; else same = 1; if(same == M) return 0; if(i>=M-1){ cout<<i<<endl; int d = 0; int loop = i; int n = M; while(n>0){ d += (heights[i]-heights[loop]); loop--; n--; } //int d = heights[i]-heights[i-2]+heights[i]-heights[i-1]; res = min(res,d); } } return res; } };
e310de626a724cc46b82c4ff62fce40b6994501f
51407cfb371a65a9ccc8d78fd95b4966d5db6acd
/200-Number Of Islands.cpp
b2169abbd9ded43fc01a64d31d2a366e665d6d3b
[]
no_license
yangmingzi/MyLeetcode
80d79849573ea67820bc0bd20701c5c602226829
1c0c1121cb0ebbc1a9300b37ce609e682deba650
refs/heads/master
2020-05-18T06:16:49.438125
2015-12-18T09:43:58
2015-12-18T09:43:58
31,898,329
0
1
null
null
null
null
UTF-8
C++
false
false
984
cpp
/* DFS 八连通问题:POJ2386 从标记为1的点进行深搜,每经过一个为1的点则标记为X 当图中不再存在1的时候。进行的dfs次数就是所求的岛数 */ class Solution { public: void dfs(vector<vector<char>> &grid, int x, int y) { if (x < 0 || x >= grid.size()) return; if (y < 0 || y >= grid[0].size()) return; if (grid[x][y] != '1') return; grid[x][y] = 'X'; dfs(grid, x + 1, y); dfs(grid, x - 1, y); dfs(grid, x, y + 1); dfs(grid, x, y - 1); } int numIslands(vector<vector<char>> &grid) { if (grid.empty() || grid[0].empty()) return 0; int N = grid.size(), M = grid[0].size(); int cnt = 0; for (int i = 0; i < N; ++i) { for (int j = 0; j < M; ++j) { if (grid[i][j] == '1') { dfs(grid, i, j); ++cnt; } } } return cnt; } };
6d0dec28cda6b19255068fddf244aae632d1c33a
d1ece2ce8414c1d60501d7cf63b9624a6a305234
/PC/Project-FW/Pattern_Irregular31.cpp
09538d0d208b4f4ef07c678214a70d9cfbce2e48
[]
no_license
Nickchooshin/HUGP2_1week
82ba96690896f8eee689acd6f945d374a983b1b9
4cf4129e17eeb21df1adcd8abe890dc19aebaa28
refs/heads/master
2021-01-22T01:06:07.556131
2015-04-14T20:26:41
2015-04-14T20:27:05
32,618,675
1
0
null
null
null
null
UTF-8
C++
false
false
1,590
cpp
#include "Pattern_Irregular31.h" #include "Boss.h" #include "Lazer.h" #include "D3dDevice.h" #include "BossManager.h" CPattern_Irregular31::CPattern_Irregular31() : CPattern(9999.0f), m_pfnEvent(&CPattern_Irregular31::EventWait) { const float fWinHeight = g_D3dDevice->GetWinHeight() ; m_pBoss = g_BossManager->GetBossInstance("obj1") ; m_pBoss->SetPosition(646.0f, fWinHeight-402.0f) ; for(int i=0; i<2; i++) { m_pLazer[i] = new CLazer ; m_pLazer[i]->Init() ; } m_pLazer[0]->SetPosition(635.0f, fWinHeight-287.0f) ; m_pLazer[0]->SetLazerPosition(27.f, fWinHeight-646.0f, 580.0f, fWinHeight-646.0f) ; m_pLazer[1]->SetPosition(726.0f, fWinHeight-292.0f) ; m_pLazer[1]->SetLazerPosition(1252.f, fWinHeight-646.0f, 700.0f, fWinHeight-646.0f) ; } CPattern_Irregular31::~CPattern_Irregular31() { for(int i=0; i<2; i++) { if(m_pLazer[i]!=NULL) delete m_pLazer[i] ; } } void CPattern_Irregular31::Update() { Time() ; (this->*m_pfnEvent)() ; } void CPattern_Irregular31::Render() { m_pBoss->Render() ; for(int i=0; i<2; i++) m_pLazer[i]->Render() ; } void CPattern_Irregular31::EventWait() { if(m_fTime>=2.0f) { m_pfnEvent = &CPattern_Irregular31::EventShootLazer ; (this->*m_pfnEvent)() ; } } void CPattern_Irregular31::EventShootLazer() { for(int i=0; i<2; i++) m_pLazer[i]->Update() ; if(m_fTime>=3.7f) { m_pfnEvent = &CPattern_Irregular31::EventMoveLazer ; (this->*m_pfnEvent)() ; } } void CPattern_Irregular31::EventMoveLazer() { for(int i=0; i<2; i++) m_pLazer[i]->Update() ; if(m_fTime>=6.0f) m_bLife = false ; }
771379a07c6cc837794c1dccf0fdd4760d6d301d
f50ece3c6e9ae8c17f2b255994b1b9696ff893f7
/GP7/Classes/MResource.h
6f456f40b7f699089559ec1bf0650bc758ebeb7c
[]
no_license
ImanRezaeipour/G-Collection
470bc901e470f7de003c82813fc0ef246a2c4e3f
517a51b428b056d9967a2b7294ac703a37e430fd
refs/heads/master
2023-07-17T10:49:01.496686
2021-08-16T21:30:08
2021-08-16T21:30:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
497
h
#ifndef __MIDDLEWARERESOURCE__ #define __MIDDLEWARERESOURCE__ #include "DATATYPE.H" #include "RTOS.H" class MiddlewareResource { public: MiddlewareResource(); ~MiddlewareResource(); void Initial (void); virtual void DisableEvents (void) = 0; virtual void StopTimers (void) = 0; protected: virtual void initial_members (void) = 0; virtual void create_timers (void) = 0; static void safe_call_handler (EventPointer EP); static bool is_task_running (OS_TASK* OTP); }; #endif
97001bb1b37694491971c5f218c5367f6736094a
8be7a7efbaa6a4034e435bc8221cc5fb54f8067c
/safe-game/src/switch_widget.h
8c9b9c045a4ea00f6f40b64421ab983970ca5807
[]
no_license
RinatB2017/Qt_github
9faaa54e3c8e7a5f84f742d49f4559dcdd5622dd
5177baa735c0140d39d8b0e84fc6af3dcb581abd
refs/heads/master
2023-08-08T08:36:17.664868
2023-07-28T07:39:35
2023-07-28T07:39:35
163,097,727
2
1
null
null
null
null
UTF-8
C++
false
false
1,092
h
#pragma once #include <QPushButton> #include "orientation.h" class QVariantAnimation; namespace safe { class SwitchWidget : public QPushButton { Q_OBJECT public: explicit SwitchWidget(const QPixmap& image, int row, int column, Orientation orient, QWidget* parent); Orientation orientation() const; void changeOrientation(); signals: void orientationChanged(Orientation orient); void clicked(int row, int column); protected: void paintEvent(QPaintEvent* event); private slots: void onAnimationValueChanged(const QVariant& value); void onAnimationDone(); private: int orientationToDegrees(Orientation orient) const; private: const QPixmap& originalImage_; const int imageSize_; const int row_; const int column_; Orientation orient_; int angleDegrees_; static constexpr int DurationOfAnimationMsec = 350; QVariantAnimation* animation_; }; }
9e102136e7fc815a2c96a31522d632ed07bd891e
fbdb5912a1c1819bfc4979a3bf742a6142692b8f
/src/classes/Bullet.cpp
a785d09213ccd175230e57c6ddee26b9c2c8eb63
[]
no_license
Proch92/ld23
79d065d3c24e043bda13333c409600e8184685c7
f4b3a25acf44dd6cf000ce31a44b31a4922040c4
refs/heads/master
2016-09-06T00:32:32.019762
2012-04-22T22:10:43
2012-04-22T22:10:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
381
cpp
#include "../include.h" Bullet::Bullet() { } void Bullet::spawn(float xpos, float ypos, float xv, float yv, texture* t, int t_i) { x = xpos; y = ypos; xvel = xv; yvel = yv; tex = t; tex_index = t_i; } void Bullet::move() { yvel += GRAVITY; x += xvel; y += yvel; } void Bullet::show() { apply_surface((int)x, (int)y, BULLET_WIDTH, BULLET_WIDTH, tex[tex_index]); }
98bcfbbf62eb86c66e83fad8346505845658d7c2
12ceca2646c1a1fcc399bfaa17368426fad3d6a1
/FactoryMethod/Pizza.h
255955b4fcb4f7ed0902b46592d6db7826d11750
[]
no_license
AInsolence/DesignPatterns
e725338db4cd10a36a231692a5fa396cb6bf0b68
34de288b60d2679e8d7d2c2cfa2f75a4d16d11a8
refs/heads/master
2021-09-12T08:20:01.235167
2018-04-14T16:27:53
2018-04-14T16:27:53
115,539,217
0
0
null
null
null
null
UTF-8
C++
false
false
434
h
/* Base abstract class Pizza for all pizza types. */ #pragma once #include <string> #include <vector> #include <iostream> enum class PizzaType { Cheese, HotAndSpicy }; class Pizza { public: Pizza(); ~Pizza(); std::string GetName(); void Prepare(); virtual void Bake(); virtual void Cut(); virtual void Box(); protected: std::string Name; std::string Dough; std::string Sauce; std::vector<std::string> Toppings; };
ec7a7db346e5774a6711b3c02c85a584b4094a31
b7e97047616d9343be5b9bbe03fc0d79ba5a6143
/src/protocols/forge/remodel/ResidueVicinityRCG.hh
41467151a2dc5568f19a055dbc7b51a0cffa3db0
[]
no_license
achitturi/ROSETTA-main-source
2772623a78e33e7883a453f051d53ea6cc53ffa5
fe11c7e7cb68644f404f4c0629b64da4bb73b8f9
refs/heads/master
2021-05-09T15:04:34.006421
2018-01-26T17:10:33
2018-01-26T17:10:33
119,081,547
1
3
null
null
null
null
UTF-8
C++
false
false
6,479
hh
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington CoMotion, email: [email protected]. /// @file protocols/forge/remodel/ResidueVicinityRCG.hh /// /// @brief /// @author Florian Richter, [email protected], april 2009 #ifndef INCLUDED_protocols_forge_remodel_ResidueVicinityRCG_hh #define INCLUDED_protocols_forge_remodel_ResidueVicinityRCG_hh // protocol headers #include <protocols/forge/remodel/RemodelConstraintGenerator.hh> // project headers #include <core/pose/Pose.fwd.hh> #include <core/scoring/constraints/Constraint.fwd.hh> #include <core/scoring/func/Func.fwd.hh> #include <core/types.hh> #include <basic/datacache/DataMap.fwd.hh> //utility headers #include <utility/vector1.hh> namespace protocols { namespace forge { namespace remodel { class ResidueVicinityRCG; typedef utility::pointer::shared_ptr< ResidueVicinityRCG > ResidueVicinityRCGOP; typedef utility::pointer::weak_ptr< ResidueVicinityRCG const > ResidueVicinityRCGCAP; class ResidueVicinityInfo; typedef utility::pointer::shared_ptr< ResidueVicinityInfo > ResidueVicinityInfoOP; typedef utility::pointer::shared_ptr< ResidueVicinityInfo const > ResidueVicinityInfoCOP; /// @brief small helper class for the ResidueVicinityRCG class ResidueVicinityInfo : public utility::pointer::ReferenceCount { public: ResidueVicinityInfo( core::Size old_seqpos, utility::vector1< core::Size > const & residue_atoms, utility::vector1< core::Size > const & loopres_atoms, core::Size desired_remodelres_in_vicinity ); virtual ~ResidueVicinityInfo(); core::Size old_seqpos() const { return old_seqpos_; } utility::vector1< core::Size > const & residue_atoms() const { return residue_atoms_; } utility::vector1< core::Size > const & residue_base_atoms() const { return residue_base_atoms_; } utility::vector1< core::Size > const & residue_base2_atoms() const { return residue_base2_atoms_; } utility::vector1< core::Size > const & loopres_atoms() const { return loopres_atoms_; } utility::vector1< core::Size > const & loopres_base_atoms() const { return loopres_base_atoms_; } utility::vector1< core::Size > const & loopres_base2_atoms() const { return loopres_base2_atoms_; } void set_residue_base_atoms( utility::vector1< core::Size > const & residue_base_atoms ) { residue_base_atoms_ = residue_base_atoms; } void set_residue_base2_atoms( utility::vector1< core::Size > const & residue_base2_atoms ) { residue_base2_atoms_ = residue_base2_atoms; } void set_loopres_base_atoms( utility::vector1< core::Size > const & loopres_base_atoms ) { loopres_base_atoms_ = loopres_base_atoms; } void set_loopres_base2_atoms( utility::vector1< core::Size > const & loopres_base2_atoms ) { loopres_base2_atoms_ = loopres_base2_atoms; } core::Size desired_remodelres_in_vicinity() const { return desired_remodelres_in_vicinity_; } core::scoring::func::FuncOP dis() const; core::scoring::func::FuncOP loop_ang() const; core::scoring::func::FuncOP targ_ang() const; core::scoring::func::FuncOP loop_dih() const; core::scoring::func::FuncOP targ_dih() const; core::scoring::func::FuncOP lt_dih() const; void set_dis( core::scoring::func::FuncOP dis ); void set_loop_ang( core::scoring::func::FuncOP loop_ang ); void set_targ_ang( core::scoring::func::FuncOP targ_ang ); void set_loop_dih( core::scoring::func::FuncOP loop_dih ); void set_targ_dih( core::scoring::func::FuncOP targ_dih ); void set_lt_dih( core::scoring::func::FuncOP lt_dih ); private: core::Size old_seqpos_; utility::vector1< core::Size > residue_atoms_, residue_base_atoms_, residue_base2_atoms_; utility::vector1< core::Size > loopres_atoms_, loopres_base_atoms_, loopres_base2_atoms_; core::scoring::func::FuncOP dis_, loop_ang_, targ_ang_, loop_dih_, targ_dih_, lt_dih_; core::Size desired_remodelres_in_vicinity_; }; //ResidueVicinityInfo /// @brief a RemodelConstraintGenerator that creates AmbiguousMultiConstraints for all positions /// @brief in the remodeled loop to the desired positions, such that during remodeling, the remodeled /// @brief region will be driven towards the vicinity of these residues class ResidueVicinityRCG : public RemodelConstraintGenerator { public: // Constructors and virtual functions ResidueVicinityRCG(); /// @brief copy construtor ResidueVicinityRCG( ResidueVicinityRCG const & rval ); ResidueVicinityRCG( core::Size lstart, core::Size lstop, utility::vector1< ResidueVicinityInfoOP > const & rv_infos ); virtual ~ResidueVicinityRCG(); void generate_remodel_constraints( core::pose::Pose const & pose ) override; void parse_my_tag( TagCOP tag, basic::datacache::DataMap & data, protocols::filters::Filters_map const & filters, protocols::moves::Movers_map const & movers, core::pose::Pose const & pose ) override; // XRW TEMP virtual std::string // XRW TEMP get_name() const; protocols::moves::MoverOP fresh_instance() const override; protocols::moves::MoverOP clone() const override; public: // Public member functions void clear_rv_infos(){ rv_infos_.clear(); } void add_rv_info( ResidueVicinityInfoOP rv_info ){ rv_infos_.push_back( rv_info ); } void lstart( core::Size const lstart ); void lstop( core::Size const lstop ); void set_rv_infos( utility::vector1< ResidueVicinityInfoOP > const & rv_infos ); std::string get_name() const override; static std::string mover_name(); static void provide_xml_schema( utility::tag::XMLSchemaDefinition & xsd ); protected: void generate_remodel_constraints_for_respair( core::pose::Pose const & pose, core::Size const loopres, ResidueVicinityInfo const & rv_info, utility::vector1< core::scoring::constraints::ConstraintCOP > & csts ); private: core::Size lstart_, lstop_; utility::vector1< ResidueVicinityInfoOP > rv_infos_; }; //class ResidueVicinityRCG } //namespace remodel } //namespace forge } //namespace protocols #endif // INCLUDED_protocols_forge_remodel_ResidueVicinityRCG_HH
5c72403b430b3847163692c6d0a7ff79e6536783
6edc7762f23ec36e231ecb5c9847ecd54c26171d
/EmptyGeneralTesting/SPA/ExpressionParser.h
00bbd6e8648298fa65eef8f731d13844e61fa423
[]
no_license
Humberd/ATS-projekt
a1c3b47895065152c42841d6fdb57c6c91c3b646
753e5fed7101ea02e2b3545ed6cfe262bd8982b0
refs/heads/master
2021-03-22T03:07:27.004755
2017-05-29T01:20:24
2017-05-29T01:20:24
87,347,800
0
0
null
null
null
null
UTF-8
C++
false
false
742
h
#pragma once #include <vector> #include "LexerToken.h" #include "Node.h" #include "ParsingEntity.h" #include "ExpressionNode.h" using namespace std; class OperatorNode { public: int weight; ExpressionNode* operatorNode; int index; OperatorNode(int weight, ExpressionNode* operatorNode); }; class ExpressionParser: public ParsingEntity { public: static const int TIMES_WEIGHT; static const int PLUS_MINUS_WEIGHT; explicit ExpressionParser(ParsersRepository* parsersRepo, vector<LexerToken*>::iterator& iterator, vector<LexerToken*>::iterator& iteratorEnd); ~ExpressionParser(); Node* parse() override; OperatorNode* findWithHighestWeight(vector<OperatorNode*>& vector); };
5cae7924c35e1dc8f15ae07b96bc72ebb41644e5
a0be589685bb724106d3a0df6737d20c5ccdbd99
/Crocus/Source/Loader.hpp
efb1aa265f2d3791d315fb098ea337fe7a8ea602
[ "Unlicense" ]
permissive
ChunChunMorning/CrocusEngine
5d980215422984e4692cc8564a0939455c2f9e7e
a93a7f813b60bf6f221abaf6b9d580263e708900
refs/heads/master
2020-03-15T11:21:15.543470
2018-05-04T09:53:09
2018-05-04T09:53:09
132,119,198
0
0
null
null
null
null
UTF-8
C++
false
false
677
hpp
# pragma once # include <Siv3D.hpp> # include "../Assets.hpp" # include "../Component.hpp" # include "../Pointer.hpp" namespace cre { class Transform; using Factory = std::function<unique_ptr<Component>(const XMLElement&, const Assets&)>; class Loader { public: enum class State { Unloaded, Loading, Loaded }; private: State m_state; FilePath m_path; double m_stopwatch; Vec3 m_center; Vec3 m_size; weak_ptr<Transform> m_root; AssetsLoader m_assetsLoader; # ifdef _DEBUG Assets m_assets; # endif public: Loader::Loader(const FilePath& path, const Vec3& center, const Vec3& size); void update(); bool notYet() const; }; }
48b84f0cfb8e9097d3ca9eb628d9cc02b4cbb4eb
832c45ae5979dbcf4e07bc3b096e076d4d2d83e7
/20131014/Crackers.cpp
7fb8bf1c0e55cc570c61e496ea155e648451f66a
[]
no_license
personaluser01/Algorithm-problems
9e62da04724a6f4a71c10d0d3f0459bc926da594
9e2ad4571660711cdbed0402969d0cb74d6e4792
refs/heads/master
2021-01-03T12:08:55.749408
2018-10-13T10:59:02
2018-10-13T10:59:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
523
cpp
#include <bits/stdc++.h> #define elif else if using namespace std; int c[10011]; int a[10011]; main() { int ans=0,n,m; ios_base::sync_with_stdio(false); cin>>n>>m; for(int i=0;i<n;i++) for(int j=0;j<m;j++){ int x; cin>>x; a[j]|=(x<<i); } for(int i=0;i<(1<<n);i++){ int tmp=0; for(int j=0;j<m;j++){ int t=__builtin_popcount(a[j]^i); tmp+=max(t,n-t); } ans=max(ans,tmp); } cout<<ans; }
2ddca216a23485846a0506c52aa2c6154cc64920
df2f2c89943e42743510bab97f30423018f94db1
/src/EA.hpp
8d37865d212efe1071ade5cb7d1927f4a47327a6
[ "MIT" ]
permissive
chiefstone/eaOpcUa
5a6a2ef111f51beaddc0b7d5b9a606cc03f6d97b
48f66bbf98a8894fdeae91ae985ce921c58eb55a
refs/heads/master
2022-04-07T06:05:44.878206
2020-02-21T11:19:02
2020-02-21T11:19:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,492
hpp
#ifndef EAOPCUA_EA_HPP #define EAOPCUA_EA_HPP #include "piControl.h" #include "piTest/piControlIf.h" #include "types.hpp" bool writeValue(const std::uint16_t byte, const std::uint8_t bit, std::uint32_t value){ int rc; rc = piControlWrite(byte, bit, (uint8_t*) &value); return rc == 0; } bool writeValue(const address& adr, std::uint32_t value){ return writeValue(adr.byte, adr.bit, value); } bool writeBit(const std::uint16_t byte, const std::uint8_t bit, bool value){ int rc; SPIValue sPIValue; sPIValue.i16uAddress = byte; sPIValue.i8uBit = bit; sPIValue.i8uValue = (std::uint8_t)value; rc = piControlSetBitValue(&sPIValue); return rc == 0; } bool writeBit(const address& adr, bool value){ return writeBit(adr.byte, adr.bit, value); } bool readBytes(const std::uint16_t byte, const std::uint8_t length, std::uint8_t* value){ int rc; rc = piControlRead(byte, length, value); return rc == length; } bool readBytes(const address& adr, const std::uint8_t length, std::uint8_t* value){ return readBytes(adr.byte, length, value); } bool readBytes(const address& adr, std::uint8_t* value){ return readBytes(adr.byte, 1, value); } bool readBit(const std::uint16_t byte, const std::uint8_t bit){ int rc; SPIValue sPIValue; sPIValue.i16uAddress = byte; sPIValue.i8uBit = bit; rc = piControlGetBitValue(&sPIValue); //return rc == 0; return sPIValue.i8uValue; } bool readBit(const address& adr){ return readBit(adr.byte, adr.bit); } #endif //EAOPCUA_EA_HPP
0835eda35a5d0d4a1031ca634789359f337d0c37
bf031912026690fae445e26594823761a6df76f4
/homero_disp.ino
18852fe8131b8d1d4a2fde4090f8c450647d5990
[]
no_license
Cilazizo/homero_disp_modul
3cee3645fcde1b2f84385eda991f0d2a8324f233
cd2eb1c4169477dbcbef144dfc2311cb52e2ed8e
refs/heads/master
2021-01-10T18:20:16.642205
2016-01-31T21:26:58
2016-01-31T21:26:58
50,432,487
0
0
null
null
null
null
UTF-8
C++
false
false
19,727
ino
#include <ESP8266WiFi.h> /* OLED arduino D0-----------10 D1-----------9 RST----------13 DC-----------11 VCC----------5V GND----------GND*/ int SCL_PIN=13;//D0 int SDA_PIN=2; //D1 int RST_PIN=12;//RST int DC_PIN=14; //DC // replace with your channel's thingspeak API key, String readApiKey = "ITTLLGD37U85571S"; const char* ssid = "mudvayne"; const char* password = "0101010101"; const char* host = "api.thingspeak.com"; //int value = 1; void LED_CLS(void); void LED_Set_Pos(unsigned char x,unsigned char y);//Set the coordinate void LED_WrDat(unsigned char data); //Write Data void LED_P8x16Str(unsigned char x,unsigned char y,unsigned char ch[]); void LED_Fill(unsigned char dat); void LED_PrintEdge(void); void LED_Cursor(unsigned char cursor_column, unsigned char cursor_row); void LED_PrintLine(void); const unsigned char F8X16[]= { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,// 0 0x00,0x00,0x00,0xF8,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x33,0x30,0x00,0x00,0x00,//!1 0x00,0x10,0x0C,0x06,0x10,0x0C,0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,//"2 0x40,0xC0,0x78,0x40,0xC0,0x78,0x40,0x00,0x04,0x3F,0x04,0x04,0x3F,0x04,0x04,0x00,//#3 0x00,0x70,0x88,0xFC,0x08,0x30,0x00,0x00,0x00,0x18,0x20,0xFF,0x21,0x1E,0x00,0x00,//$4 0xF0,0x08,0xF0,0x00,0xE0,0x18,0x00,0x00,0x00,0x21,0x1C,0x03,0x1E,0x21,0x1E,0x00,//%5 0x00,0xF0,0x08,0x88,0x70,0x00,0x00,0x00,0x1E,0x21,0x23,0x24,0x19,0x27,0x21,0x10,//&6 0x10,0x16,0x0E,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,//'7 0x00,0x00,0x00,0xE0,0x18,0x04,0x02,0x00,0x00,0x00,0x00,0x07,0x18,0x20,0x40,0x00,//(8 0x00,0x02,0x04,0x18,0xE0,0x00,0x00,0x00,0x00,0x40,0x20,0x18,0x07,0x00,0x00,0x00,//)9 0x40,0x40,0x80,0xF0,0x80,0x40,0x40,0x00,0x02,0x02,0x01,0x0F,0x01,0x02,0x02,0x00,//*10 0x00,0x00,0x00,0xF0,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x1F,0x01,0x01,0x01,0x00,//+11 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0xB0,0x70,0x00,0x00,0x00,0x00,0x00,//,12 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x01,//-13 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x30,0x00,0x00,0x00,0x00,0x00,//.14 0x00,0x00,0x00,0x00,0x80,0x60,0x18,0x04,0x00,0x60,0x18,0x06,0x01,0x00,0x00,0x00,///15 0x00,0xE0,0x10,0x08,0x08,0x10,0xE0,0x00,0x00,0x0F,0x10,0x20,0x20,0x10,0x0F,0x00,//016 0x00,0x10,0x10,0xF8,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,//117 0x00,0x70,0x08,0x08,0x08,0x88,0x70,0x00,0x00,0x30,0x28,0x24,0x22,0x21,0x30,0x00,//218 0x00,0x30,0x08,0x88,0x88,0x48,0x30,0x00,0x00,0x18,0x20,0x20,0x20,0x11,0x0E,0x00,//319 0x00,0x00,0xC0,0x20,0x10,0xF8,0x00,0x00,0x00,0x07,0x04,0x24,0x24,0x3F,0x24,0x00,//420 0x00,0xF8,0x08,0x88,0x88,0x08,0x08,0x00,0x00,0x19,0x21,0x20,0x20,0x11,0x0E,0x00,//521 0x00,0xE0,0x10,0x88,0x88,0x18,0x00,0x00,0x00,0x0F,0x11,0x20,0x20,0x11,0x0E,0x00,//622 0x00,0x38,0x08,0x08,0xC8,0x38,0x08,0x00,0x00,0x00,0x00,0x3F,0x00,0x00,0x00,0x00,//723 0x00,0x70,0x88,0x08,0x08,0x88,0x70,0x00,0x00,0x1C,0x22,0x21,0x21,0x22,0x1C,0x00,//824 0x00,0xE0,0x10,0x08,0x08,0x10,0xE0,0x00,0x00,0x00,0x31,0x22,0x22,0x11,0x0F,0x00,//925 0x00,0x00,0x00,0xC0,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x30,0x00,0x00,0x00,//:26 0x00,0x00,0x00,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x60,0x00,0x00,0x00,0x00,//;27 0x00,0x00,0x80,0x40,0x20,0x10,0x08,0x00,0x00,0x01,0x02,0x04,0x08,0x10,0x20,0x00,//<28 0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x00,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x00,//=29 0x00,0x08,0x10,0x20,0x40,0x80,0x00,0x00,0x00,0x20,0x10,0x08,0x04,0x02,0x01,0x00,//>30 0x00,0x70,0x48,0x08,0x08,0x08,0xF0,0x00,0x00,0x00,0x00,0x30,0x36,0x01,0x00,0x00,//?31 0xC0,0x30,0xC8,0x28,0xE8,0x10,0xE0,0x00,0x07,0x18,0x27,0x24,0x23,0x14,0x0B,0x00,//@32 0x00,0x00,0xC0,0x38,0xE0,0x00,0x00,0x00,0x20,0x3C,0x23,0x02,0x02,0x27,0x38,0x20,//A33 0x08,0xF8,0x88,0x88,0x88,0x70,0x00,0x00,0x20,0x3F,0x20,0x20,0x20,0x11,0x0E,0x00,//B34 0xC0,0x30,0x08,0x08,0x08,0x08,0x38,0x00,0x07,0x18,0x20,0x20,0x20,0x10,0x08,0x00,//C35 0x08,0xF8,0x08,0x08,0x08,0x10,0xE0,0x00,0x20,0x3F,0x20,0x20,0x20,0x10,0x0F,0x00,//D36 0x08,0xF8,0x88,0x88,0xE8,0x08,0x10,0x00,0x20,0x3F,0x20,0x20,0x23,0x20,0x18,0x00,//E37 0x08,0xF8,0x88,0x88,0xE8,0x08,0x10,0x00,0x20,0x3F,0x20,0x00,0x03,0x00,0x00,0x00,//F38 0xC0,0x30,0x08,0x08,0x08,0x38,0x00,0x00,0x07,0x18,0x20,0x20,0x22,0x1E,0x02,0x00,//G39 0x08,0xF8,0x08,0x00,0x00,0x08,0xF8,0x08,0x20,0x3F,0x21,0x01,0x01,0x21,0x3F,0x20,//H40 0x00,0x08,0x08,0xF8,0x08,0x08,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,//I41 0x00,0x00,0x08,0x08,0xF8,0x08,0x08,0x00,0xC0,0x80,0x80,0x80,0x7F,0x00,0x00,0x00,//J42 0x08,0xF8,0x88,0xC0,0x28,0x18,0x08,0x00,0x20,0x3F,0x20,0x01,0x26,0x38,0x20,0x00,//K43 0x08,0xF8,0x08,0x00,0x00,0x00,0x00,0x00,0x20,0x3F,0x20,0x20,0x20,0x20,0x30,0x00,//L44 0x08,0xF8,0xF8,0x00,0xF8,0xF8,0x08,0x00,0x20,0x3F,0x00,0x3F,0x00,0x3F,0x20,0x00,//M45 0x08,0xF8,0x30,0xC0,0x00,0x08,0xF8,0x08,0x20,0x3F,0x20,0x00,0x07,0x18,0x3F,0x00,//N46 0xE0,0x10,0x08,0x08,0x08,0x10,0xE0,0x00,0x0F,0x10,0x20,0x20,0x20,0x10,0x0F,0x00,//O47 0x08,0xF8,0x08,0x08,0x08,0x08,0xF0,0x00,0x20,0x3F,0x21,0x01,0x01,0x01,0x00,0x00,//P48 0xE0,0x10,0x08,0x08,0x08,0x10,0xE0,0x00,0x0F,0x18,0x24,0x24,0x38,0x50,0x4F,0x00,//Q49 0x08,0xF8,0x88,0x88,0x88,0x88,0x70,0x00,0x20,0x3F,0x20,0x00,0x03,0x0C,0x30,0x20,//R50 0x00,0x70,0x88,0x08,0x08,0x08,0x38,0x00,0x00,0x38,0x20,0x21,0x21,0x22,0x1C,0x00,//S51 0x18,0x08,0x08,0xF8,0x08,0x08,0x18,0x00,0x00,0x00,0x20,0x3F,0x20,0x00,0x00,0x00,//T52 0x08,0xF8,0x08,0x00,0x00,0x08,0xF8,0x08,0x00,0x1F,0x20,0x20,0x20,0x20,0x1F,0x00,//U53 0x08,0x78,0x88,0x00,0x00,0xC8,0x38,0x08,0x00,0x00,0x07,0x38,0x0E,0x01,0x00,0x00,//V54 0xF8,0x08,0x00,0xF8,0x00,0x08,0xF8,0x00,0x03,0x3C,0x07,0x00,0x07,0x3C,0x03,0x00,//W55 0x08,0x18,0x68,0x80,0x80,0x68,0x18,0x08,0x20,0x30,0x2C,0x03,0x03,0x2C,0x30,0x20,//X56 0x08,0x38,0xC8,0x00,0xC8,0x38,0x08,0x00,0x00,0x00,0x20,0x3F,0x20,0x00,0x00,0x00,//Y57 0x10,0x08,0x08,0x08,0xC8,0x38,0x08,0x00,0x20,0x38,0x26,0x21,0x20,0x20,0x18,0x00,//Z58 0x00,0x00,0x00,0xFE,0x02,0x02,0x02,0x00,0x00,0x00,0x00,0x7F,0x40,0x40,0x40,0x00,//[59 0x00,0x0C,0x30,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x06,0x38,0xC0,0x00,//\60 0x00,0x02,0x02,0x02,0xFE,0x00,0x00,0x00,0x00,0x40,0x40,0x40,0x7F,0x00,0x00,0x00,//]61 0x00,0x00,0x04,0x02,0x02,0x02,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,//^62 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,//_63 0x00,0x02,0x02,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,//`64 0x00,0x00,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x19,0x24,0x22,0x22,0x22,0x3F,0x20,//a65 0x08,0xF8,0x00,0x80,0x80,0x00,0x00,0x00,0x00,0x3F,0x11,0x20,0x20,0x11,0x0E,0x00,//b66 0x00,0x00,0x00,0x80,0x80,0x80,0x00,0x00,0x00,0x0E,0x11,0x20,0x20,0x20,0x11,0x00,//c67 0x00,0x00,0x00,0x80,0x80,0x88,0xF8,0x00,0x00,0x0E,0x11,0x20,0x20,0x10,0x3F,0x20,//d68 0x00,0x00,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x1F,0x22,0x22,0x22,0x22,0x13,0x00,//e69 0x00,0x80,0x80,0xF0,0x88,0x88,0x88,0x18,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,//f70 0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x6B,0x94,0x94,0x94,0x93,0x60,0x00,//g71 0x08,0xF8,0x00,0x80,0x80,0x80,0x00,0x00,0x20,0x3F,0x21,0x00,0x00,0x20,0x3F,0x20,//h72 0x00,0x80,0x98,0x98,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,//i73 0x00,0x00,0x00,0x80,0x98,0x98,0x00,0x00,0x00,0xC0,0x80,0x80,0x80,0x7F,0x00,0x00,//j74 0x08,0xF8,0x00,0x00,0x80,0x80,0x80,0x00,0x20,0x3F,0x24,0x02,0x2D,0x30,0x20,0x00,//k75 0x00,0x08,0x08,0xF8,0x00,0x00,0x00,0x00,0x00,0x20,0x20,0x3F,0x20,0x20,0x00,0x00,//l76 0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x00,0x20,0x3F,0x20,0x00,0x3F,0x20,0x00,0x3F,//m77 0x80,0x80,0x00,0x80,0x80,0x80,0x00,0x00,0x20,0x3F,0x21,0x00,0x00,0x20,0x3F,0x20,//n78 0x00,0x00,0x80,0x80,0x80,0x80,0x00,0x00,0x00,0x1F,0x20,0x20,0x20,0x20,0x1F,0x00,//o79 0x80,0x80,0x00,0x80,0x80,0x00,0x00,0x00,0x80,0xFF,0xA1,0x20,0x20,0x11,0x0E,0x00,//p80 0x00,0x00,0x00,0x80,0x80,0x80,0x80,0x00,0x00,0x0E,0x11,0x20,0x20,0xA0,0xFF,0x80,//q81 0x80,0x80,0x80,0x00,0x80,0x80,0x80,0x00,0x20,0x20,0x3F,0x21,0x20,0x00,0x01,0x00,//r82 0x00,0x00,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x33,0x24,0x24,0x24,0x24,0x19,0x00,//s83 0x00,0x80,0x80,0xE0,0x80,0x80,0x00,0x00,0x00,0x00,0x00,0x1F,0x20,0x20,0x00,0x00,//t84 0x80,0x80,0x00,0x00,0x00,0x80,0x80,0x00,0x00,0x1F,0x20,0x20,0x20,0x10,0x3F,0x20,//unsigned char5 0x80,0x80,0x80,0x00,0x00,0x80,0x80,0x80,0x00,0x01,0x0E,0x30,0x08,0x06,0x01,0x00,//v86 0x80,0x80,0x00,0x80,0x00,0x80,0x80,0x80,0x0F,0x30,0x0C,0x03,0x0C,0x30,0x0F,0x00,//w87 0x00,0x80,0x80,0x00,0x80,0x80,0x80,0x00,0x00,0x20,0x31,0x2E,0x0E,0x31,0x20,0x00,//x88 0x80,0x80,0x80,0x00,0x00,0x80,0x80,0x80,0x80,0x81,0x8E,0x70,0x18,0x06,0x01,0x00,//y89 0x00,0x80,0x80,0x80,0x80,0x80,0x80,0x00,0x00,0x21,0x30,0x2C,0x22,0x21,0x30,0x00,//z90 0x00,0x00,0x00,0x00,0x80,0x7C,0x02,0x02,0x00,0x00,0x00,0x00,0x00,0x3F,0x40,0x40,//{91 0x00,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,//|92 0x00,0x02,0x02,0x7C,0x80,0x00,0x00,0x00,0x00,0x40,0x40,0x3F,0x00,0x00,0x00,0x00,//}93 0x00,0x06,0x01,0x01,0x02,0x02,0x04,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 //~94 }; void LEDPIN_Init(void) { /* LED_SCL_Init; LED_SDA_Init; LED_RST_Init; LED_DC_Init;*/ pinMode(SCL_PIN,OUTPUT); pinMode(SDA_PIN,OUTPUT); pinMode(RST_PIN,OUTPUT); pinMode(DC_PIN,OUTPUT); } void LED_WrDat(unsigned char data) { unsigned char i = 8; //LED_CS=0; //LED_DCH;;; digitalWrite(DC_PIN,HIGH); //LED_SCLL;;; digitalWrite(SCL_PIN,LOW); while (i--) { if (data & 0x80) { digitalWrite(SDA_PIN,HIGH);;;; } else { digitalWrite(SDA_PIN,LOW);;; } //LED_SCLH;;; digitalWrite(SCL_PIN,HIGH);;; asm("nop");;; //LED_SCLL;;; digitalWrite(SCL_PIN,LOW); data <<= 1; } //LED_CS=1; } void LED_WrCmd(unsigned char cmd) { unsigned char i = 8; //LED_CS = 0; //LED_DCL;;; digitalWrite(DC_PIN,LOW);;; //LED_SCLL;;; digitalWrite(SCL_PIN,LOW);;; while (i--) { if (cmd & 0x80) { //LED_SDAH;;; digitalWrite(SDA_PIN,HIGH);;; } else { //LED_SDAL;;; digitalWrite(SDA_PIN,LOW);;; } //LED_SCLH;;; digitalWrite(SCL_PIN,HIGH);;; asm("nop");;; //LED_SCLL;;; digitalWrite(SCL_PIN,LOW);;; cmd <<= 1; } //LED_CS = 1; } void LED_Set_Pos(unsigned char x, unsigned char y) { LED_WrCmd(0xb0+y); LED_WrCmd(((x&0xf0)>>4)|0x10); LED_WrCmd((x&0x0f)|0x00); } void LED_Fill(unsigned char bmp_data) { unsigned char y,x; for(y=0;y<8;y++) { LED_WrCmd(0xb0+y); LED_WrCmd(0x00); LED_WrCmd(0x10); for(x=0;x<128;x++) LED_WrDat(bmp_data); } } void LED_CLS(void) { unsigned char y,x; for(y=0;y<8;y++) { LED_WrCmd(0xb0+y); LED_WrCmd(0x00); LED_WrCmd(0x10); for(x=0;x<128;x++) LED_WrDat(0); } } void LED_DLY_ms(unsigned int ms) { unsigned int a; while(ms) { a=6675; while(a--); ms--; } return; // time_delay_ms(ms); } void SetStartColumn(unsigned char d) { LED_WrCmd(0x00+d%16); // Set Lower Column Start Address for Page Addressing Mode // Default => 0x00 LED_WrCmd(0x10+d/16); // Set Higher Column Start Address for Page Addressing Mode // Default => 0x10 } void SetAddressingMode(unsigned char d) { LED_WrCmd(0x20); // Set Memory Addressing Mode LED_WrCmd(d); // Default => 0x02 // 0x00 => Horizontal Addressing Mode // 0x01 => Vertical Addressing Mode // 0x02 => Page Addressing Mode } void SetColumnAddress(unsigned char a, unsigned char b) { LED_WrCmd(0x21); // Set Column Address LED_WrCmd(a); // Default => 0x00 (Column Start Address) LED_WrCmd(b); // Default => 0x7F (Column End Address) } void SetPageAddress(unsigned char a, unsigned char b) { LED_WrCmd(0x22); // Set Page Address LED_WrCmd(a); // Default => 0x00 (Page Start Address) LED_WrCmd(b); // Default => 0x07 (Page End Address) } void SetStartLine(unsigned char d) { LED_WrCmd(0x40|d); // Set Display Start Line // Default => 0x40 (0x00) } void SetContrastControl(unsigned char d) { LED_WrCmd(0x81); // Set Contrast Control LED_WrCmd(d); // Default => 0x7F } void Set_Charge_Pump(unsigned char d) { LED_WrCmd(0x8D); // Set Charge Pump LED_WrCmd(0x10|d); // Default => 0x10 // 0x10 (0x00) => Disable Charge Pump // 0x14 (0x04) => Enable Charge Pump } void Set_Segment_Remap(unsigned char d) { LED_WrCmd(0xA0|d); // Set Segment Re-Map // Default => 0xA0 // 0xA0 (0x00) => Column Address 0 Mapped to SEG0 // 0xA1 (0x01) => Column Address 0 Mapped to SEG127 } void Set_Entire_Display(unsigned char d) { LED_WrCmd(0xA4|d); // Set Entire Display On / Off // Default => 0xA4 // 0xA4 (0x00) => Normal Display // 0xA5 (0x01) => Entire Display On } void Set_Inverse_Display(unsigned char d) { LED_WrCmd(0xA6|d); // Set Inverse Display On/Off // Default => 0xA6 // 0xA6 (0x00) => Normal Display // 0xA7 (0x01) => Inverse Display On } void Set_Multiplex_Ratio(unsigned char d) { LED_WrCmd(0xA8); // Set Multiplex Ratio LED_WrCmd(d); // Default => 0x3F (1/64 Duty) } void Set_Display_On_Off(unsigned char d) { LED_WrCmd(0xAE|d); // Set Display On/Off // Default => 0xAE // 0xAE (0x00) => Display Off // 0xAF (0x01) => Display On } void SetStartPage(unsigned char d) { LED_WrCmd(0xB0|d); // Set Page Start Address for Page Addressing Mode // Default => 0xB0 (0x00) } void Set_Common_Remap(unsigned char d) { LED_WrCmd(0xC0|d); // Set COM Output Scan Direction // Default => 0xC0 // 0xC0 (0x00) => Scan from COM0 to 63 // 0xC8 (0x08) => Scan from COM63 to 0 } void Set_Display_Offset(unsigned char d) { LED_WrCmd(0xD3); // Set Display Offset LED_WrCmd(d); // Default => 0x00 } void Set_Display_Clock(unsigned char d) { LED_WrCmd(0xD5); // Set Display Clock Divide Ratio / Oscillator Frequency LED_WrCmd(d); // Default => 0x80 // D[3:0] => Display Clock Divider // D[7:4] => Oscillator Frequency } void Set_Precharge_Period(unsigned char d) { LED_WrCmd(0xD9); // Set Pre-Charge Period LED_WrCmd(d); // Default => 0x22 (2 Display Clocks [Phase 2] / 2 Display Clocks [Phase 1]) // D[3:0] => Phase 1 Period in 1~15 Display Clocks // D[7:4] => Phase 2 Period in 1~15 Display Clocks } void Set_Common_Config(unsigned char d) { LED_WrCmd(0xDA); // Set COM Pins Hardware Configuration LED_WrCmd(0x02|d); // Default => 0x12 (0x10) // Alternative COM Pin Configuration // Disable COM Left/Right Re-Map } void Set_VCOMH(unsigned char d) { LED_WrCmd(0xDB); // Set VCOMH Deselect Level LED_WrCmd(d); // Default => 0x20 (0.77*VCC) } void Set_NOP(void) { LED_WrCmd(0xE3); // Command for No Operation } void LED_Init(void) { unsigned char i; LEDPIN_Init(); // LED_PORT=0X0F; //LED_SCLH;;; //LED_RSTL;;; digitalWrite(SCL_PIN,HIGH);;; digitalWrite(RST_PIN,LOW);;; // for(i=0;i<100;i++)asm("nop"); LED_DLY_ms(50); //LED_RSTH;;; digitalWrite(RST_PIN,HIGH); Set_Display_On_Off(0x00); // Display Off (0x00/0x01) Set_Display_Clock(0x80); // Set Clock as 100 Frames/Sec Set_Multiplex_Ratio(0x3F); // 1/64 Duty (0x0F~0x3F) Set_Display_Offset(0x00); // Shift Mapping RAM Counter (0x00~0x3F) SetStartLine(0x00); // Set Mapping RAM Display Start Line (0x00~0x3F) Set_Charge_Pump(0x04); // Enable Embedded DC/DC Converter (0x00/0x04) SetAddressingMode(0x02); // Set Page Addressing Mode (0x00/0x01/0x02) Set_Segment_Remap(0x01); // Set SEG/Column Mapping Set_Common_Remap(0x08); // Set COM/Row Scan Direction Set_Common_Config(0x10); // Set Sequential Configuration (0x00/0x10) SetContrastControl(0xCF); // Set SEG Output Current Set_Precharge_Period(0xF1); // Set Pre-Charge as 15 Clocks & Discharge as 1 Clock Set_VCOMH(0x40); // Set VCOM Deselect Level Set_Entire_Display(0x00); // Disable Entire Display On (0x00/0x01) Set_Inverse_Display(0x00); // Disable Inverse Display On (0x00/0x01) Set_Display_On_Off(0x01); // Display On (0x00/0x01) LED_Fill(0x00); //clear all LED_Set_Pos(0,0); } void LED_P8x16Str(unsigned char x,unsigned char y,char ch[]) { unsigned char c=0,i=0,j=0; while (ch[j]!='\0') { c =ch[j]-32; if(x>120) { x=0; y++; } LED_Set_Pos(x,y); for(i=0;i<8;i++) { LED_WrDat(F8X16[(c<<4)+i]); } LED_Set_Pos(x,y+1); for(i=0;i<8;i++) { LED_WrDat(F8X16[(c<<4)+i+8]); } x+=8; j++; } } void LED_Cursor(unsigned char cursor_column, unsigned char cursor_row) { if(cursor_row != 0) { if(cursor_column == 1) LED_Set_Pos(0, cursor_row + 2); else LED_Set_Pos(80 + (cursor_column - 2)*6, cursor_row + 2); LED_WrDat(0xFF); LED_WrDat(0xFF); LED_WrDat(0xFF); LED_WrDat(0xFF); LED_WrDat(0xFF); LED_WrDat(0xFF); } } void setup() { LEDPIN_Init(); LED_Init(); Serial.begin(9600); delay(15000);//Let system settle //init wifi WiFi.begin(ssid, password); Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("Humidity and temperature\n\n"); } void loop() { float temp; float hum; int lineNr = 0; char charTemp[10]; char charHum[10]; WiFiClient client1; if (!client1.connect(host,80)) { Serial.println("Connection client1 failed"); return; } WiFiClient client2; if (!client2.connect(host, 80)) { Serial.println("Connection client2 failed"); return; } Serial.println("Read temperature..."); // We now create a URI for the request String url = "/channels/CHID/fields/1/last.txt?api_key=ITTLLGD37U85571S"; // This will send the request to the server client1.print(String("GET ") + url + "&headers=false" + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n"); delay(2000);//was 500 originally // Read all the lines of the reply from server and print them to Serial while(client1.available()){ String line = client1.readStringUntil('\r'); lineNr++; Serial.println(line); Serial.println(lineNr); if(16==lineNr){ temp=line.toFloat(); break; }//if }//while //************* HUMIDITY ************************* Serial.println("Read humidity..."); lineNr=0; url = "/channels/CHID/fields/2/last.txt?api_key=ITTLLGD37U85571S"; //fields/2 -> humidity // This will send the request to the server client2.print(String("GET ") + url + "&headers=false" + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n"); delay(2000);//was 500 originally // Read all the lines of the reply from server and print them to Serial while(client2.available()){ String line = client2.readStringUntil('\r'); lineNr++; Serial.println(line); Serial.println(lineNr); if(16==lineNr){ hum=line.toFloat(); break; }//if }//while Serial.print("TEMP is: "); Serial.println(temp); Serial.print("HUM is: "); Serial.println(hum); Serial.println("Waiting for next try..."); LED_P8x16Str(0,0,"Room temp"); LED_P8x16Str(0,2,"Temp:"); dtostrf(temp, 4, 2, charTemp); LED_P8x16Str(70,2,charTemp); LED_P8x16Str(0,4,"Hum:"); dtostrf(hum, 4, 2, charHum); LED_P8x16Str(70,4,charHum); delay(30000); }
a0b82f895431575a4226e235d0aa666b2f5e83e5
52507f7928ba44b7266eddf0f1a9bf6fae7322a4
/SDK/BP_ChatBox_functions.cpp
7ced01b5e263e4764a8caa358f4f6ea24ee3d75e
[]
no_license
LuaFan2/mordhau-sdk
7268c9c65745b7af511429cfd3bf16aa109bc20c
ab10ad70bc80512e51a0319c2f9b5effddd47249
refs/heads/master
2022-11-30T08:14:30.825803
2020-08-13T16:31:27
2020-08-13T16:31:27
287,329,560
1
0
null
null
null
null
UTF-8
C++
false
false
25,617
cpp
#include "../SDK.h" // Name: Mordhau, Version: 1.0.0 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- // Function BP_ChatBox.BP_ChatBox_C.GetText_2 // (Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent, BlueprintPure) // Parameters: // struct FText ReturnValue (Parm, OutParm, ReturnParm) struct FText UBP_ChatBox_C::GetText_2() { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.GetText_2"); UBP_ChatBox_C_GetText_2_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function BP_ChatBox.BP_ChatBox_C.GetVisibility_4 // (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure) // Parameters: // ESlateVisibility ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) ESlateVisibility UBP_ChatBox_C::GetVisibility_4() { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.GetVisibility_4"); UBP_ChatBox_C_GetVisibility_4_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function BP_ChatBox.BP_ChatBox_C.GetVisibility_3 // (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure) // Parameters: // ESlateVisibility ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) ESlateVisibility UBP_ChatBox_C::GetVisibility_3() { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.GetVisibility_3"); UBP_ChatBox_C_GetVisibility_3_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function BP_ChatBox.BP_ChatBox_C.Get_TextArea_bIsEnabled_1 // (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UBP_ChatBox_C::Get_TextArea_bIsEnabled_1() { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.Get_TextArea_bIsEnabled_1"); UBP_ChatBox_C_Get_TextArea_bIsEnabled_1_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function BP_ChatBox.BP_ChatBox_C.GetVisibility_2 // (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure) // Parameters: // ESlateVisibility ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) ESlateVisibility UBP_ChatBox_C::GetVisibility_2() { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.GetVisibility_2"); UBP_ChatBox_C_GetVisibility_2_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function BP_ChatBox.BP_ChatBox_C.Repopulate Muted Player List // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) void UBP_ChatBox_C::Repopulate_Muted_Player_List() { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.Repopulate Muted Player List"); UBP_ChatBox_C_Repopulate_Muted_Player_List_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_ChatBox.BP_ChatBox_C.RemovePlayerFromMutedMap // (Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // struct FString SteamID (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor) // int SteamID_Index (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UBP_ChatBox_C::RemovePlayerFromMutedMap(const struct FString& SteamID, int* SteamID_Index) { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.RemovePlayerFromMutedMap"); UBP_ChatBox_C_RemovePlayerFromMutedMap_Params params; params.SteamID = SteamID; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (SteamID_Index != nullptr) *SteamID_Index = params.SteamID_Index; } // Function BP_ChatBox.BP_ChatBox_C.IsPlayerMuted // (Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // struct FString SteamID (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor) // TEnumAsByte<E_ChatMuteTypes> Mute_Type (Parm, OutParm, ZeroConstructor, IsPlainOldData) // bool isMuted (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UBP_ChatBox_C::IsPlayerMuted(const struct FString& SteamID, TEnumAsByte<E_ChatMuteTypes>* Mute_Type, bool* isMuted) { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.IsPlayerMuted"); UBP_ChatBox_C_IsPlayerMuted_Params params; params.SteamID = SteamID; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Mute_Type != nullptr) *Mute_Type = params.Mute_Type; if (isMuted != nullptr) *isMuted = params.isMuted; } // Function BP_ChatBox.BP_ChatBox_C.AddPlayerToMutedMap // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // struct FString SteamID (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor) // TEnumAsByte<E_ChatMuteTypes> Mute_Type (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) // struct FText Player_Name (BlueprintVisible, BlueprintReadOnly, Parm) void UBP_ChatBox_C::AddPlayerToMutedMap(const struct FString& SteamID, TEnumAsByte<E_ChatMuteTypes> Mute_Type, const struct FText& Player_Name) { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.AddPlayerToMutedMap"); UBP_ChatBox_C_AddPlayerToMutedMap_Params params; params.SteamID = SteamID; params.Mute_Type = Mute_Type; params.Player_Name = Player_Name; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_ChatBox.BP_ChatBox_C.Get Keys From Value // (Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // TMap<class UBP_ChatBoxEntry_C*, struct FString> PreviousMessagesMap (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor) // struct FString Value__SteamID_ (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor) // TArray<class UBP_ChatBoxEntry_C*> Keys (Parm, OutParm, ZeroConstructor) void UBP_ChatBox_C::Get_Keys_From_Value(TMap<class UBP_ChatBoxEntry_C*, struct FString> PreviousMessagesMap, const struct FString& Value__SteamID_, TArray<class UBP_ChatBoxEntry_C*>* Keys) { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.Get Keys From Value"); UBP_ChatBox_C_Get_Keys_From_Value_Params params; params.PreviousMessagesMap = PreviousMessagesMap; params.Value__SteamID_ = Value__SteamID_; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Keys != nullptr) *Keys = params.Keys; } // Function BP_ChatBox.BP_ChatBox_C.UnmutePlayer // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // struct FString SteamID (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor) void UBP_ChatBox_C::UnmutePlayer(const struct FString& SteamID) { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.UnmutePlayer"); UBP_ChatBox_C_UnmutePlayer_Params params; params.SteamID = SteamID; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_ChatBox.BP_ChatBox_C.MutePlayer // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // TEnumAsByte<E_ChatMuteTypes> MuteType (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) // struct FString SteamID (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor) // struct FText PlayerName (BlueprintVisible, BlueprintReadOnly, Parm) void UBP_ChatBox_C::MutePlayer(TEnumAsByte<E_ChatMuteTypes> MuteType, const struct FString& SteamID, const struct FText& PlayerName) { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.MutePlayer"); UBP_ChatBox_C_MutePlayer_Params params; params.MuteType = MuteType; params.SteamID = SteamID; params.PlayerName = PlayerName; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_ChatBox.BP_ChatBox_C.GetVisibility_1 // (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure) // Parameters: // ESlateVisibility ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) ESlateVisibility UBP_ChatBox_C::GetVisibility_1() { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.GetVisibility_1"); UBP_ChatBox_C_GetVisibility_1_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function BP_ChatBox.BP_ChatBox_C.ResetThreshold // (Public, BlueprintCallable, BlueprintEvent) void UBP_ChatBox_C::ResetThreshold() { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.ResetThreshold"); UBP_ChatBox_C_ResetThreshold_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_ChatBox.BP_ChatBox_C.GetText_1 // (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure) // Parameters: // struct FText ReturnValue (Parm, OutParm, ReturnParm) struct FText UBP_ChatBox_C::GetText_1() { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.GetText_1"); UBP_ChatBox_C_GetText_1_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function BP_ChatBox.BP_ChatBox_C.AddViewModeEntry // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // class UBP_ChatBoxEntry_C* Entry (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData) void UBP_ChatBox_C::AddViewModeEntry(class UBP_ChatBoxEntry_C* Entry) { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.AddViewModeEntry"); UBP_ChatBox_C_AddViewModeEntry_Params params; params.Entry = Entry; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_ChatBox.BP_ChatBox_C.AddEntriesEntry // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // class UBP_ChatBoxEntry_C* Entry (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData) void UBP_ChatBox_C::AddEntriesEntry(class UBP_ChatBoxEntry_C* Entry) { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.AddEntriesEntry"); UBP_ChatBox_C_AddEntriesEntry_Params params; params.Entry = Entry; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_ChatBox.BP_ChatBox_C.GetEntriesVisibility // (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure) // Parameters: // ESlateVisibility ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) ESlateVisibility UBP_ChatBox_C::GetEntriesVisibility() { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.GetEntriesVisibility"); UBP_ChatBox_C_GetEntriesVisibility_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function BP_ChatBox.BP_ChatBox_C.GetChatBoxVisibility // (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure) // Parameters: // ESlateVisibility ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) ESlateVisibility UBP_ChatBox_C::GetChatBoxVisibility() { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.GetChatBoxVisibility"); UBP_ChatBox_C_GetChatBoxVisibility_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function BP_ChatBox.BP_ChatBox_C.OnEscape // (Public, BlueprintCallable, BlueprintEvent) void UBP_ChatBox_C::OnEscape() { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.OnEscape"); UBP_ChatBox_C_OnEscape_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_ChatBox.BP_ChatBox_C.OnMessageReceived // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // struct FText Message (BlueprintVisible, BlueprintReadOnly, Parm) // class APlayerState* Player (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) // struct FText Prefix (BlueprintVisible, BlueprintReadOnly, Parm) void UBP_ChatBox_C::OnMessageReceived(const struct FText& Message, class APlayerState* Player, const struct FText& Prefix) { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.OnMessageReceived"); UBP_ChatBox_C_OnMessageReceived_Params params; params.Message = Message; params.Player = Player; params.Prefix = Prefix; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_ChatBox.BP_ChatBox_C.OnEnter // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) void UBP_ChatBox_C::OnEnter() { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.OnEnter"); UBP_ChatBox_C_OnEnter_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_ChatBox.BP_ChatBox_C.GoToChatMode // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // bool Team (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) void UBP_ChatBox_C::GoToChatMode(bool Team) { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.GoToChatMode"); UBP_ChatBox_C_GoToChatMode_Params params; params.Team = Team; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_ChatBox.BP_ChatBox_C.GetViewModeVisibility // (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure) // Parameters: // ESlateVisibility ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) ESlateVisibility UBP_ChatBox_C::GetViewModeVisibility() { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.GetViewModeVisibility"); UBP_ChatBox_C_GetViewModeVisibility_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function BP_ChatBox.BP_ChatBox_C.GetInputContainerVisibility // (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure) // Parameters: // ESlateVisibility ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) ESlateVisibility UBP_ChatBox_C::GetInputContainerVisibility() { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.GetInputContainerVisibility"); UBP_ChatBox_C_GetInputContainerVisibility_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function BP_ChatBox.BP_ChatBox_C.OnPreviewKeyDown // (Event, Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // struct FGeometry* MyGeometry (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData) // struct FKeyEvent* InKeyEvent (BlueprintVisible, BlueprintReadOnly, Parm) // struct FEventReply ReturnValue (Parm, OutParm, ReturnParm) struct FEventReply UBP_ChatBox_C::OnPreviewKeyDown(struct FGeometry* MyGeometry, struct FKeyEvent* InKeyEvent) { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.OnPreviewKeyDown"); UBP_ChatBox_C_OnPreviewKeyDown_Params params; params.MyGeometry = MyGeometry; params.InKeyEvent = InKeyEvent; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function BP_ChatBox.BP_ChatBox_C.AddEntry // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // struct FText PlayerName (BlueprintVisible, BlueprintReadOnly, Parm) // struct FText Message (BlueprintVisible, BlueprintReadOnly, Parm) // struct FLinearColor NameColor (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData) // struct FText Prefix (BlueprintVisible, BlueprintReadOnly, Parm) // struct FString SteamID (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor) void UBP_ChatBox_C::AddEntry(const struct FText& PlayerName, const struct FText& Message, const struct FLinearColor& NameColor, const struct FText& Prefix, const struct FString& SteamID) { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.AddEntry"); UBP_ChatBox_C_AddEntry_Params params; params.PlayerName = PlayerName; params.Message = Message; params.NameColor = NameColor; params.Prefix = Prefix; params.SteamID = SteamID; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_ChatBox.BP_ChatBox_C.Tick // (BlueprintCosmetic, Event, Public, BlueprintEvent) // Parameters: // struct FGeometry* MyGeometry (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData) // float* InDeltaTime (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) void UBP_ChatBox_C::Tick(struct FGeometry* MyGeometry, float* InDeltaTime) { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.Tick"); UBP_ChatBox_C_Tick_Params params; params.MyGeometry = MyGeometry; params.InDeltaTime = InDeltaTime; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_ChatBox.BP_ChatBox_C.Construct // (BlueprintCosmetic, Event, Public, BlueprintEvent) void UBP_ChatBox_C::Construct() { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.Construct"); UBP_ChatBox_C_Construct_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_ChatBox.BP_ChatBox_C.GoToViewMode // (BlueprintCallable, BlueprintEvent) void UBP_ChatBox_C::GoToViewMode() { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.GoToViewMode"); UBP_ChatBox_C_GoToViewMode_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_ChatBox.BP_ChatBox_C.GoToViewModeCallback // (BlueprintCallable, BlueprintEvent) void UBP_ChatBox_C::GoToViewModeCallback() { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.GoToViewModeCallback"); UBP_ChatBox_C_GoToViewModeCallback_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_ChatBox.BP_ChatBox_C.BndEvt__TextArea_K2Node_ComponentBoundEvent_594_OnMultiLineEditableTextBoxChangedEvent__DelegateSignature // (HasOutParms, BlueprintEvent) // Parameters: // struct FText Text (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm) void UBP_ChatBox_C::BndEvt__TextArea_K2Node_ComponentBoundEvent_594_OnMultiLineEditableTextBoxChangedEvent__DelegateSignature(const struct FText& Text) { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.BndEvt__TextArea_K2Node_ComponentBoundEvent_594_OnMultiLineEditableTextBoxChangedEvent__DelegateSignature"); UBP_ChatBox_C_BndEvt__TextArea_K2Node_ComponentBoundEvent_594_OnMultiLineEditableTextBoxChangedEvent__DelegateSignature_Params params; params.Text = Text; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_ChatBox.BP_ChatBox_C.BndEvt__CheckBox_0_K2Node_ComponentBoundEvent_1_OnCheckBoxComponentStateChanged__DelegateSignature // (BlueprintEvent) // Parameters: // bool bIsChecked (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) void UBP_ChatBox_C::BndEvt__CheckBox_0_K2Node_ComponentBoundEvent_1_OnCheckBoxComponentStateChanged__DelegateSignature(bool bIsChecked) { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.BndEvt__CheckBox_0_K2Node_ComponentBoundEvent_1_OnCheckBoxComponentStateChanged__DelegateSignature"); UBP_ChatBox_C_BndEvt__CheckBox_0_K2Node_ComponentBoundEvent_1_OnCheckBoxComponentStateChanged__DelegateSignature_Params params; params.bIsChecked = bIsChecked; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_ChatBox.BP_ChatBox_C.OnServerRestrictionInfoReceived // (HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // struct FServerRestrictionInfo ServerRestrictionInfo (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm) void UBP_ChatBox_C::OnServerRestrictionInfoReceived(const struct FServerRestrictionInfo& ServerRestrictionInfo) { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.OnServerRestrictionInfoReceived"); UBP_ChatBox_C_OnServerRestrictionInfoReceived_Params params; params.ServerRestrictionInfo = ServerRestrictionInfo; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_ChatBox.BP_ChatBox_C.OnMouseLeave // (BlueprintCosmetic, Event, Public, HasOutParms, BlueprintEvent) // Parameters: // struct FPointerEvent* MouseEvent (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm) void UBP_ChatBox_C::OnMouseLeave(struct FPointerEvent* MouseEvent) { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.OnMouseLeave"); UBP_ChatBox_C_OnMouseLeave_Params params; params.MouseEvent = MouseEvent; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_ChatBox.BP_ChatBox_C.OnMouseEnter // (BlueprintCosmetic, Event, Public, HasOutParms, BlueprintEvent) // Parameters: // struct FGeometry* MyGeometry (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData) // struct FPointerEvent* MouseEvent (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm) void UBP_ChatBox_C::OnMouseEnter(struct FGeometry* MyGeometry, struct FPointerEvent* MouseEvent) { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.OnMouseEnter"); UBP_ChatBox_C_OnMouseEnter_Params params; params.MyGeometry = MyGeometry; params.MouseEvent = MouseEvent; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_ChatBox.BP_ChatBox_C.ExecuteUbergraph_BP_ChatBox // (HasDefaults) // Parameters: // int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) void UBP_ChatBox_C::ExecuteUbergraph_BP_ChatBox(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function BP_ChatBox.BP_ChatBox_C.ExecuteUbergraph_BP_ChatBox"); UBP_ChatBox_C_ExecuteUbergraph_BP_ChatBox_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
060bf8d592f3a554ed5979276b5d950491cab439
bd1fea86d862456a2ec9f56d57f8948456d55ee6
/000/084/651/CWE190_Integer_Overflow__unsigned_int_rand_multiply_82a.cpp
260ee64b1dab562a749aa1e7e60dcf7d3d08da96
[]
no_license
CU-0xff/juliet-cpp
d62b8485104d8a9160f29213368324c946f38274
d8586a217bc94cbcfeeec5d39b12d02e9c6045a2
refs/heads/master
2021-03-07T15:44:19.446957
2020-03-10T12:45:40
2020-03-10T12:45:40
246,275,244
0
1
null
null
null
null
UTF-8
C++
false
false
2,892
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE190_Integer_Overflow__unsigned_int_rand_multiply_82a.cpp Label Definition File: CWE190_Integer_Overflow.label.xml Template File: sources-sinks-82a.tmpl.cpp */ /* * @description * CWE: 190 Integer Overflow * BadSource: rand Set data to result of rand() * GoodSource: Set data to a small, non-zero number (two) * Sinks: multiply * GoodSink: Ensure there will not be an overflow before multiplying data by 2 * BadSink : If data is positive, multiply by 2, which can cause an overflow * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer * * */ #include "std_testcase.h" #include "CWE190_Integer_Overflow__unsigned_int_rand_multiply_82.h" namespace CWE190_Integer_Overflow__unsigned_int_rand_multiply_82 { #ifndef OMITBAD void bad() { unsigned int data; data = 0; /* POTENTIAL FLAW: Use a random value */ data = (unsigned int)RAND32(); CWE190_Integer_Overflow__unsigned_int_rand_multiply_82_base* baseObject = new CWE190_Integer_Overflow__unsigned_int_rand_multiply_82_bad; baseObject->action(data); delete baseObject; } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { unsigned int data; data = 0; /* FIX: Use a small, non-zero value that will not cause an overflow in the sinks */ data = 2; CWE190_Integer_Overflow__unsigned_int_rand_multiply_82_base* baseObject = new CWE190_Integer_Overflow__unsigned_int_rand_multiply_82_goodG2B; baseObject->action(data); delete baseObject; } /* goodB2G uses the BadSource with the GoodSink */ static void goodB2G() { unsigned int data; data = 0; /* POTENTIAL FLAW: Use a random value */ data = (unsigned int)RAND32(); CWE190_Integer_Overflow__unsigned_int_rand_multiply_82_base* baseObject = new CWE190_Integer_Overflow__unsigned_int_rand_multiply_82_goodB2G; baseObject->action(data); delete baseObject; } void good() { goodG2B(); goodB2G(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE190_Integer_Overflow__unsigned_int_rand_multiply_82; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
a32c1316abe475b6a15b8abec8ff42197bde084c
cf3302a478551167d14c577be171fe0c1b4a3507
/src/cpp/muthurlib/Include/MLApi.h
1fc64155ac6c2716dee8fd0b56836a7c278dd6fb
[]
no_license
WilliamDrewAeroNomos/muthur
7babb320ed3bfb6ed7905a1a943e3d35aa03aedc
0c66c78af245ef3b06b92172e0df62eb54b3fb84
refs/heads/master
2016-09-05T11:15:50.083267
2015-07-01T15:49:56
2015-07-01T15:49:56
38,366,076
0
0
null
null
null
null
UTF-8
C++
false
false
9,658
h
//------------------------------------------------------------------------------ /*! \file MLApi.h // // Contains definitions and prototypes for the MuthurLib library // // <table> // <tr> <td colspan="4"><b>History</b> </tr> // <tr> <td>Date <td>Revision <td>Description <td>Author </tr> // <tr> <td>05-22-2011 <td>1.00 <td>Original Release <td>KRM </tr> // </table> // */ //------------------------------------------------------------------------------ // Copyright CSC - All Rights Reserved //------------------------------------------------------------------------------ #if !defined(__ML_API_H__) #define __ML_API_H__ //------------------------------------------------------------------------------ // INCLUDES //------------------------------------------------------------------------------ #ifndef VC_EXTRALEAN #define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers #endif #include <windows.h> #include <stdio.h> #include <stdlib.h> #include <cstdlib> #include <assert.h> #include <string> //#include <Reporter.h> //------------------------------------------------------------------------------ // DEFINES //------------------------------------------------------------------------------ #if defined (MUTHURLIB_EXPORT) #define MUTHURLIB_API __declspec(dllexport) #else #define MUTHURLIB_API __declspec(dllimport) #endif // Character buffer extents (includes NULL terminator) #define ML_MAXLEN_FEDERATE_NAME 64 #define ML_MAXLEN_MUTHUR_HB_QUEUE_NAME 128 #define ML_MAXLEN_MUTHUR_TM_QUEUE_NAME 128 #define ML_MAXLEN_MUTHUR_OWNERSHIP_QUEUE_NAME 128 #define ML_MAXLEN_FED_EXEC_MODEL_NAME 64 #define ML_MAXLEN_FED_EXEC_MODEL_DESCRIPTION 128 #define ML_MAXLEN_UUID 64 #define ML_MAXLEN_AIRCRAFT_TAIL_NUMBER 32 #define ML_MAXLEN_AIRCRAFT_ID 32 #define ML_MAXLEN_AIRPORT_ID 32 #define ML_MAXLEN_DEPT_AIRPORT_CODE 32 #define ML_MAXLEN_ARRIVAL_AIRPORT_CODE 32 #define ML_MAXLEN_SECTOR 32 #define ML_MAXLEN_CENTER 32 #define ML_MAXLEN_SOURCE 64 #define ML_MAXLEN_AIRCRAFT_TYPE 32 #define ML_MAXLEN_ROUTE 128 #define ML_MAXLEN_DEPT_CENTER 32 #define ML_MAXLEN_ARRIVAL_CENTER 32 #define ML_MAXLEN_DEPT_FIX 32 #define ML_MAXLEN_ARRIVAL_FIX 32 #define ML_MAXLEN_PHYSICAL_CLASS 32 #define ML_MAXLEN_WEIGHT_CLASS 32 #define ML_MAXLEN_USER_CLASS 32 #define ML_MAXLEN_EQUIPMENT_QUALIFIER 32 #define ML_MAXLEN_ID 16 #define ML_MAXLEN_EVENT_NAME 64 #define ML_MAXLEN_TYPE 16 #define ML_MAXLEN_DATAOBJECT_TYPE 128 #define ML_MAXLEN_CUSTOM_BUFFERS 100 #define ML_MAXLEN_STANDARD_BUFFERS 100 #define ML_MAXLEN_HANDLE_ID 64 #define ML_MAXLEN_MUTHUR_URL 256 #define ML_MAXLEN_SQUAWK 8 #define ML_MAXLEN_FREQ 8 #define ML_MAXLEN_PARKING_SPOT 8 #define ML_MAXLEN_ASSIGNED_RUNWAY 8 #define ML_MAXLEN_DATA_ACTION 8 # #define ML_XML_ROOT_ATTR_NAME "Properties" #define ML_XML_PROP_ATTR_NAME "Property" #define ML_XML_MEMBER_ID_ATTR_NAME "MemberId" #define ML_XML_PROPERTY_TYPE "Type" #define ML_XML_DEFAULT_DOUBLE_PRECISION 8 #define ML_XML_DEFAULT_SINGLE_PRECISION 4 #define ML_XML_BLOCK_NAME_CONTROL "controlBlock" #define ML_XML_BLOCK_NAME_DATA "dataBlock" #define ML_XML_BLOCK_NAME_ERROR "errorBlock" #define ML_XML_DATA_BLOCK_AIRCRAFT_ID "aircraftID" #define ML_XML_DATA_BLOCK_AIRPORT_ID "airportID" #define ML_XML_DATA_BLOCK_TAXI_OUT "taxiOutData" #define ML_XML_DATA_BLOCK_TAXI_IN "taxiInData" #define ML_XML_DATA_BLOCK_AC_ARRIVAL_DATA "arrivalData" #define ML_XML_DATA_BLOCK_AC_DEPT_DATA "departureData" #define ML_XML_DATA_BLOCK_FLIGHT_PLAN "flightPlanData" #define ML_XML_DATA_BLOCK_POSITION_DATA "positionData" #define ML_XML_DATA_BLOCK_RUNWAY_DATA "runway" #define ML_DEFAULT_MUTHUR_URL "LocalHost" #define ML_DEFAULT_MUTHUR_PORT 61616 #define ML_FREQ_OF_MUTHUR_HEARTBEATS 5 #define ML_XML_SYSEVENT_NAME_TERMINATE_FED "FederationTerminationEvent" #define ML_XML_SYSEVENT_NAME_RESET_REQUIRED "ResetRequiredEvent" //------------------------------------------------------------------------------ // CONSTANTS //------------------------------------------------------------------------------ /*! \enum EMLRequestClass // These values are used to identify the various classes derived from CMLEvent. // Each derived class has its own enumerated identifier */ typedef enum { ML_REQUEST_CLASS_BASE = 0, //!< CMLEvent class identifier ML_REQUEST_CLASS_REGISTER, //!< CMLRegisterRequest class identifier ML_REQUEST_CLASS_LIST_FEM, //!< CMLListFEMRequest class identifier ML_REQUEST_CLASS_JOIN_FED, //!< CMLJoinFedRequest class identifier ML_REQUEST_CLASS_ADD_DATA_SUB, //!< CMLAddDataSubRequest class identifier ML_REQUEST_CLASS_READY, //!< CMLReadyRequest class identifier ML_REQUEST_CLASS_CREATE_OBJ, //!< CMLCreateObjectParams class identifier ML_REQUEST_CLASS_DELETE_OBJ, //!< CMLDeleteObjectParams class identifier ML_REQUEST_CLASS_UPDATE_OBJ, //!< CMLUpdateObjectParams class identifier ML_REQUEST_CLASS_TRANSFER_OWNERSHIP, //!< CMLTransferObjectOwnershipParams class identifier ML_REQUEST_CLASS_RELINQUISH_OWNERSHIP, //!< CMLRelinquishObjectOwnershipParams class identifier ML_REQUEST_CLASS_TERMINATE, //!< CMLTerminateRequest class identifier ML_REQUEST_START_FEDERATIONS, //!< CMLStartFederationParams class identifier ML_REQUEST_PAUSE_FEDERATIONS, //!< CMLStartFederationParams class identifier ML_REQUEST_RESUME_FEDERATIONS, //!< CMLResumeFederationParams class identifier }EMLRequestClass; /*! \enum EMLRequestTypeClass // These values are used to identify the types of request events: request, data or system */ typedef enum { ML_REQUEST_STANDARD = 0, //!< Standard request event ML_REQUEST_DATA, //!< Data Publication event request ML_REQUEST_SYSTEM, //!< System event request }EMLRequestTypeClass; /*! \enum EMLResponseClass // These values are used to identify the various classes derived from CMLEvent. // Each derived class has its own enumerated identifier */ typedef enum { ML_RESPONSE_CLASS_BASE = 0, //!< CMLEvent class identifier ML_RESPONSE_CLASS_REGISTER, //!< CMLRegisterResponse class identifier ML_RESPONSE_CLASS_LIST_FEM, //!< CMLListFEMResponse class identifier ML_RESPONSE_CLASS_JOIN_FED, //!< CMLJoinFedResponse class identifier ML_RESPONSE_CLASS_ADD_DATA_SUB, //!< CMLAddDataSubResponse class identifier ML_RESPONSE_CLASS_CREATE_OBJECT, //!< CMLCreateObjectResponse class identifier ML_RESPONSE_CLASS_UPDATE_OBJECT, //!< CMLUpdateObjectResponse class identifier ML_RESPONSE_CLASS_DELETE_OBJECT, //!< CMLDeleteObjectResponse class identifier ML_RESPONSE_CLASS_RELINQUISH_OBJECT_OWNERSHIP, //!< CMLTransferObjectOwnershipResponse class identifier ML_RESPONSE_CLASS_TRANSFER_OBJECT_OWNERSHIP, //!< CMLTransferObjectOwnershipResponse class identifier ML_RESPONSE_CLASS_READY, //!< CMLReadyResponse class identifier ML_RESPONSE_CLASS_START_FED, //!< CMLStartFederationResponse class identifier ML_RESPONSE_CLASS_PAUSE_FED, //!< CMLPauseFederationResponse class identifier ML_RESPONSE_CLASS_RESUME_FED, //!< CMLResumeFederationResponse class identifier }EMLResponseClass; /*! \enum EMLSystemEventTypes // These values are used to identify the types of possible system events */ typedef enum { ML_SYSTEM_EVENT_UNKOWN = 0, //!< Terminate the active federation (either on error or normal shutdown) ML_SYSTEM_TERMINATE_FEDERATION, //!< Terminate the active federation (either on error or normal shutdown) ML_SYSTEM_RESET_REQUIRED, //!< Reset is required, usually the result of loosing comms with Muthur }EMLSystemEventTypes; /*! \enum EMLDataObjectClass // These values are used to identify the various classes derived from CMLDataObject. // Each derived class has its own enumerated identifier */ typedef enum { ML_DATAOBJECT_CLASS_BASE = 0, //!< CMLDataObject class identifier ML_DATAOBJECT_CLASS_AC_ARRIVAL, //!< CMLAircraftArrivalData class identifier ML_DATAOBJECT_CLASS_AC_DEPT, //!< CMLAircraftDepartureData class identifier ML_DATAOBJECT_CLASS_AC_TAXI_OUT, //!< CMLAircraftTaxiOut class identifier ML_DATAOBJECT_CLASS_AC_TAXI_IN, //!< CMLAircraftTaxiIn class identifier ML_DATAOBJECT_CLASS_FP_FILED, //!< CMLFlightPlan class identifier ML_DATAOBJECT_CLASS_FL_POSITION, //!< CMLFlightPosition class identifier ML_DATAOBJECT_CLASS_AIRCRAFT, //!< CMLAircraft class identifier ML_DATAOBJECT_CLASS_AIRPORT_CONFIG, //!< CMLAirportConfiguration class identifier }EMLDataObjectClass; typedef enum { ML_EVENT_STATUS_UNKNOWN = 0, //!< Uninitialized ML_EVENT_STATUS_PROCESSED, //!< Request was processed ML_EVENT_STATUS_IGNORED, //!< Request was ignored }EMLEventStatus; /*! \enum EMLXMLBlock // These values are used to identify XML property blocks */ typedef enum { ML_XML_BLOCK_UNKNOWN = 0, ML_XML_BLOCK_CONTROL, ML_XML_BLOCK_DATA, ML_XML_BLOCK_ERROR, ML_XML_BLOCK_AIRCRAFT_ID, ML_XML_BLOCK_AC_ARRIVAL, }EMLXMLBlock; #define ML_ADD_DATAOBJECT_STRING "Add" #define ML_UPDATE_DATAOBJECT_STRING "Update" #define ML_DELETE_DATAOBJECT_STRING "Delete" //------------------------------------------------------------------------------ // GLOBALS //------------------------------------------------------------------------------ #endif // !defined(__ML_API_H__)
e4e7ca1f47b3b131948a88bd34372206e5749334
36b22f80a3325d95bb913a4bd0b16a73d113906c
/src/bixd/consensus/LedgerTrie.h
fa4ad4bbbf83b859f976ee1898d313c34444042e
[ "MIT" ]
permissive
VardanMelik/bixrp-old
32ec279ba1d5e3ff1799a9c17ed6a5b884ba044a
eab3140ea4bc3ef65ff9e4d73d7badff5f39e6cf
refs/heads/main
2023-06-07T06:13:29.320600
2021-06-23T04:10:57
2021-06-23T04:10:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
26,786
h
//------------------------------------------------------------------------------ /* This file is part of bixd Copyright (c) 2017 bixd Labs Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #ifndef BIXD_APP_CONSENSUS_LEDGERS_TRIE_H_INCLUDED #define BIXD_APP_CONSENSUS_LEDGERS_TRIE_H_INCLUDED #include <bixd/basics/ToString.h> #include <bixd/basics/tagged_integer.h> #include <bixd/json/json_value.h> #include <boost/optional.hpp> #include <algorithm> #include <memory> #include <sstream> #include <stack> #include <vector> namespace bixd { /** The tip of a span of ledger ancestry */ template <class Ledger> class SpanTip { public: using Seq = typename Ledger::Seq; using ID = typename Ledger::ID; SpanTip(Seq s, ID i, Ledger const lgr) : seq{s}, id{i}, ledger{std::move(lgr)} { } // The sequence number of the tip ledger Seq seq; // The ID of the tip ledger ID id; /** Lookup the ID of an ancestor of the tip ledger @param s The sequence number of the ancestor @return The ID of the ancestor with that sequence number @note s must be less than or equal to the sequence number of the tip ledger */ ID ancestor(Seq const& s) const { assert(s <= seq); return ledger[s]; } private: Ledger const ledger; }; namespace ledger_trie_detail { // Represents a span of ancestry of a ledger template <class Ledger> class Span { using Seq = typename Ledger::Seq; using ID = typename Ledger::ID; // The span is the half-open interval [start,end) of ledger_ Seq start_{0}; Seq end_{1}; Ledger ledger_; public: Span() : ledger_{typename Ledger::MakeGenesis{}} { // Require default ledger to be genesis seq assert(ledger_.seq() == start_); } Span(Ledger ledger) : start_{0}, end_{ledger.seq() + Seq{1}}, ledger_{std::move(ledger)} { } Span(Span const& s) = default; Span(Span&& s) = default; Span& operator=(Span const&) = default; Span& operator=(Span&&) = default; Seq start() const { return start_; } Seq end() const { return end_; } // Return the Span from [spot,end_) or none if no such valid span boost::optional<Span> from(Seq spot) const { return sub(spot, end_); } // Return the Span from [start_,spot) or none if no such valid span boost::optional<Span> before(Seq spot) const { return sub(start_, spot); } // Return the ID of the ledger that starts this span ID startID() const { return ledger_[start_]; } // Return the ledger sequence number of the first possible difference // between this span and a given ledger. Seq diff(Ledger const& o) const { return clamp(mismatch(ledger_, o)); } // The tip of this span SpanTip<Ledger> tip() const { Seq tipSeq{end_ - Seq{1}}; return SpanTip<Ledger>{tipSeq, ledger_[tipSeq], ledger_}; } private: Span(Seq start, Seq end, Ledger const& l) : start_{start}, end_{end}, ledger_{l} { // Spans cannot be empty assert(start < end); } Seq clamp(Seq val) const { return std::min(std::max(start_, val), end_); } // Return a span of this over the half-open interval [from,to) boost::optional<Span> sub(Seq from, Seq to) const { Seq newFrom = clamp(from); Seq newTo = clamp(to); if (newFrom < newTo) return Span(newFrom, newTo, ledger_); return boost::none; } friend std::ostream& operator<<(std::ostream& o, Span const& s) { return o << s.tip().id << "[" << s.start_ << "," << s.end_ << ")"; } friend Span merge(Span const& a, Span const& b) { // Return combined span, using ledger_ from higher sequence span if (a.end_ < b.end_) return Span(std::min(a.start_, b.start_), b.end_, b.ledger_); return Span(std::min(a.start_, b.start_), a.end_, a.ledger_); } }; // A node in the trie template <class Ledger> struct Node { Node() = default; explicit Node(Ledger const& l) : span{l}, tipSupport{1}, branchSupport{1} { } explicit Node(Span<Ledger> s) : span{std::move(s)} { } Span<Ledger> span; std::uint32_t tipSupport = 0; std::uint32_t branchSupport = 0; std::vector<std::unique_ptr<Node>> children; Node* parent = nullptr; /** Remove the given node from this Node's children @param child The address of the child node to remove @note The child must be a member of the vector. The passed pointer will be dangling as a result of this call */ void erase(Node const* child) { auto it = std::find_if( children.begin(), children.end(), [child](std::unique_ptr<Node> const& curr) { return curr.get() == child; }); assert(it != children.end()); std::swap(*it, children.back()); children.pop_back(); } friend std::ostream& operator<<(std::ostream& o, Node const& s) { return o << s.span << "(T:" << s.tipSupport << ",B:" << s.branchSupport << ")"; } Json::Value getJson() const { Json::Value res; std::stringstream sps; sps << span; res["span"] = sps.str(); res["startID"] = to_string(span.startID()); res["seq"] = static_cast<std::uint32_t>(span.tip().seq); res["tipSupport"] = tipSupport; res["branchSupport"] = branchSupport; if (!children.empty()) { Json::Value& cs = (res["children"] = Json::arrayValue); for (auto const& child : children) { cs.append(child->getJson()); } } return res; } }; } // namespace ledger_trie_detail /** Ancestry trie of ledgers A compressed trie tree that maintains validation support of recent ledgers based on their ancestry. The compressed trie structure comes from recognizing that ledger history can be viewed as a string over the alphabet of ledger ids. That is, a given ledger with sequence number `seq` defines a length `seq` string, with i-th entry equal to the id of the ancestor ledger with sequence number i. "Sequence" strings with a common prefix share those ancestor ledgers in common. Tracking this ancestry information and relations across all validated ledgers is done conveniently in a compressed trie. A node in the trie is an ancestor of all its children. If a parent node has sequence number `seq`, each child node has a different ledger starting at `seq+1`. The compression comes from the invariant that any non-root node with 0 tip support has either no children or multiple children. In other words, a non-root 0-tip-support node can be combined with its single child. Each node has a tipSupport, which is the number of current validations for that particular ledger. The node's branch support is the sum of the tip support and the branch support of that node's children: @code node->branchSupport = node->tipSupport; for (child : node->children) node->branchSupport += child->branchSupport; @endcode The templated Ledger type represents a ledger which has a unique history. It should be lightweight and cheap to copy. @code // Identifier types that should be equality-comparable and copyable struct ID; struct Seq; struct Ledger { struct MakeGenesis{}; // The genesis ledger represents a ledger that prefixes all other // ledgers Ledger(MakeGenesis{}); Ledger(Ledger const&); Ledger& operator=(Ledger const&); // Return the sequence number of this ledger Seq seq() const; // Return the ID of this ledger's ancestor with given sequence number // or ID{0} if unknown ID operator[](Seq s); }; // Return the sequence number of the first possible mismatching ancestor // between two ledgers Seq mismatch(ledgerA, ledgerB); @endcode The unique history invariant of ledgers requires any ledgers that agree on the id of a given sequence number agree on ALL ancestors before that ledger: @code Ledger a,b; // For all Seq s: if(a[s] == b[s]); for(Seq p = 0; p < s; ++p) assert(a[p] == b[p]); @endcode @tparam Ledger A type representing a ledger and its history */ template <class Ledger> class LedgerTrie { using Seq = typename Ledger::Seq; using ID = typename Ledger::ID; using Node = ledger_trie_detail::Node<Ledger>; using Span = ledger_trie_detail::Span<Ledger>; // The root of the trie. The root is allowed to break the no-single child // invariant. std::unique_ptr<Node> root; // Count of the tip support for each sequence number std::map<Seq, std::uint32_t> seqSupport; /** Find the node in the trie that represents the longest common ancestry with the given ledger. @return Pair of the found node and the sequence number of the first ledger difference. */ std::pair<Node*, Seq> find(Ledger const& ledger) const { Node* curr = root.get(); // Root is always defined and is in common with all ledgers assert(curr); Seq pos = curr->span.diff(ledger); bool done = false; // Continue searching for a better span as long as the current position // matches the entire span while (!done && pos == curr->span.end()) { done = true; // Find the child with the longest ancestry match for (std::unique_ptr<Node> const& child : curr->children) { auto const childPos = child->span.diff(ledger); if (childPos > pos) { done = false; pos = childPos; curr = child.get(); break; } } } return std::make_pair(curr, pos); } /** Find the node in the trie with an exact match to the given ledger ID @return the found node or nullptr if an exact match was not found. @note O(n) since this searches all nodes until a match is found */ Node* findByLedgerID(Ledger const& ledger, Node* parent = nullptr) const { if (!parent) parent = root.get(); if (ledger.id() == parent->span.tip().id) return parent; for (auto const& child : parent->children) { auto cl = findByLedgerID(ledger, child.get()); if (cl) return cl; } return nullptr; } void dumpImpl(std::ostream& o, std::unique_ptr<Node> const& curr, int offset) const { if (curr) { if (offset > 0) o << std::setw(offset) << "|-"; std::stringstream ss; ss << *curr; o << ss.str() << std::endl; for (std::unique_ptr<Node> const& child : curr->children) dumpImpl(o, child, offset + 1 + ss.str().size() + 2); } } public: LedgerTrie() : root{std::make_unique<Node>()} { } /** Insert and/or increment the support for the given ledger. @param ledger A ledger and its ancestry @param count The count of support for this ledger */ void insert(Ledger const& ledger, std::uint32_t count = 1) { auto const [loc, diffSeq] = find(ledger); // There is always a place to insert assert(loc); // Node from which to start incrementing branchSupport Node* incNode = loc; // loc->span has the longest common prefix with Span{ledger} of all // existing nodes in the trie. The optional<Span>'s below represent // the possible common suffixes between loc->span and Span{ledger}. // // loc->span // a b c | d e f // prefix | oldSuffix // // Span{ledger} // a b c | g h i // prefix | newSuffix boost::optional<Span> prefix = loc->span.before(diffSeq); boost::optional<Span> oldSuffix = loc->span.from(diffSeq); boost::optional<Span> newSuffix = Span{ledger}.from(diffSeq); if (oldSuffix) { // Have // abcdef -> .... // Inserting // abc // Becomes // abc -> def -> ... // Create oldSuffix node that takes over loc auto newNode = std::make_unique<Node>(*oldSuffix); newNode->tipSupport = loc->tipSupport; newNode->branchSupport = loc->branchSupport; newNode->children = std::move(loc->children); assert(loc->children.empty()); for (std::unique_ptr<Node>& child : newNode->children) child->parent = newNode.get(); // Loc truncates to prefix and newNode is its child assert(prefix); loc->span = *prefix; newNode->parent = loc; loc->children.emplace_back(std::move(newNode)); loc->tipSupport = 0; } if (newSuffix) { // Have // abc -> ... // Inserting // abcdef-> ... // Becomes // abc -> ... // \-> def auto newNode = std::make_unique<Node>(*newSuffix); newNode->parent = loc; // increment support starting from the new node incNode = newNode.get(); loc->children.push_back(std::move(newNode)); } incNode->tipSupport += count; while (incNode) { incNode->branchSupport += count; incNode = incNode->parent; } seqSupport[ledger.seq()] += count; } /** Decrease support for a ledger, removing and compressing if possible. @param ledger The ledger history to remove @param count The amount of tip support to remove @return Whether a matching node was decremented and possibly removed. */ bool remove(Ledger const& ledger, std::uint32_t count = 1) { Node* loc = findByLedgerID(ledger); // Must be exact match with tip support if (!loc || loc->tipSupport == 0) return false; // found our node, remove it count = std::min(count, loc->tipSupport); loc->tipSupport -= count; auto const it = seqSupport.find(ledger.seq()); assert(it != seqSupport.end() && it->second >= count); it->second -= count; if (it->second == 0) seqSupport.erase(it->first); Node* decNode = loc; while (decNode) { decNode->branchSupport -= count; decNode = decNode->parent; } while (loc->tipSupport == 0 && loc != root.get()) { Node* parent = loc->parent; if (loc->children.empty()) { // this node can be erased parent->erase(loc); } else if (loc->children.size() == 1) { // This node can be combined with its child std::unique_ptr<Node> child = std::move(loc->children.front()); child->span = merge(loc->span, child->span); child->parent = parent; parent->children.emplace_back(std::move(child)); parent->erase(loc); } else break; loc = parent; } return true; } /** Return count of tip support for the specific ledger. @param ledger The ledger to lookup @return The number of entries in the trie for this *exact* ledger */ std::uint32_t tipSupport(Ledger const& ledger) const { if (auto const* loc = findByLedgerID(ledger)) return loc->tipSupport; return 0; } /** Return the count of branch support for the specific ledger @param ledger The ledger to lookup @return The number of entries in the trie for this ledger or a descendant */ std::uint32_t branchSupport(Ledger const& ledger) const { Node const* loc = findByLedgerID(ledger); if (!loc) { Seq diffSeq; std::tie(loc, diffSeq) = find(ledger); // Check that ledger is a proper prefix of loc if (!(diffSeq > ledger.seq() && ledger.seq() < loc->span.end())) loc = nullptr; } return loc ? loc->branchSupport : 0; } /** Return the preferred ledger ID The preferred ledger is used to determine the working ledger for consensus amongst competing alternatives. Recall that each validator is normally validating a chain of ledgers, e.g. A->B->C->D. However, if due to network connectivity or other issues, validators generate different chains @code /->C A->B \->D->E @endcode we need a way for validators to converge on the chain with the most support. We call this the preferred ledger. Intuitively, the idea is to be conservative and only switch to a different branch when you see enough peer validations to *know* another branch won't have preferred support. The preferred ledger is found by walking this tree of validated ledgers starting from the common ancestor ledger. At each sequence number, we have - The prior sequence preferred ledger, e.g. B. - The (tip) support of ledgers with this sequence number,e.g. the number of validators whose last validation was for C or D. - The (branch) total support of all descendants of the current sequence number ledgers, e.g. the branch support of D is the tip support of D plus the tip support of E; the branch support of C is just the tip support of C. - The number of validators that have yet to validate a ledger with this sequence number (uncommitted support). Uncommitted includes all validators whose last sequence number is smaller than our last issued sequence number, since due to asynchrony, we may not have heard from those nodes yet. The preferred ledger for this sequence number is then the ledger with relative majority of support, where uncommitted support can be given to ANY ledger at that sequence number (including one not yet known). If no such preferred ledger exists, then the prior sequence preferred ledger is the overall preferred ledger. In this example, for D to be preferred, the number of validators supporting it or a descendant must exceed the number of validators supporting C _plus_ the current uncommitted support. This is because if all uncommitted validators end up validating C, that new support must be less than that for D to be preferred. If a preferred ledger does exist, then we continue with the next sequence using that ledger as the root. @param largestIssued The sequence number of the largest validation issued by this node. @return Pair with the sequence number and ID of the preferred ledger or boost::none if no preferred ledger exists */ boost::optional<SpanTip<Ledger>> getPreferred(Seq const largestIssued) const { if (empty()) return boost::none; Node* curr = root.get(); bool done = false; std::uint32_t uncommitted = 0; auto uncommittedIt = seqSupport.begin(); while (curr && !done) { // Within a single span, the preferred by branch strategy is simply // to continue along the span as long as the branch support of // the next ledger exceeds the uncommitted support for that ledger. { // Add any initial uncommitted support prior for ledgers // earlier than nextSeq or earlier than largestIssued Seq nextSeq = curr->span.start() + Seq{1}; while (uncommittedIt != seqSupport.end() && uncommittedIt->first < std::max(nextSeq, largestIssued)) { uncommitted += uncommittedIt->second; uncommittedIt++; } // Advance nextSeq along the span while (nextSeq < curr->span.end() && curr->branchSupport > uncommitted) { // Jump to the next seqSupport change if (uncommittedIt != seqSupport.end() && uncommittedIt->first < curr->span.end()) { nextSeq = uncommittedIt->first + Seq{1}; uncommitted += uncommittedIt->second; uncommittedIt++; } else // otherwise we jump to the end of the span nextSeq = curr->span.end(); } // We did not consume the entire span, so we have found the // preferred ledger if (nextSeq < curr->span.end()) return curr->span.before(nextSeq)->tip(); } // We have reached the end of the current span, so we need to // find the best child Node* best = nullptr; std::uint32_t margin = 0; if (curr->children.size() == 1) { best = curr->children[0].get(); margin = best->branchSupport; } else if (!curr->children.empty()) { // Sort placing children with largest branch support in the // front, breaking ties with the span's starting ID std::partial_sort( curr->children.begin(), curr->children.begin() + 2, curr->children.end(), [](std::unique_ptr<Node> const& a, std::unique_ptr<Node> const& b) { return std::make_tuple( a->branchSupport, a->span.startID()) > std::make_tuple( b->branchSupport, b->span.startID()); }); best = curr->children[0].get(); margin = curr->children[0]->branchSupport - curr->children[1]->branchSupport; // If best holds the tie-breaker, gets one larger margin // since the second best needs additional branchSupport // to overcome the tie if (best->span.startID() > curr->children[1]->span.startID()) margin++; } // If the best child has margin exceeding the uncommitted support, // continue from that child, otherwise we are done if (best && ((margin > uncommitted) || (uncommitted == 0))) curr = best; else // current is the best done = true; } return curr->span.tip(); } /** Return whether the trie is tracking any ledgers */ bool empty() const { return !root || root->branchSupport == 0; } /** Dump an ascii representation of the trie to the stream */ void dump(std::ostream& o) const { dumpImpl(o, root, 0); } /** Dump JSON representation of trie state */ Json::Value getJson() const { Json::Value res; res["trie"] = root->getJson(); res["seq_support"] = Json::objectValue; for (auto const& [seq, sup] : seqSupport) res["seq_support"][to_string(seq)] = sup; return res; } /** Check the compressed trie and support invariants. */ bool checkInvariants() const { std::map<Seq, std::uint32_t> expectedSeqSupport; std::stack<Node const*> nodes; nodes.push(root.get()); while (!nodes.empty()) { Node const* curr = nodes.top(); nodes.pop(); if (!curr) continue; // Node with 0 tip support must have multiple children // unless it is the root node if (curr != root.get() && curr->tipSupport == 0 && curr->children.size() < 2) return false; // branchSupport = tipSupport + sum(child->branchSupport) std::size_t support = curr->tipSupport; if (curr->tipSupport != 0) expectedSeqSupport[curr->span.end() - Seq{1}] += curr->tipSupport; for (auto const& child : curr->children) { if (child->parent != curr) return false; support += child->branchSupport; nodes.push(child.get()); } if (support != curr->branchSupport) return false; } return expectedSeqSupport == seqSupport; } }; } // namespace bixd #endif
aa693ca1b0462fae0c5ca84f327fc52a7d60a1a8
8aa507b8f4f0ae362812d84234c64e632373c2d8
/map.h
0d2083a99dc68a15da0be9e0a9a05770f899a1f7
[]
no_license
Centronics/MySEH
87c93f48fb683d9a4d02e80ae4e8a8078e3b18e0
076bf87098e5a170907923c5e96f5e4f9629fc1c
refs/heads/master
2020-05-29T17:50:42.634548
2020-03-19T20:05:27
2020-03-19T20:05:27
189,285,184
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
3,690
h
#pragma once #include <map> #include <iostream> #include <vector> #include <string> using namespace std; class BigClass { public: unsigned char cr[524288];//000]; // не хватит размера кучи }; class MyMap { public: MyMap(const initializer_list<int>& elems) { } MyMap(int i) { } MyMap(float, int) { } }; void vd(int& i) {} inline void MultiMapTest() { int u; vd(u); multimap<int, char> mm; mm.insert(pair<int, char>(10, 'a')); mm.insert(pair<int, char>(10, 'a')); mm.insert(pair<int, char>(10, 'a')); mm.insert(pair<int, char>(13, 'a')); auto mb = mm.insert(pair<int, char>(15, 'b')); multimap<int, char>::iterator i = mm.find(10);//только ключ auto t1 = i->first; auto t2 = i->second; i->second = 'c'; // только значение можно менять (second) //*i=180;//pair<int, char>(180, 'a'); // перечисляем все элементы /*for(auto& e : mm) // поменяет все на s { e.second = 's'; //e.first = 10; // писать нельзя }*/ auto f1 = mm.lower_bound(10); // нижний диапазон auto f2 = mm.upper_bound(10); // верхний диапазон mm.erase(f1); mm.erase(f2); mm.erase(10); // удалит все элементы с ключами 10 mm.erase(mb); } inline void MapTest() { MultiMapTest(); map<int, BigClass> bg; // можно const size_t sz = sizeof(map<int, BigClass>); map<char*, int> mp; mp.insert(std::pair<char*, int>("a", 100)); // не может вставить, если такой уже есть mp.insert(std::pair<char*, int>("a", 102)); mp.insert(std::pair<char*, int>("b", 101)); map<void*, int> mp1; int i, i1; mp1.insert(std::pair<void*, int>(&i, 100)); mp1.insert(std::pair<void*, int>(&i1, 100)); map<string, int> test_map; test_map["ten"] = 10; // изменяет существующий test_map["ten"] = 8; test_map["ten"] = 9; /* В mm элементы будут расположены по ключу в порядке инициализации: {'a',1},{'a',4},{'a',5},{'b',2},{'c',3},{'c',1}. * Инициализация m начнётся со второго элемента и закончится до первого элемента с ключём 'c'. Значит, m будет содержать {'a',4} и {'b',2}. * В первом цикле изменяется копия m, то есть во втором цикле будет выведена неизменённая исходная карта. * Программа выведет: 4 2. */ multimap<char, int> mm = { {'a',1}, {'b',2}, {'c',3}, {'a',4}, {'a',5}, {'c',1} }; map<char, int> m(++mm.begin(), mm.lower_bound('c')); for (auto i : m) ++i.second; for (decltype(auto) i : m) cout << i.second << ' '; map<string, size_t> albums = { {"Coven", 1991}, {"Fool", 1997} }; auto[position, inserted] = albums.emplace("Outcast", 2005); for (const auto&[name, year] : albums) cout << name << ": " << year << "\n"; MyMap mp2 = { 1, 2, 3 }; MyMap op = 9; // explicit даёт здесь ошибку. При нём надо писать static_cast<MyMap>(9). MyMap(6.7f, 23); initializer_list<float> el(nullptr, nullptr); // ЗАДАЧА по нахождению дубликатов vector<string> names = { "photo", "photo(1)", "photo", "doc", "photo(1)", "photo(2)", "photo" }; // {"photo", "photo", "doc", "photo(1)", "photo"}; // изначальный map<string, int> libNames; for (auto& t : names) { const string ct = t; auto e = libNames[t]; if (e > 0) { t += '('; t += to_string(e); t += ')'; libNames[t] = e; } ++e; libNames[ct] = e; } }
ad9cbdcbe4c4bc83f7898d5b046468c78a38292c
612325535126eaddebc230d8c27af095c8e5cc2f
/src/base/win/scoped_hdc.h
c160d49b854ff39a9fcbd7aeb941d52d02315e5d
[ "BSD-3-Clause" ]
permissive
TrellixVulnTeam/proto-quic_1V94
1a3a03ac7a08a494b3d4e9857b24bb8f2c2cd673
feee14d96ee95313f236e0f0e3ff7719246c84f7
refs/heads/master
2023-04-01T14:36:53.888576
2019-10-17T02:23:04
2019-10-17T02:23:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,857
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_WIN_SCOPED_HDC_H_ #define BASE_WIN_SCOPED_HDC_H_ #include <windows.h> #include "base/debug/gdi_debug_util_win.h" #include "base/logging.h" #include "base/macros.h" #include "base/win/scoped_handle.h" namespace base { namespace win { // Like ScopedHandle but for HDC. Only use this on HDCs returned from // GetDC. class ScopedGetDC { public: explicit ScopedGetDC(HWND hwnd) : hwnd_(hwnd), hdc_(GetDC(hwnd)) { if (hwnd_) { DCHECK(IsWindow(hwnd_)); DCHECK(hdc_); } else { // If GetDC(NULL) returns NULL, something really bad has happened, like // GDI handle exhaustion. In this case Chrome is going to behave badly no // matter what, so we may as well just force a crash now. if (!hdc_) base::debug::CollectGDIUsageAndDie(); } } ~ScopedGetDC() { if (hdc_) ReleaseDC(hwnd_, hdc_); } operator HDC() { return hdc_; } private: HWND hwnd_; HDC hdc_; DISALLOW_COPY_AND_ASSIGN(ScopedGetDC); }; // Like ScopedHandle but for HDC. Only use this on HDCs returned from // CreateCompatibleDC, CreateDC and CreateIC. class CreateDCTraits { public: typedef HDC Handle; static bool CloseHandle(HDC handle) { return ::DeleteDC(handle) != FALSE; } static bool IsHandleValid(HDC handle) { return handle != NULL; } static HDC NullHandle() { return NULL; } private: DISALLOW_IMPLICIT_CONSTRUCTORS(CreateDCTraits); }; typedef GenericScopedHandle<CreateDCTraits, DummyVerifierTraits> ScopedCreateDC; } // namespace win } // namespace base #endif // BASE_WIN_SCOPED_HDC_H_
aa75fb48d77a89f54362eb26b7fe4cd7559310df
c5784cc1f59a863b52a34f592898b8ab4230e6cb
/Code-for-lessons/Information Security/exp_4/rsa.h
b58761b5bb1fc35fa94c8ff18e78e2548f3ee722
[]
no_license
Aeonni/MyGarage
6f28bb332cd6b90fea6520ce41cf87252e6b129c
52c8dfb3cec675007d8ad3cf3747aa00ab638b27
refs/heads/master
2020-05-02T10:56:49.363559
2019-07-10T13:58:48
2019-07-10T13:58:48
177,912,604
0
0
null
null
null
null
UTF-8
C++
false
false
412
h
#ifndef RSA_H #define RSA_H #include "mpir.h" #include "gmp.h" #include "encoding.h" #include <iostream> using namespace std; void get_prime(mpz_t prime, gmp_randstate_t grt, int length); void calc_phiN(mpz_t phi_n, mpz_t p, mpz_t q); void get_e(mpz_t e, gmp_randstate_t grt, mpz_t phi_n); void gen_keys(mpz_t p, mpz_t q, mpz_t n, mpz_t e, mpz_t d, size_t length); int test(size_t length = 2048); #endif
af56a9a1c9cd09ef7a6250a2c004eda7ad459f07
23b721f54ccdd030ce9a8797613d1f215cf95f45
/Libraryload/library.cpp
1fa4410dee5a6834f4a31820370bb57ac70b4a46
[]
no_license
Lonnyhuang/BaseLibarary
cb9491cdc8f5c44fa820e5b27d38ea4ea23e4e0d
e82314342b8294f31ebda4c0d1d1a071982766e4
refs/heads/master
2021-05-18T12:54:06.974162
2020-12-09T09:29:10
2020-12-09T09:29:10
251,250,471
0
0
null
null
null
null
UTF-8
C++
false
false
1,324
cpp
#include "library.h" #include "libraryprivate.h" HCommon::Library::Library():Object(*new LibraryPrivate()) { } HCommon::Library::~Library() { } bool HCommon::Library::load(std::string name, bool ignoreError) { return this->load(name, "", ignoreError); } bool HCommon::Library::load(std::string name, int verNum, bool ignoreError) { return this->load(name, std::to_string(verNum), ignoreError); } bool HCommon::Library::load(std::string name, std::string version, bool ignoreError) { D_PTR(Library) d->setFileNameAndVersion(name, version); bool re = d->load(); if(!ignoreError){ DefaultErrorHandler().OnLoadLibrary(name.c_str()); } return re; } void HCommon::Library::Unload() { D_PTR(Library) return d->Unload(); } void *HCommon::Library::resolve(const std::string funcname, bool ignoreError) { D_PTR(Library) void *ptr = d->resolve(funcname); if(!ignoreError){ DefaultErrorHandler().OnLoadSymbol(funcname.c_str(), ignoreError); return ptr; } else return ptr; } bool HCommon::Library::isLoad() { D_PTR(Library) return d->isLoad(); } std::string HCommon::Library::fileName() { D_PTR(Library) return d->fileName(); } std::string HCommon::Library::version() { D_PTR(Library) return d->version(); }
f32a6fc561d7aec9e6b4800989431d7a6a56d694
36ed85609e97bc73c8c7f2dc257ba69507e6abd2
/Trie/suffixTree.cpp
8bb09ba78a71ede2fc74be43b9c75c2d5e1ac8e6
[]
no_license
rk946/cpp
464f57cab02001fd0a79f1354cce682a32d368bd
256d175b0bc49e3e51eb828dbd637eaac43b603b
refs/heads/master
2023-07-14T05:49:13.764214
2021-08-16T12:32:12
2021-08-16T12:32:12
275,735,567
0
0
null
2021-08-16T09:29:23
2020-06-29T05:06:07
C++
UTF-8
C++
false
false
1,029
cpp
#include<bits/stdc++.h> using namespace std; class Node{ public: char data; unordered_map<char,Node*> m; bool isTerminal; Node(){ isTerminal=false; } Node(char c) { data=c; isTerminal=false; } }; class Trie{ public: Node*root; Trie(){ root= new Node('\0'); } void insert_helper(string word){ Node*temp = root; for(char c: word) { if(temp->m.count(c)==0) { Node*n = new Node(c); temp->m[c]=n; } temp=temp->m[c]; } temp->isTerminal=true; } bool search(string word){ Node*temp = root; for(char ch:word) { if(temp->m.count(ch)==0) return false; temp=temp->m[ch]; } if(temp->isTerminal==true) return true; return false; } void insert(string word){ int n = word.length(); for(int i=0;i<n-1;i++) { insert_helper(word.substr(i)); } } }; int main(){ string s = "hello"; string suffixes[]={"lo","ell","hello"}; Trie t; t.insert(s); for(auto sf:suffixes) { if(t.search(sf)) cout <<"Yes "; else cout <<"No"; } return 0; }
07f6b364da1d14aeea2671f3a83f42e8dda87fbd
0e0bbc2f8b45df5c855d1bf58cc47defc2ea2179
/cambienmua/cambienmua.ino
8dc20d024f2f2634a48c808919060c07f23088dd
[]
no_license
tridung141196/HACKATHON-DEVICES
758950875edec0446df37b8824d53f8a35dad59c
8f7655a717772f180e4efb57a2c543179cb83bba
refs/heads/master
2021-05-07T20:40:49.024118
2017-10-31T09:58:29
2017-10-31T09:58:29
108,936,826
0
0
null
2017-10-31T02:54:23
2017-10-31T02:54:23
null
UTF-8
C++
false
false
809
ino
int rainSensor = 15; // Chân tín hiệu cảm biến mưa ở chân digital 6 (arduino) void setup() { pinMode(rainSensor,INPUT);// Đặt chân cảm biến mưa là INPUT, vì tín hiệu sẽ được truyền đến cho Arduino Serial.begin(9600);// Khởi động Serial ở baudrate 9600 Serial.println("Da khoi dong xong"); } void loop() { int value = digitalRead(rainSensor);//Đọc tín hiệu cảm biến mưa if (value == HIGH) { // Cảm biến đang không mưa Serial.println("Dang khong mua"); } else { Serial.println("Dang mua"); } delay(1000); // Đợi 1 tí cho lần kiểm tra tiếp theo. Bạn hãy tham khảo bài "Viết chương trình không dùng làm delay" trên Arduino.VN để kết hợp đoạn code này và cả chương trình của bạn }
fbcbca4a058579ed63effe3fe30a1ac2db2832dc
6796e4c70100172c1166a649d7d6d6c32e053c5d
/SdlGame/rigidbody.h
72482e2efa33d65fc96defee08386dcf0f715ad8
[]
no_license
KKozlowski/SdlGame
c4a54a52bb857c86b1e286c1c8389182656ed660
822413178a595bb15ee0eebcc42128e01c201daa
refs/heads/master
2021-05-01T15:23:11.046976
2016-08-21T14:51:03
2016-08-21T14:51:03
63,421,713
0
0
null
null
null
null
UTF-8
C++
false
false
227
h
#pragma once #include "actor_component.h" #include "vector2.h" class rigidbody : public actor_component { private: public: vector2f velocity; float drag = 0.f; rigidbody(actor *a); virtual void update() override; };
425805e851b29d373f57d496dbf24a0fec1043b1
7200d66329486d7d7b92552ac72d82f3f72a47de
/lab13/application.cpp
1b0a4b2eef3f2847951a17d6b0cbed8caf4367d3
[]
no_license
duartega/Programming-II---cs215
c135090ac8f069a81287a4a7f48a7f7130950ee5
516c53d3060c7f976f0c7ce49a6275f1909b9167
refs/heads/master
2020-04-11T04:49:02.245145
2018-12-12T18:15:44
2018-12-12T18:15:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
892
cpp
#include <iostream> #include "LList2.hpp" using namespace std; #define MAX 10 int main() { LList2 <int> L1, L2; for (int i = 0; i < MAX; i++) if (i%2) L1.InsertFirst (i); else L1.InsertLast (i); cout << "L1 in order: "; cout << L1 << endl; cout << "Tesing the [] operator \n"; cout << "First to last :\n"; for (int i = 0; i < L1.Size(); i++) cout << "L1[" << i << "] is " << L1[i] << endl; L1[3] = 7; cout << "Last to first : \n"; for (int i = L1.Size()-1; i >= 0; i--) cout << "L1[" << i << "] is " << L1[i] << endl; cout << "This is the value: "; for (LList2<int>::Iterator itr = L1.begin(); itr != L1.end(); itr++) { cout << *itr << ' '; } cout << endl; for (LList2<int>::Iterator itr = L1.begin(); itr != L1.end(); itr++) { int x = *itr; cout << x << ' '; } cout << endl; return 0; }
a64e746959dd639943321c02fe74818980656c56
b11c9c0cdcb28ca005ef89630a180f101778661a
/src/Situation.cpp
d53a7db3a7e8d8fddb763fe43aeca9937eebfe4d
[]
no_license
sfdevgirl/Humanoid
ce6f4943b5c31fbda60b943a9c35e3a1a7400cbf
fac236c1e3abf5e5a9c85a0c07b26423d127d46c
refs/heads/master
2021-05-03T21:56:21.511547
2016-10-25T19:38:54
2016-10-25T19:38:54
71,571,492
0
2
null
2017-07-25T12:37:39
2016-10-21T14:18:47
C++
UTF-8
C++
false
false
748
cpp
/* * Situation.cpp * * Created on: Oct 20, 2016 * Author: linuxuser */ #include "Situation.hpp" #include "Humanoid.hpp" Situation::Situation() { // TODO Auto-generated constructor stub } Situation::~Situation() { // TODO Auto-generated destructor stub } void Situation::fight(Humanoid *a, Humanoid *b){ // if(newEvilHuman->getRank() > newGoodHuman->getRank()){ // cout << "True\n"; // } if (a->getRank() > b->getRank()){ cout << a->whoami() << " has killed " << b->whoami() << endl; }//if else if (a->getRank() < b->getRank()){ cout << b->whoami() << " has killed " << a->whoami() << endl; }//else if else if ( a->getRank() == b->getRank()){ cout << "No fight here!\n"; }//else if else{} }//sich
8addbbd144000544c4b150deafba32c9ae6544cf
14722fa6327ed96d1913e4d45bdc99298cca5fc8
/ue/ue1/src/mergesort.h
abcd8d63a7a0cd08807d2ad49122f176484023b3
[]
no_license
jsangmeister/AE
f2f58f3c4aeadbc33ba6cdffbbacf44259e99041
ae8b34929c1eead1c263254dd54947c541b7286b
refs/heads/master
2023-07-11T08:20:24.592890
2021-08-11T07:56:25
2021-08-11T07:56:25
305,436,434
0
0
null
null
null
null
UTF-8
C++
false
false
99
h
#include <cstdint> #ifndef Q_t #define Q_t int #endif void mergesort(Q_t* data, uint64_t n);
2a70777d0f5faec101ab7b84aac6427fe98bd782
0afcd1a43a811c1b675b872fc674f72369b9d3be
/ProjetER_RFID.ino
ba887881e5d812b48253aa06daf647bdee29aed5
[]
no_license
jocelynr24/ProjetRFID
8f900da4a2eddbf88cfe9a5171d3b0de4ac1763a
6aaf788f3aec7498cb5d94bdafab2f29dc82db88
refs/heads/master
2020-04-14T16:13:43.700917
2019-01-03T08:41:00
2019-01-03T08:41:00
163,945,964
0
0
null
null
null
null
ISO-8859-1
C++
false
false
7,140
ino
/* _____ ______ _____ _____ | __ \ | ____| |_ _| | __ \ | |__) | | |__ | | | | | | | _ / | __| | | | | | | | | \ \ | | _| |_ | |__| | |_| \_\ |_| |_____| |_____/ Fichier Arduino Général .ino ROUTIN Jocelyn, GERARDI Marcelin Dernière modification : 09/06/2016 */ // On inclut les fichiers essentiels au projet #include "ProjetER_RFID.h" #include "Fonctions.h" #include "AccesPort.h" #include "AccesADC.h" // Variable permettant de stocker l'identifiant de la carte (première valeur du tableau iTabMemoire, nombre de lignes de 0 à NB_CARTES-1) int iIdentifiant = 0; // Structure de la variable que l'on utilise pour mémoriser la donnée stockée (tableau de double dimensions de NB_CARTES lignes et de 11 valeurs pour 11 octets pour chaque ligne) unsigned int iTabMemoire[NB_CARTES][11]; // Variables globales permettant de mémoriser le temps depuis lequel le programme est lancé (éviter les attentes bloquantes) unsigned long lTemps5sValid[NB_CARTES]; // Tableau qui permet de stocker la carte actuellement posée sur le lecteur (variable tampon) unsigned int iTabLecture[11] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // Variable temporaire qui sera utilisée dans les boucles for int iBcl; // Type d'état du programme typedef enum{ ATTENTE, LECTURE, IDENTIFICATION, VALIDE, AJOUTER, SUPPRIMER }TEtat; TEtat Etat; TEtat EtatOld; void setup(){ Serial.begin(9600); // Initialisation du port série InitPortCarteFille(); // Initialisation de la carte fille Etat = ATTENTE; EtatOld = ATTENTE; InitCartes(); // Permet d'initialiser les cases mémoire en fonction du nombre maximal de cartes défini par l'utilisateur dans le #define (Fonctions.h) } void loop(){ bool bCarteValide = 0; // Variable permettant de déterminer si la carte est présente ou non dans la mémoire bool bMemoireDispo = 0; // Variable permettant de déterminer si de la mémoire est disponible bool bBP1 = BP1(); // Variable permettant de déterminer l'appui sur le BP1 bool bBP2 = BP2(); // Variable permettant de déterminer l'appui sur le BP2 // Évolution du graphe d'états switch (Etat){ case ATTENTE: // Si on est dans l'état attente d'une carte Serial.println("Attente d'une carte..."); if (Serial.available() == 11){ Etat = LECTURE; // Et si 11 octets sont présent dans le buffer, on passe dans l'état lecture } else if (Serial.available() > 11){ SerialClear(); // Et si une personne appuie trop longtemps sur le bouton d'ajout de carte et qu'on a atteint la limite de cartes, on vide le buffer pour éviter de le bloquer (sécurité) } break; case LECTURE: // Si on est dans l'état lecture Etat = IDENTIFICATION; // On passe directement à l'état identification au prochain passage du loop() break; case IDENTIFICATION: // On identifie la carte et la fonction qui lui est demandée (lecture, ajouter ou supprimer) for (iBcl = 0; iBcl < NB_CARTES; iBcl++){ // On cherche à savoir si la carte est présente dans la mémoire if ((iTabLecture[0] == iTabMemoire[iBcl][0]) && (iTabLecture[1] == iTabMemoire[iBcl][1]) && (iTabLecture[2] == iTabMemoire[iBcl][2]) && (iTabLecture[3] == iTabMemoire[iBcl][3]) && (iTabLecture[4] == iTabMemoire[iBcl][4]) && (iTabLecture[5] == iTabMemoire[iBcl][5]) && (iTabLecture[6] == iTabMemoire[iBcl][6]) && (iTabLecture[7] == iTabMemoire[iBcl][7]) && (iTabLecture[8] == iTabMemoire[iBcl][8]) && (iTabLecture[9] == iTabMemoire[iBcl][9]) && (iTabLecture[10] == iTabMemoire[iBcl][10])){ // à l'aide de tous les octets Serial.println("La carte est existante"); iIdentifiant = iBcl; // Si on l'a trouvé, son identifiant sera égal à la valeur de iBcl à cet instant if (bBP2){ // Appui sur BP2 Serial.println("Le BP2 est appuye, on supprime cette carte de la memoire"); Etat = SUPPRIMER; // Permet de supprimer la carte de la mémoire } else if ((lTemps5sValid[iBcl] + 5000) <= millis()) { // Si la carte est valide et qu'elle a été activée il y a plus de 5 secondes Serial.println("La carte est valide"); Etat = VALIDE; // Si la carte est dans la mémoire et qu'elle n'a pas été activée lors des 5 dernières secondes, elle est valide } else{ Serial.println("La carte a deja ete activee durant les 5 dernieres secondes"); Etat = ATTENTE; // Si la carte est valide mais qu'elle a été activée lors des 5 dernières secondes } bCarteValide = 1; // On passe un booléen à 1 afin d'indiquer que la carte était bien présente dans la mémoire } } if (bCarteValide == 0){ // Si la carte n'était pas présente dans la mémoire if (bBP1){ // Appui sur BP1 for (iBcl = 0; iBcl < NB_CARTES; iBcl++){ // On cherche à déterminer le premier identifiant disponible pour stocker la valeur de la carte en mémoire if (iTabMemoire[iBcl][0] == 0){ // Si une ligne de la mémoire est libre (le premier octet est forcément égal à 1, donc s'il vaut 0, c'est qu'il n'y a pas de carte) iIdentifiant = iBcl; // On stocke la valeur de cet identifiant dans la variable iIdentifiant bMemoireDispo = 1; // Et on indique que la mémoire est disponible pour stocker une carte } else { // Si le nombre maximal de cartes a été atteint Serial.println("Le nombre maximal de cartes a ete atteint"); Etat = ATTENTE; // On abandonne la lecture et on attend de nouveau une carte } } if (bMemoireDispo == 1){ // S'il reste de la mémoire libre et que l'on ajoute une carte Serial.println("Le BP1 est appuye, on ajoute cette carte a la memoire"); Etat = AJOUTER; // On passe dans l'état ajouter } } else{ Serial.println("Cette carte n'est pas valide"); Etat = ATTENTE; // Si la carte n'est pas dans la mémoire, on retourne en attente de lecture d'une carte } } SerialClear(); // On vide le buffer break; case VALIDE: // On retourne dans l'état d'attente des données Etat = ATTENTE; break; case AJOUTER: // On retourne dans l'état d'attente des données Etat = ATTENTE; break; case SUPPRIMER: // On retourne dans l'état d'attente des données Etat = ATTENTE; break; } // Sorties if (Etat != EtatOld){ switch (Etat){ case LECTURE: // On stocke dans la variable tampon les 11 octets lus de la carte for (iBcl = 0; iBcl < 11; iBcl++){ iTabLecture[iBcl] = Serial.read(); } break; case VALIDE: // Gestion de la carte valide CarteValide(); // On envoie un niveau logique haut en sortie de la carte (sur la base et la DEL) lTemps5sValid[iIdentifiant] = millis(); // Permet de déterminer l'intervalle de 5 secondes sans bloquer le programme SerialClear(); // On vide le buffer break; case AJOUTER: // Ajout d'une carte à la mémoire (avec l'identifiant trouvé précédemment) for (iBcl = 0; iBcl < 11; iBcl++){ iTabMemoire[iIdentifiant][iBcl] = iTabLecture[iBcl]; } break; case SUPPRIMER: // Supression d'une carte de la mémoire (avec l'identifiant trouvé précédemment) for (iBcl = 0; iBcl < 11; iBcl++){ iTabMemoire[iIdentifiant][iBcl] = 0; } break; } } }
c2fdc54230ba4cb7f20a8caadb8464d6f260c3f7
1c96ef17a108055d44b4f1f8108e6f1d8228c65f
/src/125.valid-palindrome.cpp
689b3ef341b464886be981a9b02ead2fa50588c9
[]
no_license
pomelo00o/LEETCODE
fd3db967a2e83941fc90263aeea69043e294e248
69f58165b14a4d68ab673e52a595006462e63a9f
refs/heads/master
2022-03-30T09:27:59.838597
2019-11-17T20:02:21
2019-11-17T20:02:21
126,688,560
1
0
null
null
null
null
UTF-8
C++
false
false
567
cpp
/* * @lc app=leetcode id=125 lang=cpp * * [125] Valid Palindrome */ class Solution { public: bool isPalindrome(string s) { if (s.empty()) return true; int start = 0, end = s.size() - 1; while (start < end) { while (start < end && !isalnum(s[start])) { start ++; } while (start < end && !isalnum(s[end])) { end --; } if (tolower(s[start]) != tolower(s[end])) return false; start ++; end --; } return true; } };
8a9f2defc8dc30d1bcffe747c78811e1833457b7
9589635b89d7433154d0319fc07a360b92f66325
/lzsui/utility/lzs-file.hpp
936b46d37fdccf01441f3416173ea8e9d3ef81af
[]
no_license
hitner/lzsui
974482a63ecf64b400eb48c41ebfaf60a11db7eb
a1b5167f778ef845310bffc1fd3cd271ed1bdd6d
refs/heads/master
2021-01-22T11:07:20.865089
2017-06-01T09:08:06
2017-06-01T09:08:06
50,223,261
1
0
null
null
null
null
UTF-8
C++
false
false
550
hpp
#pragma once #include <stdio.h> #include <cassert> int read_file(const wchar_t * filename, void * buf, size_t bufsize) { assert(filename); assert(buf); assert(bufsize > 0); if (filename == NULL || buf == NULL || bufsize <= 0) { return 0; } FILE * stream = NULL; errno_t error = _wfopen_s(&stream, filename, L"rb"); assert(error == 0); size_t readnum = 0; if (error == 0) { readnum = fread_s(buf, bufsize, 1, bufsize, stream); //need check later } if (stream) { int ret = fclose(stream); assert(ret == 0); } return readnum; }
dd3f8d84eca929a9be1c5873cb678b67ae64f414
94a15dc3e12ffaa5d2670f313c2011c900170633
/include/core/label.h
9cdfa0440e964f3c4c3c64034f16659c2503e4ca
[ "MIT" ]
permissive
Slattz/NLTK
21c5c4a54c262479f9250c0af627338ffae691b0
b4e687c329ac4820a02fd45ce13d8afdddd26ef3
refs/heads/master
2021-06-04T23:16:38.093563
2020-07-19T22:49:08
2020-07-19T22:49:08
132,379,138
26
10
MIT
2018-06-14T07:47:12
2018-05-06T21:57:12
C++
UTF-8
C++
false
false
616
h
#pragma once #include "control.h" #include "CTRFont.hpp" class Label : public Control { public: Label(void); Label(Point_t location, Size_t size, u32 bgColor, u32 textColor, std::string text); Label(u32 x, u32 y, u32 width, u32 height, u32 bgColor, u32 textColor, std::string text); void Draw(void); void SetVisibility(bool visibility); void SetTextSize(float scaleX, float scaleY); void SetTextColor(u32 color); void SetTextPos(float posX, float posY); void CenterInBounds(float left, float top, float width, float height); Text myText; float FontScale = 0.5; };
3ad1a44e5256ca6a225674a05ba94e89a71d19c3
6bc3f5955699fcdac540823c51354bc21919fb06
/Codeforces/985/985D.cpp
754b2992c9d09ba6be1c794183b7981e4eca88f1
[]
no_license
soroush-tabesh/Competitive-Programming
e1a265e2224359962088c74191b7dc87bbf314bf
a677578c2a0e21c0510258933548a251970d330d
refs/heads/master
2021-09-24T06:36:43.037300
2018-10-04T14:12:00
2018-10-04T14:12:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,107
cpp
//In The Name of Allah //Thu 31/2/97 #include <bits/stdc++.h> #define Init ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0) #define forar(i,n) for(long long int i = 0; i < n;i++) #define fori(i,a,b) for(long long int i = a; i < b;i++) #define WFile freopen("test.in","r",stdin),freopen("test.out","w",stdout) #define Log(x) cout << "Log: " << x << endl; #define F first #define S second #define pb push_back #define mp make_pair using namespace std; typedef long long int ll; typedef unsigned long long int ull; typedef long double ld; typedef pair<int,int> pii; typedef pair<ll,ll> pll; const ll mod = 1e9+7,M = 2e5+100; void Solution(); ull n,h; int32_t main() { Init; Solution(); return 0; } bool check(ull base){ ull bc = base; ll ext = min(base,h)-1; base += ext; bool is = (base % 2 == 0); base = (base + 1)/2; ll vol = base*base; vol -= (ext*(ext+1))/2; if(is) vol += base; return vol >= n; } inline void Solution(){ cin >> n >> h; ull l = 1,r = ull(2e9); while(r-l){ ull mid = (r+l)/2; if(check(mid)){ r = mid; }else{ l = mid+1; } } cout << l << endl; }
bf004c092acc341b880e415e25eba553fc2b2e78
2f10f807d3307b83293a521da600c02623cdda82
/deps/boost/win/debug/include/boost/geometry/algorithms/detail/point_is_spike_or_equal.hpp
5a8968f94308e973c6a21a6b0871ebc3809a77f7
[]
no_license
xpierrohk/dpt-rp1-cpp
2ca4e377628363c3e9d41f88c8cbccc0fc2f1a1e
643d053983fce3e6b099e2d3c9ab8387d0ea5a75
refs/heads/master
2021-05-23T08:19:48.823198
2019-07-26T17:35:28
2019-07-26T17:35:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
129
hpp
version https://git-lfs.github.com/spec/v1 oid sha256:4b5ee8d00e7e3adb48ecd672cb06f57547377ff47b165e413123571d659f9c98 size 6497
fe8e1e5fc924a2d1ad703ba7436e3596bb86192c
280b69f8b382f3495c4c0966fcf14ee9d8693eee
/Gimmick/Gimmick/Medicine.cpp
4619959959d0b0d00ab1a04f3c350ced6982db13
[]
no_license
HaMinhThanh/GimmickNes
a6fa5e6496087442da63f10c2ddb0b549dcf7bff
d52e58fdb0566fb5265b9a7c16988636574ed9ff
refs/heads/main
2023-06-19T02:44:29.745733
2021-07-14T09:03:46
2021-07-14T09:03:46
355,019,986
0
0
null
null
null
null
UTF-8
C++
false
false
1,675
cpp
#include "Medicine.h" #include "Brick.h" #include "ScrollBar.h" #include "Slide.h" CMedicine::CMedicine(float _x, float _y, int _type) { x = _x; y = _y; type = _type; } CMedicine::~CMedicine() { } void CMedicine::GetBoundingBox(float& left, float& top, float& right, float& bottom) { if (!isFinish) { left = x; top = y; right = x + MEDICINE_BBOX_WIDTH; bottom = y - MEDICINE_BBOX_HEIGHT; } } void CMedicine::Update(DWORD dt, vector<LPGAMEOBJECT>* coObjects) { if (isFinish) return; CGameObject::Update(dt, coObjects); vy += ITEM_GRAVITY * dt; vector<LPGAMEOBJECT> Bricks; Bricks.clear(); for (UINT i = 0; i < coObjects->size(); i++) if (dynamic_cast<CBrick*>(coObjects->at(i)) || dynamic_cast<CScrollBar*>(coObjects->at(i)) || dynamic_cast<CSlide*>(coObjects->at(i))) { Bricks.push_back(coObjects->at(i)); } vector<LPCOLLISIONEVENT> coEvents; vector<LPCOLLISIONEVENT> coEventsResult; coEvents.clear(); CalcPotentialCollisions(&Bricks, coEvents); if (coEvents.size() == 0) { x += dx; y += dy; } else { float min_tx, min_ty, nx = 0, ny; float rdx, rdy; FilterCollision(coEvents, coEventsResult, min_tx, min_ty, nx, ny, rdx, rdy); for (UINT i = 0; i < coEventsResult.size(); i++) { LPCOLLISIONEVENT e = coEventsResult[i]; } x += min_tx * dx + nx * 0.04f; y += min_ty * dy + ny * 0.04f; if (ny != 0) { vy = 0; } } for (UINT i = 0; i < coEvents.size(); i++) delete coEvents[i]; } void CMedicine::Render() { if (!isFinish) { if (type == 1) CSprites::GetInstance()->Get(MEDICINE_SPRITE_1)->Draw(x, y); else CSprites::GetInstance()->Get(MEDICINE_SPRITE_2)->Draw(x, y); } }
890a4ea83bab246c1438761afacb2e3c64885659
41ab8e131a349bd6386080745b64618d318ef217
/QtPastePic/GeneratedFiles/ui_QtPastePic.h
b3509262a5bf204de6fd4e938b8b2bd3454f38ab
[]
no_license
tanxuehan/Image-Composition-of-Partially-Occluded-Objects
5a671b3eaf224fc5b6239f908a7985f1bf7f42af
c65ac351351ef457cf7e64abd74ab3d5961842b6
refs/heads/master
2020-06-10T14:15:10.787794
2020-05-23T14:30:14
2020-05-23T14:30:14
193,655,618
6
1
null
null
null
null
UTF-8
C++
false
false
16,188
h
/******************************************************************************** ** Form generated from reading UI file 'QtPastePic.ui' ** ** Created by: Qt User Interface Compiler version 5.10.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_QTPASTEPIC_H #define UI_QTPASTEPIC_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QMainWindow> #include <QtWidgets/QMenuBar> #include <QtWidgets/QPushButton> #include <QtWidgets/QScrollArea> #include <QtWidgets/QStatusBar> #include <QtWidgets/QToolBar> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_QtPastePicClass { public: QWidget *centralWidget; QScrollArea *source_pic_show; QWidget *scrollAreaWidgetContents; QScrollArea *target_pic_show; QWidget *scrollAreaWidgetContents_2; QLabel *source_pic_lable; QLabel *target_pic_lable; QPushButton *source_pic_load_button; QPushButton *target_pic_load_button; QPushButton *LittleButton; QPushButton *BigButton; QPushButton *UpButton; QPushButton *DownButton; QPushButton *RightButton; QPushButton *LiftButton; QPushButton *source_mask_load_button; QScrollArea *source_mask_show; QWidget *scrollAreaWidgetContents_3; QPushButton *target_mask_load_button; QLabel *source_pic_lable_2; QScrollArea *target_mask_show; QWidget *scrollAreaWidgetContents_4; QLabel *target_mask_lable; QLabel *target_depth_lable; QPushButton *target_depth_load_button; QScrollArea *target_depth_show; QWidget *scrollAreaWidgetContents_5; QScrollArea *output_show; QWidget *scrollAreaWidgetContents_6; QPushButton *output; QLabel *label; QPushButton *mask; QLabel *label_2; QMenuBar *menuBar; QToolBar *mainToolBar; QStatusBar *statusBar; void setupUi(QMainWindow *QtPastePicClass) { if (QtPastePicClass->objectName().isEmpty()) QtPastePicClass->setObjectName(QStringLiteral("QtPastePicClass")); QtPastePicClass->resize(1155, 921); QtPastePicClass->setMouseTracking(true); QtPastePicClass->setTabletTracking(true); QtPastePicClass->setFocusPolicy(Qt::WheelFocus); QtPastePicClass->setAcceptDrops(true); QtPastePicClass->setAutoFillBackground(true); QtPastePicClass->setToolButtonStyle(Qt::ToolButtonFollowStyle); QtPastePicClass->setDocumentMode(true); QtPastePicClass->setDockNestingEnabled(true); QtPastePicClass->setUnifiedTitleAndToolBarOnMac(true); centralWidget = new QWidget(QtPastePicClass); centralWidget->setObjectName(QStringLiteral("centralWidget")); source_pic_show = new QScrollArea(centralWidget); source_pic_show->setObjectName(QStringLiteral("source_pic_show")); source_pic_show->setGeometry(QRect(600, 50, 250, 188)); source_pic_show->setWidgetResizable(false); source_pic_show->setAlignment(Qt::AlignCenter); scrollAreaWidgetContents = new QWidget(); scrollAreaWidgetContents->setObjectName(QStringLiteral("scrollAreaWidgetContents")); scrollAreaWidgetContents->setGeometry(QRect(10, 39, 229, 109)); source_pic_show->setWidget(scrollAreaWidgetContents); target_pic_show = new QScrollArea(centralWidget); target_pic_show->setObjectName(QStringLiteral("target_pic_show")); target_pic_show->setGeometry(QRect(600, 300, 250, 188)); target_pic_show->setWidgetResizable(false); target_pic_show->setAlignment(Qt::AlignCenter); scrollAreaWidgetContents_2 = new QWidget(); scrollAreaWidgetContents_2->setObjectName(QStringLiteral("scrollAreaWidgetContents_2")); scrollAreaWidgetContents_2->setGeometry(QRect(10, 49, 229, 89)); target_pic_show->setWidget(scrollAreaWidgetContents_2); source_pic_lable = new QLabel(centralWidget); source_pic_lable->setObjectName(QStringLiteral("source_pic_lable")); source_pic_lable->setGeometry(QRect(600, 20, 101, 21)); QFont font; font.setFamily(QStringLiteral("Times New Roman")); font.setPointSize(14); font.setBold(true); font.setWeight(75); source_pic_lable->setFont(font); target_pic_lable = new QLabel(centralWidget); target_pic_lable->setObjectName(QStringLiteral("target_pic_lable")); target_pic_lable->setGeometry(QRect(600, 270, 111, 21)); target_pic_lable->setFont(font); source_pic_load_button = new QPushButton(centralWidget); source_pic_load_button->setObjectName(QStringLiteral("source_pic_load_button")); source_pic_load_button->setGeometry(QRect(730, 20, 121, 23)); QFont font1; font1.setFamily(QStringLiteral("Times New Roman")); font1.setPointSize(10); font1.setBold(false); font1.setWeight(50); source_pic_load_button->setFont(font1); target_pic_load_button = new QPushButton(centralWidget); target_pic_load_button->setObjectName(QStringLiteral("target_pic_load_button")); target_pic_load_button->setGeometry(QRect(730, 270, 121, 23)); QFont font2; font2.setFamily(QStringLiteral("Times New Roman")); font2.setPointSize(10); target_pic_load_button->setFont(font2); LittleButton = new QPushButton(centralWidget); LittleButton->setObjectName(QStringLiteral("LittleButton")); LittleButton->setGeometry(QRect(881, 570, 250, 27)); QFont font3; font3.setFamily(QStringLiteral("Times New Roman")); font3.setPointSize(12); font3.setBold(false); font3.setWeight(50); LittleButton->setFont(font3); BigButton = new QPushButton(centralWidget); BigButton->setObjectName(QStringLiteral("BigButton")); BigButton->setGeometry(QRect(881, 535, 250, 27)); BigButton->setFont(font3); UpButton = new QPushButton(centralWidget); UpButton->setObjectName(QStringLiteral("UpButton")); UpButton->setGeometry(QRect(881, 605, 250, 27)); UpButton->setFont(font3); DownButton = new QPushButton(centralWidget); DownButton->setObjectName(QStringLiteral("DownButton")); DownButton->setGeometry(QRect(881, 640, 250, 27)); DownButton->setFont(font3); RightButton = new QPushButton(centralWidget); RightButton->setObjectName(QStringLiteral("RightButton")); RightButton->setGeometry(QRect(881, 710, 250, 27)); RightButton->setFont(font3); LiftButton = new QPushButton(centralWidget); LiftButton->setObjectName(QStringLiteral("LiftButton")); LiftButton->setGeometry(QRect(881, 675, 250, 27)); LiftButton->setFont(font3); source_mask_load_button = new QPushButton(centralWidget); source_mask_load_button->setObjectName(QStringLiteral("source_mask_load_button")); source_mask_load_button->setGeometry(QRect(1010, 20, 121, 23)); source_mask_load_button->setFont(font2); source_mask_show = new QScrollArea(centralWidget); source_mask_show->setObjectName(QStringLiteral("source_mask_show")); source_mask_show->setGeometry(QRect(880, 50, 250, 188)); source_mask_show->setWidgetResizable(false); source_mask_show->setAlignment(Qt::AlignCenter); scrollAreaWidgetContents_3 = new QWidget(); scrollAreaWidgetContents_3->setObjectName(QStringLiteral("scrollAreaWidgetContents_3")); scrollAreaWidgetContents_3->setGeometry(QRect(10, 39, 229, 109)); source_mask_show->setWidget(scrollAreaWidgetContents_3); target_mask_load_button = new QPushButton(centralWidget); target_mask_load_button->setObjectName(QStringLiteral("target_mask_load_button")); target_mask_load_button->setGeometry(QRect(1010, 270, 121, 23)); target_mask_load_button->setFont(font2); source_pic_lable_2 = new QLabel(centralWidget); source_pic_lable_2->setObjectName(QStringLiteral("source_pic_lable_2")); source_pic_lable_2->setGeometry(QRect(880, 20, 131, 21)); source_pic_lable_2->setFont(font); target_mask_show = new QScrollArea(centralWidget); target_mask_show->setObjectName(QStringLiteral("target_mask_show")); target_mask_show->setGeometry(QRect(880, 300, 250, 188)); target_mask_show->setWidgetResizable(false); target_mask_show->setAlignment(Qt::AlignCenter); scrollAreaWidgetContents_4 = new QWidget(); scrollAreaWidgetContents_4->setObjectName(QStringLiteral("scrollAreaWidgetContents_4")); scrollAreaWidgetContents_4->setGeometry(QRect(10, 49, 229, 89)); target_mask_show->setWidget(scrollAreaWidgetContents_4); target_mask_lable = new QLabel(centralWidget); target_mask_lable->setObjectName(QStringLiteral("target_mask_lable")); target_mask_lable->setGeometry(QRect(880, 270, 131, 21)); target_mask_lable->setFont(font); target_depth_lable = new QLabel(centralWidget); target_depth_lable->setObjectName(QStringLiteral("target_depth_lable")); target_depth_lable->setGeometry(QRect(599, 522, 121, 21)); target_depth_lable->setFont(font); target_depth_load_button = new QPushButton(centralWidget); target_depth_load_button->setObjectName(QStringLiteral("target_depth_load_button")); target_depth_load_button->setGeometry(QRect(730, 522, 121, 23)); target_depth_load_button->setFont(font2); target_depth_show = new QScrollArea(centralWidget); target_depth_show->setObjectName(QStringLiteral("target_depth_show")); target_depth_show->setGeometry(QRect(600, 552, 250, 188)); target_depth_show->setWidgetResizable(false); target_depth_show->setAlignment(Qt::AlignCenter); scrollAreaWidgetContents_5 = new QWidget(); scrollAreaWidgetContents_5->setObjectName(QStringLiteral("scrollAreaWidgetContents_5")); scrollAreaWidgetContents_5->setGeometry(QRect(10, 49, 229, 89)); target_depth_show->setWidget(scrollAreaWidgetContents_5); output_show = new QScrollArea(centralWidget); output_show->setObjectName(QStringLiteral("output_show")); output_show->setGeometry(QRect(20, 470, 550, 380)); output_show->setLineWidth(0); output_show->setWidgetResizable(false); output_show->setAlignment(Qt::AlignCenter); scrollAreaWidgetContents_6 = new QWidget(); scrollAreaWidgetContents_6->setObjectName(QStringLiteral("scrollAreaWidgetContents_6")); scrollAreaWidgetContents_6->setGeometry(QRect(0, 0, 548, 378)); output_show->setWidget(scrollAreaWidgetContents_6); output = new QPushButton(centralWidget); output->setObjectName(QStringLiteral("output")); output->setGeometry(QRect(880, 780, 250, 50)); QFont font4; font4.setFamily(QStringLiteral("Times New Roman")); font4.setPointSize(16); font4.setBold(true); font4.setWeight(75); output->setFont(font4); label = new QLabel(centralWidget); label->setObjectName(QStringLiteral("label")); label->setGeometry(QRect(20, 440, 91, 21)); label->setFont(font); mask = new QPushButton(centralWidget); mask->setObjectName(QStringLiteral("mask")); mask->setGeometry(QRect(600, 780, 250, 50)); mask->setFont(font4); label_2 = new QLabel(centralWidget); label_2->setObjectName(QStringLiteral("label_2")); label_2->setGeometry(QRect(20, 20, 91, 21)); label_2->setFont(font); QtPastePicClass->setCentralWidget(centralWidget); menuBar = new QMenuBar(QtPastePicClass); menuBar->setObjectName(QStringLiteral("menuBar")); menuBar->setGeometry(QRect(0, 0, 1155, 21)); QtPastePicClass->setMenuBar(menuBar); mainToolBar = new QToolBar(QtPastePicClass); mainToolBar->setObjectName(QStringLiteral("mainToolBar")); QtPastePicClass->addToolBar(Qt::TopToolBarArea, mainToolBar); statusBar = new QStatusBar(QtPastePicClass); statusBar->setObjectName(QStringLiteral("statusBar")); QtPastePicClass->setStatusBar(statusBar); #ifndef QT_NO_SHORTCUT source_pic_lable->setBuddy(source_pic_load_button); target_pic_lable->setBuddy(target_pic_load_button); source_pic_lable_2->setBuddy(source_pic_load_button); target_mask_lable->setBuddy(target_pic_load_button); target_depth_lable->setBuddy(target_pic_load_button); #endif // QT_NO_SHORTCUT retranslateUi(QtPastePicClass); QObject::connect(LittleButton, SIGNAL(clicked()), QtPastePicClass, SLOT(on_little_clicked())); QObject::connect(UpButton, SIGNAL(clicked()), QtPastePicClass, SLOT(on_up_clicked())); QObject::connect(DownButton, SIGNAL(clicked()), QtPastePicClass, SLOT(on_down_clicked())); QObject::connect(LiftButton, SIGNAL(clicked()), QtPastePicClass, SLOT(on_left_clicked())); QObject::connect(RightButton, SIGNAL(clicked()), QtPastePicClass, SLOT(on_right_clicked())); QObject::connect(BigButton, SIGNAL(clicked()), QtPastePicClass, SLOT(on_big_clicked())); QMetaObject::connectSlotsByName(QtPastePicClass); } // setupUi void retranslateUi(QMainWindow *QtPastePicClass) { QtPastePicClass->setWindowTitle(QApplication::translate("QtPastePicClass", "QtPastePic", nullptr)); source_pic_lable->setText(QApplication::translate("QtPastePicClass", "Source Pic", nullptr)); target_pic_lable->setText(QApplication::translate("QtPastePicClass", "Target Pic", nullptr)); source_pic_load_button->setText(QApplication::translate("QtPastePicClass", "Source Pic Load ", nullptr)); target_pic_load_button->setText(QApplication::translate("QtPastePicClass", "Target Pic Load ", nullptr)); LittleButton->setText(QApplication::translate("QtPastePicClass", "Zoom Out", nullptr)); BigButton->setText(QApplication::translate("QtPastePicClass", "Zoom In", nullptr)); UpButton->setText(QApplication::translate("QtPastePicClass", "Up", nullptr)); DownButton->setText(QApplication::translate("QtPastePicClass", "Down", nullptr)); RightButton->setText(QApplication::translate("QtPastePicClass", "Right", nullptr)); LiftButton->setText(QApplication::translate("QtPastePicClass", "Left", nullptr)); source_mask_load_button->setText(QApplication::translate("QtPastePicClass", "Segment", nullptr)); target_mask_load_button->setText(QApplication::translate("QtPastePicClass", "Segment", nullptr)); source_pic_lable_2->setText(QApplication::translate("QtPastePicClass", "Source Mask", nullptr)); target_mask_lable->setText(QApplication::translate("QtPastePicClass", "Target Mask", nullptr)); target_depth_lable->setText(QApplication::translate("QtPastePicClass", "Target Depth", nullptr)); target_depth_load_button->setText(QApplication::translate("QtPastePicClass", "Depth Estimation", nullptr)); output->setText(QApplication::translate("QtPastePicClass", "Make Pic", nullptr)); label->setText(QApplication::translate("QtPastePicClass", "Output", nullptr)); mask->setText(QApplication::translate("QtPastePicClass", "Make Mask", nullptr)); label_2->setText(QApplication::translate("QtPastePicClass", "Painter", nullptr)); } // retranslateUi }; namespace Ui { class QtPastePicClass: public Ui_QtPastePicClass {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_QTPASTEPIC_H
0c6cf9d38d5a0ebc3be9fd3764ac82ffda64a801
75b5c937385191313a2d0b1aefc28a26e02c3573
/sketch/src/HumidSensor.h
9cda58536c3be2828e037e4391977d8805c35714
[]
no_license
y0gi44/JardinDuino
e16687060735b90608918f978736f93bf8105e42
f43d93c110e73c867b2ee0776b43e460fe809b65
refs/heads/master
2021-01-22T06:12:04.541706
2018-03-24T08:09:23
2018-03-24T08:09:23
92,529,875
0
1
null
null
null
null
UTF-8
C++
false
false
286
h
#ifndef HumidSensor_h #define HumidSensor_h #include "Arduino.h" class HumidSensor { public: HumidSensor(int analog); HumidSensor(int pin, int analog); void powerOff(); void powerUp(); int getRawValue(); double getPctValue(); private: int _pinPwr; int _pinAnalog; }; #endif
37b58a35e7826447ec2f2f39be564f5e377d8520
05c1039487d53711217e58eec3a3baa7d98e970c
/HW/3/B_Mindist/main.cpp
ed67a080de0b71727cc8581ad84fd85a5da8822b
[]
no_license
makci97/algo_tinkoff
a388cd9294a36020313f1ee1ca48908f87d4dda1
211ec75ace46c5be3cab85f7efafae364461d42a
refs/heads/master
2020-03-28T19:36:04.547933
2018-12-09T14:32:55
2018-12-09T14:32:55
148,983,628
0
0
null
null
null
null
UTF-8
C++
false
false
1,940
cpp
#include <algorithm> #include <iostream> #include <fstream> #include <sstream> #include <list> #include <vector> std::vector<std::vector<int> > read_matrix_graph( int n, std::ifstream& in_stream ) { int v; std::vector<std::vector<int> > graph; for (int i = 0; i < n; ++i) { std::vector<int> vertex; for (int j = 0; j < n; ++j) { in_stream >> v; vertex.push_back(v); } graph.push_back(std::move(vertex)); } return std::move(graph); } std::vector<std::list<int> > matrix2list( std::vector<std::vector<int> >&& matrix_graph ) { int n = matrix_graph.size(); std::vector<std::list<int> > list_graph(n + 1); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (matrix_graph[i][j] == 1) { list_graph[i + 1].push_back(j + 1); } } } return std::move(list_graph); } int main() { int n, v, x; std::string line; std::ifstream in_stream; std::ofstream out_stream; in_stream.open ("mindist.in"); out_stream.open("mindist.out"); // read graph in_stream >> n >> x; auto graph = matrix2list(read_matrix_graph(n, in_stream)); std::vector<int> dist(n + 1, -1); dist[x] = 0; // Bellman–Ford for (int n_iter = 0; n_iter < n - 1; ++n_iter) { for (int i = 1; i <= n; ++i) { if (graph[i].empty() || dist[i] == -1) continue; for (auto j: graph[i]) { if (dist[j] == -1 || dist[j] > dist[i] + 1) { dist[j] = dist[i] + 1; } } } } // output for (auto it = dist.begin() + 1, end = dist.end(); it != end; ++it) { out_stream << *it << ' '; } in_stream.close(); out_stream.close(); return 0; }
31cb160883245288a1b5d11c7b1bd7cf253cd826
02f8627455b5ba78553a873c9da3cddc75ee6f3a
/hikyuu_cpp/hikyuu_server/service/user/UserHandle.h
9f2f01348ed8bd0923d4504e950732e5709afdec
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
dragon86cn/hikyuu
adec357434ee2bbae6dd3d04aa22bb755ba53823
70210fa7a683de2cbbcf98a66d7e384dd0b93526
refs/heads/master
2023-04-13T00:10:52.179378
2023-03-22T18:13:45
2023-03-22T18:13:45
224,981,047
0
0
NOASSERTION
2019-11-30T08:16:38
2019-11-30T08:16:37
null
UTF-8
C++
false
false
6,936
h
/* * Copyright(C) 2021 hikyuu.org * * Create on: 2021-04-25 * Author: fasiondog */ #pragma once #include <vector> #include <hikyuu/utilities/db_connect/DBCondition.h> #include "common/uuid.h" #include "../TokenCache.h" #include "../RestHandle.h" #include "model/UserModel.h" #include "model/TokenModel.h" namespace hku { /*********************************** * * 用户相关操作仅有 admin 有权限 * **********************************/ /** * 新增用户 */ class AddUserHandle : public RestHandle { public: static const int MIN_NAME_LENGTH = 1; static const int MAX_NAME_LENGTH = 128; static const int MAX_PASSWORD_LENGTH = 72; // 目前 bcrypt 最长密码只支持到72位 REST_HANDLE_IMP(AddUserHandle) virtual void run() override { auto con = DB::getConnect(); UserModel admin; con->load(admin, fmt::format("userid={}", getCurrentUserId())); REQ_CHECK(admin.getName() == "admin", UserErrorCode::USER_NO_RIGHT, _ctr("user", "No operation permission")); check_missing_param("user"); check_missing_param("password"); UserModel user; user.setName(req["user"].get<string>()); size_t name_len = user.getName().size(); REQ_CHECK(name_len >= MIN_NAME_LENGTH && name_len <= MAX_NAME_LENGTH, UserErrorCode::USER_INVALID_NAME_OR_PASSWORD, _ctr("user", "The user name must be 1 to 128 characters long")); std::string pwd = req["password"].get<string>(); size_t password_len = pwd.size(); REQ_CHECK(password_len <= MAX_PASSWORD_LENGTH, UserErrorCode::USER_INVALID_NAME_OR_PASSWORD, fmt::format(_ctr("user", "The password must be less than {} characters"), MAX_PASSWORD_LENGTH)); user.setPassword(req["password"].get<string>()); user.setStartTime(Datetime::now()); user.setStatus(UserModel::STATUS::NORMAL); { TransAction trans(con); int count = con->queryInt(fmt::format(R"(select count(id) from {} where name="{}")", UserModel::getTableName(), user.getName())); REQ_CHECK(count == 0, UserErrorCode::USER_NAME_REPETITION, _ctr("user", "Unavailable user name")); user.setUserId(DB::getNewUserId()); con->save(user, false); } res["userid"] = user.getUserId(); res["name"] = user.getName(); res["start_time"] = user.getStartTime().str(); } }; /** * 删除用户 */ class RemoveUserHandle : public RestHandle { REST_HANDLE_IMP(RemoveUserHandle) virtual void run() override { auto con = DB::getConnect(); UserModel admin; con->load(admin, fmt::format("userid={}", getCurrentUserId())); REQ_CHECK(admin.getName() == "admin", UserErrorCode::USER_NO_RIGHT, _ctr("user", "No operation permission")); check_missing_param("userid"); uint64_t userid = req["userid"].get<uint64_t>(); REQ_CHECK(userid != admin.getUserId(), UserErrorCode::USER_TRY_DELETE_ADMIN, _ctr("user", "The admin account cannot be deleted")); { UserModel user; TransAction trans(con); con->load(user, fmt::format(R"(userid="{}")", req["userid"].get<uint64_t>())); if (user.id() != 0 && user.getStatus() != UserModel::DELETED) { TokenModel tm; con->load(tm, DBCondition(Field("userid") == user.getUserId())); if (tm.id() != 0) { con->remove(tm, false); TokenCache::remove(tm.getToken()); } user.setEndTime(Datetime::now()); user.setStatus(UserModel::DELETED); con->save(user, false); } } } }; class QueryUserHandle : public RestHandle { REST_HANDLE_IMP(QueryUserHandle) virtual void run() override { auto con = DB::getConnect(); UserModel admin; con->load(admin, fmt::format("userid={}", getCurrentUserId())); REQ_CHECK(admin.getName() == "admin", UserErrorCode::USER_NO_RIGHT, _ctr("user", "No operation permission")); DBCondition cond; QueryParams params; if (getQueryParams(params)) { auto iter = params.find("userid"); if (iter != params.end()) { cond = Field("userid") == (uint64_t)std::stoll(iter->second); } iter = params.find("name"); if (iter != params.end()) { cond = cond & Field("name") == iter->second; } } cond = (cond & Field("status") != UserModel::DELETED) + ASC("start_time"); std::vector<UserModel> users; con->batchLoad(users, cond.str()); json jarray; for (auto& user : users) { json j; j["userid"] = user.getUserId(); j["name"] = user.getName(); j["start_time"] = user.getStartTime().str(); jarray.push_back(j); } res["data"] = jarray; } }; class ResetPasswordUserHandle : public RestHandle { REST_HANDLE_IMP(ResetPasswordUserHandle) virtual void run() override { auto con = DB::getConnect(); UserModel admin; con->load(admin, fmt::format("userid={}", getCurrentUserId())); REQ_CHECK(admin.getName() == "admin", UserErrorCode::USER_NO_RIGHT, _ctr("user", "No operation permission")); check_missing_param("userid"); { UserModel user; TransAction trans(con); con->load(user, fmt::format(R"(userid="{}")", req["userid"].get<uint64_t>())); if (user.id() != 0 && user.getStatus() != UserModel::DELETED) { user.setPassword( "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92"); // 123456 con->save(user, false); } } } }; class ChangePasswordUserHandle : public RestHandle { REST_HANDLE_IMP(ChangePasswordUserHandle) virtual void run() override { check_missing_param({"old", "new", "confirm"}); uint64_t userid = getCurrentUserId(); UserModel user; auto con = DB::getConnect(); con->load(user, Field("userid") == userid); REQ_CHECK(user.checkPassword(req["old"].get<std::string>()), UserErrorCode::USER_INVALID_NAME_OR_PASSWORD, "old password error!"); std::string new_pwd = req["new"].get<std::string>(); REQ_CHECK(new_pwd == req["confirm"].get<std::string>(), UserErrorCode::USER_INVALID_NAME_OR_PASSWORD, "The two passwords are different!"); user.setPassword(new_pwd); con->save(user); } }; } // namespace hku
4bd1dea0c45440ece680e2f3bd5588460ad8af9f
a0443c0dc6ba2545ffe8ddf4496c8223265557b3
/draw_font_24triple.cpp
0a837d197d75aabbc6ab4d709e314ffd4190f75f
[]
no_license
embeddedadventures/draw
3557c872ec465fc35ee408bb9cee8954b4241153
04b4f67ee38136a274ad993cd2399a039fad31ca
refs/heads/master
2021-01-11T06:41:58.848882
2017-05-09T19:02:04
2017-05-09T19:02:04
69,996,818
2
3
null
null
null
null
UTF-8
C++
false
false
36,068
cpp
/* Copyright (c) 2016, Embedded Adventures, www.embeddedadventures.com 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 Embedded Adventures nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Contact us at admin [at] embeddedadventures.com */ #include "draw_font_24triple.h" uns16 const font_24triple_index[] = { 0, // 32 - 3, // 33 - ! 7, // 34 - " 16, // 35 - # 32, // 36 - $ 45, // 37 - % 60, // 38 - & 60, // 39 - ' 64, // 40 - ( 71, // 41 - ) 78, // 42 - * 93, // 43 - + 106, // 44 - , 110, // 45 - - 120, // 46 - . 124, // 47 - / 138, // 48 - 0 153, // 49 - 1 164, // 50 - 2 179, // 51 - 3 194, // 52 - 4 210, // 53 - 5 225, // 54 - 6 240, // 55 - 7 255, // 56 - 8 270, // 57 - 9 285, // 58 - : 289, // 59 - ; 293, // 60 - < 308, // 61 - = 318, // 62 - > 333, // 63 - ? 347, // 64 - @ 347, // 65 - A 361, // 66 - B 375, // 67 - C 389, // 68 - D 403, // 69 - E 417, // 70 - F 431, // 71 - G 445, // 72 - H 459, // 73 - I 468, // 74 - J 484, // 75 - K 500, // 76 - L 514, // 77 - M 529, // 78 - N 543, // 79 - O 557, // 80 - P 571, // 81 - Q 586, // 82 - R 600, // 83 - S 614, // 84 - T 627, // 85 - U 641, // 86 - V 656, // 87 - W 671, // 88 - X 687, // 89 - Y 702, // 90 - Z 717, // 91 - [ 724, // 92 - backslash 738, // 93 - ] 745, // 94 - ^ 745, // 95 - _ 759, // 96 - ` }; uns8 const font_24triple_data[] = { // 0, 32 - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // // // // 3, 33 - ! 0x63, 0xff, 0xfe, 0xf7, 0xff, 0xff, 0xf7, 0xff, 0xff, 0x63, 0xff, 0xfe, // ** ***************** // **** ******************* // **** ******************* // ** ***************** // 7, 34 - " 0x00, 0x00, 0x23, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x0f, // * ** // ****** // ***** // **** // // * ** // ****** // ***** // **** // 16, 35 - # 0x01, 0xc3, 0x80, 0x01, 0xc3, 0x80, 0x01, 0xc3, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0xc3, 0x80, 0x01, 0xc3, 0x80, 0x01, 0xc3, 0x80, 0x01, 0xc3, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0xc3, 0x80, 0x01, 0xc3, 0x80, 0x01, 0xc3, 0x80, // *** *** // *** *** // *** *** // ************************ // ************************ // ************************ // *** *** // *** *** // *** *** // *** *** // ************************ // ************************ // ************************ // *** *** // *** *** // *** *** // 32, 36 - $ 0x07, 0x07, 0xe0, 0x0f, 0x0f, 0xf0, 0x1f, 0x1f, 0xf8, 0x3c, 0x3c, 0x3c, 0x38, 0x38, 0x1c, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x38, 0x38, 0x1c, 0x3c, 0x78, 0x3c, 0x1f, 0xf0, 0xf8, 0x0f, 0xe0, 0xf0, 0x07, 0xc0, 0xe0, // *** ****** // **** ******** // ***** ********** // **** **** **** // *** *** *** // ************************ // ************************ // ************************ // *** *** *** // **** **** **** // ********* ***** // ******* **** // ***** *** // 45, 37 - % 0xc0, 0x00, 0x0e, 0xf0, 0x00, 0x1f, 0xfc, 0x00, 0x1b, 0x3f, 0x00, 0x1f, 0x0f, 0xc0, 0x0e, 0x03, 0xf0, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x0f, 0xc0, 0x00, 0x03, 0xf0, 0x70, 0x00, 0xfc, 0xf8, 0x00, 0x3f, 0xd8, 0x00, 0x0f, 0xf8, 0x00, 0x03, 0x70, 0x00, 0x00, // ** *** // **** ***** // ****** ** ** // ****** ***** // ****** *** // ****** // ****** // ****** // ****** // ****** // *** ****** // ***** ****** // ** ** **** // ***** ** // *** // 60, 38 - & // 60, 39 - ' 0x00, 0x00, 0x23, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x0f, // * ** // ****** // ***** // **** // 64, 40 - ( 0x1f, 0xff, 0xf8, 0x3f, 0xff, 0xfc, 0x7f, 0xff, 0xfe, 0xf0, 0x00, 0x0f, 0xe0, 0x00, 0x07, 0xc0, 0x00, 0x03, 0x80, 0x00, 0x01, // ****************** // ******************** // ********************** // **** **** // *** *** // ** ** // * * // 71, 41 - ) 0x80, 0x00, 0x01, 0xc0, 0x00, 0x03, 0xe0, 0x00, 0x07, 0xf0, 0x00, 0x0f, 0x7f, 0xff, 0xfe, 0x3f, 0xff, 0xfc, 0x1f, 0xff, 0xf8, // * * // ** ** // *** *** // **** **** // ********************** // ******************** // ****************** // 78, 42 - * 0x06, 0x1c, 0x30, 0x07, 0x1c, 0x70, 0x03, 0x9c, 0xe0, 0x01, 0xdd, 0xc0, 0x00, 0xff, 0x80, 0x00, 0x7f, 0x00, 0x07, 0xff, 0xf0, 0x07, 0xff, 0xf0, 0x07, 0xff, 0xf0, 0x00, 0x7f, 0x00, 0x00, 0xff, 0x80, 0x01, 0xdd, 0xc0, 0x03, 0x9c, 0xe0, 0x07, 0x1c, 0x70, 0x06, 0x1c, 0x30, // ** *** ** // *** *** *** // *** *** *** // *** *** *** // ********* // ******* // *************** // *************** // *************** // ******* // ********* // *** *** *** // *** *** *** // *** *** *** // ** *** ** // 93, 43 - + 0x00, 0x38, 0x00, 0x00, 0x38, 0x00, 0x00, 0x38, 0x00, 0x00, 0x38, 0x00, 0x00, 0x38, 0x00, 0x07, 0xff, 0xc0, 0x07, 0xff, 0xc0, 0x07, 0xff, 0xc0, 0x00, 0x38, 0x00, 0x00, 0x38, 0x00, 0x00, 0x38, 0x00, 0x00, 0x38, 0x00, 0x00, 0x38, 0x00, // *** // *** // *** // *** // *** // ************* // ************* // ************* // *** // *** // *** // *** // *** // 106, 44 - , 0x8c, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x7c, 0x00, 0x00, 0x3c, 0x00, 0x00, // * ** // ****** // ***** // **** // 110, 45 - - 0x00, 0x38, 0x00, 0x00, 0x38, 0x00, 0x00, 0x38, 0x00, 0x00, 0x38, 0x00, 0x00, 0x38, 0x00, 0x00, 0x38, 0x00, 0x00, 0x38, 0x00, 0x00, 0x38, 0x00, 0x00, 0x38, 0x00, 0x00, 0x38, 0x00, // *** // *** // *** // *** // *** // *** // *** // *** // *** // *** // 120, 46 - . 0x60, 0x00, 0x00, 0xf0, 0x00, 0x00, 0xf0, 0x00, 0x00, 0x60, 0x00, 0x00, // ** // **** // **** // ** // 124, 47 - / 0xc0, 0x00, 0x00, 0xf0, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x0f, 0xc0, 0x00, 0x03, 0xf0, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x0f, 0xc0, 0x00, 0x03, 0xf0, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x03, // ** // **** // ****** // ****** // ****** // ****** // ****** // ****** // ****** // ****** // ****** // ****** // **** // ** // 138, 48 - 0 0x1f, 0xff, 0xf8, 0x3f, 0xff, 0xfc, 0x7f, 0xff, 0xfe, 0xf0, 0x00, 0x0f, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xf0, 0x00, 0x0f, 0x7f, 0xff, 0xfe, 0x3f, 0xff, 0xfc, 0x1f, 0xff, 0xf8, // ****************** // ******************** // ********************** // **** **** // *** *** // *** *** // *** *** // *** *** // *** *** // *** *** // *** *** // **** **** // ********************** // ******************** // ****************** // 153, 49 - 1 0xe0, 0x00, 0x10, 0xe0, 0x00, 0x18, 0xe0, 0x00, 0x1c, 0xe0, 0x00, 0x1e, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, // *** * // *** ** // *** *** // *** **** // ************************ // ************************ // ************************ // *** // *** // *** // *** // 164, 50 - 2 0xf0, 0x00, 0x38, 0xf8, 0x00, 0x3c, 0xfc, 0x00, 0x3e, 0xfe, 0x00, 0x0f, 0xef, 0x00, 0x07, 0xe7, 0x80, 0x07, 0xe3, 0xc0, 0x07, 0xe1, 0xe0, 0x07, 0xe0, 0xf0, 0x07, 0xe0, 0x78, 0x07, 0xe0, 0x3c, 0x07, 0xe0, 0x1e, 0x0f, 0xe0, 0x0f, 0xfe, 0xe0, 0x07, 0xfc, 0xe0, 0x03, 0xf8, // **** *** // ***** **** // ****** ***** // ******* **** // *** **** *** // *** **** *** // *** **** *** // *** **** *** // *** **** *** // *** **** *** // *** **** *** // *** **** **** // *** *********** // *** ********* // *** ******* // 179, 51 - 3 0x1c, 0x00, 0x38, 0x3c, 0x00, 0x3c, 0x7c, 0x00, 0x3e, 0xf0, 0x00, 0x0f, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x1c, 0x07, 0xe0, 0x1c, 0x07, 0xe0, 0x1c, 0x07, 0xe0, 0x3e, 0x07, 0xf0, 0x7f, 0x0f, 0x7f, 0xf7, 0xfe, 0x3f, 0xe3, 0xfc, 0x1f, 0xc1, 0xf8, // *** *** // **** **** // ***** ***** // **** **** // *** *** // *** *** // *** *** // *** *** *** // *** *** *** // *** *** *** // *** ***** *** // **** ******* **** // *********** ********** // ********* ******** // ******* ****** // 194, 52 - 4 0x00, 0xfc, 0x00, 0x00, 0xfe, 0x00, 0x00, 0xff, 0x00, 0x00, 0xe7, 0x80, 0x00, 0xe3, 0xc0, 0x00, 0xe1, 0xe0, 0x00, 0xe0, 0xf0, 0x00, 0xe0, 0x78, 0x00, 0xe0, 0x3c, 0x00, 0xe0, 0x1e, 0x00, 0xe0, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, // ****** // ******* // ******** // *** **** // *** **** // *** **** // *** **** // *** **** // *** **** // *** **** // *** **** // ************************ // ************************ // ************************ // *** // *** // 210, 53 - 5 0x1c, 0x1f, 0xff, 0x3c, 0x1f, 0xff, 0x7c, 0x1f, 0xff, 0xf0, 0x0e, 0x07, 0xe0, 0x07, 0x07, 0xe0, 0x07, 0x07, 0xe0, 0x07, 0x07, 0xe0, 0x07, 0x07, 0xe0, 0x07, 0x07, 0xe0, 0x07, 0x07, 0xe0, 0x07, 0x07, 0xf0, 0x0f, 0x07, 0x7f, 0xfe, 0x07, 0x3f, 0xfc, 0x07, 0x1f, 0xf8, 0x00, // *** ************* // **** ************* // ***** ************* // **** *** *** // *** *** *** // *** *** *** // *** *** *** // *** *** *** // *** *** *** // *** *** *** // *** *** *** // **** **** *** // ************** *** // ************ *** // ********** // 225, 54 - 6 0x1f, 0xff, 0xf8, 0x3f, 0xff, 0xfc, 0x7f, 0xff, 0xfe, 0xf0, 0x1c, 0x0f, 0xe0, 0x0e, 0x07, 0xe0, 0x0e, 0x07, 0xe0, 0x0e, 0x07, 0xe0, 0x0e, 0x07, 0xe0, 0x0e, 0x07, 0xe0, 0x0e, 0x07, 0xe0, 0x0e, 0x07, 0xf0, 0x1e, 0x0f, 0x7f, 0xfc, 0x3e, 0x3f, 0xf8, 0x3c, 0x1f, 0xf0, 0x38, // ****************** // ******************** // ********************** // **** *** **** // *** *** *** // *** *** *** // *** *** *** // *** *** *** // *** *** *** // *** *** *** // *** *** *** // **** **** **** // ************* ***** // *********** **** // ********* *** // 240, 55 - 7 0x00, 0x00, 0x1f, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x07, 0x00, 0x00, 0x07, 0x00, 0x00, 0x07, 0xff, 0xf0, 0x07, 0xff, 0xf8, 0x07, 0xff, 0xfc, 0x07, 0x00, 0x1e, 0x07, 0x00, 0x0f, 0x07, 0x00, 0x07, 0x87, 0x00, 0x03, 0xff, 0x00, 0x01, 0xff, 0x00, 0x00, 0xff, // ***** // ***** // ***** // *** // *** // *** // ************ *** // ************* *** // ************** *** // **** *** // **** *** // **** *** // ********** // ********* // ******** // 255, 56 - 8 0x1f, 0xc1, 0xf8, 0x3f, 0xe3, 0xfc, 0x7f, 0xf7, 0xfe, 0xf0, 0x7f, 0x0f, 0xe0, 0x3e, 0x07, 0xe0, 0x1c, 0x07, 0xe0, 0x1c, 0x07, 0xe0, 0x1c, 0x07, 0xe0, 0x1c, 0x07, 0xe0, 0x1c, 0x07, 0xe0, 0x3e, 0x07, 0xf0, 0x7f, 0x0f, 0x7f, 0xf7, 0xfe, 0x3f, 0xe3, 0xfc, 0x1f, 0xc1, 0xf8, // ******* ****** // ********* ******** // *********** ********** // **** ******* **** // *** ***** *** // *** *** *** // *** *** *** // *** *** *** // *** *** *** // *** *** *** // *** ***** *** // **** ******* **** // *********** ********** // ********* ******** // ******* ****** // 270, 57 - 9 0x1c, 0x0f, 0xf8, 0x3c, 0x1f, 0xfc, 0x7c, 0x3f, 0xfe, 0xf0, 0x78, 0x0f, 0xe0, 0x70, 0x07, 0xe0, 0x70, 0x07, 0xe0, 0x70, 0x07, 0xe0, 0x70, 0x07, 0xe0, 0x70, 0x07, 0xe0, 0x70, 0x07, 0xe0, 0x70, 0x07, 0xf0, 0x38, 0x0f, 0x7f, 0xff, 0xfe, 0x3f, 0xff, 0xfc, 0x1f, 0xff, 0xf8, // *** ********* // **** *********** // ***** ************* // **** **** **** // *** *** *** // *** *** *** // *** *** *** // *** *** *** // *** *** *** // *** *** *** // *** *** *** // **** *** **** // ********************** // ******************** // ****************** // 285, 58 - : 0x01, 0x81, 0x80, 0x03, 0xc3, 0xc0, 0x03, 0xc3, 0xc0, 0x01, 0x81, 0x80, // ** ** // **** **** // **** **** // ** ** // 289, 59 - ; 0x8c, 0xc0, 0x00, 0xfd, 0xe0, 0x00, 0x7d, 0xe0, 0x00, 0x3c, 0xc0, 0x00, // * ** ** // ****** **** // ***** **** // **** ** // 293, 60 - < 0x00, 0x18, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x7e, 0x00, 0x00, 0xff, 0x00, 0x01, 0xe7, 0x80, 0x03, 0xc3, 0xc0, 0x07, 0x81, 0xe0, 0x0f, 0x00, 0xf0, 0x1e, 0x00, 0x78, 0x3c, 0x00, 0x3c, 0x78, 0x00, 0x1e, 0xf0, 0x00, 0x0f, 0xe0, 0x00, 0x07, 0xc0, 0x00, 0x03, 0x80, 0x00, 0x01, // ** // **** // ****** // ******** // **** **** // **** **** // **** **** // **** **** // **** **** // **** **** // **** **** // **** **** // *** *** // ** ** // * * // 308, 61 - = 0x00, 0xe7, 0x00, 0x00, 0xe7, 0x00, 0x00, 0xe7, 0x00, 0x00, 0xe7, 0x00, 0x00, 0xe7, 0x00, 0x00, 0xe7, 0x00, 0x00, 0xe7, 0x00, 0x00, 0xe7, 0x00, 0x00, 0xe7, 0x00, 0x00, 0xe7, 0x00, // *** *** // *** *** // *** *** // *** *** // *** *** // *** *** // *** *** // *** *** // *** *** // *** *** // 318, 62 - > 0x80, 0x00, 0x01, 0xc0, 0x00, 0x03, 0xe0, 0x00, 0x07, 0xf0, 0x00, 0x0f, 0x78, 0x00, 0x1e, 0x3c, 0x00, 0x3c, 0x1e, 0x00, 0x78, 0x0f, 0x00, 0xf0, 0x07, 0x81, 0xe0, 0x03, 0xc3, 0xc0, 0x01, 0xe7, 0x80, 0x00, 0xff, 0x00, 0x00, 0x7e, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x18, 0x00, // * * // ** ** // *** *** // **** **** // **** **** // **** **** // **** **** // **** **** // **** **** // **** **** // **** **** // ******** // ****** // **** // ** // 333, 63 - ? 0x00, 0x00, 0x38, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x07, 0x00, 0x00, 0x07, 0xe7, 0xf0, 0x07, 0xe7, 0xf8, 0x07, 0xe7, 0xfc, 0x07, 0x00, 0x1e, 0x07, 0x00, 0x0f, 0x0f, 0x00, 0x07, 0xfe, 0x00, 0x03, 0xfc, 0x00, 0x01, 0xf8, // *** // **** // ***** // **** // *** // *** // *** ******* *** // *** ******** *** // *** ********* *** // **** *** // **** **** // ********** // ******** // ****** // 347, 64 - @ // 347, 65 - A 0x1ff, 0xff, 0xf8, 0xff, 0xff, 0xfc, 0xff, 0xff, 0xfe, 0x00, 0x70, 0x0f, 0x00, 0x70, 0x07, 0x00, 0x70, 0x07, 0x00, 0x70, 0x07, 0x00, 0x70, 0x07, 0x00, 0x70, 0x07, 0x00, 0x70, 0x07, 0x00, 0x70, 0x0f, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0xff, 0xff, 0xf8, // ********************* // ********************** // *********************** // *** **** // *** *** // *** *** // *** *** // *** *** // *** *** // *** *** // *** **** // *********************** // ********************** // ********************* // 361, 66 - B 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x1c, 0x07, 0xe0, 0x1c, 0x07, 0xe0, 0x1c, 0x07, 0xe0, 0x1c, 0x07, 0xe0, 0x1c, 0x07, 0xe0, 0x1c, 0x07, 0xe0, 0x3e, 0x07, 0xf0, 0x7f, 0x0f, 0x7f, 0xf7, 0xfe, 0x3f, 0xe3, 0xfc, 0x1f, 0xc1, 0xf8, // ************************ // ************************ // ************************ // *** *** *** // *** *** *** // *** *** *** // *** *** *** // *** *** *** // *** *** *** // *** ***** *** // **** ******* **** // *********** ********** // ********* ******** // ******* ****** // 375, 67 - C 0x1f, 0xff, 0xf8, 0x3f, 0xff, 0xfc, 0x7f, 0xff, 0xfe, 0xf0, 0x00, 0x0f, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xf0, 0x00, 0x0f, 0x78, 0x00, 0x1e, 0x38, 0x00, 0x1c, 0x18, 0x00, 0x18, // ****************** // ******************** // ********************** // **** **** // *** *** // *** *** // *** *** // *** *** // *** *** // *** *** // **** **** // **** **** // *** *** // ** ** // 389, 68 - D 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xf0, 0x00, 0x0f, 0x7f, 0xff, 0xfe, 0x3f, 0xff, 0xfc, 0x1f, 0xff, 0xf8, // ************************ // ************************ // ************************ // *** *** // *** *** // *** *** // *** *** // *** *** // *** *** // *** *** // **** **** // ********************** // ******************** // ****************** // 403, 69 - E 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x38, 0x07, 0xe0, 0x38, 0x07, 0xe0, 0x38, 0x07, 0xe0, 0x38, 0x07, 0xe0, 0x38, 0x07, 0xe0, 0x38, 0x07, 0xe0, 0x38, 0x07, 0xe0, 0x38, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, // ************************ // ************************ // ************************ // *** *** *** // *** *** *** // *** *** *** // *** *** *** // *** *** *** // *** *** *** // *** *** *** // *** *** *** // *** *** // *** *** // *** *** // 417, 70 - F 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x38, 0x07, 0x00, 0x38, 0x07, 0x00, 0x38, 0x07, 0x00, 0x38, 0x07, 0x00, 0x38, 0x07, 0x00, 0x38, 0x07, 0x00, 0x38, 0x07, 0x00, 0x38, 0x07, 0x00, 0x00, 0x07, 0x00, 0x00, 0x07, 0x00, 0x00, 0x07, // ************************ // ************************ // ************************ // *** *** // *** *** // *** *** // *** *** // *** *** // *** *** // *** *** // *** *** // *** // *** // *** // 431, 71 - G 0x1f, 0xff, 0xf8, 0x3f, 0xff, 0xfc, 0x7f, 0xff, 0xfe, 0xf0, 0x00, 0x0f, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0xe0, 0x07, 0xe0, 0xe0, 0x07, 0xe0, 0xe0, 0x0f, 0xff, 0xe0, 0x1e, 0xff, 0xe0, 0x1c, 0xff, 0xe0, 0x18, // ****************** // ******************** // ********************** // **** **** // *** *** // *** *** // *** *** // *** *** // *** *** *** // *** *** *** // *** *** **** // *********** **** // *********** *** // *********** ** // 445, 72 - H 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x1c, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x1c, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, // ************************ // ************************ // ************************ // *** // *** // *** // *** // *** // *** // *** // *** // ************************ // ************************ // ************************ // 459, 73 - I 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, // *** *** // *** *** // *** *** // ************************ // ************************ // ************************ // *** *** // *** *** // *** *** // 468, 74 - J 0x18, 0x00, 0x00, 0x38, 0x00, 0x00, 0x78, 0x00, 0x00, 0xf0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xf0, 0x00, 0x07, 0x7f, 0xff, 0xff, 0x3f, 0xff, 0xff, 0x1f, 0xff, 0xff, 0x00, 0x00, 0x07, 0x00, 0x00, 0x07, 0x00, 0x00, 0x07, // ** // *** // **** // **** // *** // *** // *** *** // *** *** // *** *** // **** *** // *********************** // ********************** // ********************* // *** // *** // *** // 484, 75 - K 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x7c, 0x00, 0x00, 0xfe, 0x00, 0x01, 0xef, 0x00, 0x03, 0xc7, 0x80, 0x07, 0x83, 0xc0, 0x0f, 0x01, 0xe0, 0x1e, 0x00, 0xf0, 0x3c, 0x00, 0x78, 0x78, 0x00, 0x3c, 0xf0, 0x00, 0x1e, 0xe0, 0x00, 0x0f, 0xc0, 0x00, 0x07, 0x80, 0x00, 0x03, // ************************ // ************************ // ************************ // ***** // ******* // **** **** // **** **** // **** **** // **** **** // **** **** // **** **** // **** **** // **** **** // *** **** // ** *** // * ** // 500, 76 - L 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, // ************************ // ************************ // ************************ // *** // *** // *** // *** // *** // *** // *** // *** // *** // *** // *** // 514, 77 - M 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x78, 0x00, 0x00, 0xf0, 0x00, 0x01, 0xe0, 0x00, 0x00, 0xf0, 0x00, 0x00, 0x78, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x1e, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, // ************************ // ************************ // ************************ // **** // **** // **** // **** // **** // **** // **** // **** // **** // ************************ // ************************ // ************************ // 529, 78 - N 0x1ff, 0xff, 0xff, 0x1ff, 0xff, 0xff, 0x1ff, 0xff, 0xff, 0x00, 0x00, 0xfc, 0x00, 0x03, 0xf0, 0x00, 0x0f, 0xc0, 0x00, 0x3f, 0x00, 0x00, 0xfc, 0x00, 0x03, 0xf0, 0x00, 0x0f, 0xc0, 0x00, 0x3f, 0x00, 0x00, 0x1ff, 0xff, 0xff, 0x1ff, 0xff, 0xff, 0x1ff, 0xff, 0xff, // ************************ // ************************ // ************************ // ****** // ****** // ****** // ****** // ****** // ****** // ****** // ****** // ************************ // ************************ // ************************ // 543, 79 - O 0x1f, 0xff, 0xf8, 0x3f, 0xff, 0xfc, 0x7f, 0xff, 0xfe, 0xf0, 0x00, 0x0f, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xf0, 0x00, 0x0f, 0x7f, 0xff, 0xfe, 0x3f, 0xff, 0xfc, 0x1f, 0xff, 0xf8, // ****************** // ******************** // ********************** // **** **** // *** *** // *** *** // *** *** // *** *** // *** *** // *** *** // **** **** // ********************** // ******************** // ****************** // 557, 80 - P 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x1c, 0x07, 0x00, 0x1c, 0x07, 0x00, 0x1c, 0x07, 0x00, 0x1c, 0x07, 0x00, 0x1c, 0x07, 0x00, 0x1c, 0x07, 0x00, 0x1c, 0x07, 0x00, 0x1e, 0x0f, 0x00, 0x0f, 0xfe, 0x00, 0x07, 0xfc, 0x00, 0x03, 0xf8, // ************************ // ************************ // ************************ // *** *** // *** *** // *** *** // *** *** // *** *** // *** *** // *** *** // **** **** // *********** // ********* // ******* // 571, 81 - Q 0x1f, 0xff, 0xf8, 0x3f, 0xff, 0xfc, 0x7f, 0xff, 0xfe, 0xf0, 0x00, 0x0f, 0xe0, 0x00, 0x07, 0xe2, 0x00, 0x07, 0xe6, 0x00, 0x07, 0xee, 0x00, 0x07, 0xfe, 0x00, 0x07, 0x7c, 0x00, 0x07, 0x78, 0x00, 0x0f, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0xcf, 0xff, 0xf8, 0x80, 0x00, 0x00, // ****************** // ******************** // ********************** // **** **** // *** *** // *** * *** // *** ** *** // *** *** *** // ******* *** // ***** *** // **** **** // *********************** // ********************** // ** ***************** // * // 586, 82 - R 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x1c, 0x07, 0x00, 0x1c, 0x07, 0x00, 0x1c, 0x07, 0x00, 0x1c, 0x07, 0x00, 0x3c, 0x07, 0x00, 0x7c, 0x07, 0x00, 0xfc, 0x07, 0x01, 0xfe, 0x0f, 0xff, 0xcf, 0xfe, 0xff, 0x87, 0xfc, 0xff, 0x03, 0xf8, // ************************ // ************************ // ************************ // *** *** // *** *** // *** *** // *** *** // **** *** // ***** *** // ****** *** // ******** **** // ********** *********** // ********* ********* // ******** ******* // 600, 83 - S 0x18, 0x03, 0xf8, 0x38, 0x07, 0xfc, 0x78, 0x0f, 0xfe, 0xf0, 0x1e, 0x0f, 0xe0, 0x1c, 0x07, 0xe0, 0x1c, 0x07, 0xe0, 0x1c, 0x07, 0xe0, 0x1c, 0x07, 0xe0, 0x1c, 0x07, 0xe0, 0x3c, 0x07, 0xf0, 0x78, 0x0f, 0x7f, 0xf0, 0x1e, 0x3f, 0xe0, 0x1c, 0x1f, 0xc0, 0x18, // ** ******* // *** ********* // **** *********** // **** **** **** // *** *** *** // *** *** *** // *** *** *** // *** *** *** // *** *** *** // *** **** *** // **** **** **** // *********** **** // ********* *** // ******* ** // 614, 84 - T 0x00, 0x00, 0x07, 0x00, 0x00, 0x07, 0x00, 0x00, 0x07, 0x00, 0x00, 0x07, 0x00, 0x00, 0x07, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x07, 0x00, 0x00, 0x07, 0x00, 0x00, 0x07, 0x00, 0x00, 0x07, 0x00, 0x00, 0x07, // *** // *** // *** // *** // *** // ************************ // ************************ // ************************ // *** // *** // *** // *** // *** // 627, 85 - U 0x1f, 0xff, 0xff, 0x3f, 0xff, 0xff, 0x7f, 0xff, 0xff, 0xf0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xf0, 0x00, 0x00, 0x7f, 0xff, 0xff, 0x3f, 0xff, 0xff, 0x1f, 0xff, 0xff, // ********************* // ********************** // *********************** // **** // *** // *** // *** // *** // *** // *** // **** // *********************** // ********************** // ********************* // 641, 86 - V 0x01, 0xff, 0xff, 0x03, 0xff, 0xff, 0x07, 0xff, 0xff, 0x0f, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x78, 0x00, 0x00, 0xf0, 0x00, 0x00, 0x78, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x07, 0xff, 0xff, 0x03, 0xff, 0xff, 0x01, 0xff, 0xff, // ***************** // ****************** // ******************* // **** // **** // **** // **** // **** // **** // **** // **** // **** // ******************* // ****************** // ***************** // 656, 87 - W 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xff, 0xff, 0x3c, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x07, 0x80, 0x00, 0x03, 0xc0, 0x00, 0x07, 0x80, 0x00, 0x0f, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, // ************************ // ************************ // *********************** // **** // **** // **** // **** // **** // **** // **** // **** // **** // *********************** // ************************ // ************************ // 671, 88 - X 0xfe, 0x00, 0x3f, 0xff, 0x00, 0x7f, 0xff, 0x80, 0xff, 0x03, 0xc1, 0xe0, 0x01, 0xe3, 0xc0, 0x00, 0xf7, 0x80, 0x00, 0x7f, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x7f, 0x00, 0x00, 0xf7, 0x80, 0x01, 0xe3, 0xc0, 0x03, 0xc1, 0xe0, 0xff, 0x80, 0xff, 0xff, 0x00, 0x7f, 0xfe, 0x00, 0x3f, // ******* ****** // ******** ******* // ********* ******** // **** **** // **** **** // **** **** // ******* // ***** // ***** // ******* // **** **** // **** **** // **** **** // ********* ******** // ******** ******* // ******* ****** // 687, 89 - Y 0x00, 0x00, 0x7f, 0x00, 0x00, 0xff, 0x00, 0x01, 0xff, 0x00, 0x03, 0xc0, 0x00, 0x07, 0x80, 0x00, 0x0f, 0x00, 0xff, 0xfe, 0x00, 0xff, 0xfc, 0x00, 0xff, 0xfe, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x07, 0x80, 0x00, 0x03, 0xc0, 0x00, 0x01, 0xff, 0x00, 0x00, 0xff, 0x00, 0x00, 0x7f, // ******* // ******** // ********* // **** // **** // **** // *************** // ************** // *************** // **** // **** // **** // ********* // ******** // ******* // 702, 90 - Z 0xfe, 0x00, 0x07, 0xff, 0x00, 0x07, 0xff, 0x80, 0x07, 0xe3, 0xc0, 0x07, 0xe1, 0xe0, 0x07, 0xe0, 0xf0, 0x07, 0xe0, 0x78, 0x07, 0xe0, 0x3c, 0x07, 0xe0, 0x1e, 0x07, 0xe0, 0x0f, 0x07, 0xe0, 0x07, 0x87, 0xe0, 0x03, 0xc7, 0xe0, 0x01, 0xff, 0xe0, 0x00, 0xff, 0xe0, 0x00, 0x7f, // ******* *** // ******** *** // ********* *** // *** **** *** // *** **** *** // *** **** *** // *** **** *** // *** **** *** // *** **** *** // *** **** *** // *** **** *** // *** **** *** // *** ********* // *** ******** // *** ******* // 717, 91 - [ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, // ************************ // ************************ // ************************ // *** *** // *** *** // *** *** // *** *** // 724, 92 - backslash 0x00, 0x00, 0x03, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x3f, 0x00, 0x00, 0xfc, 0x00, 0x03, 0xf0, 0x00, 0x0f, 0xc0, 0x00, 0x3f, 0x00, 0x00, 0xfc, 0x00, 0x03, 0xf0, 0x00, 0x0f, 0xc0, 0x00, 0x3f, 0x00, 0x00, 0xfc, 0x00, 0x00, 0xf0, 0x00, 0x00, 0xc0, 0x00, 0x00, // ** // **** // ****** // ****** // ****** // ****** // ****** // ****** // ****** // ****** // ****** // ****** // **** // ** // 738, 93 - ] 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xe0, 0x00, 0x07, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, // *** *** // *** *** // *** *** // *** *** // ************************ // ************************ // ************************ // 745, 94 - ^ // 745, 95 - _ 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, 0xe0, 0x00, 0x00, // *** // *** // *** // *** // *** // *** // *** // *** // *** // *** // *** // *** // *** // *** 00, };
98075fa2e67ef2227e9cef65ef84f7d326a6f053
e03e0bb3f32574c8159dfe43f1319d7426ca2d83
/Classes/enemySprite.h
7380bd605173782fc5f1c9e62d6a0673a6a9b77a
[]
no_license
svgame/airplane
f4c5386a58611c8523fb327b4dfa48c0b9606659
bb2e495a0f73c3b73b9f3ff0e0b5973773d3c90d
refs/heads/master
2021-01-01T17:42:38.736315
2014-12-07T09:47:06
2014-12-07T09:47:06
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
430
h
#pragma once #include "cocos2d.h" class enemySprite : public cocos2d::Sprite { public: enemySprite(); ~enemySprite(); static enemySprite* create(); static enemySprite* createWithSpriteFrame(cocos2d::SpriteFrame *spriteFrame); virtual bool init(); void set_hp(int hp){ enemy_hp = hp; }; int get_hp(){ return enemy_hp; }; void lose_hp(int hp = 1) { enemy_hp -= hp; }; private: int enemy_hp; /*µÐ»úÉúÃüÖµ*/ };
cd51ee0a3c4073c8e9ff7909325911097312c20f
c04f14564f21bf3ca235179404e8730b43139096
/String.h
b818cc243db7ee22dc3f733d0ab3b22b355831a6
[]
no_license
masDevpp/ARM_Test
f25d46f132b802d26d149821dd7849ad9a86696a
97db2c739dade42b2858a5d0b186051fe615e795
refs/heads/master
2023-01-03T23:41:24.066223
2020-10-27T14:06:06
2020-10-27T14:06:06
294,105,235
0
0
null
null
null
null
UTF-8
C++
false
false
628
h
#pragma once #include "DataType.h" #include "Memory.h" class String { public: String(); String(const void *source, uint32 length = 0xffffffff); String(uint32 value, uint32 base = 10); //~String(); void Release(); bool Equal(String target); bool Equal(const void *target, uint32 length = 0xffffffff); String SubString(uint32 start, uint32 length = 0xffffffff); int32 IndexOf(char c); const uint8 *GetBuffer(); bool ToUInt32(uint32 &value, uint32 base = 0); uint32 Length; public: static const uint32 BUFFER_LENGTH = Memory::SEGMENT_SIZE; uint8 *Buffer = nullptr; };
d51922da1ad7f63901f4ae09a64c1d33f7504407
77bc4d919b11e8c3dbe5c8a6f689527f7535e79c
/PSGRADE.cpp
9923f057f046f65be24ea50a7c31d7be3b35f572
[]
no_license
DionysiosB/CodeChef
3610626548089f667280f0e1713517d9ddd3927a
8b4ddf58173df0e1577215c09adcc2c03d67ffca
refs/heads/master
2023-09-04T05:03:40.767798
2023-09-02T17:17:14
2023-09-02T17:17:14
10,135,601
10
7
null
2020-10-01T04:54:41
2013-05-18T02:27:54
C++
UTF-8
C++
false
false
330
cpp
#include <cstdio> int main(){ long t; scanf("%ld", &t); while(t--){ long amin, bmin, cmin, smin, a, b, c; scanf("%ld %ld %ld %ld %ld %ld %ld", &amin, &bmin, &cmin, &smin, &a, &b, &c); bool res = (a >= amin) && (b >= bmin) && (c >= cmin) && (a + b + c >= smin); puts(res ? "YES" : "NO"); } }
a153113cbbc0474e9955dce184310f1417fed1cf
5cf6a78ba34d93aa604968bdf554ccb5ed4ebe17
/devel/include/collide_free/SetPointResponse.h
c16be648c45f425c6d29c572517c68fe38a30e03
[]
no_license
ykhan1998/RBE580-neurosurgery-robot-collision-detection
687fc54b8b10665bbdee7d8fc2a049b7fb646aa1
19c12398f6aff873159504446a31ae2bec38cf52
refs/heads/master
2023-04-22T16:29:20.977507
2021-05-13T00:57:47
2021-05-13T00:57:47
366,219,343
0
0
null
null
null
null
UTF-8
C++
false
false
5,895
h
// Generated by gencpp from file collide_free/SetPointResponse.msg // DO NOT EDIT! #ifndef COLLIDE_FREE_MESSAGE_SETPOINTRESPONSE_H #define COLLIDE_FREE_MESSAGE_SETPOINTRESPONSE_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace collide_free { template <class ContainerAllocator> struct SetPointResponse_ { typedef SetPointResponse_<ContainerAllocator> Type; SetPointResponse_() : wm() , wh() , t() { } SetPointResponse_(const ContainerAllocator& _alloc) : wm(_alloc) , wh(_alloc) , t(_alloc) { (void)_alloc; } typedef std::vector<double, typename ContainerAllocator::template rebind<double>::other > _wm_type; _wm_type wm; typedef std::vector<double, typename ContainerAllocator::template rebind<double>::other > _wh_type; _wh_type wh; typedef std::vector<double, typename ContainerAllocator::template rebind<double>::other > _t_type; _t_type t; typedef boost::shared_ptr< ::collide_free::SetPointResponse_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::collide_free::SetPointResponse_<ContainerAllocator> const> ConstPtr; }; // struct SetPointResponse_ typedef ::collide_free::SetPointResponse_<std::allocator<void> > SetPointResponse; typedef boost::shared_ptr< ::collide_free::SetPointResponse > SetPointResponsePtr; typedef boost::shared_ptr< ::collide_free::SetPointResponse const> SetPointResponseConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::collide_free::SetPointResponse_<ContainerAllocator> & v) { ros::message_operations::Printer< ::collide_free::SetPointResponse_<ContainerAllocator> >::stream(s, "", v); return s; } template<typename ContainerAllocator1, typename ContainerAllocator2> bool operator==(const ::collide_free::SetPointResponse_<ContainerAllocator1> & lhs, const ::collide_free::SetPointResponse_<ContainerAllocator2> & rhs) { return lhs.wm == rhs.wm && lhs.wh == rhs.wh && lhs.t == rhs.t; } template<typename ContainerAllocator1, typename ContainerAllocator2> bool operator!=(const ::collide_free::SetPointResponse_<ContainerAllocator1> & lhs, const ::collide_free::SetPointResponse_<ContainerAllocator2> & rhs) { return !(lhs == rhs); } } // namespace collide_free namespace ros { namespace message_traits { template <class ContainerAllocator> struct IsMessage< ::collide_free::SetPointResponse_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::collide_free::SetPointResponse_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct IsFixedSize< ::collide_free::SetPointResponse_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::collide_free::SetPointResponse_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::collide_free::SetPointResponse_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::collide_free::SetPointResponse_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::collide_free::SetPointResponse_<ContainerAllocator> > { static const char* value() { return "217099dae91577c60de7e73dd2aa8c7c"; } static const char* value(const ::collide_free::SetPointResponse_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x217099dae91577c6ULL; static const uint64_t static_value2 = 0x0de7e73dd2aa8c7cULL; }; template<class ContainerAllocator> struct DataType< ::collide_free::SetPointResponse_<ContainerAllocator> > { static const char* value() { return "collide_free/SetPointResponse"; } static const char* value(const ::collide_free::SetPointResponse_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::collide_free::SetPointResponse_<ContainerAllocator> > { static const char* value() { return "float64[] wm\n" "float64[] wh\n" "float64[] t\n" "\n" ; } static const char* value(const ::collide_free::SetPointResponse_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::collide_free::SetPointResponse_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.wm); stream.next(m.wh); stream.next(m.t); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct SetPointResponse_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::collide_free::SetPointResponse_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::collide_free::SetPointResponse_<ContainerAllocator>& v) { s << indent << "wm[]" << std::endl; for (size_t i = 0; i < v.wm.size(); ++i) { s << indent << " wm[" << i << "]: "; Printer<double>::stream(s, indent + " ", v.wm[i]); } s << indent << "wh[]" << std::endl; for (size_t i = 0; i < v.wh.size(); ++i) { s << indent << " wh[" << i << "]: "; Printer<double>::stream(s, indent + " ", v.wh[i]); } s << indent << "t[]" << std::endl; for (size_t i = 0; i < v.t.size(); ++i) { s << indent << " t[" << i << "]: "; Printer<double>::stream(s, indent + " ", v.t[i]); } } }; } // namespace message_operations } // namespace ros #endif // COLLIDE_FREE_MESSAGE_SETPOINTRESPONSE_H
67a9e62371d04ef62f9b143c900547b078313b6f
5ee30bf72ec7e6e46d892e03b2d8bd70575540d5
/base.h
bc5a1c84a3f9408de937cb479bd29959aa18a5d1
[]
no_license
shi-yan/graphicsrelatedcodes
c7a788418b17b7417016f038b6c6275448f63ba1
466ab305f8ac2a6486626e9f8dadbec5e2a18d04
refs/heads/master
2016-09-05T10:24:16.536717
2011-08-21T01:24:22
2011-08-21T01:24:22
2,241,036
1
0
null
null
null
null
UTF-8
C++
false
false
3,361
h
#pragma once #include <cmath> #include <assert.h> #include <limits.h> /// static_assert: implemented as a macro for "assert", but it is separated for clarity. /// Should be used for checking integrity constraints that can be tested at complile time, /// as the ones involving templated constants in templated classes. #define static_assert assert namespace GGL { namespace Math { template <class SCALAR> class MagnitudoComparer { public: inline bool operator() ( const SCALAR a, const SCALAR b ) { return fabs(a)>fabs(b); } }; inline float Sqrt(const short v) { return sqrtf(v); } inline float Sqrt(const int v) { return sqrtf((float)v); } inline float Sqrt(const float v) { return sqrtf(v); } inline float Abs(const float v) { return fabsf(v); } inline float Cos(const float v) { return cosf(v); } inline float Sin(const float v) { return sinf(v); } inline float Acos(const float v) { return acosf(v); } inline float Asin(const float v) { return asinf(v); } inline float Atan2(const float v0,const float v1) { return atan2f(v0,v1); } inline double Sqrt(const double v) { return sqrt(v); } inline double Abs(const double v) { return fabs(v); } inline double Cos(const double v) { return cos(v); } inline double Sin(const double v) { return sin(v); } inline double Acos(const double v) { return acos(v); } inline double Asin(const double v) { return asin(v); } inline double Atan2(const double v0,const double v1) { return atan2(v0,v1); } template<class T> inline const T & Min(const T &a, const T &b) { if (a<b) return a; else return b; } template<class T> inline const T & Max(const T &a, const T &b) { if (a<b) return b; else return a; } template<class T> inline void Swap(T &a, T &b) { T tmp=a; a=b; b=tmp; } template<class T> inline void Sort(T &a, T &b) { if (a>b) Swap(a,b); } template<class T> inline void Sort(T &a, T &b, T &c) { if (a>b) Swap(a,b); if (b>c) { Swap(b,c); if (a>b) Swap(a,b); } } /* Some <math.h> files do not define M_PI... */ #ifndef M_PI #define M_PI 3.14159265358979323846 #endif template <class SCALAR> inline SCALAR Clamp( const SCALAR & val, const SCALAR& minval, const SCALAR& maxval) { if(val < minval) return minval; if(val > maxval) return maxval; return val; } inline float ToDeg(const float &a) { return a*180.0f/float(M_PI); } inline float ToRad(const float &a) { return float(M_PI)*a/180.0f; } inline double ToDeg(const double &a) { return a*180.0/M_PI; } inline double ToRad(const double &a) { return M_PI*a/180.0; } #if defined(_MSC_VER) // Microsoft Visual C++ template<class T> int IsNAN(T t) { return _isnan(t); } #elif defined(__GNUC__) // GCC template<class T> int IsNAN(T t) { return isnan(t); } #else // generic template<class T> int IsNAN(T t) { if(std::numeric_limits<T>::has_infinity) return !(t <= std::numeric_limits<T>::infinity()); else return t != t; } #endif } // End math namespace /// a type that stands for "void". Useful for Parameter type of a point. class VoidType { public: VoidType() {}; };}
113936c0a42f7fe9c25b177383638b18dab84d4f
98b1e51f55fe389379b0db00365402359309186a
/homework_6/problem_2/50x50/0.151/uniform/time
3e29fec176078a5d6867bb38edc9d0aeae46d698
[]
no_license
taddyb/597-009
f14c0e75a03ae2fd741905c4c0bc92440d10adda
5f67e7d3910e3ec115fb3f3dc89a21dcc9a1b927
refs/heads/main
2023-01-23T08:14:47.028429
2020-12-03T13:24:27
2020-12-03T13:24:27
311,713,551
1
0
null
null
null
null
UTF-8
C++
false
false
828
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 8 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "0.151/uniform"; object time; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // value 0.151000000000000106; name "0.151"; index 151; deltaT 0.001; deltaT0 0.001; // ************************************************************************* //
4b94f7f14125347e71c6f2308697ecd7e3cc5c4e
e35dd506083ad5119d035f517f8487bd0d0090bb
/WI/2008/pp0504d.cpp
d905ec60e4c73601e97eaac64886e27ebc7539db
[]
no_license
Neverous/xivlo08-11
95088ded4aa7aeebc28da7c22b255446e4a43bda
7daa4f5125aece228fc2f067a455e24ff20eb3f4
refs/heads/master
2016-08-12T15:59:21.258466
2016-03-22T14:41:25
2016-03-22T14:41:25
54,478,420
0
0
null
null
null
null
UTF-8
C++
false
false
288
cpp
#include<cstdio> long long int sumGlob,sum,tmp; int main(void) { while(true) { scanf("%lld", &tmp); sum += tmp; sumGlob += tmp; if(tmp == 0) printf("%lld\n", sum); if(tmp == 0 && sum == 0) break; if(tmp == 0) sum = 0; } printf("%lld\n", sumGlob); return 0; }
59105445647c4a44fbce17d7c7ccba1430005f50
ad22dedd60c7acb34b9c8f673c0a88e3ca74781c
/calculator.hpp
7e21de64a412324e01d65c767b4910d66b3be647
[]
no_license
Daniel-Ri/CPP-Calculator
49367c8940d81264220f0ed2221378ab8a1a1583
5253e784a4b2df0279e7637eb3425a35716bc0ca
refs/heads/main
2023-04-17T21:37:31.270898
2021-05-01T09:08:15
2021-05-01T09:08:15
361,703,569
0
0
null
null
null
null
UTF-8
C++
false
false
212
hpp
#ifndef __CALCULATOR__HPP__ #define __CALCULATOR__HPP__ #include <iostream> float tambah(float x, float y); float kurang(float x, float y); float kali(float x, float y); float bagi(float x, float y); #endif
38dd904a60d2a01dc71d3cb02791c2fbf54eceea
d14b5d78b72711e4614808051c0364b7bd5d6d98
/third_party/llvm-16.0/llvm/lib/DebugInfo/MSF/MSFError.cpp
fd93c3e726ccbe0e02723e7de54b32b505e32f2c
[ "Apache-2.0" ]
permissive
google/swiftshader
76659addb1c12eb1477050fded1e7d067f2ed25b
5be49d4aef266ae6dcc95085e1e3011dad0e7eb7
refs/heads/master
2023-07-21T23:19:29.415159
2023-07-21T19:58:29
2023-07-21T20:50:19
62,297,898
1,981
306
Apache-2.0
2023-07-05T21:29:34
2016-06-30T09:25:24
C++
UTF-8
C++
false
false
2,203
cpp
//===- MSFError.cpp - Error extensions for MSF files ------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "llvm/DebugInfo/MSF/MSFError.h" #include "llvm/Support/ErrorHandling.h" #include <string> using namespace llvm; using namespace llvm::msf; namespace { // FIXME: This class is only here to support the transition to llvm::Error. It // will be removed once this transition is complete. Clients should prefer to // deal with the Error value directly, rather than converting to error_code. class MSFErrorCategory : public std::error_category { public: const char *name() const noexcept override { return "llvm.msf"; } std::string message(int Condition) const override { switch (static_cast<msf_error_code>(Condition)) { case msf_error_code::unspecified: return "An unknown error has occurred."; case msf_error_code::insufficient_buffer: return "The buffer is not large enough to read the requested number of " "bytes."; case msf_error_code::size_overflow_4096: return "Output data is larger than 4 GiB."; case msf_error_code::size_overflow_8192: return "Output data is larger than 8 GiB."; case msf_error_code::size_overflow_16384: return "Output data is larger than 16 GiB."; case msf_error_code::size_overflow_32768: return "Output data is larger than 32 GiB."; case msf_error_code::not_writable: return "The specified stream is not writable."; case msf_error_code::no_stream: return "The specified stream does not exist."; case msf_error_code::invalid_format: return "The data is in an unexpected format."; case msf_error_code::block_in_use: return "The block is already in use."; } llvm_unreachable("Unrecognized msf_error_code"); } }; } // namespace const std::error_category &llvm::msf::MSFErrCategory() { static MSFErrorCategory MSFCategory; return MSFCategory; } char MSFError::ID;
bf43e95097b5fabee5caa1a607ac6c5c91f508d5
45eda4611f8fee12f1764d2f7b67ce1393436c51
/src/dom/DOMNode.h
f43765d12d5c6b1e4d8339a446c90921dfbf7153
[]
no_license
nukes/pyXerces
116a4b4a0a36028efd41f99174faee5e3822eb6a
3cccd979e134491fcf6a1db57fd6c9b4d3109017
refs/heads/master
2020-05-19T12:12:57.976210
2017-09-10T08:01:18
2017-09-10T08:01:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
216
h
/* * DOMNode.h * * Created on: 2013/02/20 * Author: mugwort_rc */ #ifndef DOMNODE_H_ #define DOMNODE_H_ namespace pyxerces { void DOMNode_init(void); } /* namespace pyxerces */ #endif /* DOMNODE_H_ */
dab1ef3821d688fc1e402ff1f6e7f5b5411267b1
46c920184cbf807709b30289e737cc2bc238af41
/week02/code/hand_drawn_knob/hand_drawn_knob.ino
1fa185424015747d912a8b09615633f8060bf0d3
[]
no_license
phoenixperry/physical_computing_grad
9ac46a28bef86c5c9dad7d1c4cc15eb86441c82a
f6ba4db198fd71c979bb103680843d41ec37c0b3
refs/heads/master
2021-01-10T06:17:31.192473
2016-03-23T15:52:35
2016-03-23T15:52:35
49,836,761
6
1
null
null
null
null
UTF-8
C++
false
false
269
ino
int knob = A5; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(knob,INPUT_PULLUP); } void loop() { // put your main code here, to run repeatedly: int myKnobData = analogRead(knob); Serial.println(myKnobData); }
eeafba5f25d7638cced36a06215bb1ee8960dc46
04782689f9bcd1d542f895a03968a9c2ff0b2646
/Server/src/TimeList.cpp
a8f49759536c993e519b4397759dd4e4e776dfd0
[]
no_license
bailongxian/network
5fe95694baed6e51da4f01c54c7ddefad6726466
bdb585ab08e3ee945799da747b9e561bddc3b942
refs/heads/master
2016-09-05T22:31:57.392812
2015-09-07T07:06:20
2015-09-07T07:06:20
41,648,614
6
2
null
null
null
null
UTF-8
C++
false
false
1,143
cpp
#include "TimeList.h" #include <assert.h> #include <stdio.h> #define DEFAULT_TIME_OUT 60 CTimeList::CTimeList() :len_(0), Head_(NULL), Tail_(NULL) { } CTimeList::~CTimeList() { } void CTimeList::Insert(TimeNode* Node) { assert(Node); if(len_ == 0) { Head_ = Tail_ = Node; Head_->Pre = Tail_->Pre = Node->Pre = NULL; Head_->Next = Tail_->Next = Node->Next = NULL; } else { Node->Next = Tail_->Next; Node->Pre = Tail_; Tail_->Next= Node; Tail_ = Node; } len_++; } void CTimeList::Remove(TimeNode* Node) { assert(len_ > 0); if(Node == Head_) { Head_ = Node->Next; } else { Node->Pre->Next = Node->Next; } if(Node == Tail_) { Tail_ = Node->Pre; } else { Node->Next->Pre = Node->Pre; } len_--; } TimeNode* CTimeList::GetExpireNode(time_t cur) { if(len_ == 0) return NULL; TimeNode *Node = Head_; if(Node->ExpireTime < cur) return Node; return NULL; } time_t CTimeList::GetMinExpireTime() { if(len_ == 0) return DEFAULT_TIME_OUT; time_t cur = time(NULL); time_t expireTime = Head_->ExpireTime; if(cur >= expireTime) { return DEFAULT_TIME_OUT; } return expireTime - cur; }
22222a43bad75b0774ea3ea1b70eaab70a59dc5f
0848c444881c3c8cf499db42db5a9b7778800229
/src/board.h
dcbe477cf5b49b0191754418c7a722b237691bc2
[]
no_license
fffasttime/Reversi-bwcore
f0c63df10ef5e900bb7b8da5df3ab2f80edf30ab
d43e6b283fe456d76ea22e2c26b0f3123d3efb4a
refs/heads/master
2022-05-28T03:32:24.564822
2022-03-09T05:11:18
2022-03-09T05:11:18
101,889,159
10
1
null
2022-03-09T05:11:19
2017-08-30T14:07:51
C++
UTF-8
C++
false
false
4,411
h
#pragma once #include "util.h" #include <string> #include <algorithm> /* bitmove: UL U UR >>9 >>8 >>7 L . R => >>1 . <<1 DL D DR <<7 <<8 <<9 */ class Board{ public: u64 b[2]; Board(){} Board(u64 _0, u64 _1):b{_0,_1}{} void setStart(){b[0]=0x810000000,b[1]=0x1008000000;} bool operator==(const Board &v) const{return b[0]==v.b[0] && b[1]==v.b[1];} std::string repr() const; #ifndef ONLINE std::string str(bool fcol=0) const; #endif //ONLINE template<int col=0> u64 genmove() const{ // This part of code is brought from Zebra & stdrick cu64 b_cur = b[col], b_opp = b[!col]; u64 b_opp_inner = b_opp & 0x7E7E7E7E7E7E7E7Eu; u64 moves = 0; u64 b_flip, b_opp_adj; #define GENMOVE(arrow, d, opp) \ b_flip = (b_cur arrow d) & opp; \ b_flip |= (b_flip arrow d) & opp; \ b_opp_adj = opp & (opp arrow d); \ b_flip |= (b_flip arrow (d+d)) & b_opp_adj; \ b_flip |= (b_flip arrow (d+d)) & b_opp_adj; \ moves |= b_flip arrow d GENMOVE(>>, 1, b_opp_inner); GENMOVE(<<, 1, b_opp_inner); GENMOVE(>>, 8, b_opp); GENMOVE(<<, 8, b_opp); GENMOVE(>>, 7, b_opp_inner); GENMOVE(<<, 7, b_opp_inner); GENMOVE(>>, 9, b_opp_inner); GENMOVE(<<, 9, b_opp_inner); #undef GENMOVE return moves & ~(b_cur | b_opp); } bool testmove(int p) const{return bget(genmove(),p);} template<int col=0> bool makemove(int p){ using namespace bitptn; u64 &b_cur = b[col]; u64 &b_opp = b[!col]; u64 b_flip, b_opp_adj, flips = 0; u64 b_opp_inner = b_opp & 0x7E7E7E7E7E7E7E7Eu; #define GENMOVE(arrow, d, opp) \ b_flip = ((1ull<<p) arrow d) & opp; \ b_flip |= (b_flip arrow d) & opp; \ b_opp_adj = opp & (opp arrow d); \ b_flip |= (b_flip arrow (d+d)) & b_opp_adj; \ b_flip |= (b_flip arrow (d+d)) & b_opp_adj; \ if((b_flip arrow d) & b_cur) flips |= b_flip GENMOVE(>>, 1, b_opp_inner); GENMOVE(<<, 1, b_opp_inner); GENMOVE(>>, 8, b_opp); GENMOVE(<<, 8, b_opp); GENMOVE(>>, 7, b_opp_inner); GENMOVE(<<, 7, b_opp_inner); GENMOVE(>>, 9, b_opp_inner); GENMOVE(<<, 9, b_opp_inner); #undef GENMOVE if(flips) b_cur^=flips, b_opp^=flips, bts(b_cur, p); return flips; } // prefix c_ swap color // suffix _r return a new borad bool cmakemove(int p){cswap();return makemove<1>(p);} Board makemove_r(int p) const{Board r=*this;r.makemove(p);return r;} Board cmakemove_r(int p) const{Board r(b[1],b[0]);r.makemove<1>(p);return r;} int cnt0() const{return popcnt(b[0]);} int cnt1() const{return popcnt(b[1]);} u64 hash() const{return ((b[0]*19260817)^b[1])%998244353;} Board cswap_r() const{return Board(b[1],b[0]);} void cswap(){std::swap(b[0],b[1]);} void flip_h(){::flip_h(b[0]);::flip_h(b[1]);} void flip_v(){::flip_v(b[0]);::flip_v(b[1]);} void rotate_l(){::rotate_l(b[0]);::rotate_l(b[1]);} void rotate_r(){::rotate_r(b[0]);::rotate_r(b[1]);} u64 emptys() const{return ~(b[0]|b[1]);} u64 occupys() const{return b[0]|b[1];} int operator[](int p) const{return 2-2*bget(b[0], p)-bget(b[1], p);} }; typedef const Board &CBoard; class Game{ public: #ifndef ONLINE std::string str() const; void savesgf(std::string filename); Board& board_begin(){return step?board_before[0]:board;} #endif //ONLINE std::string repr() const; Board board; Board board_before[60]; int col_before[60], move_before[60]; int step,col; Game(){ step=col=0; board.setStart(); } bool testmove(int p){return p>=0 && p<64 && board.testmove(p);} void makemove(int p, bool autopass=1){ assertprintf(p>=0 && p<64, "invalid move at %d\n", p); assertprintf(board.testmove(p),"invalid move at %d\n", p); assertprintf(step<60, "makemove unbelievably outbound\n"); col_before[step]=col; board_before[step]=board; move_before[step]=p; step++; board.cmakemove(p); col=!col; if (autopass && !hasmove()) col=!col, board.cswap(); } void unmakemove(){ assertprintf(step>=0, "unmakemove outbound\n"); --step; board=board_before[step]; col=col_before[step]; } void reset(){ step=0, col=0; board.setStart(); } bool isend(){return !hasmove();} int cnt(int _col) const{return popcnt(board.b[col^_col]);} int winner() const{ if (cnt(PBLACK)>cnt(PWHITE)) return PBLACK; else if (cnt(PBLACK)<cnt(PWHITE)) return PWHITE; return 2; } u64 genmove() const{return board.genmove();} bool hasmove() const{return board.genmove();} int operator[](int p) const{ assertprintf(p>=0 && p<64, "invalid pos call at [%d]\n", p); return board[p]; } };
7625c3b5404b9083cdf76d3b978991fbde2afd81
3d30dd522b32cc44eebb4f74a91e5be37bc1d23e
/src/asm.cpp
bdac5c9e223fdb5dbbc10ed067cb5e72f151c1d9
[]
no_license
bibekdahal/Zero-X-
b6846d8bfa7f4d54572c903230171d9bd3fc675e
9278310f299d75597a1edc311d800cb8c1b901e5
refs/heads/master
2021-01-10T14:15:11.210332
2015-12-25T07:05:51
2015-12-25T07:05:51
48,567,709
0
0
null
null
null
null
UTF-8
C++
false
false
39
cpp
#include "stdinc.h" #include "asm.h"
9c9be52bfbeb8ce44c426f382d4629a042d6faad
fb1ba7899d85f4ef9b6bd8c59663fed6cdbc673f
/src/sstream
714be717e5071b8a7de2f36036ad1e1ceefbbc0b
[ "Apache-2.0" ]
permissive
AnotherSuperIntensiveMinecraftPlayer/ATACS
cc9e534c6b8c97f809be0717e3149c9dbf0913ec
d6eeec63fbc53794f0376592e7357ad08a7dddd1
refs/heads/master
2023-05-13T03:30:30.199530
2020-06-06T20:10:53
2020-06-06T20:10:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,467
/* This is part of libio/iostream, providing -*- C++ -*- input/output. Copyright (C) 2000 Free Software Foundation This file is part of the GNU IO Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this library; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, if you link this library with files compiled with a GNU compiler to produce an executable, this does not cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. */ /* Written by Magnus Fromreide ([email protected]). */ #ifndef __SSTREAM__ #define __SSTREAM__ #include <string> #include <iostream.h> #include <streambuf.h> namespace std { class stringbuf : public streambuf { public: typedef char char_type; typedef int int_type; typedef streampos pos_type; typedef streamoff off_type; explicit stringbuf(int which=ios::in|ios::out) : streambuf(which), buf(), mode(static_cast<ios::open_mode>(which)), rpos(0), bufsize(1) { } explicit stringbuf(const std::string &s, int which=ios::in|ios::out) : streambuf(which), buf(s), mode(static_cast<ios::open_mode>(which)), bufsize(1) { if(mode & ios::in) { setg(&defbuf, &defbuf + bufsize, &defbuf + bufsize); } if(mode & ios::out) { setp(&defbuf, &defbuf + bufsize); } rpos = (mode & ios::ate ? s.size() : 0); } std::string str() const { const_cast<stringbuf*>(this)->sync(); // Sigh, really ugly hack return buf; }; void str(const std::string& s) { buf = s; if(mode & ios::in) { gbump(egptr() - gptr()); } if(mode & ios::out) { pbump(pbase() - pptr()); } rpos = (mode & ios::ate ? s.size() : 0); } protected: inline virtual int sync(); inline virtual int overflow(int = EOF); inline virtual int underflow(); private: std::string buf; ios::open_mode mode; std::string::size_type rpos; streamsize bufsize; char defbuf; }; class stringstreambase : virtual public ios { protected: stringbuf __my_sb; public: std::string str() const { return dynamic_cast<stringbuf*>(_strbuf)->str(); } void str(const std::string& s) { clear(); dynamic_cast<stringbuf*>(_strbuf)->str(s); } stringbuf* rdbuf() { return &__my_sb; } protected: stringstreambase(int which) : __my_sb(which) { init (&__my_sb); } stringstreambase(const std::string& s, int which) : __my_sb(s, which) { init (&__my_sb); } }; class istringstream : public stringstreambase, public istream { public: istringstream(int which=ios::in) : stringstreambase(which) { } istringstream(const std::string& s, int which=ios::in) : stringstreambase(s, which) { } }; class ostringstream : public stringstreambase, public ostream { public: ostringstream(int which=ios::out) : stringstreambase(which) { } ostringstream(const std::string& s, int which=ios::out) : stringstreambase(s, which) { } }; class stringstream : public stringstreambase, public iostream { public: stringstream(int which=ios::in|ios::out) : stringstreambase(which) { } stringstream(const std::string &s, int which=ios::in|ios::out) : stringstreambase(s, which) { } }; } inline int std::stringbuf::sync() { if((mode & ios::out) == 0) return EOF; streamsize n = pptr() - pbase(); if(n) { buf.replace(rpos, std::string::npos, pbase(), n); if(buf.size() - rpos != n) return EOF; rpos += n; pbump(-n); gbump(egptr() - gptr()); } return 0; } inline int std::stringbuf::overflow(int ch) { if((mode & ios::out) == 0) return EOF; streamsize n = pptr() - pbase(); if(n && sync()) return EOF; if(ch != EOF) { std::string::size_type oldSize = buf.size(); buf.replace(rpos, std::string::npos, ch); if(buf.size() - oldSize != 1) return EOF; ++rpos; } return 0; } inline int std::stringbuf::underflow() { sync(); if((mode & ios::in) == 0) { return EOF; } if(rpos >= buf.size()) { return EOF; } std::string::size_type n = egptr() - eback(); std::string::size_type s; s = buf.copy(eback(), n, rpos); pbump(pbase() - pptr()); gbump(eback() - gptr()); int res = (0377 & buf[rpos]); rpos += s; return res; } #endif /* not __STRSTREAM__ */
0479adb1dc6c662524cc972185ee8c3cbcc9c130
e3e0c4e9842ad2912f74a815c6793211630f95fd
/scheduler.h
0f33f54b3197532229d8eff7d90a837323a1b3a7
[]
no_license
johnalexiv/Project3
c03ecb494e1c6841e30198b210439d9999b849dc
2b7ea115721fd7388b05ad7e9bffdfa7edc79133
refs/heads/master
2021-03-30T16:56:43.156925
2017-10-14T05:40:33
2017-10-14T05:40:33
106,150,823
0
0
null
null
null
null
UTF-8
C++
false
false
2,308
h
// // scheduler.h // Project3 // // Created by John Alexander on 10/5/17. // Copyright © 2017 John Alexander. All rights reserved. // #ifndef _SCHEDULER_H #define _SCHEDULER_H #include <iostream> #include <iomanip> #include <queue> #include <vector> #include <string> #include "process.h" #include "queuetypes.h" class Scheduler { public: Scheduler(std::vector<Process> processes); ~Scheduler(); void runProcesses(); void printStatistics(); private: void initializeScheduler(std::vector<Process>); Process startTop(); void startPop(); void startPush(Process); bool isStartEmpty(); Process activeTop(); void activePop(); void activePush(Process); bool isActiveEmpty(); Process expiredTop(); void expiredPop(); void expiredPush(Process); bool isExpiredEmpty(); Process ioTop(); void ioPop(); void ioPush(Process); bool isIoEmpty(); Process finishedTop(); void finishedPop(); void finishedPush(Process); bool isFinishedEmpty(); Process cpuTop(); void cpuPop(); void cpuPush(Process); bool isCpuEmpty(); int getClock(); void resetClock(); void incrementClock(); void checkProcessFinishedCpu(); void checkProcessesFinishedIO(); void checkArrivingProcesses(); void checkPreemptRequired(); void assignLowestPriorityProcessToCpu(); void decrementIoBursts(); void updateCpuBurstAndTimeSlice(); bool allQueuesEmpty(); void swapQueuesIfRequired(); void swapActiveAndExpiredQueues(); void printMessage(int, int); void printMessage(int, Process, int); void printMessage(int, Process, Process, int); void printProcessStatistics(Process); void printAverages(std::vector<Process>); double round(double); private: StartQueue * _startQueue; ActiveExpiredQueue * _activeQueue; ActiveExpiredQueue * _expiredQueue; IOQueue * _ioQueue; FinishedQueue * _finishedQueue; CPU * _cpu; int _clock; enum PrintOption { TO_ACTIVE, TO_CPU, PREEMPT, FINISHED, TO_IO, TO_EXPIRED, IO_TO_EXPIRED, IO_TO_ACTIVE, SWAPPED }; }; #endif // _SCHEDULER_H
5ed5152464225c3b49a1f753ceb86c81a13294dd
d084c3bf832051b3efd45e28065db5c21b795165
/commons/common/applications/ranvar.h
0aca72745818ed9643169b5c04bdbb6a61b89b92
[ "CC0-1.0" ]
permissive
zhou-yukun/rocc
5fec792a4b228dde0ad1457d336d155787d38a70
d4fae7dee35869dded24985221beb218e4ce81e0
refs/heads/main
2023-02-20T22:40:35.142878
2021-01-26T17:35:49
2021-01-26T17:35:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,486
h
#ifndef __ranvar_h #define __ranvar_h #include <random> #include <sys/time.h> namespace commons { #define INTER_DISCRETE 0 // no interpolation (discrete) #define INTER_CONTINUOUS 1 // linear interpolation #define INTER_INTEGRAL 2 // linear interpolation and round up struct CDFentry { double cdf_; double val_; }; class EmpiricalRandomVariable { public: virtual double value(); virtual double interpolate(double u, double x1, double y1, double x2, double y2); virtual double avg(); EmpiricalRandomVariable(int interp, int seed); ~EmpiricalRandomVariable(); double& minCDF() { return minCDF_; } double& maxCDF() { return maxCDF_; } int loadCDF(const char* filename); protected: int lookup(double u); double minCDF_; // min value of the CDF (default to 0) double maxCDF_; // max value of the CDF (default to 1) int interpolation_; // how to interpolate data (INTER_DISCRETE...) int numEntry_; // number of entries in the CDF table int maxEntry_; // size of the CDF table (mem allocation) CDFentry* table_; // CDF table of (val_, cdf_) std::uniform_real_distribution<double> uni; std::ranlux48_base gen; }; //class ExponentialRandomVariable { // public: // virtual double value(); // ExponentialRandomVariable(double, int); // virtual inline double avg() { return avg_; }; // void setavg(double d) { avg_ = d; }; // private: // double avg_; // std::tr1::exponential_distribution<double> exponential; // std::tr1::ranlux64_base_01 gen; //}; } #endif
ec8f9ba05017402a9609b799469fb6e39ae265ea
924049378ea1e986b5b2f09c7c99ee5577b4675e
/src/swifttx.cpp
85dba166bad945767cca39c7d9d95efbda0dde07
[ "MIT" ]
permissive
wincash/WincashGold
06bc94246b23d1931076067b2b8ef509d2fb6541
ff5935c021acde8b78d10cff7dce2fcfadc3518a
refs/heads/master
2022-11-22T00:45:47.164233
2020-07-20T22:20:57
2020-07-20T22:20:57
271,636,521
1
0
null
null
null
null
UTF-8
C++
false
false
20,182
cpp
// Copyright (c) 2014-2016 The Dash developers // Copyright (c) 2016-2019 The WINCASHGOLD developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "swifttx.h" #include "activemasternode.h" #include "base58.h" #include "key.h" #include "masternodeman.h" #include "net.h" #include "obfuscation.h" #include "protocol.h" #include "spork.h" #include "sync.h" #include "util.h" #include "validationinterface.h" #include <boost/foreach.hpp> std::map<uint256, CTransaction> mapTxLockReq; std::map<uint256, CTransaction> mapTxLockReqRejected; std::map<uint256, CConsensusVote> mapTxLockVote; std::map<uint256, CTransactionLock> mapTxLocks; std::map<COutPoint, uint256> mapLockedInputs; std::map<uint256, int64_t> mapUnknownVotes; //track votes with no tx for DOS int nCompleteTXLocks; //txlock - Locks transaction // //step 1.) Broadcast intention to lock transaction inputs, "txlreg", CTransaction //step 2.) Top SWIFTTX_SIGNATURES_TOTAL masternodes, open connect to top 1 masternode. // Send "txvote", CTransaction, Signature, Approve //step 3.) Top 1 masternode, waits for SWIFTTX_SIGNATURES_REQUIRED messages. Upon success, sends "txlock' void ProcessMessageSwiftTX(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) { if (fLiteMode) return; //disable all obfuscation/masternode related functionality if (!IsSporkActive(SPORK_2_SWIFTTX)) return; if (!masternodeSync.IsBlockchainSynced()) return; if (strCommand == "ix") { //LogPrintf("ProcessMessageSwiftTX::ix\n"); CDataStream vMsg(vRecv); CTransaction tx; vRecv >> tx; CInv inv(MSG_TXLOCK_REQUEST, tx.GetHash()); pfrom->AddInventoryKnown(inv); GetMainSignals().Inventory(inv.hash); if (mapTxLockReq.count(tx.GetHash()) || mapTxLockReqRejected.count(tx.GetHash())) { return; } if (!IsIXTXValid(tx)) { return; } for (const CTxOut &o : tx.vout) { // IX supports normal scripts and unspendable scripts (used in DS collateral and Budget collateral). // TODO: Look into other script types that are normal and can be included if (!o.scriptPubKey.IsNormalPaymentScript() && !o.scriptPubKey.IsUnspendable()) { LogPrintf("ProcessMessageSwiftTX::ix - Invalid Script %s\n", tx.ToString().c_str()); return; } } int nBlockHeight = CreateNewLock(tx); bool fMissingInputs = false; CValidationState state; bool fAccepted = false; { LOCK(cs_main); fAccepted = AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs); } if (fAccepted) { RelayInv(inv); DoConsensusVote(tx, nBlockHeight); mapTxLockReq.insert(std::make_pair(tx.GetHash(), tx)); LogPrintf("ProcessMessageSwiftTX::ix - Transaction Lock Request: %s %s : accepted %s\n", pfrom->addr.ToString().c_str(), pfrom->cleanSubVer.c_str(), tx.GetHash().ToString().c_str()); if (GetTransactionLockSignatures(tx.GetHash()) == SWIFTTX_SIGNATURES_REQUIRED) { GetMainSignals().NotifyTransactionLock(tx); } return; } else { mapTxLockReqRejected.insert(std::make_pair(tx.GetHash(), tx)); // can we get the conflicting transaction as proof? LogPrintf("ProcessMessageSwiftTX::ix - Transaction Lock Request: %s %s : rejected %s\n", pfrom->addr.ToString().c_str(), pfrom->cleanSubVer.c_str(), tx.GetHash().ToString().c_str()); for (const CTxIn& in : tx.vin) { if (!mapLockedInputs.count(in.prevout)) { mapLockedInputs.insert(std::make_pair(in.prevout, tx.GetHash())); } } // resolve conflicts std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(tx.GetHash()); if (i != mapTxLocks.end()) { //we only care if we have a complete tx lock if ((*i).second.CountSignatures() >= SWIFTTX_SIGNATURES_REQUIRED) { if (!CheckForConflictingLocks(tx)) { LogPrintf("ProcessMessageSwiftTX::ix - Found Existing Complete IX Lock\n"); //reprocess the last 15 blocks ReprocessBlocks(15); mapTxLockReq.insert(std::make_pair(tx.GetHash(), tx)); } } } return; } } else if (strCommand == "txlvote") // SwiftX Lock Consensus Votes { CConsensusVote ctx; vRecv >> ctx; CInv inv(MSG_TXLOCK_VOTE, ctx.GetHash()); pfrom->AddInventoryKnown(inv); if (mapTxLockVote.count(ctx.GetHash())) { return; } mapTxLockVote.insert(std::make_pair(ctx.GetHash(), ctx)); if (ProcessConsensusVote(pfrom, ctx)) { //Spam/Dos protection /* Masternodes will sometimes propagate votes before the transaction is known to the client. This tracks those messages and allows it at the same rate of the rest of the network, if a peer violates it, it will simply be ignored */ if (!mapTxLockReq.count(ctx.txHash) && !mapTxLockReqRejected.count(ctx.txHash)) { if (!mapUnknownVotes.count(ctx.vinMasternode.prevout.hash)) { mapUnknownVotes[ctx.vinMasternode.prevout.hash] = GetTime() + (60 * 10); } if (mapUnknownVotes[ctx.vinMasternode.prevout.hash] > GetTime() && mapUnknownVotes[ctx.vinMasternode.prevout.hash] - GetAverageVoteTime() > 60 * 10) { LogPrintf("ProcessMessageSwiftTX::ix - masternode is spamming transaction votes: %s %s\n", ctx.vinMasternode.ToString().c_str(), ctx.txHash.ToString().c_str()); return; } else { mapUnknownVotes[ctx.vinMasternode.prevout.hash] = GetTime() + (60 * 10); } } RelayInv(inv); } if (mapTxLockReq.count(ctx.txHash) && GetTransactionLockSignatures(ctx.txHash) == SWIFTTX_SIGNATURES_REQUIRED) { GetMainSignals().NotifyTransactionLock(mapTxLockReq[ctx.txHash]); } return; } } bool IsIXTXValid(const CTransaction& txCollateral) { if (txCollateral.vout.size() < 1) return false; if (txCollateral.nLockTime != 0) return false; CAmount nValueIn = 0; CAmount nValueOut = 0; bool missingTx = false; for (const CTxOut &o : txCollateral.vout) nValueOut += o.nValue; for (const CTxIn &i : txCollateral.vin) { CTransaction tx2; uint256 hash; if (GetTransaction(i.prevout.hash, tx2, hash, true)) { if (tx2.vout.size() > i.prevout.n) { nValueIn += tx2.vout[i.prevout.n].nValue; } } else { missingTx = true; } } if (nValueOut > GetSporkValue(SPORK_5_MAX_VALUE) * COIN) { LogPrint("swiftx", "IsIXTXValid - Transaction value too high - %s\n", txCollateral.ToString().c_str()); return false; } if (missingTx) { LogPrint("swiftx", "IsIXTXValid - Unknown inputs in IX transaction - %s\n", txCollateral.ToString().c_str()); /* This happens sometimes for an unknown reason, so we'll return that it's a valid transaction. If someone submits an invalid transaction it will be rejected by the network anyway and this isn't very common, but we don't want to block IX just because the client can't figure out the fee. */ return true; } if (nValueIn - nValueOut < COIN * 0.01) { LogPrint("swiftx", "IsIXTXValid - did not include enough fees in transaction %d\n%s\n", nValueOut - nValueIn, txCollateral.ToString().c_str()); return false; } return true; } int64_t CreateNewLock(CTransaction tx) { int64_t nTxAge = 0; BOOST_REVERSE_FOREACH (CTxIn i, tx.vin) { nTxAge = GetInputAge(i); if (nTxAge < 5) //1 less than the "send IX" gui requires, incase of a block propagating the network at the time { LogPrintf("CreateNewLock - Transaction not found / too new: %d / %s\n", nTxAge, tx.GetHash().ToString().c_str()); return 0; } } /* Use a blockheight newer than the input. This prevents attackers from using transaction mallibility to predict which masternodes they'll use. */ int nBlockHeight = (chainActive.Tip()->nHeight - nTxAge) + 4; if (!mapTxLocks.count(tx.GetHash())) { LogPrintf("CreateNewLock - New Transaction Lock %s !\n", tx.GetHash().ToString().c_str()); CTransactionLock newLock; newLock.nBlockHeight = nBlockHeight; newLock.nExpiration = GetTime() + (60 * 60); //locks expire after 60 minutes (24 confirmations) newLock.nTimeout = GetTime() + (60 * 5); newLock.txHash = tx.GetHash(); mapTxLocks.insert(std::make_pair(tx.GetHash(), newLock)); } else { mapTxLocks[tx.GetHash()].nBlockHeight = nBlockHeight; LogPrint("swiftx", "CreateNewLock - Transaction Lock Exists %s !\n", tx.GetHash().ToString().c_str()); } return nBlockHeight; } // check if we need to vote on this transaction void DoConsensusVote(CTransaction& tx, int64_t nBlockHeight) { if (!fMasterNode) return; int n = mnodeman.GetMasternodeRank(activeMasternode.vin, nBlockHeight, MIN_SWIFTTX_PROTO_VERSION); if (n == -1) { LogPrint("swiftx", "SwiftX::DoConsensusVote - Unknown Masternode\n"); return; } if (n > SWIFTTX_SIGNATURES_TOTAL) { LogPrint("swiftx", "SwiftX::DoConsensusVote - Masternode not in the top %d (%d)\n", SWIFTTX_SIGNATURES_TOTAL, n); return; } /* nBlockHeight calculated from the transaction is the authoritive source */ LogPrint("swiftx", "SwiftX::DoConsensusVote - In the top %d (%d)\n", SWIFTTX_SIGNATURES_TOTAL, n); CConsensusVote ctx; ctx.vinMasternode = activeMasternode.vin; ctx.txHash = tx.GetHash(); ctx.nBlockHeight = nBlockHeight; if (!ctx.Sign()) { LogPrintf("SwiftX::DoConsensusVote - Failed to sign consensus vote\n"); return; } if (!ctx.SignatureValid()) { LogPrintf("SwiftX::DoConsensusVote - Signature invalid\n"); return; } mapTxLockVote[ctx.GetHash()] = ctx; CInv inv(MSG_TXLOCK_VOTE, ctx.GetHash()); RelayInv(inv); } //received a consensus vote bool ProcessConsensusVote(CNode* pnode, CConsensusVote& ctx) { int n = mnodeman.GetMasternodeRank(ctx.vinMasternode, ctx.nBlockHeight, MIN_SWIFTTX_PROTO_VERSION); CMasternode* pmn = mnodeman.Find(ctx.vinMasternode); if (pmn != NULL) LogPrint("swiftx", "SwiftX::ProcessConsensusVote - Masternode ADDR %s %d\n", pmn->addr.ToString().c_str(), n); if (n == -1) { //can be caused by past versions trying to vote with an invalid protocol LogPrint("swiftx", "SwiftX::ProcessConsensusVote - Unknown Masternode\n"); mnodeman.AskForMN(pnode, ctx.vinMasternode); return false; } if (n > SWIFTTX_SIGNATURES_TOTAL) { LogPrint("swiftx", "SwiftX::ProcessConsensusVote - Masternode not in the top %d (%d) - %s\n", SWIFTTX_SIGNATURES_TOTAL, n, ctx.GetHash().ToString().c_str()); return false; } if (!ctx.SignatureValid()) { LogPrintf("SwiftX::ProcessConsensusVote - Signature invalid\n"); // don't ban, it could just be a non-synced masternode mnodeman.AskForMN(pnode, ctx.vinMasternode); return false; } if (!mapTxLocks.count(ctx.txHash)) { LogPrintf("SwiftX::ProcessConsensusVote - New Transaction Lock %s !\n", ctx.txHash.ToString().c_str()); CTransactionLock newLock; newLock.nBlockHeight = 0; newLock.nExpiration = GetTime() + (60 * 60); newLock.nTimeout = GetTime() + (60 * 5); newLock.txHash = ctx.txHash; mapTxLocks.insert(std::make_pair(ctx.txHash, newLock)); } else LogPrint("swiftx", "SwiftX::ProcessConsensusVote - Transaction Lock Exists %s !\n", ctx.txHash.ToString().c_str()); //compile consessus vote std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(ctx.txHash); if (i != mapTxLocks.end()) { (*i).second.AddSignature(ctx); #ifdef ENABLE_WALLET if (pwalletMain) { //when we get back signatures, we'll count them as requests. Otherwise the client will think it didn't propagate. if (pwalletMain->mapRequestCount.count(ctx.txHash)) pwalletMain->mapRequestCount[ctx.txHash]++; } #endif LogPrint("swiftx", "SwiftX::ProcessConsensusVote - Transaction Lock Votes %d - %s !\n", (*i).second.CountSignatures(), ctx.GetHash().ToString().c_str()); if ((*i).second.CountSignatures() >= SWIFTTX_SIGNATURES_REQUIRED) { LogPrint("swiftx", "SwiftX::ProcessConsensusVote - Transaction Lock Is Complete %s !\n", (*i).second.GetHash().ToString().c_str()); CTransaction& tx = mapTxLockReq[ctx.txHash]; if (!CheckForConflictingLocks(tx)) { #ifdef ENABLE_WALLET if (pwalletMain) { if (pwalletMain->UpdatedTransaction((*i).second.txHash)) { nCompleteTXLocks++; } } #endif if (mapTxLockReq.count(ctx.txHash)) { for (const CTxIn& in : tx.vin) { if (!mapLockedInputs.count(in.prevout)) { mapLockedInputs.insert(std::make_pair(in.prevout, ctx.txHash)); } } } // resolve conflicts //if this tx lock was rejected, we need to remove the conflicting blocks if (mapTxLockReqRejected.count((*i).second.txHash)) { //reprocess the last 15 blocks ReprocessBlocks(15); } } } return true; } return false; } bool CheckForConflictingLocks(CTransaction& tx) { /* It's possible (very unlikely though) to get 2 conflicting transaction locks approved by the network. In that case, they will cancel each other out. Blocks could have been rejected during this time, which is OK. After they cancel out, the client will rescan the blocks and find they're acceptable and then take the chain with the most work. */ for (const CTxIn& in : tx.vin) { if (mapLockedInputs.count(in.prevout)) { if (mapLockedInputs[in.prevout] != tx.GetHash()) { LogPrintf("SwiftX::CheckForConflictingLocks - found two complete conflicting locks - removing both. %s %s", tx.GetHash().ToString().c_str(), mapLockedInputs[in.prevout].ToString().c_str()); if (mapTxLocks.count(tx.GetHash())) mapTxLocks[tx.GetHash()].nExpiration = GetTime(); if (mapTxLocks.count(mapLockedInputs[in.prevout])) mapTxLocks[mapLockedInputs[in.prevout]].nExpiration = GetTime(); return true; } } } return false; } int64_t GetAverageVoteTime() { std::map<uint256, int64_t>::iterator it = mapUnknownVotes.begin(); int64_t total = 0; int64_t count = 0; while (it != mapUnknownVotes.end()) { total += it->second; count++; it++; } return total / count; } void CleanTransactionLocksList() { if (chainActive.Tip() == NULL) return; std::map<uint256, CTransactionLock>::iterator it = mapTxLocks.begin(); while (it != mapTxLocks.end()) { if (GetTime() > it->second.nExpiration) { //keep them for an hour LogPrintf("Removing old transaction lock %s\n", it->second.txHash.ToString().c_str()); if (mapTxLockReq.count(it->second.txHash)) { CTransaction& tx = mapTxLockReq[it->second.txHash]; for (const CTxIn& in : tx.vin) mapLockedInputs.erase(in.prevout); mapTxLockReq.erase(it->second.txHash); mapTxLockReqRejected.erase(it->second.txHash); for (CConsensusVote& v : it->second.vecConsensusVotes) mapTxLockVote.erase(v.GetHash()); } mapTxLocks.erase(it++); } else { it++; } } } int GetTransactionLockSignatures(uint256 txHash) { if(fLargeWorkForkFound || fLargeWorkInvalidChainFound) return -2; if (!IsSporkActive(SPORK_2_SWIFTTX)) return -1; std::map<uint256, CTransactionLock>::iterator it = mapTxLocks.find(txHash); if(it != mapTxLocks.end()) return it->second.CountSignatures(); return -1; } uint256 CConsensusVote::GetHash() const { return vinMasternode.prevout.hash + vinMasternode.prevout.n + txHash; } bool CConsensusVote::SignatureValid() { std::string errorMessage; std::string strMessage = txHash.ToString().c_str() + std::to_string(nBlockHeight); //LogPrintf("verify strMessage %s \n", strMessage.c_str()); CMasternode* pmn = mnodeman.Find(vinMasternode); if (pmn == NULL) { LogPrintf("SwiftX::CConsensusVote::SignatureValid() - Unknown Masternode\n"); return false; } if (!obfuScationSigner.VerifyMessage(pmn->pubKeyMasternode, vchMasterNodeSignature, strMessage, errorMessage)) { LogPrintf("SwiftX::CConsensusVote::SignatureValid() - Verify message failed\n"); return false; } return true; } bool CConsensusVote::Sign() { std::string errorMessage; CKey key2; CPubKey pubkey2; std::string strMessage = txHash.ToString().c_str() + std::to_string(nBlockHeight); //LogPrintf("signing strMessage %s \n", strMessage.c_str()); //LogPrintf("signing privkey %s \n", strMasterNodePrivKey.c_str()); if (!obfuScationSigner.SetKey(strMasterNodePrivKey, errorMessage, key2, pubkey2)) { LogPrintf("CConsensusVote::Sign() - ERROR: Invalid masternodeprivkey: '%s'\n", errorMessage.c_str()); return false; } if (!obfuScationSigner.SignMessage(strMessage, errorMessage, vchMasterNodeSignature, key2)) { LogPrintf("CConsensusVote::Sign() - Sign message failed"); return false; } if (!obfuScationSigner.VerifyMessage(pubkey2, vchMasterNodeSignature, strMessage, errorMessage)) { LogPrintf("CConsensusVote::Sign() - Verify message failed"); return false; } return true; } bool CTransactionLock::SignaturesValid() { for (CConsensusVote vote : vecConsensusVotes) { int n = mnodeman.GetMasternodeRank(vote.vinMasternode, vote.nBlockHeight, MIN_SWIFTTX_PROTO_VERSION); if (n == -1) { LogPrintf("CTransactionLock::SignaturesValid() - Unknown Masternode\n"); return false; } if (n > SWIFTTX_SIGNATURES_TOTAL) { LogPrintf("CTransactionLock::SignaturesValid() - Masternode not in the top %s\n", SWIFTTX_SIGNATURES_TOTAL); return false; } if (!vote.SignatureValid()) { LogPrintf("CTransactionLock::SignaturesValid() - Signature not valid\n"); return false; } } return true; } void CTransactionLock::AddSignature(CConsensusVote& cv) { vecConsensusVotes.push_back(cv); } int CTransactionLock::CountSignatures() { /* Only count signatures where the BlockHeight matches the transaction's blockheight. The votes have no proof it's the correct blockheight */ if (nBlockHeight == 0) return -1; int n = 0; for (CConsensusVote v : vecConsensusVotes) { if (v.nBlockHeight == nBlockHeight) { n++; } } return n; }
8896157daf5aff80356188eb68af038f3dc2df9d
1f24fe23bdc4ebfe7e588d5e962e16ec9fc99327
/FourSumCount/main.cpp
787bd67c490e13e96d7ac3984b9834efc2e6d0dc
[]
no_license
AotY/Play_Interview
40a9efd3dbe9e16a2490ed98d1277df941efd6e7
868029e3cb195ccf254ab964eb73224719e38230
refs/heads/master
2020-03-22T11:05:48.926563
2018-10-14T07:37:51
2018-10-14T07:37:51
139,946,339
6
0
null
null
null
null
UTF-8
C++
false
false
1,833
cpp
/* * main.cpp * Copyright (C) 2018 LeonTao <[email protected]> * * Distributed under terms of the MIT license. */ /* #include "main.h" */ #include <iostream> #include <vector> #include <string> #include <set> #include <map> using namespace std; // memory search class Solution { private: map<pair<int, int>, int> memo; int searchSum(vector<vector<int>> &matrix, int index, int curSum, int m, int n) { if (index >= m) { return (int) curSum == 0; } // search in memory pair<int, int> key = make_pair(index, curSum); if (memo.find(key) != memo.end()){ return memo[key]; } int res = 0; for (int i = 0; i < n; i++) { res += searchSum(matrix, index + 1, curSum + matrix[index][i], m, n); } // keep in memory memo.insert(make_pair(key, res)); return res; } public: int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) { int n = A.size(); if (n == 0) return 0; // n^4 ? timeout vector<vector<int>> matrix; matrix.push_back(A); matrix.push_back(B); matrix.push_back(C); matrix.push_back(D); int m = 4; int curSum = 0; int index = 0; int res = searchSum(matrix, index, curSum, m, n); return res; } }; int main() { Solution s; vector<int> A = {1, 2}; vector<int> B = {-2, -1}; vector<int> C = {-1, 2}; vector<int> D = {0, 2}; int res = s.fourSumCount(A, B, C, D); cout << res << endl; return 0; }
4039b24c2a0de4b5821f7224443acb282f4d54a4
a7606c8002a84aa5e7cce9b0446b242386316b82
/shapes/triangles/flatuvmeshtriangle.h
94af5c4660416989ba31c25480aa2a9356b3a44a
[]
no_license
cache-tlb/rt-from-the-ground-up
5fdcfadccb686c65a6be43c6e165786471e8a4a1
2784799e5124bc8bc09e673d65e5b8bf8f149758
refs/heads/master
2016-09-11T09:37:44.312899
2012-10-12T16:04:36
2012-10-12T16:04:36
32,261,877
1
0
null
null
null
null
UTF-8
C++
false
false
645
h
#ifndef FLATUVMESHTRIANGLE_H #define FLATUVMESHTRIANGLE_H /* by L.B. */ #include "flatmeshtriangle.h" class FlatUVMeshTriangle : public FlatMeshTriangle { public: FlatUVMeshTriangle(void); FlatUVMeshTriangle(Mesh* _meshPtr, const int i0, const int i1, const int i2); virtual FlatUVMeshTriangle* clone(void) const; FlatUVMeshTriangle(const FlatUVMeshTriangle& fmt); virtual ~FlatUVMeshTriangle(void); FlatUVMeshTriangle& operator= (const FlatUVMeshTriangle& rhs); virtual bool hit(const Ray &ray, double &tmin, ShadeRec &sr) const; }; #endif // FLATUVMESHTRIANGLE_H
[ "[email protected]@66790ea4-9dcb-8dae-10e5-9860326c6d77" ]
[email protected]@66790ea4-9dcb-8dae-10e5-9860326c6d77
eb9326d324afa7bab26cf3e20915a7cda050042d
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
/Engine/Source/ThirdParty/PhysX/PhysX_3.4/Source/LowLevelParticles/src/PtSpatialLocalHash.cpp
32e94bc998f955b9db50d18c8397c4919cc66544
[ "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
6,600
cpp
// This code contains NVIDIA Confidential Information and is disclosed to you // under a form of NVIDIA software license agreement provided separately to you. // // Notice // NVIDIA Corporation and its licensors retain all intellectual property and // proprietary rights in and to this software and related documentation and // any modifications thereto. Any use, reproduction, disclosure, or // distribution of this software and related documentation without an express // license agreement from NVIDIA Corporation is strictly prohibited. // // ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES // NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO // THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, // MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. // // Information and code furnished is believed to be accurate and reliable. // However, NVIDIA Corporation assumes no responsibility for the consequences of use of such // information or for any infringement of patents or other rights of third parties that may // result from its use. No license is granted by implication or otherwise under any patent // or patent rights of NVIDIA Corporation. Details are subject to change without notice. // This code supersedes and replaces all information previously supplied. // NVIDIA Corporation products are not authorized for use as critical // components in life support devices or systems without express written approval of // NVIDIA Corporation. // // Copyright (c) 2008-2017 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "PtSpatialHashHelper.h" #if PX_USE_PARTICLE_SYSTEM_API #include "PtSpatialHash.h" #include "PtParticle.h" #include "PsUtilities.h" /*! Builds local hash and reorders particle index table. */ void physx::Pt::SpatialHash::buildLocalHash(const Particle* particles, PxU32 numParticles, ParticleCell* cells, PxU32* particleIndices, PxU16* hashKeyArray, PxU32 numHashBuckets, PxF32 cellSizeInv, const PxVec3& packetCorner) { PX_ASSERT(particles); PX_ASSERT(cells); PX_ASSERT(particleIndices); PX_ASSERT(numHashBuckets > numParticles); // Needs to be larger to have at least one empty hash bucket (required to // detect invalid cells). // Mark packet cell entries as empty. for(PxU32 c = 0; c < numHashBuckets; c++) cells[c].numParticles = PX_INVALID_U32; PX_ALIGN(16, Particle fakeParticle); fakeParticle.position = PxVec3(FLT_MAX, FLT_MAX, FLT_MAX); PxU32 numParticles4 = ((numParticles + 3) & ~0x3) + 4; // ceil up to multiple of four + 4 for save unrolling // Add particles to cell hash const Particle* prt0 = particles; const Particle* prt1 = (1 < numParticles) ? particles + 1 : &fakeParticle; const Particle* prt2 = (2 < numParticles) ? particles + 2 : &fakeParticle; const Particle* prt3 = (3 < numParticles) ? particles + 3 : &fakeParticle; struct Int32Vec3 { PX_FORCE_INLINE void set(const PxVec3& realVec, const PxF32 scale) { x = static_cast<PxI32>(Ps::floor(realVec.x * scale)); y = static_cast<PxI32>(Ps::floor(realVec.y * scale)); z = static_cast<PxI32>(Ps::floor(realVec.z * scale)); } PxI32 x; PxI32 y; PxI32 z; }; PX_ALIGN(16, Int32Vec3 cellCoords[8]); cellCoords[0].set(prt0->position - packetCorner, cellSizeInv); cellCoords[1].set(prt1->position - packetCorner, cellSizeInv); cellCoords[2].set(prt2->position - packetCorner, cellSizeInv); cellCoords[3].set(prt3->position - packetCorner, cellSizeInv); for(PxU32 p = 0; p < numParticles4; p += 4) { const Particle* prt0_N = (p + 4 < numParticles) ? particles + p + 4 : &fakeParticle; const Particle* prt1_N = (p + 5 < numParticles) ? particles + p + 5 : &fakeParticle; const Particle* prt2_N = (p + 6 < numParticles) ? particles + p + 6 : &fakeParticle; const Particle* prt3_N = (p + 7 < numParticles) ? particles + p + 7 : &fakeParticle; PxU32 wIndex = (p + 4) & 7; cellCoords[wIndex].set(prt0_N->position - packetCorner, cellSizeInv); cellCoords[wIndex + 1].set(prt1_N->position - packetCorner, cellSizeInv); cellCoords[wIndex + 2].set(prt2_N->position - packetCorner, cellSizeInv); cellCoords[wIndex + 3].set(prt3_N->position - packetCorner, cellSizeInv); PxU32 rIndex = p & 7; for(PxU32 i = 0; i < 4; ++i) { if(p + i < numParticles) { const Int32Vec3& int32Vec3 = cellCoords[rIndex + i]; const GridCellVector cellCoord(PxI16(int32Vec3.x), PxI16(int32Vec3.y), PxI16(int32Vec3.z)); PxU32 hashKey = getCellIndex(cellCoord, cells, numHashBuckets); PX_ASSERT(hashKey < PT_PARTICLE_SYSTEM_HASH_KEY_LIMIT); ParticleCell* cell = &cells[hashKey]; hashKeyArray[p + i] = Ps::to16(hashKey); PX_ASSERT(cell); if(cell->numParticles == PX_INVALID_U32) { // Entry is empty -> Initialize new entry cell->coords = cellCoord; cell->numParticles = 1; // this avoids some LHS } else { cell->numParticles++; // this avoids some LHS } PX_ASSERT(cell->numParticles != PX_INVALID_U32); } } } // Set for each cell the starting index of the associated particle index interval. PxU32 cellFirstParticle = 0; for(PxU32 c = 0; c < numHashBuckets; c++) { ParticleCell& cell = cells[c]; if(cell.numParticles == PX_INVALID_U32) continue; cell.firstParticle = cellFirstParticle; cellFirstParticle += cell.numParticles; } reorderParticleIndicesToCells(particles, numParticles, cells, particleIndices, numHashBuckets, hashKeyArray); } /*! Reorders particle indices to cells. */ void physx::Pt::SpatialHash::reorderParticleIndicesToCells(const Particle* /*particles*/, PxU32 numParticles, ParticleCell* cells, PxU32* particleIndices, PxU32 numHashBuckets, PxU16* hashKeyArray) { for(PxU32 c = 0; c < numHashBuckets; c++) { ParticleCell& cell = cells[c]; if(cell.numParticles == PX_INVALID_U32) continue; cell.numParticles = 0; } // Reorder particle indices according to cells for(PxU32 p = 0; p < numParticles; p++) { // Get cell for fluid ParticleCell* cell; cell = &cells[hashKeyArray[p]]; PX_ASSERT(cell); PX_ASSERT(cell->numParticles != PX_INVALID_U32); particleIndices[cell->firstParticle + cell->numParticles] = p; cell->numParticles++; } } #endif // PX_USE_PARTICLE_SYSTEM_API
7420bbf65366592c4b8570b3963ce28b132b3095
5d8cfc9825f84fa9cb7110b09adce4eaf8ffd52e
/multiboost/src/src/IO/OutputInfo.h
5564fcd6bb61919e59269acd1a45cc5af33f6f5a
[]
no_license
junjiek/cmu-exp
efa1535c2415b99627afb91bbd873e207f6380bc
14e01603a9e1679bd3b43e4b627e6a55f5a42504
refs/heads/master
2021-01-25T08:37:16.206435
2015-08-15T19:45:29
2015-08-15T19:45:29
38,571,325
1
0
null
null
null
null
UTF-8
C++
false
false
41,384
h
/* * * MultiBoost - Multi-purpose boosting package * * Copyright (C) AppStat group * Laboratoire de l'Accelerateur Lineaire * Universite Paris-Sud, 11, CNRS * * This file is part of the MultiBoost library * * This library is free software; you can redistribute it * and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, 5th Floor, Boston, MA 02110-1301 USA * * Contact: [email protected] * * For more information and up-to-date version, please visit * * http://www.multiboost.org/ * */ /** * \file OutputInfo.h Outputs the step-by-step information. */ #ifndef __OUTPUT_INFO_H #define __OUTPUT_INFO_H #include <fstream> #include <string> #include <vector> #include <map> #include "IO/InputData.h" #include "Defaults.h" //for the default output using namespace std; namespace MultiBoost { // forward declaration to avoid an include class BaseLearner; class BaseOutputInfoType; /** * A table representing the votes for each example. * Example: * \verbatim Ex_1: Class 0, Class 1, Class 2, .. , Class k Ex_2: Class 0, Class 1, Class 2, .. , Class k .. Ex_n: Class 0, Class 1, Class 2, .. , Class k \endverbatim * \date 16/11/2005 */ typedef vector< vector<AlphaReal> > table; typedef map<string, BaseOutputInfoType*>::iterator OutInfIt; // template<typename T> // struct SpecificInfo // { // typedef map<string, vector<T> > Type; // }; ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// /** * Format and output step-by-step information. * With this class it is possible to output and update * the error rates, margins and the edge. * These function must be called at each iteration with the * newly found weak hypothesis, but \b before the update of the * weights. * \warning Don't forget to begin the list of information * printed with outputIteration(), and close it with * a call to endLine()! * \date 16/11/2005 */ class OutputInfo { public: /** * The constructor. Create the object and open the output file. * \param args The arguments passed through command line * \param clArg The command line argument that gives the output file name * \date 17/06/2011 */ explicit OutputInfo(const nor_utils::Args& args, bool customUpdate = false, const string & clArg = "outputinfo"); /** * Forces the choice of the output information * \param list The list of the output names (eg. err, auc etc.) * \param append If true, "list" is added to the other outputs, otherwise, it * replace them. * \date 04/07/2011 */ void setOutputList(const string& list, const nor_utils::Args* args = NULL); /** * Just output the iteration number. * \param t The iteration number. * \date 14/11/2005 */ void outputIteration(int t); void initialize(InputData* pData); /** * Just output the current time. * \param * \date 14/11/2005 */ void outputCurrentTime( void ); /** * Output the column names * Note that this method must be called after the * initialization of all the datasets * \param namemap The structure that holds the class information * \date 04/08/2006 */ void outputHeader(const NameMap& namemap, bool outputIterations = true, bool outputTime = true, bool endline = true); /** * Just return the sum of alphas * \param pData pointer of the input data * \date 04/04/2012 */ AlphaReal getSumOfAlphas( InputData* pData ) { return _alphaSums[pData]; } /** * Output the information the user wants * This "wish-list" is specified either through * the command line or directly through the constructor * \param pData The input data. * \param pWeakHypothesis The current weak hypothesis. * \date 17/06/2011 */ void outputCustom(InputData* pData, BaseLearner* pWeakHypothesis = 0); /** * End of line in the file stream. * Call it when all the needed information has been outputted. * \date 16/11/2005 */ void endLine() { _outStream << endl; } void headerEndLine() { _headerOutStream << endl; } /** * Separator in the file stream. * \date 20/06/2011 */ void separator() { _outStream << OUTPUT_SEPARATOR << OUTPUT_SEPARATOR; } void outputUserData( float data ) { _outStream << data; } void outputUserHeader( const string& h ) { _headerOutStream << h << OUTPUT_SEPARATOR; } table& getTable( InputData* pData ) { table& g = _gTableMap[pData]; return g; } void setTable( InputData* pData, table& tmpTable ) { table& g = _gTableMap[pData]; // in case the dimensions are different const int newDimension = (int)tmpTable.size(); const int numClasses = pData->getNumClasses(); const int oldDimension = (int)g.size(); g.resize(newDimension); for (int i = oldDimension; i < newDimension; ++i) { g[i].resize(numClasses, 0.); } for( int i=0; i<g.size(); i++ ) copy( tmpTable[i].begin(), tmpTable[i].end(), g[i].begin() ); } table& getMargins( InputData* pData ) { table& g = _margins[pData]; return g; } /* * Updates the G and Margin tables and alphaSums vector * \date 17/06/2011 */ void updateTables(InputData* pData, BaseLearner* pWeakHypothesis); /** * Calls the updateSpecificInfo method for each OutputInfoType subclass. * The subclasses that implement this method must check whether the update is targetted to them or not * through the prefix of the param type. * \param type The name of the info to be updated, it is highly recommanded to prefix this name by an abreviation of the class name. * \param value The value to be added/updated * \date 05/07/2011 */ // void updateSpecificInfo(const string& type, AlphaReal value); BaseOutputInfoType* getOutputInfoObject(const string& type); /** * Return the specific metric output for a given * dataset and a given iteration. * If the iteration is -1, it returns the last value. * \param pData The dataset on which the metric was computed. * \param outputName The three caracters code of the output (the same as for --outputinfo argument). * \param iteration The iteration at which the metric was computed. * \date 05/04/2013 */ AlphaReal getOutputHistory(InputData *pData, const string& outputName, int iteration = -1); /** * Indicate whether a given Output information * is activated. * \param outputName The three caracters code of the output (the same as for --outputinfo argument). * \date 05/04/2013 */ bool outputIsActivated(const string& outputName); void setStartingIteration(unsigned int i) {_historyStartingIteration = i;} protected: fstream _outStream; //!< The output stream time_t _beginingTime; time_t _timeBias; // TODO: refactoring : replace the general // map<InputData*, table> _gTableMap // by // map<InputData*, table*> whithin BaseOutputInfoType subclasses // so that they can sharing tables through pointers. /** * Maps the data to its g(x) table. * It is needed to keep this information saved from iteration to * iteration. * \see table * \see outputError() * \date 16/11/2005 */ map<InputData*, table> _gTableMap; /** * Maps the data to the margins table. * It is needed to keep this information saved from iteration to * iteration. * \see table * \see outputMargins() * \date 16/11/2005 */ map<InputData*, table> _margins; /** * Maps the data to the sum of the alpha. * It is needed to keep this information saved from iteration to * iteration. * \see outputMargins() * \date 16/11/2005 */ map<InputData*, AlphaReal> _alphaSums; //double getROC( vector< pair< int, AlphaReal > > data ); /* * Keeps the list of the output types the user wants to be output * \date 17/06/2011 */ map<string, BaseOutputInfoType*> _outputList; /** * Creates the OutputInfoType instances * from a string * \date 04/07/2011 */ void getOutputListFromString(const string& list, const nor_utils::Args* args = NULL); /* * Indicates whether we systematically update the internal structures after each * call of outputCustom(). Set to true if the learner wants to manage them itself. * \date 04/07/2011 */ bool _customTablesUpdate; /** * The header output stream */ fstream _headerOutStream; unsigned int _historyStartingIteration; //to handle fastResume case }; ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// /** * The type of optimization required for the outputinfo : maximizing, minimizing or unknown */ enum OUTPUTINFO_OPTIMIZATION { UNKNOWN = 0, MIN, MAX }; /** * The elementary output information. For the most basic one is OuputErrorInfo. * This class is a factory, it creates the different outputs the user specifies * in the command line. So adding a new type of output only necessitate to * inherit from this class, implement the pure virtual methods and to update * the creation method (see further). * Please note that the subclasses can use the information on the posteriors * and the margin that OutputInfo handle and they __dont__ need to update them. * Moreover, they can implement specific structures which they will responsible to update. * * \date 17/06/2011 */ class BaseOutputInfoType { protected: map<InputData*, vector<AlphaReal> > _outputHistory; public: BaseOutputInfoType() {}; BaseOutputInfoType(const nor_utils::Args& args) {}; /* Compute the output it is specialized in and print it. * \param outStream The stream where the output is directed to * \param pData The input data. * \param pWeakHypothesis The current weak hypothesis. * \see table * \see _gTableMap * \see _alphaSums * \date 17/06/2011 */ virtual void computeAndOutput(ostream& outStream, InputData* pData, map<InputData*, table>& gTableMap, map<InputData*, table>& marginsTableMap, map<InputData*, AlphaReal>& alphaSums, BaseLearner* pWeakHypothesis = 0) = 0; /** * Print the header * \param outStream The stream where the output is directed to * \param namemap The structure that contains the class information ( \see NameMap ) * \date 17/06/2011 */ virtual void outputHeader(ostream& outStream, const NameMap& namemap) = 0; /** * Print a detailed description of the output. * \param outStream The stream where the output is directed to * \date 12/12/2012 */ virtual void outputDescription(ostream& outStream) {}; /* * The creation method of the factory */ static BaseOutputInfoType* createOutput(string type, const nor_utils::Args* args = NULL); // /** // * For specific cases (like cascades), the output info needs to keep extra information. // * This method updates the internal structure _specificInfo. It is left very generic on purpose. // * \param type The name of the info to be updated, it is highly recommanded to prefix this name by an abreviation of the class name. // * \param value The value to be added/updated // * \date 05/07/2011 // */ // virtual void updateSpecificInfo(const string& type, AlphaReal value) = 0; AlphaReal getOutputHistory(InputData *pData, int iteration) { return iteration < 0 ? _outputHistory[pData].back() : _outputHistory[pData].at(iteration); } /* * The type of optimization we are looking for the outputinfo (minimizing, maximizing or unknown) */ virtual OUTPUTINFO_OPTIMIZATION getOptimType() { return UNKNOWN; } }; // template<class T = AlphaReal> // class OutputInfoType : public BaseOutputInfoType { // public: // /** // * For specific cases (like cascades), the output info needs to keep extra information. // * This method updates the internal structure _specificInfo. It is left very generic on purpose. // * \param type The name of the info to be updated, it is highly recommanded to prefix this name by an abreviation of the class name. // * \param value The value to be added/updated // * \date 05/07/2011 // */ // virtual void updateSpecificInfo(const string& type, AlphaReal value) {} // // protected: // // typename SpecificInfo<T>::Type _specificInfo; // // }; ////////////////////////////////////////////////////////////////////////////////////////////// //Subclasses for the factory ////////////////////////////////////////////////////////////////////////////////////////////// /** * The default error output * Outputs the error of the given data. * The error is computed by holding the information on the previous * weak hypotheses. In AdaBoost, the discriminant function is computed with the formula * \f[ * {\bf g}(x) = \sum_{t=1}^T \alpha^{(t)} {\bf h}^{(t)}(x), * \f] * we therefore update the \f${\bf g}(x)\f$ vector (for each example) * each time this method is called: * \f[ * {\bf g} = {\bf g} + \alpha^{(t)} {\bf h}^{(t)}(x). * \f] * \remark There can be any number of data to have the gTable. Each one is * mapped into a map that uses the pointer of the data as key. * \date 17/06/2011 */ class RestrictedZeroOneError : public BaseOutputInfoType { public: void outputHeader(ostream& outStream, const NameMap& namemap) { outStream << "r01" ;} ////////////////////////////////////////////////////////////////////////////////////////////// void outputDescription(ostream& outStream) { outStream << "r01: Restricted Zero-One Error (error = min positive class score < max negative class score)";} ; ////////////////////////////////////////////////////////////////////////////////////////////// void computeAndOutput(ostream& outStream, InputData* pData, map<InputData*, table>& gTableMap, map<InputData*, table>& marginsTableMap, map<InputData*, AlphaReal>& alphaSums, BaseLearner* pWeakHypothesis = 0); OUTPUTINFO_OPTIMIZATION getOptimType() { return MIN; } }; ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// /** * The 0-1 error. * \date 19/07/2011 */ class ZeroOneErrorOutput : public BaseOutputInfoType { public: void outputHeader(ostream& outStream, const NameMap& namemap) { outStream << "e01" ;} ////////////////////////////////////////////////////////////////////////////////////////////// void outputDescription(ostream& outStream) { outStream << "e01: Zero-One Error (error = max positive class score < max negative class score)";} ; ////////////////////////////////////////////////////////////////////////////////////////////// void computeAndOutput(ostream& outStream, InputData* pData, map<InputData*, table>& gTableMap, map<InputData*, table>& marginsTableMap, map<InputData*, AlphaReal>& alphaSums, BaseLearner* pWeakHypothesis = 0); OUTPUTINFO_OPTIMIZATION getOptimType() { return MIN; } }; ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// /** * The weighted 0-1 error. * \date 19/07/2011 */ class WeightedZeroOneErrorOutput : public BaseOutputInfoType { public: void outputHeader(ostream& outStream, const NameMap& namemap) { outStream << "w01" ;} ////////////////////////////////////////////////////////////////////////////////////////////// void outputDescription(ostream& outStream) { outStream << "w01: Weighted Zero-One Error (error = max positive class score < max negative class score)";} ; ////////////////////////////////////////////////////////////////////////////////////////////// void computeAndOutput(ostream& outStream, InputData* pData, map<InputData*, table>& gTableMap, map<InputData*, table>& marginsTableMap, map<InputData*, AlphaReal>& alphaSums, BaseLearner* pWeakHypothesis = 0); OUTPUTINFO_OPTIMIZATION getOptimType() { return MIN; } }; ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// /** * The hamming error. * \date 19/07/2011 */ class HammingErrorOutput : public BaseOutputInfoType { public: void outputHeader(ostream& outStream, const NameMap& namemap) { outStream << "ham" ;} ////////////////////////////////////////////////////////////////////////////////////////////// void outputDescription(ostream& outStream) { outStream << "ham: Hamming Error";} ; ////////////////////////////////////////////////////////////////////////////////////////////// void computeAndOutput(ostream& outStream, InputData* pData, map<InputData*, table>& gTableMap, map<InputData*, table>& marginsTableMap, map<InputData*, AlphaReal>& alphaSums, BaseLearner* pWeakHypothesis = 0); OUTPUTINFO_OPTIMIZATION getOptimType() { return MIN; } }; ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// /** * The weighted hamming error. * \date 19/07/2011 */ class WeightedHammingErrorOutput : public BaseOutputInfoType { public: void outputHeader(ostream& outStream, const NameMap& namemap) { outStream << "wha" ;} ////////////////////////////////////////////////////////////////////////////////////////////// void outputDescription(ostream& outStream) { outStream << "wha: Weighted Hamming Error";} ; ////////////////////////////////////////////////////////////////////////////////////////////// void computeAndOutput(ostream& outStream, InputData* pData, map<InputData*, table>& gTableMap, map<InputData*, table>& marginsTableMap, map<InputData*, AlphaReal>& alphaSums, BaseLearner* pWeakHypothesis = 0); OUTPUTINFO_OPTIMIZATION getOptimType() { return MIN; } }; ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// /** * The weighted (restricted) error * \date 20/06/2011 */ class WeightedErrorOutput : public BaseOutputInfoType { public: void outputHeader(ostream& outStream, const NameMap& namemap) { outStream << "werr" ;} ////////////////////////////////////////////////////////////////////////////////////////////// void outputDescription(ostream& outStream) { outStream << "werr: Weighted Restricted Error (error = min positive class score < max negative class score)";} ; ////////////////////////////////////////////////////////////////////////////////////////////// void computeAndOutput(ostream& outStream, InputData* pData, map<InputData*, table>& gTableMap, map<InputData*, table>& marginsTableMap, map<InputData*, AlphaReal>& alphaSums, BaseLearner* pWeakHypothesis = 0); }; ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// /** * The balanced error * \ref http://www.kddcup-orange.com/evaluation.php * \date 20/06/2011 */ class BalancedErrorOutput : public BaseOutputInfoType { public: void outputHeader(ostream& outStream, const NameMap& namemap) { outStream << "balerr" ; const int numClasses = namemap.getNumNames(); for (int i = 0; i < numClasses; ++i ) { outStream << OUTPUT_SEPARATOR << "balerr[" << namemap.getNameFromIdx(i) << "]" ;} } ////////////////////////////////////////////////////////////////////////////////////////////// void outputDescription(ostream& outStream) { outStream << "balerr: Balanced Error (see http://www.kddcup-orange.com/evaluation.php)";} ; ////////////////////////////////////////////////////////////////////////////////////////////// void computeAndOutput(ostream& outStream, InputData* pData, map<InputData*, table>& gTableMap, map<InputData*, table>& marginsTableMap, map<InputData*, AlphaReal>& alphaSums, BaseLearner* pWeakHypothesis = 0); }; ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// // TODO: lack of documentation below (especially, comment how the output is computed) /** * MAE * \date 20/06/2011 */ class MAEOuput : public BaseOutputInfoType { public: void outputHeader(ostream& outStream, const NameMap& namemap) { outStream << "mae" << OUTPUT_SEPARATOR << HEADER_FIELD_LENGTH << "mse";} ////////////////////////////////////////////////////////////////////////////////////////////// void outputDescription(ostream& outStream) { outStream << "mae: MAE Error";} ; ////////////////////////////////////////////////////////////////////////////////////////////// void computeAndOutput(ostream& outStream, InputData* pData, map<InputData*, table>& gTableMap, map<InputData*, table>& marginsTableMap, map<InputData*, AlphaReal>& alphaSums, BaseLearner* pWeakHypothesis = 0); }; ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// /** * Output the minimum margin the sum of below zero margins. * These two elements are useful for an analysis of the training process. * * The margins are represent the per-class weighted correct rate, that is * \f[ * \rho_{i, \ell} = \sum_{t=1}^T \alpha^{(t)} h_\ell^{(t)}(x_i) y_i * \f] * The \b fist \b value that this method outputs is the minimum margin, that is * \f[ * \rho_{min} = \mathop{\rm arg\, min}_{i, \ell} \rho_{i, \ell}, * \f] * which is normalized by the sum of alpha * \f[ * \frac{\rho_{min}}{\sum_{t=1}^T \alpha^{(t)}}. * \f] * This can give a useful measure of the size of the functional margin. * * The \b second \b value which this method outputs is simply the sum of the * margins below zero. * \date 20/06/2011 */ class MarginsOutput : public BaseOutputInfoType { public: void outputHeader(ostream& outStream, const NameMap& namemap) { outStream << "min_mar" ;} ////////////////////////////////////////////////////////////////////////////////////////////// void outputDescription(ostream& outStream) { outStream << "min_mar: Minimum Margin";} ; ////////////////////////////////////////////////////////////////////////////////////////////// void computeAndOutput(ostream& outStream, InputData* pData, map<InputData*, table>& gTableMap, map<InputData*, table>& marginsTableMap, map<InputData*, AlphaReal>& alphaSums, BaseLearner* pWeakHypothesis = 0); }; ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// /** * Output the edge. It is the measure of the accuracy of the current * weak hypothesis relative to random guessing, and is defined as * \f[ * \gamma = \sum_{i=1}^n \sum_{\ell=1}^k w_{i, \ell}^{(t)} h_\ell^{(t)}(x_i) * \f] * \date 20/06/2011 */ class EdgeOutput : public BaseOutputInfoType { public: void outputHeader(ostream& outStream, const NameMap& namemap) { outStream << "edge" ;} ////////////////////////////////////////////////////////////////////////////////////////////// // void outputDescription(ostream& outStream) { outStream << "edge: Edge";} ; ////////////////////////////////////////////////////////////////////////////////////////////// void computeAndOutput(ostream& outStream, InputData* pData, map<InputData*, table>& gTableMap, map<InputData*, table>& marginsTableMap, map<InputData*, AlphaReal>& alphaSums, BaseLearner* pWeakHypothesis = 0); }; ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// /** * The Area Under the ROC curve * (see \link http://sites.google.com/a/lesoliveira.net/luiz-eduardo-s-oliveira/Reconhecimento-de-Padr%C3%B5es--SS-/Artigos/ROCintro.pdf ) * \date 20/06/2011 */ class AUCOutput : public BaseOutputInfoType { public: void outputHeader(ostream& outStream, const NameMap& namemap) { outStream << "auc" ; const int numClasses = namemap.getNumNames(); for (int i = 0; i < numClasses; ++i ) { outStream << OUTPUT_SEPARATOR << "auc[" << namemap.getNameFromIdx(i) << "]" ;} } ////////////////////////////////////////////////////////////////////////////////////////////// void outputDescription(ostream& outStream) { outStream << "auc: Area Under The ROC Curve";} ; ////////////////////////////////////////////////////////////////////////////////////////////// void computeAndOutput(ostream& outStream, InputData* pData, map<InputData*, table>& gTableMap, map<InputData*, table>& marginsTableMap, map<InputData*, AlphaReal>& alphaSums, BaseLearner* pWeakHypothesis = 0); OUTPUTINFO_OPTIMIZATION getOptimType() { return MAX; } }; ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// /** * True positive and False positive rates (ROC curve coodinates) * (see \link http://sites.google.com/a/lesoliveira.net/luiz-eduardo-s-oliveira/Reconhecimento-de-Padr%C3%B5es--SS-/Artigos/ROCintro.pdf ) * \date 20/06/2011 */ class TPRFPROutput : public BaseOutputInfoType { public: void outputHeader(ostream& outStream, const NameMap& namemap) { outStream << "tpr" ; const int numClasses = namemap.getNumNames(); for (int i = 0; i < numClasses; ++i ) { outStream << OUTPUT_SEPARATOR << "tpr[" << namemap.getNameFromIdx(i) << "]" ;} outStream << OUTPUT_SEPARATOR << "fpr" ; for (int i = 0; i < numClasses; ++i ) { outStream << OUTPUT_SEPARATOR << "fpr[" << namemap.getNameFromIdx(i) << "]" ;} } ////////////////////////////////////////////////////////////////////////////////////////////// void outputDescription(ostream& outStream) { outStream << "tpr/fpr: True and False Positive Rates";} ; ////////////////////////////////////////////////////////////////////////////////////////////// void computeAndOutput(ostream& outStream, InputData* pData, map<InputData*, table>& gTableMap, map<InputData*, table>& marginsTableMap, map<InputData*, AlphaReal>& alphaSums, BaseLearner* pWeakHypothesis = 0); }; ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// /** * Micro and Macro F score (ROC curve coodinates) * \date 20/07/2015 */ class FSCOREOutput : public BaseOutputInfoType { public: void outputHeader(ostream& outStream, const NameMap& namemap) { outStream << "micro-f" << OUTPUT_SEPARATOR << "macro-f"; } ////////////////////////////////////////////////////////////////////////////////////////////// void outputDescription(ostream& outStream) { outStream << "micro-f/macro-f: Micro and Macro F Scores";} ; ////////////////////////////////////////////////////////////////////////////////////////////// void computeAndOutput(ostream& outStream, InputData* pData, map<InputData*, table>& gTableMap, map<InputData*, table>& marginsTableMap, map<InputData*, AlphaReal>& alphaSums, BaseLearner* pWeakHypothesis = 0); }; ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// /** * SoftCascade (embedded-like) performance. * Outputs the error, auc, tpr, fpr. * The individual outputs should be refactored if needed. * \date 04/07/2011 */ class SoftCascadeOutput : public BaseOutputInfoType { protected: string _positiveLabelName; // vector<vector<AlphaReal> > _posteriors; vector<BaseLearner*> _calibratedWeakHypotheses; vector<AlphaReal> _rejectionThresholds; vector<char> _forecast; public: SoftCascadeOutput(const nor_utils::Args& args) { string _positiveLabelName; //!< The name of the positive class, to be used for some kinds of binary classification, otherwise set to "". if ( args.hasArgument("positivelabel") ) { args.getValue("positivelabel", 0, _positiveLabelName); } else { cout << "Error : Positive class name must be provided.\n"; exit(-1); } } void outputHeader(ostream& outStream, const NameMap& namemap) { outStream << "err" << OUTPUT_SEPARATOR << "auc" << OUTPUT_SEPARATOR << "fpr" << OUTPUT_SEPARATOR << "tpr" << OUTPUT_SEPARATOR << "nbeval" ; } ////////////////////////////////////////////////////////////////////////////////////////////// void outputDescription(ostream& outStream) {} ; ////////////////////////////////////////////////////////////////////////////////////////////// void computeAndOutput(ostream& outStream, InputData* pData, map<InputData*, table>& gTableMap, map<InputData*, table>& marginsTableMap, map<InputData*, AlphaReal>& alphaSums, BaseLearner* pWeakHypothesis = 0); ////////////////////////////////////////////////////////////////////////////////////////////// void appendRejectionThreshold(AlphaReal value) { _rejectionThresholds.push_back(value); } ////////////////////////////////////////////////////////////////////////////////////////////// vector<char> & getForcastVector() { return _forecast; } }; ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// /** * SoftCascade (embedded-like) performance. * Outputs the error, auc, tpr, fpr. * The individual outputs should be refactored if needed. * \date 04/07/2011 */ class VJCascadeOutput : public BaseOutputInfoType { protected: string _positiveLabelName; // vector<vector<AlphaReal> > _posteriors; vector<BaseLearner*> _currentBaseLearners; AlphaReal _rejectionThreshold; public: VJCascadeOutput(const nor_utils::Args& args) { string _positiveLabelName; //!< The name of the positive class, to be used for some kinds of binary classification, otherwise set to "". if ( args.hasArgument("positivelabel") ) { args.getValue("positivelabel", 0, _positiveLabelName); } else { cout << "Error : Positive class name must be provided.\n"; exit(-1); } } void outputHeader(ostream& outStream, const NameMap& namemap) { outStream << "err" << OUTPUT_SEPARATOR << "auc" << OUTPUT_SEPARATOR << "fpr" << OUTPUT_SEPARATOR << "tpr" << OUTPUT_SEPARATOR << "nbeval" ; } ////////////////////////////////////////////////////////////////////////////////////////////// void outputDescription(ostream& outStream) {} ; ////////////////////////////////////////////////////////////////////////////////////////////// void computeAndOutput(ostream& outStream, InputData* pData, map<InputData*, table>& gTableMap, map<InputData*, table>& marginsTableMap, map<InputData*, AlphaReal>& alphaSums, BaseLearner* pWeakHypothesis = 0); ////////////////////////////////////////////////////////////////////////////////////////////// void appendRejectionThreshold(AlphaReal value) { _rejectionThreshold = value; } ////////////////////////////////////////////////////////////////////////////////////////////// void setCurrentStageWeakLearners(vector<BaseLearner*>& vBaseLearners ) { _currentBaseLearners = vBaseLearners; } }; ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// /** * Output the predictor function (called also the posteriors). * One example per line. Only the specified class IdX (through \see updateSpecificInfo) * will be output. * \date 06/07/2011 */ class PosteriorsOutput : public BaseOutputInfoType { protected: vector<int> _classIdx; public: void outputHeader(ostream& outStream, const NameMap& namemap) {} ////////////////////////////////////////////////////////////////////////////////////////////// void outputDescription(ostream& outStream) {} ; ////////////////////////////////////////////////////////////////////////////////////////////// void computeAndOutput(ostream& outStream, InputData* pData, map<InputData*, table>& gTableMap, map<InputData*, table>& marginsTableMap, map<InputData*, AlphaReal>& alphaSums, BaseLearner* pWeakHypothesis = 0); ////////////////////////////////////////////////////////////////////////////////////////////// void addClassIndex(int value) { _classIdx.push_back(value); } }; } // end of namespace MultiBoost #endif // __OUTPUT_INFO_H
64dc4f2a9b2bdf4e71b8f25113307f1790ce8e75
0b300342e75de195d3f1c8a0dd11dd34ab8f2610
/binarno_stablo/main.cpp
84c8c580ae87c6199a3650e365a34ed1d6bbc514
[]
no_license
ap0h/Stablo
b04280d9cd261dc8a7112886cd811127b742ae57
9a77ea086b02fa3846979a939dbb3d3ea0ed96e2
refs/heads/master
2020-03-22T04:29:04.047359
2018-07-04T23:48:27
2018-07-04T23:48:27
139,501,690
0
0
null
null
null
null
UTF-8
C++
false
false
1,930
cpp
#include <iostream> #include "BStablo.h" #include "Node.h" #include "Heap.h" using namespace std; int main(int argc, char *argv[]) { BStablo stablo; stablo.insert(2); stablo.insert(3); stablo.insert(11); //stablo.insert(4); //stablo.insert(12); stablo.insert(1); //stablo.insert(15); /* stablo.insert(6); stablo.insert(4); stablo.insert(3); */ int s = 0; int lev = 0, des = 0; cout << "Broj cvorova sa 2 predaka: " << stablo.broji(s, lev, des) << endl; Node * cvor = stablo.findMaximal(); cout << "Visina stabla: " << stablo.Visina() << endl; cout << "Moment stabla: " << stablo.moment() << endl; cout << "Tezina stabla: " << stablo.tezina() << endl; cout << "====================================" << endl; BStablo* novo = stablo.mirror(); // stablo.ispisi_listove(); //cout << endl << "Broj listova koji su desna deca je: " << stablo.desna_deca() << endl; //cout << endl << "Broj listova koji su leva deca je: " << stablo.leva_deca() << endl; cout << "====================================" << endl; cout << "Maksimalni je: " << stablo.MaxValue() << endl; cout << stablo.isBalanced() << endl; //stablo.brisiListove(); //cout << "Tezina stabla: " << stablo.tezina() << endl; //stablo.LevelOrder(); Node **poc; poc = new Node*; //stablo.leftPathmax(poc); poc = stablo.nadji(); cout << "Ovo: " << stablo.Sum(1, 4) << endl; stablo.preorder(); cout << endl; // stablo.brisi_desnu_decu_listovi(); stablo.preorder(); cout << endl; cout << "====================================" << endl; cout << "ima ih: " << stablo.countGreater(5); Node ** naso = stablo.findCommonAncestor(1, 15); //cout << "desna or: " << stablo.deleteRightLeaves() << endl; //cout << "desn: " << stablo.izdesne(stablo.root); //cout << endl << "Broj listova koji su desna deca je: " << stablo.desna_deca() << endl; //cout << endl << "Broj listova koji su leva deca je: " << stablo.leva_deca() << endl; return 0; }
d55d53104b4dda8241a90fb79578c8dff60ddaac
728e6db1120cefc604cb99a67cae91d6c9a23ec1
/example/rng/src/rng_threefry.cpp
a9ae5c5d3552e434cc985c9492a41f41f543b9d5
[ "BSD-2-Clause" ]
permissive
freephys/vSMC
648f3768b99f1cafc9531ed1ad88e845c2a5a195
d4ec657242ea31120712644530a0f5a5e26fc540
refs/heads/master
2021-01-09T06:55:28.086749
2016-08-05T20:44:21
2016-08-05T20:44:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,496
cpp
//============================================================================ // vSMC/example/rng/src/rng_threefry.cpp //---------------------------------------------------------------------------- // vSMC: Scalable Monte Carlo //---------------------------------------------------------------------------- // Copyright (c) 2013-2016, Yan Zhou // 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 <vsmc/rng/threefry.hpp> #include "rng_test.hpp" int main(int argc, char **argv) { VSMC_RNG_TEST_PRE(rng_threefry); VSMC_RNG_TEST(vsmc::Threefry2x32); VSMC_RNG_TEST(vsmc::Threefry4x32); VSMC_RNG_TEST(vsmc::Threefry2x64); VSMC_RNG_TEST(vsmc::Threefry4x64); #if VSMC_HAS_SSE2 VSMC_RNG_TEST(vsmc::Threefry2x32SSE2); VSMC_RNG_TEST(vsmc::Threefry4x32SSE2); VSMC_RNG_TEST(vsmc::Threefry2x64SSE2); VSMC_RNG_TEST(vsmc::Threefry4x64SSE2); #endif #if VSMC_HAS_AVX2 VSMC_RNG_TEST(vsmc::Threefry2x32AVX2); VSMC_RNG_TEST(vsmc::Threefry4x32AVX2); VSMC_RNG_TEST(vsmc::Threefry2x64AVX2); VSMC_RNG_TEST(vsmc::Threefry4x64AVX2); #endif VSMC_RNG_TEST_POST; return 0; }
8a8d04d12c6ab12ea66884efa662af118f3f5138
0dca3325c194509a48d0c4056909175d6c29f7bc
/vod/include/alibabacloud/vod/model/SubmitAIImageJobRequest.h
15371ae6a063dbc7b6ee025710cd73d685c0537e
[ "Apache-2.0" ]
permissive
dingshiyu/aliyun-openapi-cpp-sdk
3eebd9149c2e6a2b835aba9d746ef9e6bef9ad62
4edd799a79f9b94330d5705bb0789105b6d0bb44
refs/heads/master
2023-07-31T10:11:20.446221
2021-09-26T10:08:42
2021-09-26T10:08:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,380
h
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ALIBABACLOUD_VOD_MODEL_SUBMITAIIMAGEJOBREQUEST_H_ #define ALIBABACLOUD_VOD_MODEL_SUBMITAIIMAGEJOBREQUEST_H_ #include <string> #include <vector> #include <alibabacloud/core/RpcServiceRequest.h> #include <alibabacloud/vod/VodExport.h> namespace AlibabaCloud { namespace Vod { namespace Model { class ALIBABACLOUD_VOD_EXPORT SubmitAIImageJobRequest : public RpcServiceRequest { public: SubmitAIImageJobRequest(); ~SubmitAIImageJobRequest(); std::string getResourceOwnerId()const; void setResourceOwnerId(const std::string& resourceOwnerId); std::string getAIPipelineId()const; void setAIPipelineId(const std::string& aIPipelineId); std::string getAccessKeyId()const; void setAccessKeyId(const std::string& accessKeyId); std::string getUserData()const; void setUserData(const std::string& userData); std::string getResourceOwnerAccount()const; void setResourceOwnerAccount(const std::string& resourceOwnerAccount); std::string getOwnerAccount()const; void setOwnerAccount(const std::string& ownerAccount); std::string getVideoId()const; void setVideoId(const std::string& videoId); std::string getAITemplateId()const; void setAITemplateId(const std::string& aITemplateId); std::string getOwnerId()const; void setOwnerId(const std::string& ownerId); private: std::string resourceOwnerId_; std::string aIPipelineId_; std::string accessKeyId_; std::string userData_; std::string resourceOwnerAccount_; std::string ownerAccount_; std::string videoId_; std::string aITemplateId_; std::string ownerId_; }; } } } #endif // !ALIBABACLOUD_VOD_MODEL_SUBMITAIIMAGEJOBREQUEST_H_
bd80fd4e688d8b105747d6e3fecc48a1fbfee585
e2ea0a550e8d35eae7da7d1591210a893004e34a
/Minemonics/src/model/universe/evolution/population/creature/phenome/morphology/limb/LimbPhysics.cpp
ce01a5fdd099807763d43e78fd794b82ef655797
[]
no_license
netzz/minemonics
cbc98cc2a33b64f3c0f5acb89328b74e22124a9f
b628eadc8f341012cd0433cb20b9c02ca1edf40b
refs/heads/master
2021-01-16T20:51:28.387476
2015-08-07T14:53:34
2015-08-07T14:53:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,662
cpp
//# corresponding header #include <model/universe/evolution/population/creature/phenome/morphology/limb/LimbPhysics.hpp> //# forward declarations //# system headers //## controller headers //## model headers //## view headers //# custom headers //## base headers //## configuration headers //## controller headers //## model headers //## view headers //## utils headers LimbPhysics::LimbPhysics() : mInWorld(false), mRestitution(0.5), mFriction(0.8), mInitialRelativeXPosition( 0), mInitialRelativeYPosition(0), mInitialRelativeZPosition(0), mInitialXOrientation( 0), mInitialYOrientation(0), mInitialZOrientation(0), mInitialWOrientation( 1), mMass(0) { } LimbPhysics::~LimbPhysics() { } bool LimbPhysics::equals(const LimbPhysics& limbPhysics) const { if (mInitialRelativeXPosition != limbPhysics.mInitialRelativeXPosition) { return false; } if (mInitialRelativeYPosition != limbPhysics.mInitialRelativeYPosition) { return false; } if (mInitialRelativeZPosition != limbPhysics.mInitialRelativeZPosition) { return false; } if (mInitialXOrientation != limbPhysics.mInitialXOrientation) { return false; } if (mInitialYOrientation != limbPhysics.mInitialYOrientation) { return false; } if (mInitialZOrientation != limbPhysics.mInitialZOrientation) { return false; } if (mInitialWOrientation != limbPhysics.mInitialWOrientation) { return false; } if (mInWorld != limbPhysics.mInWorld) { return false; } if (mRestitution != limbPhysics.mRestitution) { return false; } if (mFriction != limbPhysics.mFriction) { return false; } if (mMass != limbPhysics.mMass) { return false; } return true; }
ffcf2c4bdf1b16968982c74838bd96ba54210d1b
856fce4cdc5c01159a3864837b1a34341d324b92
/test/cpp/dist_autograd/test_dist_autograd.cpp
91bdbad3456f913396fe11702d4fb8331d6d2204
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "Apache-2.0", "BSD-2-Clause" ]
permissive
ChinmayLad/pytorch
4c04a75854b85e42855dc16c0a081b718a34a1e4
4086f7432b1172ab0bcd26d3ac1327ca081a0c5c
refs/heads/master
2020-08-04T11:20:43.326352
2019-10-01T14:12:23
2019-10-01T14:14:01
212,119,066
3
0
NOASSERTION
2019-10-01T14:35:14
2019-10-01T14:35:14
null
UTF-8
C++
false
false
2,013
cpp
#include <gtest/gtest.h> #include <ATen/ATen.h> #include <torch/csrc/distributed/autograd/utils.h> #include <torch/torch.h> TEST(DistAutogradTest, TestSendFunction) { // Initialize input tensors requiring grad. auto options = at::TensorOptions().requires_grad(true); auto in1 = torch::ones({3, 3}, options); auto in2 = torch::ones({3, 3}, options); ASSERT_FALSE(in1.grad().defined()); ASSERT_FALSE(in2.grad().defined()); // Attach the send autograd function to tensors. auto send_function = torch::distributed::autograd::addSendRpcBackward({in1, in2}); ASSERT_NE(send_function, nullptr); // Build loss and attach it as input to send autograd function. auto o1 = torch::autograd::Variable(torch::ones({3, 3})); auto edge = torch::autograd::Edge(send_function, 0); o1.set_gradient_edge(edge); auto o2 = torch::autograd::Variable(torch::ones({3, 3})); edge = torch::autograd::Edge(send_function, 1); o2.set_gradient_edge(edge); auto loss = torch::add(o1, o2); // Run backwards pass and verify gradients accumulated. auto gradient = torch::autograd::Variable(torch::rand({3, 3})); loss.backward(gradient, false, false); ASSERT_TRUE(in1.grad().defined()); ASSERT_TRUE(in2.grad().defined()); } TEST(DistAutogradTest, TestSendFunctionInvalidInputs) { auto options = at::TensorOptions().requires_grad(true); auto in1 = torch::ones({3, 3}, options); auto in2 = torch::ones({3, 3}, options); // Attach the send autograd function to tensors. auto send_function = torch::distributed::autograd::addSendRpcBackward({in1, in2}); // Build loss and attach it as input to send autograd function. auto loss = torch::autograd::Variable(torch::ones({3, 3})); loss.set_gradient_edge(torch::autograd::Edge(send_function, 1)); // This should fail since the SendRpcBackward function is looking for two // inputs and as a result encounters an undefined grad. EXPECT_THROW( loss.backward(torch::autograd::Variable(), false, false), c10::Error); }
c27239b0da047e09fcdb988989fec608bf8180b0
7d9f2017c403d1e0c4841544564b321eb55d48d0
/BackSwipeApp/app/src/main/cpp/internal/keyboardSetting/KeyboardParam.h
b0123a160cad8d0203e12a009fe18cf5570de6dc
[]
no_license
cuiwenzhe/BackSwipe
82b215f44241761e9b710d9ed3cf09a24c752157
580b5468b793944e1801f91a80afaa32a5dbc9bd
refs/heads/master
2023-08-15T11:36:57.608775
2021-10-05T18:26:13
2021-10-05T18:30:53
324,816,941
0
0
null
null
null
null
UTF-8
C++
false
false
2,652
h
// // Created by wenzhe on 4/17/20. // #ifndef SIMPLEGESTUREINPUT_KEYBOARDPARAM_H #define SIMPLEGESTUREINPUT_KEYBOARDPARAM_H #include "../base/integral_types.h" // Layout data for a single key. namespace keyboard { namespace decoder { struct Key { // Unicode codepoint for this key. This field is required. int32 codepoint = 0; // The coordinates of the center of the key. These fields are required. float x = 0; float y = 3; // The width and height of the key. These fields may be ommitted, in // which case users should fall back to the most common width and height // for the keyboard, allowing for a reduction in the size of the keyboard // layout data. float width = 0; float height = 0; void set_x(float x) { Key::x = x; } void set_y(float y) { Key::y = y; } void set_width(float width) { Key::width = width; } void set_height(float height) { Key::height = height; } void set_codepoint(int32 cp) { Key::codepoint = cp; } }; // Layout data for a keyboard. struct KeyboardLayout { // The most common width and height among keys in this layout. These // fields are required. float most_common_key_width = 1; float most_common_key_height = 2; // The dimensions of the entire keyboard. These fields are required. float keyboard_width = 3; float keyboard_height = 4; // The individual keys in this layout. std::vector<Key> keys; void clear_keys() { keys.clear(); } Key *add_keys() { keys.push_back(Key()); return &keys[keys.size() - 1]; } void set_most_common_key_width(float mostCommonKeyWidth) { most_common_key_width = mostCommonKeyWidth; } void set_most_common_key_height(float mostCommonKeyHeight) { most_common_key_height = mostCommonKeyHeight; } void set_keyboard_width(float keyboardWidth) { keyboard_width = keyboardWidth; } void set_keyboard_height(float keyboardHeight) { keyboard_height = keyboardHeight; } }; } } #endif //SIMPLEGESTUREINPUT_KEYBOARDPARAM_H
c4ab154e77eaad2ef9c7b2bc5107158a27a65c1f
ba97c2756de95190a4403fdb6b8685eb93b46afa
/unassessed/q2-soundex/soundex.cpp
07e22392d7326432aa4a232b39d968ec2145c702
[]
no_license
ben-xD/c-past-questions
b48e9aa0c32732086d9450f1d36a387c0bfa4786
eee0c9f8fb492a8d62a5bf01bb93144df349b676
refs/heads/master
2022-04-14T10:33:06.512235
2020-01-08T20:01:34
2020-01-08T20:01:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,928
cpp
#include <cctype> #include <iostream> char encode(const char character) { char words[26] = {'0','1','2','3','0','1','2','0','0','2','2','4','5','5','0','1','2','6','2','3','0','1','0','2','0','2'}; return words[toupper(character) - 65]; } void encode(const char* surname, char soundex[5]) { int soundex_pos = 0; soundex[soundex_pos++] = toupper(*surname); char previous_character = 0; while(soundex_pos < 4 && *++surname != '\0') { char temp_char = encode(*surname); if (encode(*surname) != encode(previous_character) && temp_char != '0') { soundex[soundex_pos] = temp_char; previous_character = *surname; soundex_pos++; } } while (*surname == '\0' & soundex_pos < 4) { soundex[soundex_pos++] = '0'; } } int compare(const char* one, const char* two) { if (strlen(one) == 0 && strlen(two) == 0) { return true; } if (*one != *two) { return false; } return compare(one+1, two+1); } int count(const char* const surname, const char* const sentence) { char surname_encoding[5]; encode(surname, surname_encoding); int same_encoding_count = 0; int start = 0; int end = start; while (sentence[start] != '\0') { if (!isalpha(sentence[start])) { start++; continue; } end = start; while (isalpha(sentence[end + 1])) { end++; } // get index of first non alpha char. char* first_word = new char[2+end-start]; strncpy(first_word, sentence+start, 1+end-start); first_word[1+end-start] = '\0'; char encoding[5]; encode(first_word, encoding); if (compare(surname_encoding, encoding)) { ++same_encoding_count; } delete [] first_word; start = end + 1; } return same_encoding_count; }
290cd756f926163814d75ab8311231b014619d9c
f83ef53177180ebfeb5a3e230aa29794f52ce1fc
/ACE/ACE_wrappers/TAO/tests/POA/On_Demand_Act_Direct_Coll/test_i.cpp
81d081c8b6b8b74b663ddbae451dc3be95c02fac
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-sun-iiop" ]
permissive
msrLi/portingSources
fe7528b3fd08eed4a1b41383c88ee5c09c2294ef
57d561730ab27804a3172b33807f2bffbc9e52ae
refs/heads/master
2021-07-08T01:22:29.604203
2019-07-10T13:07:06
2019-07-10T13:07:06
196,183,165
2
1
Apache-2.0
2020-10-13T14:30:53
2019-07-10T10:16:46
null
UTF-8
C++
false
false
1,109
cpp
#include "test_i.h" #include "ace/OS_NS_unistd.h" #include "ace/OS_NS_string.h" // Constructor test_i::test_i (CORBA::ORB_ptr orb, PortableServer::POA_ptr poa, ACE_thread_t thrid) : orb_ (CORBA::ORB::_duplicate (orb)) ,poa_ (PortableServer::POA::_duplicate (poa)) ,thr_id_ (thrid) { } void test_i::method (void) { } char * test_i::get_string (void) { ACE_DEBUG ((LM_DEBUG, "(%P|%t) Upcall in process ..\n")); // Use portable thread IDs ACE_Thread_ID self_ID; // Thread ID from Server ACE_Thread_ID this_ID; this_ID.id(this->thr_id_); // Servant Thread ID same as Thread ID server, so a remote call, // in case of a collocation the servant runs in calling thread (Client) if (self_ID == this_ID) { ACE_ERROR ((LM_ERROR, "(%P|%t) ERROR: A remote call has been made " " exiting ..\n")); ACE_OS::abort (); } else { ACE_DEBUG ((LM_DEBUG, "(%P|%t) OK: A collocated invocation has been made.\n")); } return CORBA::string_dup ("Hello there!"); }
17370dc02fb6bc43c7dd0461dfccf1146291ea6b
82e6375dedb79df18d5ccacd048083dae2bba383
/src/main/tests/test-symm-pair.cpp
7e1fb38e8f641b7084eba07b2b621ff55e117ce7
[]
no_license
ybouret/upsylon
0c97ac6451143323b17ed923276f3daa9a229e42
f640ae8eaf3dc3abd19b28976526fafc6a0338f4
refs/heads/master
2023-02-16T21:18:01.404133
2023-01-27T10:41:55
2023-01-27T10:41:55
138,697,127
0
0
null
null
null
null
UTF-8
C++
false
false
654
cpp
#include "y/counting/symm-pair.hpp" #include "y/utest/run.hpp" #include "y/string/convert.hpp" #include "y/type/point2d.hpp" using namespace upsylon; Y_UTEST(symm_pair) { size_t n = 10; if(argc>1) { n = string_convert::to<size_t>(argv[1],"n"); } std::cerr << n << " -> " << symm_pair::compute(n,counting::with_sz) << std::endl; symm_pair loop(n); const point2d<size_t> &vtx = *(const point2d<size_t> *) & loop.lower; for(loop.boot();loop.good();loop.next()) { std::cerr << "@" << loop.index << " : " << loop.lower << "<=" << loop.upper << " " << vtx << std::endl; } } Y_UTEST_DONE()
a49f19fd5a4e2c99366cddf465cb64a4cbb91a62
c3d6b91358067ccf8b4e3e09139d87aa0d207bbf
/src/aisdecoder.cpp
c8431d94324a5941a1a81806e0ab1335615c7ffd
[ "MIT" ]
permissive
Uetty/aisdecoder-1
684cba2d87c52d5678790ed976fa45e96c8a6e12
3c774f53b6fb00359fb9c338287712d2ea25294d
refs/heads/master
2020-03-10T11:31:37.228850
2017-02-14T05:49:33
2017-02-14T05:49:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
671
cpp
#include "aisdecoder.h" extern "C" { #include "aivdm_decode.h" // gps_device_t } #include <string.h> ais_handle_t *ais_create_handle() { ais_handle_t *handle = new ais_handle_t; memset(&handle->driver.aivdm, 0, sizeof(handle->driver.aivdm)); handle->context = new ais_handle_t::gps_context_t; return handle; } void ais_destroy_handle(ais_handle_t *handle) { delete handle; } int ais_decode(ais_handle_t *handle, const char *buf, size_t buflen, struct ais_t *ais, bool split24, int debug) { handle->context->debug = debug; return aivdm_decode(buf, buflen, handle, ais, split24, debug); }
f2a1bbd0ad061a01c3370b9908562845d60260b4
048fea369ed06d852b0457d834d3be6c4c2e8276
/win/Qt4/qt4delay.cpp
cdd5891855254703d5f46cbe08440aa61cad04aa
[]
no_license
chasonr/nethack-3.4.3-interfaces
57dc141bf6fda7f6ee795e267920d3d0a5adb607
288f341b386230ad1ca5eec13cc2c37c642dd0a9
refs/heads/master
2021-01-23T11:59:13.889353
2014-11-23T19:35:54
2014-11-23T19:35:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
748
cpp
// Copyright (c) Warwick Allison, 1999. // Qt4 conversion copyright (c) Ray Chason, 2012-2014. // NetHack may be freely redistributed. See license for details. // qt4delay.cpp -- implement a delay #include "hack.h" #undef Invisible #undef Warning #undef index #undef msleep #undef rindex #undef wizard #undef yn #include <QtGui/QtGui> #include "qt4delay.h" namespace nethack_qt4 { // RLC Can we use QTimer::single_shot for this? NetHackQtDelay::NetHackQtDelay(int ms) : msec(ms), m_timer(0), m_loop(this) { } void NetHackQtDelay::wait() { m_timer = startTimer(msec); m_loop.exec(); } void NetHackQtDelay::timerEvent(QTimerEvent* timer) { m_loop.exit(); killTimer(m_timer); m_timer = 0; } } // namespace nethack_qt4
f6db655aabb61ff4296cd1d98df97bea7e44310c
23ffbe18981c5c0573e2e7a5122795982c95de80
/codes/cityu/385.cpp
d2eec5c4fab6d334896d657d8dd800e93db9a35b
[]
no_license
KevinRSX/competitive-programming
e9b93157fef97eef35b3237b11c80c822e9dbf2e
3f5e9de948642a43c66f02ea9168fa31ab583d43
refs/heads/master
2020-04-16T11:12:38.435152
2019-11-23T07:31:27
2019-11-23T07:31:27
165,527,707
1
1
null
null
null
null
UTF-8
C++
false
false
6,407
cpp
#define EPS 1e-10 #define equals(a, b) (fabs((a) - (b)) < EPS) #include <cstdio> #include <cmath> #include <vector> #include <algorithm> #include <utility> #include <cassert> using namespace std; // definition of turning static const int COUNTER_CLOCKWISE = 1; static const int CLOCKWISE = -1; static const int ONLINE_BACK = 2; static const int ONLINE_FRONT = -2; static const int ON_SEGMENT = 0; class Point { public: double x, y; Point (double x = 0, double y = 0) : x(x), y(y) {} Point operator + (Point p) {return Point(x + p.x, y + p.y); } Point operator - (Point p) {return Point(x - p.x, y - p.y); } Point operator * (double a) {return Point(a * x, a * y); } Point operator / (double a) {return Point(x / a, y / a); } double norm() { return x * x + y * y; } double abs() { return sqrt(norm()); } bool operator < (const Point &p) const { return x != p.x ? x < p.x : y < p.y; } bool operator == (const Point &p) const { return equals(x, p.x) && equals(y, p.y); } }; typedef Point Vector; typedef vector<Point> Polygon; struct Segment { Point p1, p2; Segment() {} Segment(Point p1, Point p2) : p1(p1), p2(p2) {} Segment(double x1, double y1, double x2, double y2) { p1 = Point(x1, y1); p2 = Point(x2, y2); } }; typedef Segment Line; class Circle { public: Point c; double r; Circle(Point c = Point(), double r = 0.0) : c(c), r(r) {} }; // dot and cross product double dot(Vector a, Vector b) { return a.x * b.x + a.y * b.y; } double cross(Vector a, Vector b) { return a.x * b.y - a.y * b.x; } // orthogonality bool isOrthagonal(Vector a, Vector b) { return equals(dot(a, b), 0.0); } bool isOrthagonal(Point a1, Point a2, Point b1, Point b2) { return isOrthagonal(a1 - a2, b1 - b2); } bool isOrthagonal(Segment s1, Segment s2) { return isOrthagonal(s1.p1 - s1.p2, s2.p1 - s2.p2); } // parallelism bool isParallel(Vector a, Vector b) { return equals(cross(a, b), 0.0); } bool isParallel(Point a1, Point a2, Point b1, Point b2) { return isParallel(a1 - a2, b1 - b2); } bool isParallel(Segment s1, Segment s2) { return isParallel(s1.p1 - s1.p2, s2.p1 - s2.p2); } // projection & reflection Point project(Segment s, Point p) { Vector base = s.p2 - s.p1; double r = dot(p - s.p1, base) / base.norm(); return s.p1 + base * r; } Point reflect(Segment s, Point p) { return p + (project(s, p) - p) * 2.0; } // distance double getDistance(Point a, Point b) { return (a - b).abs(); } double getDistanceLP(Line l, Point p) { return abs(cross(l.p1 - l.p2, p - l.p1)) / (l.p2 - l.p1).abs(); } double getDistanceSP(Segment s, Point p) { if (dot(p - s.p1, s.p2 - s.p1) < 0) return getDistance(p, s.p1); if (dot(p - s.p2, s.p1 - s.p2) < 0) return getDistance(p, s.p2); return getDistanceLP(s, p); } bool intersect(Point p1, Point p2, Point p3, Point p4); bool intersect(Segment s1, Segment s2); double getDistanceSS(Segment s1, Segment s2) { if (intersect(s1, s2)) return 0.0; return min(min(getDistanceSP(s1, s2.p1), getDistanceSP(s1, s2.p2)), \ min(getDistanceSP(s2, s1.p1), getDistanceSP(s2, s1.p2))); } //ccw int ccw(Point p0, Point p1, Point p2) { Vector a = p1 - p0; Vector b = p2 - p0; if (cross(a, b) > EPS) return COUNTER_CLOCKWISE; if (cross(a, b) < -EPS) return CLOCKWISE; if (dot(a, b) < -EPS) return ONLINE_BACK; if (a.norm() < b.norm()) return ONLINE_FRONT; return ON_SEGMENT; } // intersection bool intersect(Point p1, Point p2, Point p3, Point p4) { return (ccw(p1, p2, p3) * ccw(p1, p2, p4) <= 0 && \ ccw(p3, p4, p1) * ccw(p3, p4, p2) <= 0); } bool intersect(Segment s1, Segment s2) { return intersect(s1.p1, s1.p2, s2.p1, s2.p2); } // Cross point Point getCrossPoint(Segment s1, Segment s2) { Vector base = s2.p2 - s2.p1; double d1 = abs(cross(base, s1.p1 - s2.p1)); double d2 = abs(cross(base, s1.p2 - s2.p1)); double t = d1 / (d1 + d2); return s1.p1 + (s1.p2 - s1.p1) * t; } // Cross points of a circle and a line pair<Point, Point> getCrossPoints(Circle c, Line l) { Vector pr = project(l, c.c); Vector e = (l.p2 - l.p1) / (l.p2 - l.p1).abs(); double base = sqrt(c.r * c.r - (pr - c.c).norm()); return make_pair(pr + e * base, pr - e * base); } // Cross points of two circles double arg(Vector p) { return atan2(p.y, p.x); } Vector polar(double a, double r) { return Point(cos(r) * a, sin(r) * a); } pair<Point, Point> getCrossPoints(Circle c1, Circle c2) { double d = (c1.c - c2.c).abs(); double a = acos((c1.r * c1.r + d * d - c2.r * c2.r) / (2 * c1.r * d)); double t = arg(c2.c - c1.c); return make_pair(c1.c + polar(c1.r, t + a), c1.c + polar(c1.r, t - a)); } int contains(Polygon g, Point p) { int n = g.size(); bool x = false; for (int i = 0; i < n; i++) { Point a = g[i] - p, b = g[(i + 1) % n] - p; if (abs(cross(a, b)) < EPS && dot(a, b) < EPS) return 1; if (a.y > b.y) swap(a, b); if (a.y < EPS && EPS < b.y && cross(a, b) < EPS) x = !x; } return (x ? 2 : 0); } Polygon andrewScan(Polygon s) { Polygon u, l; if (s.size() < 3) return s; sort(s.begin(), s.end()); u.push_back(s[0]); u.push_back(s[1]); l.push_back(s[s.size() - 1]); l.push_back(s[s.size() - 2]); for (int i = 2; i < s.size(); i++) { for (int n = u.size(); n >= 2 && ccw(u[n - 2], u[n - 1], s[i]) != CLOCKWISE; n--) { u.pop_back(); } u.push_back(s[i]); } for (int i = s.size() - 3; i >= 0; i--) { for (int n = l.size(); n >= 2 && ccw(l[n - 2], l[n - 1], s[i]) != CLOCKWISE; n--) { l.pop_back(); } l.push_back(s[i]); } reverse(l.begin(), l.end()); for (int i = u.size() - 2; i >= 1; i--) l.push_back(u[i]); return l; } double area(Polygon s) { double retval = 0.0; for (int i = 0; i < s.size(); i++) { Vector v1 = s[i], v2 = s[(i + 1) % s.size()]; retval += 0.5 * cross(v1, v2); } return retval >= 0 ? retval : -retval; } int main() { #ifdef DEBUG freopen("in.txt", "r", stdin); #endif int n, kase = 0; while (~scanf("%d", &n) && n) { Polygon s; double x, y; for (int i = 0; i < n; i++) { scanf("%lf%lf", &x, &y); s.push_back(Point(x, y)); } Polygon ch = andrewScan(s); double tile = area(s), container = area(ch); printf("Tile #%d\n", ++kase); printf("Wasted Space = %.2lf %%\n\n", ((container - tile) / container) * 100.0); } return 0; }
ae95f513c617d1bc605fe05efb8ec748e7201f8b
e2f4c7c33f7857dccbb3a0924db4e806641f68f8
/devel/include/xihelm_pkg/Navigate2DActionFeedback.h
630369c8da9d921d03a231b515569f827874b4f4
[]
no_license
hrabelo/rospy-learning
aaf7442934f275b3dbe7ad9e01c72dff95e24f15
b3478d411f8f26477a365805d6b7f8a1af6cd632
refs/heads/main
2023-02-15T11:14:47.010155
2021-01-10T15:47:39
2021-01-10T15:47:39
328,418,228
0
0
null
null
null
null
UTF-8
C++
false
false
9,566
h
// Generated by gencpp from file xihelm_pkg/Navigate2DActionFeedback.msg // DO NOT EDIT! #ifndef XIHELM_PKG_MESSAGE_NAVIGATE2DACTIONFEEDBACK_H #define XIHELM_PKG_MESSAGE_NAVIGATE2DACTIONFEEDBACK_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <std_msgs/Header.h> #include <actionlib_msgs/GoalStatus.h> #include <xihelm_pkg/Navigate2DFeedback.h> namespace xihelm_pkg { template <class ContainerAllocator> struct Navigate2DActionFeedback_ { typedef Navigate2DActionFeedback_<ContainerAllocator> Type; Navigate2DActionFeedback_() : header() , status() , feedback() { } Navigate2DActionFeedback_(const ContainerAllocator& _alloc) : header(_alloc) , status(_alloc) , feedback(_alloc) { (void)_alloc; } typedef ::std_msgs::Header_<ContainerAllocator> _header_type; _header_type header; typedef ::actionlib_msgs::GoalStatus_<ContainerAllocator> _status_type; _status_type status; typedef ::xihelm_pkg::Navigate2DFeedback_<ContainerAllocator> _feedback_type; _feedback_type feedback; typedef boost::shared_ptr< ::xihelm_pkg::Navigate2DActionFeedback_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::xihelm_pkg::Navigate2DActionFeedback_<ContainerAllocator> const> ConstPtr; }; // struct Navigate2DActionFeedback_ typedef ::xihelm_pkg::Navigate2DActionFeedback_<std::allocator<void> > Navigate2DActionFeedback; typedef boost::shared_ptr< ::xihelm_pkg::Navigate2DActionFeedback > Navigate2DActionFeedbackPtr; typedef boost::shared_ptr< ::xihelm_pkg::Navigate2DActionFeedback const> Navigate2DActionFeedbackConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::xihelm_pkg::Navigate2DActionFeedback_<ContainerAllocator> & v) { ros::message_operations::Printer< ::xihelm_pkg::Navigate2DActionFeedback_<ContainerAllocator> >::stream(s, "", v); return s; } template<typename ContainerAllocator1, typename ContainerAllocator2> bool operator==(const ::xihelm_pkg::Navigate2DActionFeedback_<ContainerAllocator1> & lhs, const ::xihelm_pkg::Navigate2DActionFeedback_<ContainerAllocator2> & rhs) { return lhs.header == rhs.header && lhs.status == rhs.status && lhs.feedback == rhs.feedback; } template<typename ContainerAllocator1, typename ContainerAllocator2> bool operator!=(const ::xihelm_pkg::Navigate2DActionFeedback_<ContainerAllocator1> & lhs, const ::xihelm_pkg::Navigate2DActionFeedback_<ContainerAllocator2> & rhs) { return !(lhs == rhs); } } // namespace xihelm_pkg namespace ros { namespace message_traits { template <class ContainerAllocator> struct IsMessage< ::xihelm_pkg::Navigate2DActionFeedback_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::xihelm_pkg::Navigate2DActionFeedback_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct IsFixedSize< ::xihelm_pkg::Navigate2DActionFeedback_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::xihelm_pkg::Navigate2DActionFeedback_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::xihelm_pkg::Navigate2DActionFeedback_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::xihelm_pkg::Navigate2DActionFeedback_<ContainerAllocator> const> : TrueType { }; template<class ContainerAllocator> struct MD5Sum< ::xihelm_pkg::Navigate2DActionFeedback_<ContainerAllocator> > { static const char* value() { return "64688bddd63727e7cd9b419eafcfb8df"; } static const char* value(const ::xihelm_pkg::Navigate2DActionFeedback_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x64688bddd63727e7ULL; static const uint64_t static_value2 = 0xcd9b419eafcfb8dfULL; }; template<class ContainerAllocator> struct DataType< ::xihelm_pkg::Navigate2DActionFeedback_<ContainerAllocator> > { static const char* value() { return "xihelm_pkg/Navigate2DActionFeedback"; } static const char* value(const ::xihelm_pkg::Navigate2DActionFeedback_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::xihelm_pkg::Navigate2DActionFeedback_<ContainerAllocator> > { static const char* value() { return "# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n" "\n" "Header header\n" "actionlib_msgs/GoalStatus status\n" "Navigate2DFeedback feedback\n" "\n" "================================================================================\n" "MSG: std_msgs/Header\n" "# Standard metadata for higher-level stamped data types.\n" "# This is generally used to communicate timestamped data \n" "# in a particular coordinate frame.\n" "# \n" "# sequence ID: consecutively increasing ID \n" "uint32 seq\n" "#Two-integer timestamp that is expressed as:\n" "# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n" "# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n" "# time-handling sugar is provided by the client library\n" "time stamp\n" "#Frame this data is associated with\n" "string frame_id\n" "\n" "================================================================================\n" "MSG: actionlib_msgs/GoalStatus\n" "GoalID goal_id\n" "uint8 status\n" "uint8 PENDING = 0 # The goal has yet to be processed by the action server\n" "uint8 ACTIVE = 1 # The goal is currently being processed by the action server\n" "uint8 PREEMPTED = 2 # The goal received a cancel request after it started executing\n" " # and has since completed its execution (Terminal State)\n" "uint8 SUCCEEDED = 3 # The goal was achieved successfully by the action server (Terminal State)\n" "uint8 ABORTED = 4 # The goal was aborted during execution by the action server due\n" " # to some failure (Terminal State)\n" "uint8 REJECTED = 5 # The goal was rejected by the action server without being processed,\n" " # because the goal was unattainable or invalid (Terminal State)\n" "uint8 PREEMPTING = 6 # The goal received a cancel request after it started executing\n" " # and has not yet completed execution\n" "uint8 RECALLING = 7 # The goal received a cancel request before it started executing,\n" " # but the action server has not yet confirmed that the goal is canceled\n" "uint8 RECALLED = 8 # The goal received a cancel request before it started executing\n" " # and was successfully cancelled (Terminal State)\n" "uint8 LOST = 9 # An action client can determine that a goal is LOST. This should not be\n" " # sent over the wire by an action server\n" "\n" "#Allow for the user to associate a string with GoalStatus for debugging\n" "string text\n" "\n" "\n" "================================================================================\n" "MSG: actionlib_msgs/GoalID\n" "# The stamp should store the time at which this goal was requested.\n" "# It is used by an action server when it tries to preempt all\n" "# goals that were requested before a certain time\n" "time stamp\n" "\n" "# The id provides a way to associate feedback and\n" "# result message with specific goal requests. The id\n" "# specified must be unique.\n" "string id\n" "\n" "\n" "================================================================================\n" "MSG: xihelm_pkg/Navigate2DFeedback\n" "# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n" "# Feedback\n" "float32 distance_remaining\n" "\n" ; } static const char* value(const ::xihelm_pkg::Navigate2DActionFeedback_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::xihelm_pkg::Navigate2DActionFeedback_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.header); stream.next(m.status); stream.next(m.feedback); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct Navigate2DActionFeedback_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::xihelm_pkg::Navigate2DActionFeedback_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::xihelm_pkg::Navigate2DActionFeedback_<ContainerAllocator>& v) { s << indent << "header: "; s << std::endl; Printer< ::std_msgs::Header_<ContainerAllocator> >::stream(s, indent + " ", v.header); s << indent << "status: "; s << std::endl; Printer< ::actionlib_msgs::GoalStatus_<ContainerAllocator> >::stream(s, indent + " ", v.status); s << indent << "feedback: "; s << std::endl; Printer< ::xihelm_pkg::Navigate2DFeedback_<ContainerAllocator> >::stream(s, indent + " ", v.feedback); } }; } // namespace message_operations } // namespace ros #endif // XIHELM_PKG_MESSAGE_NAVIGATE2DACTIONFEEDBACK_H
1f5955cc66c7740dfd45e650f2b8ac448e8b829a
3db63f5e3af3599923b41c79cdf5de4f8091e785
/Algorithms/Graph/Kruskal.cpp
af7d0ea745053f23ac98698662253e8c85e68164
[]
no_license
viliyani/FMI-Data-Structures-and-Algorithms
638ce9842f207a2bf8e2d210559ebc2f33da0ef6
d11033ec61abc160dc695a5539cd35d6c6aa9447
refs/heads/master
2020-08-16T16:25:44.287150
2020-03-06T16:15:50
2020-03-06T16:15:50
215,523,692
0
0
null
null
null
null
UTF-8
C++
false
false
2,907
cpp
#include <iostream> #include <vector> #include <list> #include <algorithm> using namespace std; struct Pair { int index; int weight; }; struct Edge { int from; int to; int weight; bool operator<(const Edge & rhs) const{ return weight < rhs.weight; } }; struct Node { list<Pair> neighbours; bool hasNeighbour(int index) { for (auto neighbour : neighbours) { if (index == neighbour.index) { return true; } } return false; } void addNeighbour(int index, int weight) { neighbours.push_back(Pair{index, weight}); } }; class Graph { private: vector<Node> nodes; public: Graph(int N) { nodes.resize(N); } void connect(int from, int to, int weight) { if (!nodes[from].hasNeighbour(to)) { nodes[from].addNeighbour(to, weight); } } void print() const { for (int i = 0; i < nodes.size(); i++) { cout << i << ": "; for (auto neighbour : nodes[i].neighbours) { cout << neighbour.index << "(" << neighbour.weight << "), "; } cout << "\n"; } } vector<Edge> getAllEdges() const { vector<Edge> edges; for (int from = 0; from < nodes.size(); from++) { for (auto neighbour : nodes[from].neighbours) { int to = neighbour.index; int weight = neighbour.weight; if (from < to) { edges.push_back(Edge{from, to, weight}); } } } return edges; } list<Edge> kruskal() const { if (nodes.size() < 1) { return list<Edge>(); } vector<Edge> allEdges = getAllEdges(); sort(allEdges.begin(), allEdges.end()); list<Edge> tree; vector<int> components; components.resize(nodes.size()); for (int i = 0; i < nodes.size(); i++) { components[i] = i; } for (Edge edge : allEdges) { if (components[edge.from] != components[edge.to]) { tree.push_back(edge); int oldComponent = components[edge.from]; int newComponent = components[edge.to]; for (int i = 0; i < components.size(); i++) { if (components[i] == oldComponent) { components[i] = newComponent; } } } } return tree; } }; int main() { Graph g(4); g.connect(0, 1, 5); g.connect(1, 2, 2); g.connect(1, 3, 8); g.connect(2, 0, 4); g.connect(2, 3, 3); g.connect(3, 0, 10); g.print(); list<Edge> spanningTree = g.kruskal(); for (Edge edge : spanningTree) { cout << edge.from << "-" << edge.to << "(" << edge.weight << ")\n"; } return 0; }
37b2f0026d62ab0150cd4c01ed65623875ca55ae
2cf838b54b556987cfc49f42935f8aa7563ea1f4
/aws-cpp-sdk-sagemaker/include/aws/sagemaker/model/SearchResult.h
2bdeacacec634791d299be069596204c624c139a
[ "MIT", "Apache-2.0", "JSON" ]
permissive
QPC-database/aws-sdk-cpp
d11e9f0ff6958c64e793c87a49f1e034813dac32
9f83105f7e07fe04380232981ab073c247d6fc85
refs/heads/main
2023-06-14T17:41:04.817304
2021-07-09T20:28:20
2021-07-09T20:28:20
384,714,703
1
0
Apache-2.0
2021-07-10T14:16:41
2021-07-10T14:16:41
null
UTF-8
C++
false
false
4,438
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/sagemaker/SageMaker_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/sagemaker/model/SearchRecord.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace SageMaker { namespace Model { class AWS_SAGEMAKER_API SearchResult { public: SearchResult(); SearchResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); SearchResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p>A list of <code>SearchRecord</code> objects.</p> */ inline const Aws::Vector<SearchRecord>& GetResults() const{ return m_results; } /** * <p>A list of <code>SearchRecord</code> objects.</p> */ inline void SetResults(const Aws::Vector<SearchRecord>& value) { m_results = value; } /** * <p>A list of <code>SearchRecord</code> objects.</p> */ inline void SetResults(Aws::Vector<SearchRecord>&& value) { m_results = std::move(value); } /** * <p>A list of <code>SearchRecord</code> objects.</p> */ inline SearchResult& WithResults(const Aws::Vector<SearchRecord>& value) { SetResults(value); return *this;} /** * <p>A list of <code>SearchRecord</code> objects.</p> */ inline SearchResult& WithResults(Aws::Vector<SearchRecord>&& value) { SetResults(std::move(value)); return *this;} /** * <p>A list of <code>SearchRecord</code> objects.</p> */ inline SearchResult& AddResults(const SearchRecord& value) { m_results.push_back(value); return *this; } /** * <p>A list of <code>SearchRecord</code> objects.</p> */ inline SearchResult& AddResults(SearchRecord&& value) { m_results.push_back(std::move(value)); return *this; } /** * <p>If the result of the previous <code>Search</code> request was truncated, the * response includes a NextToken. To retrieve the next set of results, use the * token in the next request.</p> */ inline const Aws::String& GetNextToken() const{ return m_nextToken; } /** * <p>If the result of the previous <code>Search</code> request was truncated, the * response includes a NextToken. To retrieve the next set of results, use the * token in the next request.</p> */ inline void SetNextToken(const Aws::String& value) { m_nextToken = value; } /** * <p>If the result of the previous <code>Search</code> request was truncated, the * response includes a NextToken. To retrieve the next set of results, use the * token in the next request.</p> */ inline void SetNextToken(Aws::String&& value) { m_nextToken = std::move(value); } /** * <p>If the result of the previous <code>Search</code> request was truncated, the * response includes a NextToken. To retrieve the next set of results, use the * token in the next request.</p> */ inline void SetNextToken(const char* value) { m_nextToken.assign(value); } /** * <p>If the result of the previous <code>Search</code> request was truncated, the * response includes a NextToken. To retrieve the next set of results, use the * token in the next request.</p> */ inline SearchResult& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;} /** * <p>If the result of the previous <code>Search</code> request was truncated, the * response includes a NextToken. To retrieve the next set of results, use the * token in the next request.</p> */ inline SearchResult& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;} /** * <p>If the result of the previous <code>Search</code> request was truncated, the * response includes a NextToken. To retrieve the next set of results, use the * token in the next request.</p> */ inline SearchResult& WithNextToken(const char* value) { SetNextToken(value); return *this;} private: Aws::Vector<SearchRecord> m_results; Aws::String m_nextToken; }; } // namespace Model } // namespace SageMaker } // namespace Aws
eccd7c94d8bca89b9f2714a76afd366d1a6d2526
cbbc248bd26d3466c3956c2163a01c7ae886fe57
/src/progs/recon_shell_radial.cpp
b1f44d5c77863ce4e804051b665d583a4b244395
[]
no_license
ajcuesta/baorecon
fb43e4bd053bf82b6966610db05387aaa8e7cb40
ad4be4bdeb6a4875135976d75cc56283b7358654
refs/heads/master
2021-01-17T22:43:14.276956
2012-02-27T04:35:25
2012-02-27T04:35:25
2,478,100
1
0
null
null
null
null
UTF-8
C++
false
false
9,649
cpp
#include <iostream> #include <cmath> #include <sstream> #include <fstream> #include <iomanip> #include "Recon.h" // Plane parallel code static char help[] = "recon_shell_radial -configfn <configuration file>\n"; using namespace std; int main(int argc, char *args[]) { PetscErrorCode ierr; ierr=PetscInitialize(&argc,&args,(char *) 0, help); CHKERRQ(ierr); { // Get MPI rank int rank; MPI_Comm_rank(PETSC_COMM_WORLD, &rank); // Read in configuration file char configfn[200]; PetscTruth flg; // See if we need help PetscOptionsHasName("-help", &flg); if (flg) exit(0); PetscOptionsGetString("-configfn", configfn, 200, &flg); if (!flg) RAISE_ERR(99,"Specify configuration file"); // Read in parameters ShellParams pars(string(configfn), "shellradial"); /**************************** * Define seeds ****************************/ int const_seed=2147; int randompart_seed=8271; /****************************************** * Define the mask and delta ******************************************/ Shell maskss(pars.shell.xcen, pars.shell.ycen, pars.shell.zcen, pars.shell.rmin, pars.shell.rmax); Delta del1(pars.Ngrid, pars.Lbox, pars.shell.nover, pars.shell.thresh, maskss); /******************************************** * Read in pk prior *******************************************/ vector<double> kvec, pkvec; int nk; // Rank 0 job reads in pk function and broadcasts to everyone if (rank == 0) { double k1, pk1; ifstream fp(pars.pkprior.fn.c_str()); do { fp >> k1 >> pk1; if (fp) { kvec.push_back(k1); pkvec.push_back(pars.pkprior.bias*pk1 + pars.pkprior.noise); } } while (fp); fp.close(); nk = kvec.size(); } MPI_Bcast(&nk, 1, MPI_INT, 0, PETSC_COMM_WORLD); if (rank !=0) {kvec.resize(nk, 0.0); pkvec.resize(nk, 0.0);} MPI_Bcast(&kvec[0], nk, MPI_DOUBLE, 0, PETSC_COMM_WORLD); MPI_Bcast(&pkvec[0], nk, MPI_DOUBLE, 0, PETSC_COMM_WORLD); PetscPrintf(PETSC_COMM_WORLD, "%d lines read in from %s...\n",nk, pars.pkprior.fn.c_str()); // Define the potential solver PotentialSolve psolve(pars.Ngrid, pars.Lbox, pars.recon.maxit); psolve.SetupOperator(RADIAL, pars.recon.fval, pars.recon.origin); // Loop over files list<ShellParams::fn>::iterator files; for (files = pars.fnlist.begin(); files !=pars.fnlist.end(); ++files) { /* ****************************** * First we get the various options and print out useful information * ********************************/ ostringstream hdr; hdr << "# Input file is " << files->in << endl; hdr << "# Output file is " << files->out << endl; hdr << "# Ngrid=" << setw(5) << pars.Ngrid << endl; hdr << "# boxsize=" << setw(8) << fixed << setprecision(2) << pars.Lbox << endl; hdr << "# bias=" << setw(8) << setprecision(2) << pars.recon.bias << endl; hdr << "# fval=" << setw(8) << setprecision(2) << pars.recon.fval << endl; hdr << "# smooth=" << setw(8) << setprecision(2) << pars.recon.smooth << endl; hdr << "# " << setw(4) << pars.xi.Nbins << " Xi bins from " << setw(8) << setprecision(2) << pars.xi.rmin << " with spacing of " << pars.xi.dr << endl; hdr << "# " << "Correlation function smoothed with a smoothing scale of" << setw(8) << setprecision(2) << pars.xi.smooth << endl; hdr << "# " << "Survey shell centered at the origin, rmin=" << setprecision(2) << pars.shell.rmin << ", rmax=" << pars.shell.rmax << endl; hdr << "# " << "Shell center at " << setprecision(3) << pars.shell.xcen << ", " << pars.shell.ycen << ", " << pars.shell.zcen << endl; hdr << "# Mask threshold =" << pars.shell.thresh << endl; PetscPrintf(PETSC_COMM_WORLD, (hdr.str()).c_str()); /**************************************** * Read in the particle data here and slab decompose ****************************************/ Particle pp; DensityGrid dg(pars.Ngrid, pars.Lbox); pp.TPMReadSerial(files->in.c_str(), pars.Lbox, true, true); PetscPrintf(PETSC_COMM_WORLD,"Read in %i particles.....\n",pp.npart); pp.SlabDecompose(dg); // Test slab decomp bool good = dg.TestSlabDecompose(pp); if (good) {PetscSynchronizedPrintf(PETSC_COMM_WORLD,"Slab decomposition succeeded on process %i\n",rank);} else {PetscSynchronizedPrintf(PETSC_COMM_WORLD,"Slab decomposition FAILED on process %i\n",rank);} PetscSynchronizedFlush(PETSC_COMM_WORLD); if (!good) RAISE_ERR(99, "Slab decomposition failed"); /************************************************* * Generate the density field and constrained realization *************************************************/ Vec grid=PETSC_NULL; del1.BuildDensityGridSmooth(pars.recon.smooth, pp, grid); PetscPrintf(PETSC_COMM_WORLD, "Density grid computed.....\n"); del1.HoffmanRibak(grid, kvec, pkvec, const_seed); const_seed+=1; PetscPrintf(PETSC_COMM_WORLD, "Constrained realization computed.....\n"); /************************************************ * Now we solve for the potential ************************************************/ // Allocate potential solver Vec pot; pot = dg.Allocate(); if (psolve.Solve(grid, pot, pars.recon.bias)) { // If the potential calculation converged PetscPrintf(PETSC_COMM_WORLD,"Potential calculated....\n"); /************************************************ * Now we shift data and randoms ************************************************/ // Generate random particles Vec dp, qx, qy, qz; Particle pr; pr.RandomInit(pp.npart*pars.recon.nrandomfac, pars.Lbox, randompart_seed); randompart_seed +=1; pr.SlabDecompose(dg); pr.TrimMask(maskss); // Compute derivatives at data positions and shift dp = dg.Deriv(pot, 0); qx = dg.Interp3d(dp, pp); _mydestroy(dp); dp = dg.Deriv(pot, 1); qy = dg.Interp3d(dp, pp); _mydestroy(dp); dp = dg.Deriv(pot, 2); qz = dg.Interp3d(dp, pp); _mydestroy(dp); // Print some statistics double sum[3]; VecSum(qx,&sum[0]); VecSum(qy, &sum[1]); VecSum(qz, &sum[2]); for (int ii=0; ii < 3; ++ii) sum[ii] /= pp.npart; PetscPrintf(PETSC_COMM_WORLD, "Mean x,y,z displacements on particles is : %10.4f,%10.4f,%10.4f\n",sum[0],sum[1],sum[2]); VecNorm(qx,NORM_2,&sum[0]); VecNorm(qy, NORM_2,&sum[1]); VecNorm(qz, NORM_2,&sum[2]); for (int ii=0; ii < 3; ++ii) sum[ii] /= sqrt(pp.npart); PetscPrintf(PETSC_COMM_WORLD, "RMS x,y,z displacements on particles is : %10.4f,%10.4f,%10.4f\n",sum[0],sum[1],sum[2]); // Do the shift in two pieces -- first the real space shift VecAXPY(pp.px, -1.0, qx); VecAXPY(pp.py, -1.0, qy); VecAXPY(pp.pz, -1.0, qz); PetscPrintf(PETSC_COMM_WORLD, "Standard displacements complete\n"); // Now shift to remove redshift distortions - this requires a little coordinate geometry // We need q.p/|r| pp.RadialDisplace(qx, qy, qz, pars.recon.origin, -pars.recon.fval); PetscPrintf(PETSC_COMM_WORLD, "zspace displacements complete\n"); // Cleanup _mydestroy(qx); _mydestroy(qy); _mydestroy(qz); // Do the same for the randoms dp = dg.Deriv(pot, 0); qx = dg.Interp3d(dp, pr); _mydestroy(dp); dp = dg.Deriv(pot, 1); qy = dg.Interp3d(dp, pr); _mydestroy(dp); dp = dg.Deriv(pot, 2); qz = dg.Interp3d(dp, pr); _mydestroy(dp); VecSum(qx,&sum[0]); VecSum(qy, &sum[1]); VecSum(qz, &sum[2]); for (int ii=0; ii < 3; ++ii) sum[ii] /= pr.npart; PetscPrintf(PETSC_COMM_WORLD, "Mean x,y,z displacements on randoms is : %10.4f,%10.4f,%10.4f\n",sum[0],sum[1],sum[2]); VecNorm(qx,NORM_2,&sum[0]); VecNorm(qy, NORM_2,&sum[1]); VecNorm(qz, NORM_2,&sum[2]); for (int ii=0; ii < 3; ++ii) sum[ii] /= sqrt(pr.npart); PetscPrintf(PETSC_COMM_WORLD, "RMS x,y,z displacements on randoms is : %10.4f,%10.4f,%10.4f\n",sum[0],sum[1],sum[2]); VecAXPY(pr.px, -1.0, qx); VecAXPY(pr.py, -1.0, qy); VecAXPY(pr.pz, -1.0, qz); PetscPrintf(PETSC_COMM_WORLD,"Displacements calculated....\n"); // Clean up _mydestroy(qx); _mydestroy(qy); _mydestroy(qz); // Shifted data and random grid Vec gridr=PETSC_NULL; del1.BuildDensityGrid(pp, grid); del1.BuildDensityGrid(pr, gridr); VecAXPY(grid, -1.0, gridr); // Correlation fn PkStruct xi2(pars.xi.rmin, pars.xi.dr, pars.xi.Nbins); dg.XiFFT_W(grid, del1.W, pars.xi.smooth, xi2); _mydestroy(gridr); // Outputs FILE *fp; double _rvec, _xi2, _n1; PetscFOpen(PETSC_COMM_WORLD,files->out.c_str(),"w", &fp); PetscFPrintf(PETSC_COMM_WORLD, fp, (hdr.str()).c_str()); for (int ii = xi2.lo; ii < xi2.hi; ++ii) { _xi2 = xi2(ii, _rvec, _n1); if (_n1>0) PetscSynchronizedFPrintf(PETSC_COMM_WORLD, fp, "%6i %9.3f %15.8e\n",ii,_rvec,_xi2); } PetscSynchronizedFlush(PETSC_COMM_WORLD); PetscFClose(PETSC_COMM_WORLD,fp); } // Cleanup _mydestroy(grid); _mydestroy(pot); } } // Only call this when everything is out of scope ierr=PetscFinalize(); CHKERRQ(ierr); }
649139f6405d6ec62f1fbf69987551ca3c73aeea
a38be41c50e512560d828bd4db1d5f289893cc4e
/Practice/chapter_07/exercise_7_41.h
6ec6c3a619476b19de50448cf8b41c9d40aa103b
[ "Apache-2.0" ]
permissive
Moyaro/Cpp-Primer-Note
0877a738a528ce78709dd3557b1d25330405a456
1f1bc0a3a23651a98afdf85e86852642fce526fa
refs/heads/master
2023-02-03T23:32:28.988728
2020-12-27T10:35:53
2020-12-27T10:35:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,056
h
#ifndef CP7_ex_7_41_h #define CP7_ex_7_41_h #include <iostream> #include <string> class Sales_data; class Sales_data{ friend Sales_data add(const Sales_data&, const Sales_data&); friend std::ostream &print(std::ostream&, const Sales_data&); friend std::istream &read(std::istream&, Sales_data&); public: Sales_data(const std::string &s, unsigned n, double p):bookNo(s), units_sold(n), revenue(p*n){ std::cout << "Sales_data(const std::string s, unsigned, double)" << std::endl; } Sales_data():Sales_data("", 0, 0.0f) { std::cout << "Sales_data()" << std::endl; } Sales_data(const std::string &s):Sales_data(s, 0, 0.0f) { std::cout << "Sales_data(const string&)" << std::endl; } Sales_data(std::istream &is); std::string isbn() const {return bookNo;}; Sales_data &combine(const Sales_data &rhs); private: inline double avg_price() const; private: std::string bookNo; unsigned units_sold = 0; double revenue = 0.0; }; inline double Sales_data::avg_price() const { return units_sold ? revenue / units_sold : 0; } #endif