blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
def14dcb866f6234dcba8c8d8c83cea719baab8e
a5c7197199ab02b644b0b4f7b53818172234938e
/core/test/lib/asio/include/asio/detail/impl/win_event.ipp
e3d77e68d8cf154274f099cdd0a31f881a868f28
[ "MIT", "BSL-1.0" ]
permissive
Electronic-Gulden-Foundation/lib-ledger-core
421b2cd0c733346a402b2830d00fcc635bf5150b
6d7d101aa1f35bbfbc74155500f56fce047a7a53
refs/heads/master
2020-09-22T11:27:47.309303
2019-10-25T09:16:31
2019-10-25T09:16:31
225,174,537
1
1
MIT
2019-12-01T14:25:18
2019-12-01T14:25:17
null
UTF-8
C++
false
false
1,845
ipp
// // detail/win_event.ipp // ~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2016 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef ASIO_DETAIL_IMPL_WIN_EVENT_IPP #define ASIO_DETAIL_IMPL_WIN_EVENT_IPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_WINDOWS) #include "asio/detail/throw_error.hpp" #include "asio/detail/win_event.hpp" #include "asio/error.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { win_event::win_event() : state_(0) { #if defined(ASIO_WINDOWS_APP) events_[0] = ::CreateEventExW(0, 0, CREATE_EVENT_MANUAL_RESET, 0); #else // defined(ASIO_WINDOWS_APP) events_[0] = ::CreateEventW(0, true, false, 0); #endif // defined(ASIO_WINDOWS_APP) if (!events_[0]) { DWORD last_error = ::GetLastError(); asio::error_code ec(last_error, asio::error::get_system_category()); asio::detail::throw_error(ec, "event"); } #if defined(ASIO_WINDOWS_APP) events_[1] = ::CreateEventExW(0, 0, 0, 0); #else // defined(ASIO_WINDOWS_APP) events_[1] = ::CreateEventW(0, false, false, 0); #endif // defined(ASIO_WINDOWS_APP) if (!events_[1]) { DWORD last_error = ::GetLastError(); ::CloseHandle(events_[0]); asio::error_code ec(last_error, asio::error::get_system_category()); asio::detail::throw_error(ec, "event"); } } win_event::~win_event() { ::CloseHandle(events_[0]); ::CloseHandle(events_[1]); } } // namespace detail } // namespace asio #include "asio/detail/pop_options.hpp" #endif // defined(ASIO_WINDOWS) #endif // ASIO_DETAIL_IMPL_WIN_EVENT_IPP
[ "pollastri.p@gmail.com" ]
pollastri.p@gmail.com
b32cc1aeeaeebb862ccad4a74dc623496c7210bc
7446fede2d71cdb7c578fe60a894645e70791953
/src/masternode.cpp
c7fe3d439b3653940c1d911f30bc5d206434d1f5
[ "MIT" ]
permissive
ondori-project/rstr
23522833c6e28e03122d40ba663c0024677d05c9
9b3a2ef39ab0f72e8efffee257b2eccc00054b38
refs/heads/master
2021-07-12T18:03:23.480909
2019-02-25T17:51:46
2019-02-25T17:51:46
149,688,410
2
3
MIT
2019-02-14T02:19:49
2018-09-21T00:44:03
C++
UTF-8
C++
false
false
30,519
cpp
// Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2018 The PIVX developers // Copyright (c) 2015-2018 The RSTR developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "masternode.h" #include "addrman.h" #include "masternodeman.h" #include "obfuscation.h" #include "sync.h" #include "util.h" #include <boost/lexical_cast.hpp> // keep track of the scanning errors I've seen map<uint256, int> mapSeenMasternodeScanningErrors; // cache block hashes as we calculate them std::map<int64_t, uint256> mapCacheBlockHashes; //Get the last hash that matches the modulus given. Processed in reverse order bool GetBlockHash(uint256& hash, int nBlockHeight) { if (chainActive.Tip() == NULL) return false; if (nBlockHeight == 0) nBlockHeight = chainActive.Tip()->nHeight; if (mapCacheBlockHashes.count(nBlockHeight)) { hash = mapCacheBlockHashes[nBlockHeight]; return true; } const CBlockIndex* BlockLastSolved = chainActive.Tip(); const CBlockIndex* BlockReading = chainActive.Tip(); if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || chainActive.Tip()->nHeight + 1 < nBlockHeight) return false; int nBlocksAgo = 0; if (nBlockHeight > 0) nBlocksAgo = (chainActive.Tip()->nHeight + 1) - nBlockHeight; assert(nBlocksAgo >= 0); int n = 0; for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) { if (n >= nBlocksAgo) { hash = BlockReading->GetBlockHash(); mapCacheBlockHashes[nBlockHeight] = hash; return true; } n++; if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } return false; } CMasternode::CMasternode() { LOCK(cs); vin = CTxIn(); addr = CService(); pubKeyCollateralAddress = CPubKey(); pubKeyMasternode = CPubKey(); sig = std::vector<unsigned char>(); activeState = MASTERNODE_ENABLED; sigTime = GetAdjustedTime(); lastPing = CMasternodePing(); cacheInputAge = 0; cacheInputAgeBlock = 0; unitTest = false; allowFreeTx = true; nActiveState = MASTERNODE_ENABLED, protocolVersion = PROTOCOL_VERSION; nLastDsq = 0; nScanningErrorCount = 0; nLastScanningErrorBlockHeight = 0; lastTimeChecked = 0; nLastDsee = 0; // temporary, do not save. Remove after migration to v12 nLastDseep = 0; // temporary, do not save. Remove after migration to v12 } CMasternode::CMasternode(const CMasternode& other) { LOCK(cs); vin = other.vin; addr = other.addr; pubKeyCollateralAddress = other.pubKeyCollateralAddress; pubKeyMasternode = other.pubKeyMasternode; sig = other.sig; activeState = other.activeState; sigTime = other.sigTime; lastPing = other.lastPing; cacheInputAge = other.cacheInputAge; cacheInputAgeBlock = other.cacheInputAgeBlock; unitTest = other.unitTest; allowFreeTx = other.allowFreeTx; nActiveState = MASTERNODE_ENABLED, protocolVersion = other.protocolVersion; nLastDsq = other.nLastDsq; nScanningErrorCount = other.nScanningErrorCount; nLastScanningErrorBlockHeight = other.nLastScanningErrorBlockHeight; lastTimeChecked = 0; nLastDsee = other.nLastDsee; // temporary, do not save. Remove after migration to v12 nLastDseep = other.nLastDseep; // temporary, do not save. Remove after migration to v12 } CMasternode::CMasternode(const CMasternodeBroadcast& mnb) { LOCK(cs); vin = mnb.vin; addr = mnb.addr; pubKeyCollateralAddress = mnb.pubKeyCollateralAddress; pubKeyMasternode = mnb.pubKeyMasternode; sig = mnb.sig; activeState = MASTERNODE_ENABLED; sigTime = mnb.sigTime; lastPing = mnb.lastPing; cacheInputAge = 0; cacheInputAgeBlock = 0; unitTest = false; allowFreeTx = true; nActiveState = MASTERNODE_ENABLED, protocolVersion = mnb.protocolVersion; nLastDsq = mnb.nLastDsq; nScanningErrorCount = 0; nLastScanningErrorBlockHeight = 0; lastTimeChecked = 0; nLastDsee = 0; // temporary, do not save. Remove after migration to v12 nLastDseep = 0; // temporary, do not save. Remove after migration to v12 } // // When a new masternode broadcast is sent, update our information // bool CMasternode::UpdateFromNewBroadcast(CMasternodeBroadcast& mnb) { if (mnb.sigTime > sigTime) { pubKeyMasternode = mnb.pubKeyMasternode; pubKeyCollateralAddress = mnb.pubKeyCollateralAddress; sigTime = mnb.sigTime; sig = mnb.sig; protocolVersion = mnb.protocolVersion; addr = mnb.addr; lastTimeChecked = 0; int nDoS = 0; if (mnb.lastPing == CMasternodePing() || (mnb.lastPing != CMasternodePing() && mnb.lastPing.CheckAndUpdate(nDoS, false))) { lastPing = mnb.lastPing; mnodeman.mapSeenMasternodePing.insert(make_pair(lastPing.GetHash(), lastPing)); } return true; } return false; } // // Deterministically calculate a given "score" for a Masternode depending on how close it's hash is to // the proof of work for that block. The further away they are the better, the furthest will win the election // and get paid this block // uint256 CMasternode::CalculateScore(int mod, int64_t nBlockHeight) { if (chainActive.Tip() == NULL) return 0; uint256 hash = 0; uint256 aux = vin.prevout.hash + vin.prevout.n; if (!GetBlockHash(hash, nBlockHeight)) { LogPrint("masternode","CalculateScore ERROR - nHeight %d - Returned 0\n", nBlockHeight); return 0; } CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << hash; uint256 hash2 = ss.GetHash(); CHashWriter ss2(SER_GETHASH, PROTOCOL_VERSION); ss2 << hash; ss2 << aux; uint256 hash3 = ss2.GetHash(); uint256 r = (hash3 > hash2 ? hash3 - hash2 : hash2 - hash3); return r; } void CMasternode::Check(bool forceCheck) { if (ShutdownRequested()) return; if (!forceCheck && (GetTime() - lastTimeChecked < MASTERNODE_CHECK_SECONDS)) return; lastTimeChecked = GetTime(); //once spent, stop doing the checks if (activeState == MASTERNODE_VIN_SPENT) return; if (!IsPingedWithin(MASTERNODE_REMOVAL_SECONDS)) { activeState = MASTERNODE_REMOVE; return; } if (!IsPingedWithin(MASTERNODE_EXPIRATION_SECONDS)) { activeState = MASTERNODE_EXPIRED; return; } if(lastPing.sigTime - sigTime < MASTERNODE_MIN_MNP_SECONDS){ activeState = MASTERNODE_PRE_ENABLED; return; } if (!unitTest) { CValidationState state; CMutableTransaction tx = CMutableTransaction(); CTxOut vout = CTxOut(4999.99 * COIN, obfuScationPool.collateralPubKey); tx.vin.push_back(vin); tx.vout.push_back(vout); { TRY_LOCK(cs_main, lockMain); if (!lockMain) return; if (!AcceptableInputs(mempool, state, CTransaction(tx), false, NULL)) { activeState = MASTERNODE_VIN_SPENT; return; } } } activeState = MASTERNODE_ENABLED; // OK } int64_t CMasternode::SecondsSincePayment() { CScript pubkeyScript; pubkeyScript = GetScriptForDestination(pubKeyCollateralAddress.GetID()); int64_t sec = (GetAdjustedTime() - GetLastPaid()); int64_t month = 60 * 60 * 24 * 30; if (sec < month) return sec; //if it's less than 30 days, give seconds CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << vin; ss << sigTime; uint256 hash = ss.GetHash(); // return some deterministic value for unknown/unpaid but force it to be more than 30 days old return month + hash.GetCompact(false); } int64_t CMasternode::GetLastPaid() { CBlockIndex* pindexPrev = chainActive.Tip(); if (pindexPrev == NULL) return false; CScript mnpayee; mnpayee = GetScriptForDestination(pubKeyCollateralAddress.GetID()); CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << vin; ss << sigTime; uint256 hash = ss.GetHash(); // use a deterministic offset to break a tie -- 2.5 minutes int64_t nOffset = hash.GetCompact(false) % 150; if (chainActive.Tip() == NULL) return false; const CBlockIndex* BlockReading = chainActive.Tip(); int nMnCount = mnodeman.CountEnabled() * 1.25; int n = 0; for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) { if (n >= nMnCount) { return 0; } n++; if (masternodePayments.mapMasternodeBlocks.count(BlockReading->nHeight)) { /* Search for this payee, with at least 2 votes. This will aid in consensus allowing the network to converge on the same payees quickly, then keep the same schedule. */ if (masternodePayments.mapMasternodeBlocks[BlockReading->nHeight].HasPayeeWithVotes(mnpayee, 2)) { return BlockReading->nTime + nOffset; } } if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } return 0; } std::string CMasternode::GetStatus() { switch (nActiveState) { case CMasternode::MASTERNODE_PRE_ENABLED: return "PRE_ENABLED"; case CMasternode::MASTERNODE_ENABLED: return "ENABLED"; case CMasternode::MASTERNODE_EXPIRED: return "EXPIRED"; case CMasternode::MASTERNODE_OUTPOINT_SPENT: return "OUTPOINT_SPENT"; case CMasternode::MASTERNODE_REMOVE: return "REMOVE"; case CMasternode::MASTERNODE_WATCHDOG_EXPIRED: return "WATCHDOG_EXPIRED"; case CMasternode::MASTERNODE_POSE_BAN: return "POSE_BAN"; default: return "UNKNOWN"; } } bool CMasternode::IsValidNetAddr() { // TODO: regtest is fine with any addresses for now, // should probably be a bit smarter if one day we start to implement tests for this return Params().NetworkID() == CBaseChainParams::REGTEST || (IsReachable(addr) && addr.IsRoutable()); } CMasternodeBroadcast::CMasternodeBroadcast() { vin = CTxIn(); addr = CService(); pubKeyCollateralAddress = CPubKey(); pubKeyMasternode1 = CPubKey(); sig = std::vector<unsigned char>(); activeState = MASTERNODE_ENABLED; sigTime = GetAdjustedTime(); lastPing = CMasternodePing(); cacheInputAge = 0; cacheInputAgeBlock = 0; unitTest = false; allowFreeTx = true; protocolVersion = PROTOCOL_VERSION; nLastDsq = 0; nScanningErrorCount = 0; nLastScanningErrorBlockHeight = 0; } CMasternodeBroadcast::CMasternodeBroadcast(CService newAddr, CTxIn newVin, CPubKey pubKeyCollateralAddressNew, CPubKey pubKeyMasternodeNew, int protocolVersionIn) { vin = newVin; addr = newAddr; pubKeyCollateralAddress = pubKeyCollateralAddressNew; pubKeyMasternode = pubKeyMasternodeNew; sig = std::vector<unsigned char>(); activeState = MASTERNODE_ENABLED; sigTime = GetAdjustedTime(); lastPing = CMasternodePing(); cacheInputAge = 0; cacheInputAgeBlock = 0; unitTest = false; allowFreeTx = true; protocolVersion = protocolVersionIn; nLastDsq = 0; nScanningErrorCount = 0; nLastScanningErrorBlockHeight = 0; } CMasternodeBroadcast::CMasternodeBroadcast(const CMasternode& mn) { vin = mn.vin; addr = mn.addr; pubKeyCollateralAddress = mn.pubKeyCollateralAddress; pubKeyMasternode = mn.pubKeyMasternode; sig = mn.sig; activeState = mn.activeState; sigTime = mn.sigTime; lastPing = mn.lastPing; cacheInputAge = mn.cacheInputAge; cacheInputAgeBlock = mn.cacheInputAgeBlock; unitTest = mn.unitTest; allowFreeTx = mn.allowFreeTx; protocolVersion = mn.protocolVersion; nLastDsq = mn.nLastDsq; nScanningErrorCount = mn.nScanningErrorCount; nLastScanningErrorBlockHeight = mn.nLastScanningErrorBlockHeight; } bool CMasternodeBroadcast::Create(std::string strService, std::string strKeyMasternode, std::string strTxHash, std::string strOutputIndex, std::string& strErrorRet, CMasternodeBroadcast& mnbRet, bool fOffline) { CTxIn txin; CPubKey pubKeyCollateralAddressNew; CKey keyCollateralAddressNew; CPubKey pubKeyMasternodeNew; CKey keyMasternodeNew; //need correct blocks to send ping if (!fOffline && !masternodeSync.IsBlockchainSynced()) { strErrorRet = "Sync in progress. Must wait until sync is complete to start Masternode"; LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet); return false; } if (!obfuScationSigner.GetKeysFromSecret(strKeyMasternode, keyMasternodeNew, pubKeyMasternodeNew)) { strErrorRet = strprintf("Invalid masternode key %s", strKeyMasternode); LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet); return false; } if (!pwalletMain->GetMasternodeVinAndKeys(txin, pubKeyCollateralAddressNew, keyCollateralAddressNew, strTxHash, strOutputIndex)) { strErrorRet = strprintf("Could not allocate txin %s:%s for masternode %s", strTxHash, strOutputIndex, strService); LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet); return false; } // The service needs the correct default port to work properly if(!CheckDefaultPort(strService, strErrorRet, "CMasternodeBroadcast::Create")) return false; return Create(txin, CService(strService), keyCollateralAddressNew, pubKeyCollateralAddressNew, keyMasternodeNew, pubKeyMasternodeNew, strErrorRet, mnbRet); } bool CMasternodeBroadcast::Create(CTxIn txin, CService service, CKey keyCollateralAddressNew, CPubKey pubKeyCollateralAddressNew, CKey keyMasternodeNew, CPubKey pubKeyMasternodeNew, std::string& strErrorRet, CMasternodeBroadcast& mnbRet) { // wait for reindex and/or import to finish if (fImporting || fReindex) return false; LogPrint("masternode", "CMasternodeBroadcast::Create -- pubKeyCollateralAddressNew = %s, pubKeyMasternodeNew.GetID() = %s\n", CBitcoinAddress(pubKeyCollateralAddressNew.GetID()).ToString(), pubKeyMasternodeNew.GetID().ToString()); CMasternodePing mnp(txin); if (!mnp.Sign(keyMasternodeNew, pubKeyMasternodeNew)) { strErrorRet = strprintf("Failed to sign ping, masternode=%s", txin.prevout.hash.ToString()); LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet); mnbRet = CMasternodeBroadcast(); return false; } mnbRet = CMasternodeBroadcast(service, txin, pubKeyCollateralAddressNew, pubKeyMasternodeNew, PROTOCOL_VERSION); if (!mnbRet.IsValidNetAddr()) { strErrorRet = strprintf("Invalid IP address %s, masternode=%s", mnbRet.addr.ToStringIP (), txin.prevout.hash.ToString()); LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet); mnbRet = CMasternodeBroadcast(); return false; } mnbRet.lastPing = mnp; if (!mnbRet.Sign(keyCollateralAddressNew)) { strErrorRet = strprintf("Failed to sign broadcast, masternode=%s", txin.prevout.hash.ToString()); LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet); mnbRet = CMasternodeBroadcast(); return false; } return true; } bool CMasternodeBroadcast::CheckDefaultPort(std::string strService, std::string& strErrorRet, std::string strContext) { CService service = CService(strService); int nDefaultPort = Params().GetDefaultPort(); if (service.GetPort() != nDefaultPort) { strErrorRet = strprintf("Invalid port %u for masternode %s, only %d is supported on %s-net.", service.GetPort(), strService, nDefaultPort, Params().NetworkIDString()); LogPrint("masternode", "%s - %s\n", strContext, strErrorRet); return false; } return true; } bool CMasternodeBroadcast::CheckAndUpdate(int& nDos) { // make sure signature isn't in the future (past is OK) if (sigTime > GetAdjustedTime() + 60 * 60) { LogPrint("masternode","mnb - Signature rejected, too far into the future %s\n", vin.prevout.hash.ToString()); nDos = 1; return false; } // incorrect ping or its sigTime if(lastPing == CMasternodePing() || !lastPing.CheckAndUpdate(nDos, false, true)) return false; if (protocolVersion < masternodePayments.GetMinMasternodePaymentsProto()) { LogPrint("masternode","mnb - ignoring outdated Masternode %s protocol version %d\n", vin.prevout.hash.ToString(), protocolVersion); return false; } CScript pubkeyScript; pubkeyScript = GetScriptForDestination(pubKeyCollateralAddress.GetID()); if (pubkeyScript.size() != 25) { LogPrint("masternode","mnb - pubkey the wrong size\n"); nDos = 100; return false; } CScript pubkeyScript2; pubkeyScript2 = GetScriptForDestination(pubKeyMasternode.GetID()); if (pubkeyScript2.size() != 25) { LogPrint("masternode","mnb - pubkey2 the wrong size\n"); nDos = 100; return false; } if (!vin.scriptSig.empty()) { LogPrint("masternode","mnb - Ignore Not Empty ScriptSig %s\n", vin.prevout.hash.ToString()); return false; } std::string errorMessage = ""; if (!obfuScationSigner.VerifyMessage(pubKeyCollateralAddress, sig, GetNewStrMessage(), errorMessage) && !obfuScationSigner.VerifyMessage(pubKeyCollateralAddress, sig, GetOldStrMessage(), errorMessage)) { // don't ban for old masternodes, their sigs could be broken because of the bug nDos = protocolVersion < MIN_PEER_MNANNOUNCE ? 0 : 100; return error("CMasternodeBroadcast::CheckAndUpdate - Got bad Masternode address signature : %s", errorMessage); } if (Params().NetworkID() == CBaseChainParams::MAIN) { if (addr.GetPort() != 22620) return false; } else if (addr.GetPort() == 22620) return false; //search existing Masternode list, this is where we update existing Masternodes with new mnb broadcasts CMasternode* pmn = mnodeman.Find(vin); // no such masternode, nothing to update if (pmn == NULL) return true; // this broadcast is older or equal than the one that we already have - it's bad and should never happen // unless someone is doing something fishy // (mapSeenMasternodeBroadcast in CMasternodeMan::ProcessMessage should filter legit duplicates) if(pmn->sigTime >= sigTime) { return error("CMasternodeBroadcast::CheckAndUpdate - Bad sigTime %d for Masternode %20s %105s (existing broadcast is at %d)", sigTime, addr.ToString(), vin.ToString(), pmn->sigTime); } // masternode is not enabled yet/already, nothing to update if (!pmn->IsEnabled()) return true; // mn.pubkey = pubkey, IsVinAssociatedWithPubkey is validated once below, // after that they just need to match if (pmn->pubKeyCollateralAddress == pubKeyCollateralAddress && !pmn->IsBroadcastedWithin(MASTERNODE_MIN_MNB_SECONDS)) { //take the newest entry LogPrint("masternode","mnb - Got updated entry for %s\n", vin.prevout.hash.ToString()); if (pmn->UpdateFromNewBroadcast((*this))) { pmn->Check(); if (pmn->IsEnabled()) Relay(); } masternodeSync.AddedMasternodeList(GetHash()); } return true; } bool CMasternodeBroadcast::CheckInputsAndAdd(int& nDoS) { // we are a masternode with the same vin (i.e. already activated) and this mnb is ours (matches our Masternode privkey) // so nothing to do here for us if (fMasterNode && vin.prevout == activeMasternode.vin.prevout && pubKeyMasternode == activeMasternode.pubKeyMasternode) return true; // incorrect ping or its sigTime if(lastPing == CMasternodePing() || !lastPing.CheckAndUpdate(nDoS, false, true)) return false; // search existing Masternode list CMasternode* pmn = mnodeman.Find(vin); if (pmn != NULL) { // nothing to do here if we already know about this masternode and it's enabled if (pmn->IsEnabled()) return true; // if it's not enabled, remove old MN first and continue else mnodeman.Remove(pmn->vin); } CValidationState state; CMutableTransaction tx = CMutableTransaction(); CTxOut vout = CTxOut(4999.99 * COIN, obfuScationPool.collateralPubKey); tx.vin.push_back(vin); tx.vout.push_back(vout); { TRY_LOCK(cs_main, lockMain); if (!lockMain) { // not mnb fault, let it to be checked again later mnodeman.mapSeenMasternodeBroadcast.erase(GetHash()); masternodeSync.mapSeenSyncMNB.erase(GetHash()); return false; } if (!AcceptableInputs(mempool, state, CTransaction(tx), false, NULL)) { //set nDos state.IsInvalid(nDoS); return false; } } LogPrint("masternode", "mnb - Accepted Masternode entry\n"); if (GetInputAge(vin) < MASTERNODE_MIN_CONFIRMATIONS) { LogPrint("masternode","mnb - Input must have at least %d confirmations\n", MASTERNODE_MIN_CONFIRMATIONS); // maybe we miss few blocks, let this mnb to be checked again later mnodeman.mapSeenMasternodeBroadcast.erase(GetHash()); masternodeSync.mapSeenSyncMNB.erase(GetHash()); return false; } // verify that sig time is legit in past // should be at least not earlier than block when 25000 RST tx got MASTERNODE_MIN_CONFIRMATIONS uint256 hashBlock = 0; CTransaction tx2; GetTransaction(vin.prevout.hash, tx2, hashBlock, true); BlockMap::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pMNIndex = (*mi).second; // block for 1000 RSTR tx -> 1 confirmation CBlockIndex* pConfIndex = chainActive[pMNIndex->nHeight + MASTERNODE_MIN_CONFIRMATIONS - 1]; // block where tx got MASTERNODE_MIN_CONFIRMATIONS if (pConfIndex->GetBlockTime() > sigTime) { LogPrint("masternode","mnb - Bad sigTime %d for Masternode %s (%i conf block is at %d)\n", sigTime, vin.prevout.hash.ToString(), MASTERNODE_MIN_CONFIRMATIONS, pConfIndex->GetBlockTime()); return false; } } LogPrint("masternode","mnb - Got NEW Masternode entry - %s - %lli \n", vin.prevout.hash.ToString(), sigTime); CMasternode mn(*this); mnodeman.Add(mn); // if it matches our Masternode privkey, then we've been remotely activated if (pubKeyMasternode == activeMasternode.pubKeyMasternode && protocolVersion == PROTOCOL_VERSION) { activeMasternode.EnableHotColdMasterNode(vin, addr); } bool isLocal = addr.IsRFC1918() || addr.IsLocal(); if (Params().NetworkID() == CBaseChainParams::REGTEST) isLocal = false; if (!isLocal) Relay(); return true; } void CMasternodeBroadcast::Relay() { CInv inv(MSG_MASTERNODE_ANNOUNCE, GetHash()); RelayInv(inv); } bool CMasternodeBroadcast::Sign(CKey& keyCollateralAddress) { std::string errorMessage; sigTime = GetAdjustedTime(); std::string strMessage; if(chainActive.Height() < Params().Zerocoin_Block_V2_Start()) strMessage = GetOldStrMessage(); else strMessage = GetNewStrMessage(); if (!obfuScationSigner.SignMessage(strMessage, errorMessage, sig, keyCollateralAddress)) return error("CMasternodeBroadcast::Sign() - Error: %s", errorMessage); if (!obfuScationSigner.VerifyMessage(pubKeyCollateralAddress, sig, strMessage, errorMessage)) return error("CMasternodeBroadcast::Sign() - Error: %s", errorMessage); return true; } bool CMasternodeBroadcast::VerifySignature() { std::string errorMessage; if(!obfuScationSigner.VerifyMessage(pubKeyCollateralAddress, sig, GetNewStrMessage(), errorMessage) && !obfuScationSigner.VerifyMessage(pubKeyCollateralAddress, sig, GetOldStrMessage(), errorMessage)) return error("CMasternodeBroadcast::VerifySignature() - Error: %s", errorMessage); return true; } std::string CMasternodeBroadcast::GetOldStrMessage() { std::string strMessage; std::string vchPubKey(pubKeyCollateralAddress.begin(), pubKeyCollateralAddress.end()); std::string vchPubKey2(pubKeyMasternode.begin(), pubKeyMasternode.end()); strMessage = addr.ToString() + boost::lexical_cast<std::string>(sigTime) + vchPubKey + vchPubKey2 + boost::lexical_cast<std::string>(protocolVersion); return strMessage; } std:: string CMasternodeBroadcast::GetNewStrMessage() { std::string strMessage; strMessage = addr.ToString() + boost::lexical_cast<std::string>(sigTime) + pubKeyCollateralAddress.GetID().ToString() + pubKeyMasternode.GetID().ToString() + boost::lexical_cast<std::string>(protocolVersion); return strMessage; } CMasternodePing::CMasternodePing() { vin = CTxIn(); blockHash = uint256(0); sigTime = 0; vchSig = std::vector<unsigned char>(); } CMasternodePing::CMasternodePing(CTxIn& newVin) { vin = newVin; blockHash = chainActive[chainActive.Height() - 12]->GetBlockHash(); sigTime = GetAdjustedTime(); vchSig = std::vector<unsigned char>(); } bool CMasternodePing::Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode) { std::string errorMessage; std::string strMasterNodeSignMessage; sigTime = GetAdjustedTime(); std::string strMessage = vin.ToString() + blockHash.ToString() + boost::lexical_cast<std::string>(sigTime); if (!obfuScationSigner.SignMessage(strMessage, errorMessage, vchSig, keyMasternode)) { LogPrint("masternode","CMasternodePing::Sign() - Error: %s\n", errorMessage); return false; } if (!obfuScationSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, errorMessage)) { LogPrint("masternode","CMasternodePing::Sign() - Error: %s\n", errorMessage); return false; } return true; } bool CMasternodePing::VerifySignature(CPubKey& pubKeyMasternode, int &nDos) { std::string strMessage = vin.ToString() + blockHash.ToString() + boost::lexical_cast<std::string>(sigTime); std::string errorMessage = ""; if(!obfuScationSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, errorMessage)){ nDos = 33; return error("CMasternodePing::VerifySignature - Got bad Masternode ping signature %s Error: %s", vin.ToString(), errorMessage); } return true; } bool CMasternodePing::CheckAndUpdate(int& nDos, bool fRequireEnabled, bool fCheckSigTimeOnly) { if (sigTime > GetAdjustedTime() + 60 * 60) { LogPrint("masternode","CMasternodePing::CheckAndUpdate - Signature rejected, too far into the future %s\n", vin.prevout.hash.ToString()); nDos = 1; return false; } if (sigTime <= GetAdjustedTime() - 60 * 60) { LogPrint("masternode","CMasternodePing::CheckAndUpdate - Signature rejected, too far into the past %s - %d %d \n", vin.prevout.hash.ToString(), sigTime, GetAdjustedTime()); nDos = 1; return false; } if(fCheckSigTimeOnly) { CMasternode* pmn = mnodeman.Find(vin); if(pmn) return VerifySignature(pmn->pubKeyMasternode, nDos); return true; } LogPrint("masternode", "CMasternodePing::CheckAndUpdate - New Ping - %s - %s - %lli\n", GetHash().ToString(), blockHash.ToString(), sigTime); // see if we have this Masternode CMasternode* pmn = mnodeman.Find(vin); if (pmn != NULL && pmn->protocolVersion >= masternodePayments.GetMinMasternodePaymentsProto()) { if (fRequireEnabled && !pmn->IsEnabled()) return false; // LogPrint("masternode","mnping - Found corresponding mn for vin: %s\n", vin.ToString()); // update only if there is no known ping for this masternode or // last ping was more then MASTERNODE_MIN_MNP_SECONDS-60 ago comparing to this one if (!pmn->IsPingedWithin(MASTERNODE_MIN_MNP_SECONDS - 60, sigTime)) { if (!VerifySignature(pmn->pubKeyMasternode, nDos)) return false; BlockMap::iterator mi = mapBlockIndex.find(blockHash); if (mi != mapBlockIndex.end() && (*mi).second) { if ((*mi).second->nHeight < chainActive.Height() - 24) { LogPrint("masternode","CMasternodePing::CheckAndUpdate - Masternode %s block hash %s is too old\n", vin.prevout.hash.ToString(), blockHash.ToString()); // Do nothing here (no Masternode update, no mnping relay) // Let this node to be visible but fail to accept mnping return false; } } else { if (fDebug) LogPrint("masternode","CMasternodePing::CheckAndUpdate - Masternode %s block hash %s is unknown\n", vin.prevout.hash.ToString(), blockHash.ToString()); // maybe we stuck so we shouldn't ban this node, just fail to accept it // TODO: or should we also request this block? return false; } pmn->lastPing = *this; //mnodeman.mapSeenMasternodeBroadcast.lastPing is probably outdated, so we'll update it CMasternodeBroadcast mnb(*pmn); uint256 hash = mnb.GetHash(); if (mnodeman.mapSeenMasternodeBroadcast.count(hash)) { mnodeman.mapSeenMasternodeBroadcast[hash].lastPing = *this; } pmn->Check(true); if (!pmn->IsEnabled()) return false; LogPrint("masternode", "CMasternodePing::CheckAndUpdate - Masternode ping accepted, vin: %s\n", vin.prevout.hash.ToString()); Relay(); return true; } LogPrint("masternode", "CMasternodePing::CheckAndUpdate - Masternode ping arrived too early, vin: %s\n", vin.prevout.hash.ToString()); //nDos = 1; //disable, this is happening frequently and causing banned peers return false; } LogPrint("masternode", "CMasternodePing::CheckAndUpdate - Couldn't find compatible Masternode entry, vin: %s\n", vin.prevout.hash.ToString()); return false; } void CMasternodePing::Relay() { CInv inv(MSG_MASTERNODE_PING, GetHash()); RelayInv(inv); }
[ "ondoricoin@gmail.com" ]
ondoricoin@gmail.com
3354f7be6aa64e585ecbd980126c714102718d79
ee213de65cea159d0fdaf487bddf2745315da7f3
/Project1/Main.cpp
9a428eaabfb378a736895e8c94f906adba298cd5
[]
no_license
Linda394/Snake-Game
05404f449748d9a73b6c023691f4da83b7eac08c
5e822df083f480a1a1056a0dbb9b66bb4ae42e0c
refs/heads/master
2021-01-14T08:04:27.266872
2017-02-14T07:40:32
2017-02-14T07:40:32
81,914,629
0
0
null
null
null
null
UTF-8
C++
false
false
109
cpp
#include<iostream> #include<string.h> #include"Frame.h" using namespace std; int main() { return 0; }
[ "moseslinda@outlook.com" ]
moseslinda@outlook.com
3d131231382daee724d4e5517815ff2723ece495
9bda8d73046d34e699a3c0cc6afef60856c132cb
/src/net.cpp
9fe614266489423ac04fc71945c481b8435943ac
[ "MIT" ]
permissive
artcoindev/ArtCoin
a92761542a990e3204f9e54d5d3b12df50065af2
89cf2a9989c7e10605d39bf9ca772bd8532e85a9
refs/heads/master
2020-07-18T22:44:10.437747
2016-11-28T08:54:30
2016-11-28T08:54:30
73,916,406
0
0
null
null
null
null
UTF-8
C++
false
false
60,202
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "irc.h" #include "db.h" #include "net.h" #include "init.h" #include "strlcpy.h" #include "addrman.h" #include "ui_interface.h" #ifdef WIN32 #include <string.h> #endif #ifdef USE_UPNP #include <miniupnpc/miniwget.h> #include <miniupnpc/miniupnpc.h> #include <miniupnpc/upnpcommands.h> #include <miniupnpc/upnperrors.h> #endif using namespace std; using namespace boost; static const int MAX_OUTBOUND_CONNECTIONS = 16; void ThreadMessageHandler2(void* parg); void ThreadSocketHandler2(void* parg); void ThreadOpenConnections2(void* parg); void ThreadOpenAddedConnections2(void* parg); #ifdef USE_UPNP void ThreadMapPort2(void* parg); #endif void ThreadDNSAddressSeed2(void* parg); bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false); struct LocalServiceInfo { int nScore; int nPort; }; // // Global state variables // bool fClient = false; bool fDiscover = true; bool fUseUPnP = false; uint64_t nLocalServices = (fClient ? 0 : NODE_NETWORK); static CCriticalSection cs_mapLocalHost; static map<CNetAddr, LocalServiceInfo> mapLocalHost; static bool vfReachable[NET_MAX] = {}; static bool vfLimited[NET_MAX] = {}; static CNode* pnodeLocalHost = NULL; CAddress addrSeenByPeer(CService("0.0.0.0", 0), nLocalServices); uint64_t nLocalHostNonce = 0; array<int, THREAD_MAX> vnThreadsRunning; static std::vector<SOCKET> vhListenSocket; CAddrMan addrman; vector<CNode*> vNodes; CCriticalSection cs_vNodes; map<CInv, CDataStream> mapRelay; deque<pair<int64_t, CInv> > vRelayExpiration; CCriticalSection cs_mapRelay; map<CInv, int64_t> mapAlreadyAskedFor; static deque<string> vOneShots; CCriticalSection cs_vOneShots; set<CNetAddr> setservAddNodeAddresses; CCriticalSection cs_setservAddNodeAddresses; static CSemaphore *semOutbound = NULL; void AddOneShot(string strDest) { LOCK(cs_vOneShots); vOneShots.push_back(strDest); } unsigned short GetListenPort() { return (unsigned short)(GetArg("-port", GetDefaultPort())); } void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd) { // Filter out duplicate requests if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd) return; pindexLastGetBlocksBegin = pindexBegin; hashLastGetBlocksEnd = hashEnd; PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd); } // find 'best' local address for a particular peer bool GetLocal(CService& addr, const CNetAddr *paddrPeer) { if (fNoListen) return false; int nBestScore = -1; int nBestReachability = -1; { LOCK(cs_mapLocalHost); for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++) { int nScore = (*it).second.nScore; int nReachability = (*it).first.GetReachabilityFrom(paddrPeer); if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) { addr = CService((*it).first, (*it).second.nPort); nBestReachability = nReachability; nBestScore = nScore; } } } return nBestScore >= 0; } // get best local address for a particular peer as a CAddress CAddress GetLocalAddress(const CNetAddr *paddrPeer) { CAddress ret(CService("0.0.0.0",0),0); CService addr; if (GetLocal(addr, paddrPeer)) { ret = CAddress(addr); ret.nServices = nLocalServices; ret.nTime = GetAdjustedTime(); } return ret; } bool RecvLine(SOCKET hSocket, string& strLine) { strLine = ""; while (true) { char c; int nBytes = recv(hSocket, &c, 1, 0); if (nBytes > 0) { if (c == '\n') continue; if (c == '\r') return true; strLine += c; if (strLine.size() >= 9000) return true; } else if (nBytes <= 0) { if (fShutdown) return false; if (nBytes < 0) { int nErr = WSAGetLastError(); if (nErr == WSAEMSGSIZE) continue; if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS) { MilliSleep(10); continue; } } if (!strLine.empty()) return true; if (nBytes == 0) { // socket closed printf("socket closed\n"); return false; } else { // socket error int nErr = WSAGetLastError(); printf("recv failed: %d\n", nErr); return false; } } } } // used when scores of local addresses may have changed // pushes better local address to peers void static AdvertizeLocal() { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->fSuccessfullyConnected) { CAddress addrLocal = GetLocalAddress(&pnode->addr); if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal) { pnode->PushAddress(addrLocal); pnode->addrLocal = addrLocal; } } } } void SetReachable(enum Network net, bool fFlag) { LOCK(cs_mapLocalHost); vfReachable[net] = fFlag; if (net == NET_IPV6 && fFlag) vfReachable[NET_IPV4] = true; } // learn a new local address bool AddLocal(const CService& addr, int nScore) { if (!addr.IsRoutable()) return false; if (!fDiscover && nScore < LOCAL_MANUAL) return false; if (IsLimited(addr)) return false; printf("AddLocal(%s,%i)\n", addr.ToString().c_str(), nScore); { LOCK(cs_mapLocalHost); bool fAlready = mapLocalHost.count(addr) > 0; LocalServiceInfo &info = mapLocalHost[addr]; if (!fAlready || nScore >= info.nScore) { info.nScore = nScore + (fAlready ? 1 : 0); info.nPort = addr.GetPort(); } SetReachable(addr.GetNetwork()); } AdvertizeLocal(); return true; } bool AddLocal(const CNetAddr &addr, int nScore) { return AddLocal(CService(addr, GetListenPort()), nScore); } /** Make a particular network entirely off-limits (no automatic connects to it) */ void SetLimited(enum Network net, bool fLimited) { if (net == NET_UNROUTABLE) return; LOCK(cs_mapLocalHost); vfLimited[net] = fLimited; } bool IsLimited(enum Network net) { LOCK(cs_mapLocalHost); return vfLimited[net]; } bool IsLimited(const CNetAddr &addr) { return IsLimited(addr.GetNetwork()); } /** vote for a local address */ bool SeenLocal(const CService& addr) { { LOCK(cs_mapLocalHost); if (mapLocalHost.count(addr) == 0) return false; mapLocalHost[addr].nScore++; } AdvertizeLocal(); return true; } /** check whether a given address is potentially local */ bool IsLocal(const CService& addr) { LOCK(cs_mapLocalHost); return mapLocalHost.count(addr) > 0; } /** check whether a given address is in a network we can probably connect to */ bool IsReachable(const CNetAddr& addr) { LOCK(cs_mapLocalHost); enum Network net = addr.GetNetwork(); return vfReachable[net] && !vfLimited[net]; } bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet) { SOCKET hSocket; if (!ConnectSocket(addrConnect, hSocket)) return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str()); send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL); string strLine; while (RecvLine(hSocket, strLine)) { if (strLine.empty()) // HTTP response is separated from headers by blank line { while (true) { if (!RecvLine(hSocket, strLine)) { closesocket(hSocket); return false; } if (pszKeyword == NULL) break; if (strLine.find(pszKeyword) != string::npos) { strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword)); break; } } closesocket(hSocket); if (strLine.find("<") != string::npos) strLine = strLine.substr(0, strLine.find("<")); strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r")); while (strLine.size() > 0 && isspace(strLine[strLine.size()-1])) strLine.resize(strLine.size()-1); CService addr(strLine,0,true); printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str()); if (!addr.IsValid() || !addr.IsRoutable()) return false; ipRet.SetIP(addr); return true; } } closesocket(hSocket); return error("GetMyExternalIP() : connection closed"); } // We now get our external IP from the IRC server first and only use this as a backup bool GetMyExternalIP(CNetAddr& ipRet) { CService addrConnect; const char* pszGet; const char* pszKeyword; for (int nLookup = 0; nLookup <= 1; nLookup++) for (int nHost = 1; nHost <= 2; nHost++) { // We should be phasing out our use of sites like these. If we need // replacements, we should ask for volunteers to put this simple // php file on their web server that prints the client IP: // <?php echo $_SERVER["REMOTE_ADDR"]; ?> if (nHost == 1) { addrConnect = CService("91.198.22.70",80); // checkip.dyndns.org if (nLookup == 1) { CService addrIP("checkip.dyndns.org", 80, true); if (addrIP.IsValid()) addrConnect = addrIP; } pszGet = "GET / HTTP/1.1\r\n" "Host: checkip.dyndns.org\r\n" "User-Agent: artcoin\r\n" "Connection: close\r\n" "\r\n"; pszKeyword = "Address:"; } else if (nHost == 2) { addrConnect = CService("74.208.43.192", 80); // www.showmyip.com if (nLookup == 1) { CService addrIP("www.showmyip.com", 80, true); if (addrIP.IsValid()) addrConnect = addrIP; } pszGet = "GET /simple/ HTTP/1.1\r\n" "Host: www.showmyip.com\r\n" "User-Agent: artcoin\r\n" "Connection: close\r\n" "\r\n"; pszKeyword = NULL; // Returns just IP address } if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet)) return true; } return false; } void ThreadGetMyExternalIP(void* parg) { // Make this thread recognisable as the external IP detection thread RenameThread("artcoin-ext-ip"); CNetAddr addrLocalHost; if (GetMyExternalIP(addrLocalHost)) { printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str()); AddLocal(addrLocalHost, LOCAL_HTTP); } } void AddressCurrentlyConnected(const CService& addr) { addrman.Connected(addr); } CNode* FindNode(const CNetAddr& ip) { { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if ((CNetAddr)pnode->addr == ip) return (pnode); } return NULL; } CNode* FindNode(std::string addrName) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->addrName == addrName) return (pnode); return NULL; } CNode* FindNode(const CService& addr) { { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if ((CService)pnode->addr == addr) return (pnode); } return NULL; } CNode* ConnectNode(CAddress addrConnect, const char *pszDest) { if (pszDest == NULL) { if (IsLocal(addrConnect)) return NULL; // Look for an existing connection CNode* pnode = FindNode((CService)addrConnect); if (pnode) { pnode->AddRef(); return pnode; } } /// debug print printf("trying connection %s lastseen=%.1fhrs\n", pszDest ? pszDest : addrConnect.ToString().c_str(), pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0); // Connect SOCKET hSocket; if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, GetDefaultPort()) : ConnectSocket(addrConnect, hSocket)) { addrman.Attempt(addrConnect); /// debug print printf("connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str()); // Set to non-blocking #ifdef WIN32 u_long nOne = 1; if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) printf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %d\n", WSAGetLastError()); #else if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR) printf("ConnectSocket() : fcntl non-blocking setting failed, error %d\n", errno); #endif // Add node CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false); pnode->AddRef(); { LOCK(cs_vNodes); vNodes.push_back(pnode); } pnode->nTimeConnected = GetTime(); return pnode; } else { return NULL; } } void CNode::CloseSocketDisconnect() { fDisconnect = true; if (hSocket != INVALID_SOCKET) { printf("disconnecting node %s\n", addrName.c_str()); closesocket(hSocket); hSocket = INVALID_SOCKET; vRecv.clear(); } } void CNode::Cleanup() { } void CNode::PushVersion() { /// when NTP implemented, change to just nTime = GetAdjustedTime() int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime()); CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0))); CAddress addrMe = GetLocalAddress(&addr); RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce)); printf("send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString().c_str(), addrYou.ToString().c_str(), addr.ToString().c_str()); PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe, nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight); } std::map<CNetAddr, int64_t> CNode::setBanned; CCriticalSection CNode::cs_setBanned; void CNode::ClearBanned() { setBanned.clear(); } bool CNode::IsBanned(CNetAddr ip) { bool fResult = false; { LOCK(cs_setBanned); std::map<CNetAddr, int64_t>::iterator i = setBanned.find(ip); if (i != setBanned.end()) { int64_t t = (*i).second; if (GetTime() < t) fResult = true; } } return fResult; } bool CNode::Misbehaving(int howmuch) { if (addr.IsLocal()) { printf("Warning: Local node %s misbehaving (delta: %d)!\n", addrName.c_str(), howmuch); return false; } nMisbehavior += howmuch; if (nMisbehavior >= GetArg("-banscore", 100)) { int64_t banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban printf("Misbehaving: %s (%d -> %d) DISCONNECTING\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior); { LOCK(cs_setBanned); if (setBanned[addr] < banTime) setBanned[addr] = banTime; } CloseSocketDisconnect(); return true; } else printf("Misbehaving: %s (%d -> %d)\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior); return false; } #undef X #define X(name) stats.name = name void CNode::copyStats(CNodeStats &stats) { X(nServices); X(nLastSend); X(nLastRecv); X(nTimeConnected); X(addrName); X(nVersion); X(strSubVer); X(fInbound); X(nStartingHeight); X(nMisbehavior); } #undef X void ThreadSocketHandler(void* parg) { // Make this thread recognisable as the networking thread RenameThread("artcoin-net"); try { vnThreadsRunning[THREAD_SOCKETHANDLER]++; ThreadSocketHandler2(parg); vnThreadsRunning[THREAD_SOCKETHANDLER]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_SOCKETHANDLER]--; PrintException(&e, "ThreadSocketHandler()"); } catch (...) { vnThreadsRunning[THREAD_SOCKETHANDLER]--; throw; // support pthread_cancel() } printf("ThreadSocketHandler exited\n"); } void ThreadSocketHandler2(void* parg) { printf("ThreadSocketHandler started\n"); list<CNode*> vNodesDisconnected; unsigned int nPrevNodeCount = 0; while (true) { // // Disconnect nodes // { LOCK(cs_vNodes); // Disconnect unused nodes vector<CNode*> vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) { if (pnode->fDisconnect || (pnode->GetRefCount() <= 0 && pnode->vRecv.empty() && pnode->vSend.empty())) { // remove from vNodes vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end()); // release outbound grant (if any) pnode->grantOutbound.Release(); // close socket and cleanup pnode->CloseSocketDisconnect(); pnode->Cleanup(); // hold in disconnected pool until all refs are released if (pnode->fNetworkNode || pnode->fInbound) pnode->Release(); vNodesDisconnected.push_back(pnode); } } // Delete disconnected nodes list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected; BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy) { // wait until threads are done using it if (pnode->GetRefCount() <= 0) { bool fDelete = false; { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) { TRY_LOCK(pnode->cs_vRecv, lockRecv); if (lockRecv) { TRY_LOCK(pnode->cs_mapRequests, lockReq); if (lockReq) { TRY_LOCK(pnode->cs_inventory, lockInv); if (lockInv) fDelete = true; } } } } if (fDelete) { vNodesDisconnected.remove(pnode); delete pnode; } } } } if (vNodes.size() != nPrevNodeCount) { nPrevNodeCount = vNodes.size(); uiInterface.NotifyNumConnectionsChanged(vNodes.size()); } // // Find which sockets have data to receive // struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 50000; // frequency to poll pnode->vSend fd_set fdsetRecv; fd_set fdsetSend; fd_set fdsetError; FD_ZERO(&fdsetRecv); FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); SOCKET hSocketMax = 0; bool have_fds = false; BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) { FD_SET(hListenSocket, &fdsetRecv); hSocketMax = max(hSocketMax, hListenSocket); have_fds = true; } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->hSocket == INVALID_SOCKET) continue; FD_SET(pnode->hSocket, &fdsetRecv); FD_SET(pnode->hSocket, &fdsetError); hSocketMax = max(hSocketMax, pnode->hSocket); have_fds = true; { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend && !pnode->vSend.empty()) FD_SET(pnode->hSocket, &fdsetSend); } } } vnThreadsRunning[THREAD_SOCKETHANDLER]--; int nSelect = select(have_fds ? hSocketMax + 1 : 0, &fdsetRecv, &fdsetSend, &fdsetError, &timeout); vnThreadsRunning[THREAD_SOCKETHANDLER]++; if (fShutdown) return; if (nSelect == SOCKET_ERROR) { if (have_fds) { int nErr = WSAGetLastError(); printf("socket select error %d\n", nErr); for (unsigned int i = 0; i <= hSocketMax; i++) FD_SET(i, &fdsetRecv); } FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); MilliSleep(timeout.tv_usec/1000); } // // Accept new connections // BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv)) { #ifdef USE_IPV6 struct sockaddr_storage sockaddr; #else struct sockaddr sockaddr; #endif socklen_t len = sizeof(sockaddr); SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len); CAddress addr; int nInbound = 0; if (hSocket != INVALID_SOCKET) if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr)) printf("Warning: Unknown socket family\n"); { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->fInbound) nInbound++; } if (hSocket == INVALID_SOCKET) { int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK) printf("socket error accept failed: %d\n", nErr); } else if (nInbound >= GetArg("-maxconnections", 125) - MAX_OUTBOUND_CONNECTIONS) { closesocket(hSocket); } else if (CNode::IsBanned(addr)) { printf("connection from %s dropped (banned)\n", addr.ToString().c_str()); closesocket(hSocket); } else { printf("accepted connection %s\n", addr.ToString().c_str()); CNode* pnode = new CNode(hSocket, addr, "", true); pnode->AddRef(); { LOCK(cs_vNodes); vNodes.push_back(pnode); } } } // // Service each socket // vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->AddRef(); } BOOST_FOREACH(CNode* pnode, vNodesCopy) { if (fShutdown) return; // // Receive // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError)) { TRY_LOCK(pnode->cs_vRecv, lockRecv); if (lockRecv) { CDataStream& vRecv = pnode->vRecv; unsigned int nPos = vRecv.size(); if (nPos > ReceiveBufferSize()) { if (!pnode->fDisconnect) printf("socket recv flood control disconnect (%"PRIszu" bytes)\n", vRecv.size()); pnode->CloseSocketDisconnect(); } else { // typical socket buffer is 8K-64K char pchBuf[0x10000]; int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT); if (nBytes > 0) { vRecv.resize(nPos + nBytes); memcpy(&vRecv[nPos], pchBuf, nBytes); pnode->nLastRecv = GetTime(); } else if (nBytes == 0) { // socket closed gracefully if (!pnode->fDisconnect) printf("socket closed\n"); pnode->CloseSocketDisconnect(); } else if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { if (!pnode->fDisconnect) printf("socket recv error %d\n", nErr); pnode->CloseSocketDisconnect(); } } } } } // // Send // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetSend)) { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) { CDataStream& vSend = pnode->vSend; if (!vSend.empty()) { int nBytes = send(pnode->hSocket, &vSend[0], vSend.size(), MSG_NOSIGNAL | MSG_DONTWAIT); if (nBytes > 0) { vSend.erase(vSend.begin(), vSend.begin() + nBytes); pnode->nLastSend = GetTime(); } else if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { printf("socket send error %d\n", nErr); pnode->CloseSocketDisconnect(); } } } } } // // Inactivity checking // if (pnode->vSend.empty()) pnode->nLastSendEmpty = GetTime(); if (GetTime() - pnode->nTimeConnected > 60) { if (pnode->nLastRecv == 0 || pnode->nLastSend == 0) { printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0); pnode->fDisconnect = true; } else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60) { printf("socket not sending\n"); pnode->fDisconnect = true; } else if (GetTime() - pnode->nLastRecv > 90*60) { printf("socket inactivity timeout\n"); pnode->fDisconnect = true; } } } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->Release(); } MilliSleep(10); } } #ifdef USE_UPNP void ThreadMapPort(void* parg) { // Make this thread recognisable as the UPnP thread RenameThread("artcoin-UPnP"); try { vnThreadsRunning[THREAD_UPNP]++; ThreadMapPort2(parg); vnThreadsRunning[THREAD_UPNP]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_UPNP]--; PrintException(&e, "ThreadMapPort()"); } catch (...) { vnThreadsRunning[THREAD_UPNP]--; PrintException(NULL, "ThreadMapPort()"); } printf("ThreadMapPort exited\n"); } void ThreadMapPort2(void* parg) { printf("ThreadMapPort started\n"); std::string port = strprintf("%u", GetListenPort()); const char * multicastif = 0; const char * minissdpdpath = 0; struct UPNPDev * devlist = 0; char lanaddr[64]; #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0); #else /* miniupnpc 1.6 */ int error = 0; devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error); #endif struct UPNPUrls urls; struct IGDdatas data; int r; r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr)); if (r == 1) { if (fDiscover) { char externalIPAddress[40]; r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress); if(r != UPNPCOMMAND_SUCCESS) printf("UPnP: GetExternalIPAddress() returned %d\n", r); else { if(externalIPAddress[0]) { printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress); AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP); } else printf("UPnP: GetExternalIPAddress failed.\n"); } } string strDesc = "artcoin " + FormatFullVersion(); #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0); #else /* miniupnpc 1.6 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0"); #endif if(r!=UPNPCOMMAND_SUCCESS) printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n", port.c_str(), port.c_str(), lanaddr, r, strupnperror(r)); else printf("UPnP Port Mapping successful.\n"); int i = 1; while (true) { if (fShutdown || !fUseUPnP) { r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0); printf("UPNP_DeletePortMapping() returned : %d\n", r); freeUPNPDevlist(devlist); devlist = 0; FreeUPNPUrls(&urls); return; } if (i % 600 == 0) // Refresh every 20 minutes { #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0); #else /* miniupnpc 1.6 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0"); #endif if(r!=UPNPCOMMAND_SUCCESS) printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n", port.c_str(), port.c_str(), lanaddr, r, strupnperror(r)); else printf("UPnP Port Mapping successful.\n");; } MilliSleep(2000); i++; } } else { printf("No valid UPnP IGDs found\n"); freeUPNPDevlist(devlist); devlist = 0; if (r != 0) FreeUPNPUrls(&urls); while (true) { if (fShutdown || !fUseUPnP) return; MilliSleep(2000); } } } void MapPort() { if (fUseUPnP && vnThreadsRunning[THREAD_UPNP] < 1) { if (!NewThread(ThreadMapPort, NULL)) printf("Error: ThreadMapPort(ThreadMapPort) failed\n"); } } #else void MapPort() { // Intentionally left blank. } #endif // DNS seeds // Each pair gives a source name and a seed name. // The first name is used as information source for addrman. // The second name should resolve to a list of seed addresses. static const char *strDNSSeed[][2] = { {"artcoin.mooo.com", "artcoin.mooo.com"}, }; void ThreadDNSAddressSeed(void* parg) { // Make this thread recognisable as the DNS seeding thread RenameThread("artcoin-dnsseed"); try { vnThreadsRunning[THREAD_DNSSEED]++; ThreadDNSAddressSeed2(parg); vnThreadsRunning[THREAD_DNSSEED]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_DNSSEED]--; PrintException(&e, "ThreadDNSAddressSeed()"); } catch (...) { vnThreadsRunning[THREAD_DNSSEED]--; throw; // support pthread_cancel() } printf("ThreadDNSAddressSeed exited\n"); } void ThreadDNSAddressSeed2(void* parg) { printf("ThreadDNSAddressSeed started\n"); int found = 0; if (!fTestNet) { printf("Loading addresses from DNS seeds (could take a while)\n"); for (unsigned int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) { if (HaveNameProxy()) { AddOneShot(strDNSSeed[seed_idx][1]); } else { vector<CNetAddr> vaddr; vector<CAddress> vAdd; if (LookupHost(strDNSSeed[seed_idx][1], vaddr)) { BOOST_FOREACH(CNetAddr& ip, vaddr) { int nOneDay = 24*3600; CAddress addr = CAddress(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old vAdd.push_back(addr); found++; } } addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true)); } } } printf("%d addresses found from DNS seeds\n", found); } unsigned int pnSeed[] = { 0xdf4bd379, 0x7934d29b, 0x26bc02ad, 0x7ab743ad, 0x0ab3a7bc, 0x375ab5bc, 0xc90b1617, 0x5352fd17, 0x5efc6c18, 0xccdc7d18, 0x443d9118, 0x84031b18, 0x347c1e18, 0x86512418, 0xfcfe9031, 0xdb5eb936, 0xef8d2e3a, 0xcf51f23c, 0x18ab663e, 0x36e0df40, 0xde48b641, 0xad3e4e41, 0xd0f32b44, 0x09733b44, 0x6a51f545, 0xe593ef48, 0xc5f5ef48, 0x96f4f148, 0xd354d34a, 0x36206f4c, 0xceefe953, 0x50468c55, 0x89d38d55, 0x65e61a5a, 0x16b1b95d, 0x702b135e, 0x0f57245e, 0xdaab5f5f, 0xba15ef63, }; void DumpAddresses() { int64_t nStart = GetTimeMillis(); CAddrDB adb; adb.Write(addrman); printf("Flushed %d addresses to peers.dat %"PRId64"ms\n", addrman.size(), GetTimeMillis() - nStart); } void ThreadDumpAddress2(void* parg) { vnThreadsRunning[THREAD_DUMPADDRESS]++; while (!fShutdown) { DumpAddresses(); vnThreadsRunning[THREAD_DUMPADDRESS]--; MilliSleep(600000); vnThreadsRunning[THREAD_DUMPADDRESS]++; } vnThreadsRunning[THREAD_DUMPADDRESS]--; } void ThreadDumpAddress(void* parg) { // Make this thread recognisable as the address dumping thread RenameThread("artcoin-adrdump"); try { ThreadDumpAddress2(parg); } catch (std::exception& e) { PrintException(&e, "ThreadDumpAddress()"); } printf("ThreadDumpAddress exited\n"); } void ThreadOpenConnections(void* parg) { // Make this thread recognisable as the connection opening thread RenameThread("artcoin-opencon"); try { vnThreadsRunning[THREAD_OPENCONNECTIONS]++; ThreadOpenConnections2(parg); vnThreadsRunning[THREAD_OPENCONNECTIONS]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_OPENCONNECTIONS]--; PrintException(&e, "ThreadOpenConnections()"); } catch (...) { vnThreadsRunning[THREAD_OPENCONNECTIONS]--; PrintException(NULL, "ThreadOpenConnections()"); } printf("ThreadOpenConnections exited\n"); } void static ProcessOneShot() { string strDest; { LOCK(cs_vOneShots); if (vOneShots.empty()) return; strDest = vOneShots.front(); vOneShots.pop_front(); } CAddress addr; CSemaphoreGrant grant(*semOutbound, true); if (grant) { if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true)) AddOneShot(strDest); } } void static ThreadStakeMiner(void* parg) { printf("ThreadStakeMiner started\n"); CWallet* pwallet = (CWallet*)parg; try { vnThreadsRunning[THREAD_STAKE_MINER]++; StakeMiner(pwallet); vnThreadsRunning[THREAD_STAKE_MINER]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_STAKE_MINER]--; PrintException(&e, "ThreadStakeMiner()"); } catch (...) { vnThreadsRunning[THREAD_STAKE_MINER]--; PrintException(NULL, "ThreadStakeMiner()"); } printf("ThreadStakeMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_STAKE_MINER]); } void ThreadOpenConnections2(void* parg) { printf("ThreadOpenConnections started\n"); // Connect to specific addresses if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { for (int64_t nLoop = 0;; nLoop++) { ProcessOneShot(); BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"]) { CAddress addr; OpenNetworkConnection(addr, NULL, strAddr.c_str()); for (int i = 0; i < 10 && i < nLoop; i++) { MilliSleep(500); if (fShutdown) return; } } MilliSleep(500); } } // Initiate network connections int64_t nStart = GetTime(); while (true) { ProcessOneShot(); vnThreadsRunning[THREAD_OPENCONNECTIONS]--; MilliSleep(500); vnThreadsRunning[THREAD_OPENCONNECTIONS]++; if (fShutdown) return; vnThreadsRunning[THREAD_OPENCONNECTIONS]--; CSemaphoreGrant grant(*semOutbound); vnThreadsRunning[THREAD_OPENCONNECTIONS]++; if (fShutdown) return; // Add seed nodes if IRC isn't working if (addrman.size()==0 && (GetTime() - nStart > 60) && !fTestNet) { std::vector<CAddress> vAdd; for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek; vAdd.push_back(addr); } addrman.Add(vAdd, CNetAddr("127.0.0.1")); } // // Choose an address to connect to based on most recently seen // CAddress addrConnect; // Only connect out to one peer per network group (/16 for IPv4). // Do this here so we don't have to critsect vNodes inside mapAddresses critsect. int nOutbound = 0; set<vector<unsigned char> > setConnected; { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (!pnode->fInbound) { setConnected.insert(pnode->addr.GetGroup()); nOutbound++; } } } int64_t nANow = GetAdjustedTime(); int nTries = 0; while (true) { // use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections) CAddress addr = addrman.Select(10 + min(nOutbound,8)*10); // if we selected an invalid address, restart if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr)) break; // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman, // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates // already-connected network ranges, ...) before trying new addrman addresses. nTries++; if (nTries > 100) break; if (IsLimited(addr)) continue; // only consider very recently tried nodes after 30 failed attempts if (nANow - addr.nLastTry < 600 && nTries < 30) continue; // do not allow non-default ports, unless after 50 invalid addresses selected already if (addr.GetPort() != GetDefaultPort() && nTries < 50) continue; addrConnect = addr; break; } if (addrConnect.IsValid()) OpenNetworkConnection(addrConnect, &grant); } } void ThreadOpenAddedConnections(void* parg) { // Make this thread recognisable as the connection opening thread RenameThread("artcoin-opencon"); try { vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++; ThreadOpenAddedConnections2(parg); vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--; PrintException(&e, "ThreadOpenAddedConnections()"); } catch (...) { vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--; PrintException(NULL, "ThreadOpenAddedConnections()"); } printf("ThreadOpenAddedConnections exited\n"); } void ThreadOpenAddedConnections2(void* parg) { printf("ThreadOpenAddedConnections started\n"); if (mapArgs.count("-addnode") == 0) return; if (HaveNameProxy()) { while(!fShutdown) { BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) { CAddress addr; CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(addr, &grant, strAddNode.c_str()); MilliSleep(500); } vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--; MilliSleep(120000); // Retry every 2 minutes vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++; } return; } vector<vector<CService> > vservAddressesToAdd(0); BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) { vector<CService> vservNode(0); if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0)) { vservAddressesToAdd.push_back(vservNode); { LOCK(cs_setservAddNodeAddresses); BOOST_FOREACH(CService& serv, vservNode) setservAddNodeAddresses.insert(serv); } } } while (true) { vector<vector<CService> > vservConnectAddresses = vservAddressesToAdd; // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry // (keeping in mind that addnode entries can have many IPs if fNameLookup) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) for (vector<vector<CService> >::iterator it = vservConnectAddresses.begin(); it != vservConnectAddresses.end(); it++) BOOST_FOREACH(CService& addrNode, *(it)) if (pnode->addr == addrNode) { it = vservConnectAddresses.erase(it); it--; break; } } BOOST_FOREACH(vector<CService>& vserv, vservConnectAddresses) { CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(CAddress(*(vserv.begin())), &grant); MilliSleep(500); if (fShutdown) return; } if (fShutdown) return; vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--; MilliSleep(120000); // Retry every 2 minutes vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++; if (fShutdown) return; } } // if successful, this moves the passed grant to the constructed node bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot) { // // Initiate outbound network connection // if (fShutdown) return false; if (!strDest) if (IsLocal(addrConnect) || FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) || FindNode(addrConnect.ToStringIPPort().c_str())) return false; if (strDest && FindNode(strDest)) return false; vnThreadsRunning[THREAD_OPENCONNECTIONS]--; CNode* pnode = ConnectNode(addrConnect, strDest); vnThreadsRunning[THREAD_OPENCONNECTIONS]++; if (fShutdown) return false; if (!pnode) return false; if (grantOutbound) grantOutbound->MoveTo(pnode->grantOutbound); pnode->fNetworkNode = true; if (fOneShot) pnode->fOneShot = true; return true; } void ThreadMessageHandler(void* parg) { // Make this thread recognisable as the message handling thread RenameThread("artcoin-msghand"); try { vnThreadsRunning[THREAD_MESSAGEHANDLER]++; ThreadMessageHandler2(parg); vnThreadsRunning[THREAD_MESSAGEHANDLER]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_MESSAGEHANDLER]--; PrintException(&e, "ThreadMessageHandler()"); } catch (...) { vnThreadsRunning[THREAD_MESSAGEHANDLER]--; PrintException(NULL, "ThreadMessageHandler()"); } printf("ThreadMessageHandler exited\n"); } void ThreadMessageHandler2(void* parg) { printf("ThreadMessageHandler started\n"); SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL); while (!fShutdown) { vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->AddRef(); } // Poll the connected nodes for messages CNode* pnodeTrickle = NULL; if (!vNodesCopy.empty()) pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())]; BOOST_FOREACH(CNode* pnode, vNodesCopy) { // Receive messages { TRY_LOCK(pnode->cs_vRecv, lockRecv); if (lockRecv) ProcessMessages(pnode); } if (fShutdown) return; // Send messages { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) SendMessages(pnode, pnode == pnodeTrickle); } if (fShutdown) return; } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->Release(); } // Wait and allow messages to bunch up. // Reduce vnThreadsRunning so StopNode has permission to exit while // we're sleeping, but we must always check fShutdown after doing this. vnThreadsRunning[THREAD_MESSAGEHANDLER]--; MilliSleep(100); if (fRequestShutdown) StartShutdown(); vnThreadsRunning[THREAD_MESSAGEHANDLER]++; if (fShutdown) return; } } bool BindListenPort(const CService &addrBind, string& strError) { strError = ""; int nOne = 1; #ifdef WIN32 // Initialize Windows Sockets WSADATA wsadata; int ret = WSAStartup(MAKEWORD(2,2), &wsadata); if (ret != NO_ERROR) { strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret); printf("%s\n", strError.c_str()); return false; } #endif // Create socket for listening for incoming connections #ifdef USE_IPV6 struct sockaddr_storage sockaddr; #else struct sockaddr sockaddr; #endif socklen_t len = sizeof(sockaddr); if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len)) { strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str()); printf("%s\n", strError.c_str()); return false; } SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP); if (hListenSocket == INVALID_SOCKET) { strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError()); printf("%s\n", strError.c_str()); return false; } #ifdef SO_NOSIGPIPE // Different way of disabling SIGPIPE on BSD setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int)); #endif #ifndef WIN32 // Allow binding if the port is still in TIME_WAIT state after // the program was closed and restarted. Not an issue on windows. setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int)); #endif #ifdef WIN32 // Set to non-blocking, incoming connections will also inherit this if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR) #else if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR) #endif { strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError()); printf("%s\n", strError.c_str()); return false; } #ifdef USE_IPV6 // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option // and enable it by default or not. Try to enable it, if possible. if (addrBind.IsIPv6()) { #ifdef IPV6_V6ONLY #ifdef WIN32 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int)); #else setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int)); #endif #endif #ifdef WIN32 int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */; int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */; // this call is allowed to fail setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int)); #endif } #endif if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) { int nErr = WSAGetLastError(); if (nErr == WSAEADDRINUSE) strError = strprintf(_("Unable to bind to %s on this computer. artcoin is probably already running."), addrBind.ToString().c_str()); else strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr)); printf("%s\n", strError.c_str()); return false; } printf("Bound to %s\n", addrBind.ToString().c_str()); // Listen for incoming connections if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR) { strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError()); printf("%s\n", strError.c_str()); return false; } vhListenSocket.push_back(hListenSocket); if (addrBind.IsRoutable() && fDiscover) AddLocal(addrBind, LOCAL_BIND); return true; } void static Discover() { if (!fDiscover) return; #ifdef WIN32 // Get local host IP char pszHostName[1000] = ""; if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) { vector<CNetAddr> vaddr; if (LookupHost(pszHostName, vaddr)) { BOOST_FOREACH (const CNetAddr &addr, vaddr) { AddLocal(addr, LOCAL_IF); } } } #else // Get local host ip struct ifaddrs* myaddrs; if (getifaddrs(&myaddrs) == 0) { for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) continue; if ((ifa->ifa_flags & IFF_UP) == 0) continue; if (strcmp(ifa->ifa_name, "lo") == 0) continue; if (strcmp(ifa->ifa_name, "lo0") == 0) continue; if (ifa->ifa_addr->sa_family == AF_INET) { struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr); CNetAddr addr(s4->sin_addr); if (AddLocal(addr, LOCAL_IF)) printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str()); } #ifdef USE_IPV6 else if (ifa->ifa_addr->sa_family == AF_INET6) { struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr); CNetAddr addr(s6->sin6_addr); if (AddLocal(addr, LOCAL_IF)) printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str()); } #endif } freeifaddrs(myaddrs); } #endif // Don't use external IPv4 discovery, when -onlynet="IPv6" if (!IsLimited(NET_IPV4)) NewThread(ThreadGetMyExternalIP, NULL); } void StartNode(void* parg) { // Make this thread recognisable as the startup thread RenameThread("artcoin-start"); if (semOutbound == NULL) { // initialize semaphore int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125)); semOutbound = new CSemaphore(nMaxOutbound); } if (pnodeLocalHost == NULL) pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices)); Discover(); // // Start threads // if (!GetBoolArg("-dnsseed", true)) printf("DNS seeding disabled\n"); else if (!NewThread(ThreadDNSAddressSeed, NULL)) printf("Error: NewThread(ThreadDNSAddressSeed) failed\n"); // Map ports with UPnP if (fUseUPnP) MapPort(); // Get addresses from IRC and advertise ours if (!NewThread(ThreadIRCSeed, NULL)) printf("Error: NewThread(ThreadIRCSeed) failed\n"); // Send and receive from sockets, accept connections if (!NewThread(ThreadSocketHandler, NULL)) printf("Error: NewThread(ThreadSocketHandler) failed\n"); // Initiate outbound connections from -addnode if (!NewThread(ThreadOpenAddedConnections, NULL)) printf("Error: NewThread(ThreadOpenAddedConnections) failed\n"); // Initiate outbound connections if (!NewThread(ThreadOpenConnections, NULL)) printf("Error: NewThread(ThreadOpenConnections) failed\n"); // Process messages if (!NewThread(ThreadMessageHandler, NULL)) printf("Error: NewThread(ThreadMessageHandler) failed\n"); // Dump network addresses if (!NewThread(ThreadDumpAddress, NULL)) printf("Error; NewThread(ThreadDumpAddress) failed\n"); // Mine proof-of-stake blocks in the background if (!GetBoolArg("-staking", true)) printf("Staking disabled\n"); else if (!NewThread(ThreadStakeMiner, pwalletMain)) printf("Error: NewThread(ThreadStakeMiner) failed\n"); } bool StopNode() { printf("StopNode()\n"); fShutdown = true; nTransactionsUpdated++; int64_t nStart = GetTime(); if (semOutbound) for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++) semOutbound->post(); do { int nThreadsRunning = 0; for (int n = 0; n < THREAD_MAX; n++) nThreadsRunning += vnThreadsRunning[n]; if (nThreadsRunning == 0) break; if (GetTime() - nStart > 20) break; MilliSleep(20); } while(true); if (vnThreadsRunning[THREAD_SOCKETHANDLER] > 0) printf("ThreadSocketHandler still running\n"); if (vnThreadsRunning[THREAD_OPENCONNECTIONS] > 0) printf("ThreadOpenConnections still running\n"); if (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0) printf("ThreadMessageHandler still running\n"); if (vnThreadsRunning[THREAD_RPCLISTENER] > 0) printf("ThreadRPCListener still running\n"); if (vnThreadsRunning[THREAD_RPCHANDLER] > 0) printf("ThreadsRPCServer still running\n"); #ifdef USE_UPNP if (vnThreadsRunning[THREAD_UPNP] > 0) printf("ThreadMapPort still running\n"); #endif if (vnThreadsRunning[THREAD_DNSSEED] > 0) printf("ThreadDNSAddressSeed still running\n"); if (vnThreadsRunning[THREAD_ADDEDCONNECTIONS] > 0) printf("ThreadOpenAddedConnections still running\n"); if (vnThreadsRunning[THREAD_DUMPADDRESS] > 0) printf("ThreadDumpAddresses still running\n"); if (vnThreadsRunning[THREAD_STAKE_MINER] > 0) printf("ThreadStakeMiner still running\n"); while (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0 || vnThreadsRunning[THREAD_RPCHANDLER] > 0) MilliSleep(20); MilliSleep(50); DumpAddresses(); return true; } class CNetCleanup { public: CNetCleanup() { } ~CNetCleanup() { // Close sockets BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->hSocket != INVALID_SOCKET) closesocket(pnode->hSocket); BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) if (hListenSocket != INVALID_SOCKET) if (closesocket(hListenSocket) == SOCKET_ERROR) printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError()); #ifdef WIN32 // Shutdown Windows Sockets WSACleanup(); #endif } } instance_of_cnetcleanup; void RelayTransaction(const CTransaction& tx, const uint256& hash) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(10000); ss << tx; RelayTransaction(tx, hash, ss); } void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss) { CInv inv(MSG_TX, hash); { LOCK(cs_mapRelay); // Expire old relay messages while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime()) { mapRelay.erase(vRelayExpiration.front().second); vRelayExpiration.pop_front(); } // Save original serialized message so newer versions are preserved mapRelay.insert(std::make_pair(inv, ss)); vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv)); } RelayInventory(inv); }
[ "blank@email.com" ]
blank@email.com
42fb31069142a4265cbd0f40bc2360f959a267e1
a9e308c81c27a80c53c899ce806d6d7b4a9bbbf3
/engine/xray/render/engine/sources/terrain.cpp
a8b22e00789ee9e20bb2e568a84c2cf812c446e5
[]
no_license
NikitaNikson/xray-2_0
00d8e78112d7b3d5ec1cb790c90f614dc732f633
82b049d2d177aac15e1317cbe281e8c167b8f8d1
refs/heads/master
2023-06-25T16:51:26.243019
2020-09-29T15:49:23
2020-09-29T15:49:23
390,966,305
1
0
null
null
null
null
UTF-8
C++
false
false
15,739
cpp
//////////////////////////////////////////////////////////////////////////// // Created : 04.03.2010 // Author : Armen Abroyan // Copyright (C) GSC Game World - 2010 //////////////////////////////////////////////////////////////////////////// #include "pch.h" #include <xray/render/engine/terrain.h> #include <xray/render/core/resource_manager.h> #include <xray/render/core/effect_manager.h> #include <xray/render/engine/model_manager.h> #include <xray/render/engine/effect_terrain_NEW.h> #include <xray/render/engine/visual.h> #include <xray/fs_utils.h> namespace xray { namespace render_dx10 { static void fill_indexes ( uint2 size, u16* buffer); static u32 fill_vertices ( void* vertex_buffer, u32 vertex_conut, u32 offset, u32 vertex_row_size, float phisical_size, float4x4 transform, render::terrain_data const* t_data, terrain_visual::Textures const& textures); //struct terrain_cell_less_equal_pred //{ // bool operator () ( terrain_cell const& first, u32 id) // { // return first.user_id < id; // } //}; // //struct terrain_cell_equal_pred //{ // terrain_cell_equal_pred ( int id): m_id(id){} // // bool operator () ( terrain_cell const& first) // { // return first.user_id == m_id; // } // //private: // u32 m_id; //}; // D3DVERTEXELEMENT9 terrain_vertex_declaration[] = // { // { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, // pos+uv // { 0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, // { 0, 24, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 }, // { 0, 28, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 1 }, // { 0, 32, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, // { 0, 40, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, // { 0, 48, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 }, // { 0, 56, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD/**/, 3 }, // D3DDECL_END() // }; const u32 terrain_vertex_size = 60; D3D_INPUT_ELEMENT_DESC terrain_vertex_declaration[] = { {"POSITION",0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D_INPUT_PER_VERTEX_DATA, 0}, {"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D_INPUT_PER_VERTEX_DATA, 0}, {"COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, 24, D3D_INPUT_PER_VERTEX_DATA, 0}, {"COLOR", 1, DXGI_FORMAT_R8G8B8A8_UNORM, 0, 28, D3D_INPUT_PER_VERTEX_DATA, 0}, {"TEXCOORD",0, DXGI_FORMAT_R32G32_FLOAT, 0, 32, D3D_INPUT_PER_VERTEX_DATA, 0}, {"TEXCOORD",1, DXGI_FORMAT_R32G32_FLOAT, 0, 40, D3D_INPUT_PER_VERTEX_DATA, 0}, {"TEXCOORD",2, DXGI_FORMAT_R32G32_FLOAT, 0, 48, D3D_INPUT_PER_VERTEX_DATA, 0}, {"TEXCOORD",3, DXGI_FORMAT_R8G8B8A8_UNORM, 0, 56, D3D_INPUT_PER_VERTEX_DATA, 0} }; terrain::terrain(): m_texture_pool ( 1024, 4) { m_intermediate_vertex_stream.create( 1024*1024 ); m_effect = NEW( effect_terrain_NEW); } terrain::~terrain() { DELETE ( m_effect ); } void terrain::add_cell( render::visual_ptr v, bool beditor ) { cells& working_set = (beditor) ? m_editor_cells : m_game_cells; terrain_cell cell; cell.visual = v; cells::iterator it = std::find( working_set.begin(), working_set.end(), v ); ASSERT_U ( it == working_set.end() ); working_set.push_back ( cell); } void terrain::remove_cell(render::visual_ptr v, bool beditor ) { cells& working_set = (beditor) ? m_editor_cells : m_game_cells; cells::iterator it = std::find( working_set.begin(), working_set.end(), v); working_set.erase ( it ); } void terrain::update_cell_buffer( render::visual_ptr visual, xray::vectora<render::buffer_fragment_NEW> const& fragments, float4x4 const& transform) { terrain_visual* v = static_cast_checked<terrain_visual*>(visual.c_ptr()); u8* pLockData = 0; u32 vertex_size = terrain_vertex_size;//D3DXGetDeclVertexSize(terrain_vertex_declaration, 0); u32 lock_start = fragments[0].start*vertex_size; u32 lock_size = (fragments[fragments.size()-1].start+fragments[fragments.size()-1].size)*vertex_size; lock_size -= lock_start; ASSERT( lock_size > 0 ); // --Porting to DX10_ //IDirect3DVertexBuffer9* vb = model_manager::ref().get_vbuffer_by_id( v->vertex_buffer_id); //R_CHK ( vb->Lock( lock_start, lock_size, (void**)&pLockData, 0 ) ); u32 voffset; void* vbuffer; vectora<render::buffer_fragment_NEW>::const_iterator it_frag = fragments.begin(); vectora<render::buffer_fragment_NEW>::const_iterator en_frag = fragments.end(); pLockData = (u8*)v->vb->map( D3D_MAP_READ); v->vb->unmap (); for( ; it_frag != en_frag; ++it_frag) { vbuffer = m_intermediate_vertex_stream.lock( it_frag->size, vertex_size, voffset); fill_vertices( vbuffer, it_frag->size, it_frag->start, v->vertex_row_size, v->phisical_size, transform, &(it_frag->buffer[0]), v->textures); m_intermediate_vertex_stream.unlock(); resource_manager::ref().copy(v->vb, u32(pLockData + it_frag->start*vertex_size), m_intermediate_vertex_stream.buffer(), voffset*vertex_size, it_frag->size*vertex_size); } //m_intermediate_vertex_stream /* pLockData = (u8*)v->vb->map( D3D_MAP_WRITE); vectora<render::buffer_fragment_NEW>::const_iterator it_frag = fragments.begin(); vectora<render::buffer_fragment_NEW>::const_iterator en_frag = fragments.end(); for( ; it_frag != en_frag; ++it_frag) fill_vertices( pLockData + it_frag->start*vertex_size, it_frag->size, it_frag->start, v->vertex_row_size, v->phisical_size, transform, &(it_frag->buffer[0]), v->textures); v->vb->unmap ();*/ } void terrain::add_cell_texture ( render::visual_ptr visual, render::texture_string const & texture, u32 tex_user_id) { terrain_visual* v = static_cast_checked<terrain_visual*>(visual.c_ptr()); int tex_pool_id = m_texture_pool.add_texture( texture); ASSERT ( tex_pool_id>=0); ASSERT ( std::find( v->textures.begin(), v->textures.end(), tex_pool_id) == v->textures.end()); v->textures.resize( math::max( tex_user_id+1, v->textures.size()) , -1 ); v->textures[tex_user_id] = tex_pool_id; } void terrain::remove_cell_texture( render::visual_ptr visual, u32 tex_user_id) { terrain_visual* v = static_cast_checked<terrain_visual*>(visual.c_ptr()); int tex_pool_id = -1; ASSERT( v->textures.size()> tex_user_id); tex_pool_id = v->textures[tex_user_id]; // Mark as unused ASSERT( tex_pool_id >=0); v->textures[tex_user_id] = -1; // Remove void tail int i = int(v->textures.size()-1); for( ; i >= 0; --i) if( v->textures[i] != -1) break; v->textures.resize(i+1); ASSERT( tex_pool_id>=0); if( tex_pool_id <0) return; // Remove texture from the pool if it isn't used any more by other cells. cells::iterator it = m_editor_cells.begin(); cells::const_iterator en = m_editor_cells.end(); for( ; it!= en; ++it) if( v->textures.end() != std::find( v->textures.begin(), v->textures.end(), tex_pool_id)) return; m_texture_pool.remove_texture( tex_pool_id); } void terrain::exchange_texture ( render::texture_string const & old_texture, render::texture_string const & new_texture) { m_texture_pool.exchange_texture( old_texture, new_texture); } render::visual_ptr terrain::get_cell( pcstr cell_id) { cells::const_iterator it = m_editor_cells.begin(); cells::const_iterator it_e = m_editor_cells.end(); // need optimization later for( ; it!= it_e; ++it) { terrain_visual* const v = static_cast_checked<terrain_visual* const>(it->visual.c_ptr()); if(v->name == cell_id) return it->visual; } //.------- m_game_cells.begin(); m_game_cells.end(); // need optimization later for( ; it!= it_e; ++it) { terrain_visual* const v = static_cast_checked<terrain_visual* const>(it->visual.c_ptr()); if(v->name == cell_id) return it->visual; } //.------- return 0; } bool terrain::has_cell( pcstr cell_id) const { cells::const_iterator it = m_editor_cells.begin(); cells::const_iterator it_e = m_editor_cells.end(); // need optimization later for( ; it!= it_e; ++it) { terrain_visual* const v = static_cast_checked<terrain_visual* const>(it->visual.c_ptr()); if(v->name == cell_id) return true; } //.------- it = m_game_cells.begin(); it_e = m_game_cells.end(); // need optimization later for( ; it!= it_e; ++it) { terrain_visual* const v = static_cast_checked<terrain_visual* const>(it->visual.c_ptr()); if(v->name == cell_id) return true; } //.--------- return false; } static u32 fill_vertices( void* vertex_buffer, u32 vertex_count, u32 offset, u32 vertex_row_size, float phisical_size, float4x4 transform, render::terrain_data const* t_data, terrain_visual::Textures const& textures) { ASSERT( vertex_count <= vertex_row_size*vertex_row_size); float inv_row_size = 1.f/vertex_row_size; // { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, // pos+uv // { 0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, // { 0, 24, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 }, // { 0, 28, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 1 }, // { 0, 32, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, // { 0, 40, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, // { 0, 48, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 }, // { 0, 56, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD/**/, 3 }, render::terrain_data const* src_ptr = t_data; char* dst_ptr = (char*)vertex_buffer; for( u32 i = 0; i < vertex_count; ++i, ++src_ptr) { float z = (float)math::floor((i+offset)*inv_row_size); float x = (i+offset)-z*vertex_row_size; x*= phisical_size/(vertex_row_size-1); z*= -phisical_size/(vertex_row_size-1); // writing position *(float3*) dst_ptr = transform.transform_position( float3( x, src_ptr->height, z)); dst_ptr+= sizeof(float3); // writing normal *(float3*) dst_ptr = float3( 0, 1, 0); dst_ptr+= sizeof(float3); u32 c0 = math::color_argb( 0, src_ptr->alpha0, src_ptr->alpha1, src_ptr->alpha2) ; *(u32*) dst_ptr = c0; dst_ptr+= sizeof(u32); u32 color_aaa = src_ptr->color; // u8 const tex_id2 = u8(textures[src_ptr->tex_id2]); // writing diffuse color //color_aaa = (color_aaa&0x00FFFFFF)|(tex_id2<<24); *(u32*) dst_ptr = color_aaa; dst_ptr+= sizeof(u32); // Tex0 coordinates *(float2*) dst_ptr = src_ptr->tex_coord0; dst_ptr+= sizeof(float2); // Tex1 coordinates *(float2*) dst_ptr = src_ptr->tex_coord1; dst_ptr+= sizeof(float2); // Tex2 coordinates *(float2*) dst_ptr = src_ptr->tex_coord2; dst_ptr+= sizeof(float2); // Writing texture indices u32 tex_indices = math::color_argb( 0, u8(textures[src_ptr->tex_id0]), u8(textures[src_ptr->tex_id1]), u8(textures[src_ptr->tex_id2])) ; *(u32*) dst_ptr = tex_indices; dst_ptr+= sizeof(u32); } return vertex_count; } static void fill_indexes( uint2 size, u16* buffer) { u32 ptr = 0; for( u32 i = 0; i< size.y-1; ++i) for( u32 j = 0; j< size.x-1; ++j) { buffer[ptr] = u16(i*size.x+j); ptr++; buffer[ptr] = u16(i*size.x+j+1); ptr++; buffer[ptr] = u16((i+1)*size.x+j); ptr++; buffer[ptr] = u16(i*size.x+j+1); ptr++; buffer[ptr] = u16((i+1)*size.x+j+1); ptr++; buffer[ptr] = u16((i+1)*size.x+j); ptr++; } } terrain_cell_cook::terrain_cell_cook( ) :super( resources::terrain_cell_class, reuse_true, threading::current_thread_id(), threading::current_thread_id() ) {} void terrain_cell_cook::create_resource (resources::query_result_for_cook & in_out_query, const_buffer raw_file_data, mutable_buffer in_out_unmanaged_resource_buffer) { XRAY_UNREFERENCED_PARAMETER (in_out_unmanaged_resource_buffer); fs::path_string cell_name; pcstr req_path = in_out_query.get_requested_path(); xray::fs::file_name_with_no_extension_from_path (&cell_name, req_path); memory::reader F((pbyte)raw_file_data.c_ptr(), raw_file_data.size()); render_dx10::terrain_visual* visual = static_cast_checked<terrain_visual*>(model_manager::ref().create_instance( mt_terrain_cell )); u32 vertex_row_size = F.r_u32(); float phisical_size = F.r_float(); u32 tex_count = F.r_u32(); visual->textures.resize (tex_count); for(u32 tidx = 0; tidx<tex_count; ++tidx) { pcstr texture_name = F.r_string(); int id_tex = terrain::ref().m_texture_pool.add_texture(texture_name); visual->textures[tidx] = id_tex; } float4x4 transform; transform.identity (); transform.i.xyz() = F.r_float3(); transform.j.xyz() = F.r_float3(); transform.k.xyz() = F.r_float3(); transform.c.xyz() = F.r_float3(); u32 vertex_size = terrain_vertex_size;// D3DXGetDeclVertexSize( terrain_vertex_declaration,0); visual->mesh()->vertex_count = math::sqr(vertex_row_size); visual->mesh()->primitive_count = 2*math::sqr(vertex_row_size-1); visual->mesh()->index_count = visual->mesh()->primitive_count*3; void* tmp_buffer = NEW_ARRAY( char, math::max( vertex_size*visual->mesh()->vertex_count, u32(visual->mesh()->index_count*sizeof(u16)) )); // Filling vertices here fill_vertices( tmp_buffer, visual->mesh()->vertex_count, 0, vertex_row_size, phisical_size, transform, (render::terrain_data*)F.pointer(), visual->textures ); // --porting to DX10 // u32 buffer_usage = D3DUSAGE_WRITEONLY; // visual->vertex_buffer_id = model_manager::ref().create_vb ( visual->vertex_count*vertex_size, buffer_usage, tmp_buffer); ref_buffer vb = resource_manager::ref().create_buffer ( visual->mesh()->vertex_count*vertex_size, tmp_buffer, enum_buffer_type_vertex, true); visual->vb = &*vb; visual->mesh()->vertex_base = 0; //Filling indices here fill_indexes( uint2(vertex_row_size,vertex_row_size), (u16*)tmp_buffer); ref_buffer ib = resource_manager::ref().create_buffer ( visual->mesh()->index_count*sizeof(u16), tmp_buffer, enum_buffer_type_index, false); visual->mesh()->index_base = 0; DELETE_ARRAY (tmp_buffer); ref_declaration decl_ptr = resource_manager::ref().create_declaration ( terrain_vertex_declaration); visual->mesh()->geom = resource_manager::ref().create_geometry ( &*decl_ptr, terrain_vertex_size, &*vb, &*ib); visual->m_effect = effect_manager::ref().create_effect ( terrain::ref().m_effect, 0, terrain::ref().m_texture_pool.get_pool_texture_name()); visual->vertex_row_size = vertex_row_size; visual->phisical_size = phisical_size; visual->name = cell_name; in_out_query.set_unmanaged_resource (visual, resources::memory_type_non_cacheable_resource, sizeof(render_dx10::terrain_visual)); in_out_query.finish_query (result_success); } void terrain_cell_cook::destroy_resource (resources::unmanaged_resource* const res) { render_visual * const visual = dynamic_cast<render_visual*>(res); R_ASSERT (visual); model_manager::destroy_instance (visual); } void terrain_cell_cook::create_resource_if_no_file(resources::query_result_for_cook & in_out_query, mutable_buffer in_out_unmanaged_resource_buffer) { XRAY_UNREFERENCED_PARAMETER (in_out_unmanaged_resource_buffer); pcstr cell_name = in_out_query.get_requested_path(); fs::path_string req_path; resources::user_data_variant* v = in_out_query.user_data(); if ( !v ) { in_out_query.finish_query (result_error); return; } pcstr project_name = NULL; if ( !v->try_get(project_name) ) { in_out_query.finish_query (result_error); return; } req_path = "resources/projects/"; req_path += project_name; req_path += "/"; req_path += cell_name; in_out_query.set_request_path ( req_path.c_str() ); in_out_query.finish_query (result_requery); } } // namespace render_dx10 } // namespace xray
[ "loxotron@bk.ru" ]
loxotron@bk.ru
8c0cc54974f9aefc4c3e537ad50ce1ca18df6f88
057eff64adf244988b77b3b68aeeae98f78554cd
/lib/touchgfx/framework/include/touchgfx/containers/buttons/WildcardTextButtonStyle.hpp
54fb2d84227232c45efdff87622643debe77e1a1
[]
no_license
tBeslan/F746_disco_mbed_tgfx
b9c79b87dc79c0772c6969ec902f69af33311a8c
8c6bf13f26b0c90f6f96437d1b5ba0c0d824fc37
refs/heads/master
2022-12-15T21:44:05.185681
2020-09-04T07:58:06
2020-09-04T07:58:06
292,780,121
1
0
null
null
null
null
UTF-8
C++
false
false
4,902
hpp
/** ****************************************************************************** * This file is part of the TouchGFX 4.14.0 distribution. * * <h2><center>&copy; Copyright (c) 2020 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ /** * @file touchgfx/containers/buttons/WildcardTextButtonStyle.hpp * * Declares the touchgfx::WildcardTextButtonStyle class. */ #ifndef WILDCARDTEXTBUTTONSTYLE_HPP #define WILDCARDTEXTBUTTONSTYLE_HPP #include <touchgfx/widgets/TextAreaWithWildcard.hpp> namespace touchgfx { /** * A wildcard text button style. * * An wildcard text button style. This class is supposed to be used with one of the * ButtonTrigger classes to create a functional button. This class will show a text with * a wildcard in one of two colors depending on the state of the button (pressed or * released). * * The WildcardTextButtonStyle does not set the size of the enclosing container * (normally AbstractButtonContainer). The size must be set manually. * * To get a background behind the text, use WildcardTextButtonStyle together with e.g. * ImageButtonStyle: * @code * WildcardTextButtonStyle<ImageButtonStyle<ClickButtonTrigger> > myButton; * @endcode * * The position of the text can be adjusted with setTextXY (default is centered). * * @tparam T Generic type parameter. Typically a AbstractButtonContainer subclass. * * @see AbstractButtonContainer */ template <class T> class WildcardTextButtonStyle : public T { public: WildcardTextButtonStyle() : T() { T::add(wildcardText); } /** * Sets wildcard text. * * @param t A TypedText to process. */ void setWildcardText(TypedText t) { wildcardText.setTypedText(t); wildcardText.setWidth(T::getWidth()); wildcardText.setHeight(T::getHeight()); } /** * Sets wildcard text x coordinate. * * @param x The x coordinate. */ void setWildcardTextX(int16_t x) { wildcardText.setX(x); } /** * Sets wildcard text y coordinate. * * @param y The y coordinate. */ void setWildcardTextY(int16_t y) { wildcardText.setY(y); } /** * Sets wildcard text position. * * @param x The x coordinate. * @param y The y coordinate. */ void setWildcardTextXY(int16_t x, int16_t y) { setWildcardTextX(x); setWildcardTextY(y); } /** * Sets text position and dimensions. * * @param x The x coordinate. * @param y The y coordinate. * @param width The width of the text. * @param height The height of the text. */ void setWildcardTextPosition(int16_t x, int16_t y, int16_t width, int16_t height) { wildcardText.setPosition(x, y, width, height); } /** * Sets wildcard text rotation. * * @param rotation The rotation. */ void setWildcardTextRotation(TextRotation rotation) { wildcardText.setRotation(rotation); } /** * Sets wildcard text buffer. * * @param buffer If non-null, the buffer. */ void setWildcardTextBuffer(const Unicode::UnicodeChar* buffer) { wildcardText.setWildcard(buffer); } /** * Sets wild card text colors. * * @param newColorReleased The new color released. * @param newColorPressed The new color pressed. */ void setWildcardTextColors(colortype newColorReleased, colortype newColorPressed) { colorReleased = newColorReleased; colorPressed = newColorPressed; handlePressedUpdated(); } protected: TextAreaWithOneWildcard wildcardText; ///< The wildcard text colortype colorReleased; ///< The color released colortype colorPressed; ///< The color pressed /** @copydoc AbstractButtonContainer::handlePressedUpdated() */ virtual void handlePressedUpdated() { wildcardText.setColor(T::getPressed() ? colorPressed : colorReleased); T::handlePressedUpdated(); } /** @copydoc AbstractButtonContainer::handleAlphaUpdated() */ virtual void handleAlphaUpdated() { wildcardText.setAlpha(T::getAlpha()); T::handleAlphaUpdated(); } }; } // namespace touchgfx #endif // WILDCARDTEXTBUTTONSTYLE_HPP
[ "tbeslan@gmail.com" ]
tbeslan@gmail.com
e299e2f7b3ec0fcf2dda518f063d7c771c524a2f
4c23be1a0ca76f68e7146f7d098e26c2bbfb2650
/ic8h18/0.0005/DC6H11-D
1780656b427ae31c017d15a93976b9885ff59216
[]
no_license
labsandy/OpenFOAM_workspace
a74b473903ddbd34b31dc93917e3719bc051e379
6e0193ad9dabd613acf40d6b3ec4c0536c90aed4
refs/heads/master
2022-02-25T02:36:04.164324
2019-08-23T02:27:16
2019-08-23T02:27:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
841
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 6 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.0005"; object DC6H11-D; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 0 0 0 0 0 0]; internalField uniform 2.98009e-13; boundaryField { boundary { type empty; } } // ************************************************************************* //
[ "jfeatherstone123@gmail.com" ]
jfeatherstone123@gmail.com
739dce061edb33bf545d958008b2cab50054762f
a011692f67757ff5c0ccb6602affa16370279d62
/src/classes/scoop/scoop.h
fe14286f994bdad9393e713a3f1395988913f5e3
[ "MIT" ]
permissive
kevinxtung/MICE
0884c229b82c4b433fd3d4c01172ae52b0fa5f3e
6559c8d242893f0697f64853ab49688198e9692d
refs/heads/master
2020-03-16T20:55:59.609212
2018-05-18T23:37:03
2018-05-18T23:37:03
132,978,265
0
0
MIT
2018-05-18T23:37:04
2018-05-11T02:23:28
C++
UTF-8
C++
false
false
440
h
#pragma once #include "classes/item/item.h" class Scoop : public Item { public: Scoop(std::string name, std::string description, double rawCost, double retailPrice) : Item(name, description, rawCost, retailPrice) { } Scoop(std::string name, std::string description, double rawCost, double retailPrice, int quantity) : Item(name, description, rawCost, retailPrice, quantity) { } std::string getType() const override; };
[ "kevin.tung@mavs.uta.edu" ]
kevin.tung@mavs.uta.edu
44f4201e0c9da1d975e15abe5060bdfe771f8727
afe8a0cf2bfc556f212c200e336a1fbcd7106e18
/data/win/launch/launch.cpp
d41b8f4103b830685716ef49b8bdffbbd0b5f7c3
[ "MIT" ]
permissive
nvdnkpr/appjs
35d3e906591fb3c664f98e43dc3f88521499c376
ba7e659bac96536086fe426fb943934d4f32d473
refs/heads/master
2021-01-20T23:02:51.319738
2012-07-03T21:15:46
2012-07-03T21:15:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,962
cpp
#include <windows.h> #include <stdio.h> #include <string> #include <iostream> size_t Launch(std::wstring FullPathToExe, std::wstring Parameters, size_t SecondsToWait) { size_t iMyCounter = 0, iReturnVal = 0, iPos = 0; DWORD dwExitCode = 0; std::wstring sTempStr = L""; /* Add a space to the beginning of the Parameters */ if (Parameters.size() != 0) { if (Parameters[0] != L' ') { Parameters.insert(0,L" "); } } /* The first parameter needs to be the exe itself */ sTempStr = FullPathToExe; iPos = sTempStr.find_last_of(L"\\"); sTempStr.erase(0, iPos +1); Parameters = sTempStr.append(Parameters); /* CreateProcessW can modify Parameters thus we allocate needed memory */ wchar_t * pwszParam = new wchar_t[Parameters.size() + 1]; if (pwszParam == 0) return 1; const wchar_t* pchrTemp = Parameters.c_str(); wcscpy_s(pwszParam, Parameters.size() + 1, pchrTemp); /* CreateProcess API initialization */ STARTUPINFOW siStartupInfo; PROCESS_INFORMATION piProcessInfo; memset(&siStartupInfo, 0, sizeof(siStartupInfo)); memset(&piProcessInfo, 0, sizeof(piProcessInfo)); siStartupInfo.cb = sizeof(siStartupInfo); if (CreateProcessW(const_cast<LPCWSTR>(FullPathToExe.c_str()), pwszParam, 0, 0, false, CREATE_NO_WINDOW, 0, 0, &siStartupInfo, &piProcessInfo) != false) /* Watch the process. */ dwExitCode = WaitForSingleObject(piProcessInfo.hProcess, (SecondsToWait * 1000)); else /* CreateProcess failed */ iReturnVal = GetLastError(); /* Free memory */ delete[]pwszParam; pwszParam = 0; /* Release handles */ CloseHandle(piProcessInfo.hProcess); CloseHandle(piProcessInfo.hThread); return iReturnVal; } int WINAPI WinMain(HINSTANCE hinst, HINSTANCE, LPSTR szArgs, int nCmdShow){ return Launch(std::wstring(L".\\bin\\node.exe"), std::wstring(L"app.js"), 1); }
[ "brandon@bbenvie.com" ]
brandon@bbenvie.com
24189be9ea8a3afe94105ee974d1c9a05f920a55
73ccf5aa3e16787e57dc0871236c024b244b004d
/RpiBt/blinkenbt/lib/handle.cpp
3a79f18557d6bc042cc80993a8336501dec4c561
[]
no_license
aantczakpiotr/EmbeddedSystems
79e7bb5d2b811ca4ba8b666b08885b9169293806
a1e581f7c95492cd992375336b435cd368a9a8b2
refs/heads/master
2022-11-19T20:42:44.600820
2020-07-24T20:30:53
2020-07-24T20:30:53
256,281,216
1
1
null
null
null
null
UTF-8
C++
false
false
4,198
cpp
// // Created by beton on 30.06.2020. // #include "handle.h" handle::handle() : gpioHandler(const_cast<uint8_t *>(leds), 9), btHandler() { gpioHandler.bindNotify(2); for (int i = 0; i < 8; i++) gpioHandler.bind(leds[i + 1], i); gpioHandler.setFrameTime(20000); aniRoll = std::thread( [this]() { gpioHandler.rollAnimation(); }); infoled = std::thread( [](gpio* g, btcon* b) { g->setPortNotifyFast(true); bool var = true; while (var) { usleep(20000); btconState st = b->getState(); switch (st) { case initial: g->setPortNotifyFast(true); break; case listeningWaiting: g->setPortNotifyFast(true); usleep(20000); g->setPortNotifyFast(false); usleep(300000); break; case listenedAccepted: for (int i = 0; i < 10; i++) { g->setPortNotifyFast(true); usleep(100000); g->setPortNotifyFast(false); usleep(100000); } break; case listenedDenied: for (int i = 0; i < 4; i++) { g->setPortNotifyFast(true); usleep(50000); g->setPortNotifyFast(false); usleep(50000); g->setPortNotifyFast(true); usleep(50000); g->setPortNotifyFast(false); usleep(300000); } var = false; break; case connected: g->setPortNotifyFast(false); usleep(100000); break; case exited: var = false; break; } } }, &gpioHandler, &btHandler); xmodemReader = std::thread([this](){btHandler.xmodemHandler();}); } handle::~handle() { btHandler.setState(exited); btHandler.explicitClientClose(); gpioHandler.closeAnimation(); gpioHandler.triggerAnimation(); std::cout << "joining aniRoll\n"; aniRoll.join(); std::cout << "joining infoled\n"; infoled.join(); std::cout << "joining btReader\n"; btReader.join(); std::cout << "joining xmodemReader\n"; xmodemReader.join(); std::cout << "all threads joined\n"; } void handle::listen() { btHandler.setState(listeningWaiting); btHandler.listen(); btHandler.setState(listenedAccepted); btReader = std::thread( [this]() { btHandler.handleConnection(); }); } std::list<uint8_t> handle::getAnimation() { std::list<uint8_t> animation; bool done; do { done = btHandler.extractXmodemMessage(animation, false); btHandler.waitForXmodemUpdate(10); if (btHandler.getState() == exited) { animation.clear(); animation.push_back(0); return animation; } } while (!done); //clear ending while (!animation.empty() && animation.back() == 0) { animation.pop_back(); } animation.push_back(0); std::cout << "\nreformated animation: " << animation.size() << "\n\n"; return animation; } void handle::animate(std::list<uint8_t> &l) { if (btHandler.getState() == exited) { return; } std::vector<uint8_t> v(l.begin(), l.end()); gpioHandler.loadAnimation(v); gpioHandler.triggerAnimation(); } bool handle::notExited() { return btHandler.getState() != exited; }
[ "bl000dy@o2.pl" ]
bl000dy@o2.pl
9fe0ad292567a50f5258d363c1c8f4e0a4a2ae87
c5e19b8b076ae31befe1f6eb95b1a1919f80d5a4
/sketch_jun12a.ino
7180c017c201911b24554c7f064ccd14613da781
[]
no_license
j14007/raspberry
e37e34da0643fa2987a1417405e3eb9d417ff28f
b84b9feb8bab7e1c24ac2863f98ecee55962d5d8
refs/heads/master
2021-01-13T16:50:07.611874
2017-06-26T07:24:41
2017-06-26T07:24:41
95,075,358
0
0
null
null
null
null
UTF-8
C++
false
false
246
ino
int val = 0; void setup() { // put your setup code here, to run once: Serial.begin(57600); pinMode(13, OUTPUT); } void loop() { // put your main code here, to run repeatedly: val = analogRead(0); delay(420); Serial.println(val); }
[ "j14007@sangi.jp" ]
j14007@sangi.jp
94ee972494c90b4f8891e71d0447a8ec3dd0b428
857ad2a52e2df470d8728815e79d7a6502d0b741
/lib/Timer/Timer.h
714720d3bffcfe2d6fb6035df5ba36807b1c81ca
[]
no_license
BriBan2-afk/Social-Distance-Device
bc05c92ce18fc900cf0803fff53da48ea7cfc3c3
2dea4aa74dea0bc5eafe2cfbd02469b866f7f9af
refs/heads/main
2023-06-13T03:10:30.237369
2021-06-23T18:29:01
2021-06-23T18:29:01
376,034,541
0
0
null
null
null
null
UTF-8
C++
false
false
220
h
#ifndef TIMER_H #define TIMER_H #include <Arduino.h> #endif class Timer { unsigned long previousMillis; public: Timer(); bool timer (unsigned long interval); uint32_t timeIt (uint32_t prev); };
[ "banziebright2@gmail.com" ]
banziebright2@gmail.com
4251d2c397175e1e2765ad7e52fe775e74da13ed
66904d7443fa6eacbd990facd0bd1c5908d89be0
/parser/header/program.h
a287698296703bdc7395f0e4661d37801280280f
[]
no_license
birgizz/regxparser
b9dc7862125c213b65fc6e6b6755d62666a91899
e18a523f542062340aa7812851f5c501466caed7
refs/heads/master
2020-07-10T12:47:24.651328
2019-08-25T08:18:54
2019-08-25T08:18:54
204,265,943
0
0
null
null
null
null
UTF-8
C++
false
false
983
h
#ifndef PROGRAM_H #define PROGRAM_H #include <iostream> #include "op.h" #include <string> extern std::vector<std::string> captures; extern std::string capture; struct program : op { std::string _id; bool eval(it &begin, it &end) override{ auto original_begin = begin; auto original_end = begin; while(begin != end){ auto current_begin = begin; if(operands[0]->eval(current_begin, end)){ if(operands[0]->id() == "OUT"){ std::cout << captures[std::stoi(capture)] << std::endl; } else if(operands[0]->id() == "EXPR") { std::cout << std::string(begin,current_begin) << std::endl; } return true; } begin++; } std::cout << "false" << std::endl; return false; } std::string id() override{ return "PROGRAM"; } }; #endif /* PROGRAM_H */
[ "birger.oberg@gmail.com" ]
birger.oberg@gmail.com
cb61d9bac898537e5a4b256efe7ccdba87092066
a008d8eed53ca796b131fabf7ad35f27f182b2cc
/include/kdtree.h
354e750c7425aa3f4d3e29fc52a986117326478c
[]
no_license
luisclaudio26/renderer
a550a3880d5d7610a20190b852a9154c58f395be
a9aed5fdbf2e89abea17207e68509c23a5e378fb
refs/heads/master
2021-01-22T22:02:59.055753
2017-08-22T03:35:22
2017-08-22T03:35:22
85,500,576
1
0
null
null
null
null
UTF-8
C++
false
false
844
h
#ifndef KDTREE_H #define KDTREE_H #include <vector> #include "Primitives/primitive.h" #include "intersection.h" #include <stack> namespace Renderer { namespace Scene { using namespace Shapes; using namespace Geometry; class kdNode { public: AABB bbox; kdNode *r, *l; int axis; float t; std::vector<int> primNum; }; class kdTree { private: mutable bool tryBackfaceCulling; public: kdNode root; int maxDepth; std::vector<Primitive*> prim; kdTree() : maxDepth(-1), tryBackfaceCulling(false) {} void build(std::vector<Primitive*>&& prim); void hit(const Ray& r, Intersection& out, bool tryBackfaceCulling) const; void hit(const kdNode& n, const Ray& r, float tmin, float tmax, Intersection& out) const; private: void buildNode(kdNode& n, int depth = 0); }; } } #endif
[ "luisclaudiogouveiarocha@gmail.com" ]
luisclaudiogouveiarocha@gmail.com
4e0137e5e77d9202b14e5557654f6fde325b1122
adb0be7d00d78d4eaf880be1ba227500e8fee82b
/src/op/bounded_relu.cpp
659ec95b976b874316a18ce6176d6fcbacb53547
[ "Apache-2.0" ]
permissive
kthur/he-transformer
8a93f72d0f0784c34d9f28888f1fe74d9be5c4bc
5d3294473edba10f2789197043b8d8704409719e
refs/heads/master
2020-07-06T13:09:57.696018
2019-11-12T18:26:40
2019-11-12T18:26:40
203,027,114
0
0
Apache-2.0
2019-11-12T18:26:41
2019-08-18T16:02:57
C++
UTF-8
C++
false
false
1,432
cpp
//***************************************************************************** // Copyright 2018-2019 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include "op/bounded_relu.hpp" #include <string> #include "ngraph/util.hpp" namespace ngraph::op { const std::string BoundedRelu::type_name{"BoundedRelu"}; BoundedRelu::BoundedRelu(const Output<Node>& arg, float alpha) : UnaryElementwiseArithmetic(arg), m_alpha(alpha) { constructor_validate_and_infer_types(); set_output_type(0, arg.get_element_type(), arg.get_shape()); } std::shared_ptr<Node> BoundedRelu::copy_with_new_args( const NodeVector& new_args) const { if (new_args.size() != 1) { throw ngraph_error("Incorrect number of new arguments"); } return std::make_shared<BoundedRelu>(new_args.at(0), m_alpha); } } // namespace ngraph::op
[ "noreply@github.com" ]
kthur.noreply@github.com
80b89e43a0c094a1a26fd19dd782cac57ae86c0d
d747ba6a8c1255adda08d1681a5e72dba844b83d
/Magik Carpet/Hailey.h
b4cff05081425f54eaf0e03a877e236ac490aeb4
[]
no_license
AshleyFitness/Magik-CarpetMadeByArca
bd234bf54be655794d736d7480b41b7e68f1b516
a52ead687c8331bf3377add51912ca50faf57feb
refs/heads/master
2020-12-02T18:54:23.171785
2019-12-31T13:19:40
2019-12-31T13:19:40
231,089,101
0
0
null
null
null
null
UTF-8
C++
false
false
578
h
#pragma once #include "Personnage.h" class Hailey : public Personnage { public: void SummonTree(Personnage& cible); Hailey(std::string nom,int vie,int love,int level,int xp); ~Hailey(); void afficherEtat2() const; void Compliment(Personnage& cible) const; void Joke(Personnage& cible) const; void DrawingDogMenu() const; void LevelUp(); void Spare(Personnage &cible) const; void GetXpCustom(int XP); void DrawingNavaRobotMenu() const; void HPlifeLimit(); void DrawingRabbitMenu() const; void DrawingRustyRobot() const; private: int m_level = 1; int m_xp = 0; };
[ "57031701+AshleyFitness@users.noreply.github.com" ]
57031701+AshleyFitness@users.noreply.github.com
28e6150355a2d2474a6b31a601904867e7882250
a51bee05492b93ead5c529ad7f43c89b785dc728
/Basic_Programming_exercises/Calculator.cpp
a5a339187416c2326af0dbf3d34c77e25486baf1
[]
no_license
Sakthi299/Working-with-C-
62ee8ecf0a13f4cb4eb669387841352698fbc519
4e71bffa0537b50eea8667aa642dc745acac319b
refs/heads/master
2022-12-15T13:33:25.448532
2020-09-04T14:22:47
2020-09-04T14:22:47
292,860,155
0
0
null
null
null
null
UTF-8
C++
false
false
727
cpp
#include<iostream> using namespace std; class calculator { int a,b; public: calculator() { cout<<"Constructor called.\n"; a=0;b=0; } void get_details() { cout<<"Enter two numbers"; cin>>a>>b; } void sum() { cout<<"Sum="<<a+b; } void diff() { cout<<"Difference="<<a-b; } void mul() { cout<<"Product="<<a*b; } void div() { cout<<"Quotient="<<a/b; } }; int main() { int ch;char op; calculator cal; cal.get_details(); do { cout<<"Enter choice"; cin>>ch; switch(ch) { case 1:cal.sum(); break; case 2:cal.diff(); break; case 3:cal.mul(); break; case 4:cal.div(); break; } cout<<"Whether continue(y/n):"; cin>>op; } while(op == 'y'); return 0; }
[ "60822530+Sakthi299@users.noreply.github.com" ]
60822530+Sakthi299@users.noreply.github.com
e1a825ac914dec9edf1b1e361754bc165abc1baf
e0c8293982efe9b606cd256480f41bbc1db6a40b
/SketcherDoc.h
bc2de8bd250b9f14f12ecac2e0887329c45c4f72
[ "MIT" ]
permissive
chen0040/mfc-npr-interactive-ant-sketch
91a8962b6853dcbb2c50ed183cb7d6c3bbc20b84
e26d989efd3c72799dd13f153170585e640c5523
refs/heads/master
2021-01-01T17:06:32.070437
2017-07-22T00:57:44
2017-07-22T00:57:44
97,997,120
2
0
null
null
null
null
UTF-8
C++
false
false
1,603
h
// SketcherDoc.h : interface of the CSketcherDoc class // #pragma once #include "SketcherEngine.h" #include "AntColony.h" #include "AntColonyConfiguration.h" class CSketcherDoc : public CDocument { protected: // create from serialization only CSketcherDoc(); DECLARE_DYNCREATE(CSketcherDoc) // Attributes public: // Operations public: // Overrides public: virtual BOOL OnNewDocument(); virtual void Serialize(CArchive& ar); // Implementation public: virtual ~CSketcherDoc(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: DECLARE_MESSAGE_MAP() SketcherEngine m_sketcher; AntColony m_colony; AntColonyConfiguration m_configuration; BOOL m_bRedrawCanvas; public: bool Load(LPCTSTR pFileName); void Display(CDC* pDC, const CRect& rect); void OnImageDisplaysource(); afx_msg void OnSketcherSaveimage(); afx_msg void OnUpdateSketcherSaveimage(CCmdUI *pCmdUI); afx_msg void OnUpdateImageDisplaysource(CCmdUI *pCmdUI); void OnImageDisplaygradientmap(void); afx_msg void OnUpdateImageDisplaygradientmap(CCmdUI *pCmdUI); void OnImageDisplayluminancemap(void); afx_msg void OnUpdateImageDisplayluminancemap(CCmdUI *pCmdUI); void OnImageDisplaycanvas(void); afx_msg void OnUpdateImageDisplaycanvas(CCmdUI *pCmdUI); void OnSketcherSketch(void); afx_msg void OnUpdateSketcherSketch(CCmdUI *pCmdUI); afx_msg void OnSketcherOptions(); afx_msg void OnSketcherClearcanvas(); afx_msg void OnSketcherBatchrun(); afx_msg void OnUpdateSketcherBatchrun(CCmdUI *pCmdUI); };
[ "xs0040@gmail.com" ]
xs0040@gmail.com
17e8e04d64d35bb5d821fbd8913f862d763ad4b9
e3d7ff2ec7721b21575a2ab801c64b78f605698f
/11721 열개씩 끊기/11721 열개씩 끊기.cpp
3d9c540baf9422effa477b61c0955569076eef29
[]
no_license
KimYongHwan97/Algorithms
a9afea819181f84ff9b1309775a2db9546097380
2aa8f4854495ae53f6b0d8e5f5d09807758a7dad
refs/heads/master
2023-04-11T21:05:15.166726
2021-04-30T16:23:50
2021-04-30T16:23:50
325,365,339
0
0
null
null
null
null
UTF-8
C++
false
false
247
cpp
#include <stdio.h> #include <string.h> int main() { int count = 0; char c [100 + 1]; scanf("%s",&c); count = strlen(c); for(int i = 0; i < count ; i++) { if(i % 10 == 0 && i != 0) { printf("\n"); } printf("%c",c[i]); } }
[ "koh5594@Naver.com" ]
koh5594@Naver.com
4f225436cdef6c1c1a0ac8a7d5b36de236b3b7c7
6693c202f4aa960b05d7dfd0ac8e19a0d1199a16
/COJ/eliogovea-cojAC/eliogovea-p2695-Accepted-s642467.cpp
6e19b75dbac28b0da694e9e80dd725a43d29f012
[]
no_license
eliogovea/solutions_cp
001cf73566ee819990065ea054e5f110d3187777
088e45dc48bfb4d06be8a03f4b38e9211a5039df
refs/heads/master
2020-09-11T11:13:47.691359
2019-11-17T19:30:57
2019-11-17T19:30:57
222,045,090
0
0
null
null
null
null
UTF-8
C++
false
false
1,141
cpp
#include <iostream> #include <vector> //#include <fstream> using namespace std; int n, k; vector<int> v[25]; string str; vector<int> func(const string &s) { int i = 1, num = 0; bool menos = false; vector<int> r; r.clear(); for (int i = 0; s[i]; i++) { if (s[i] == '{') continue; if (s[i] == ',' || s[i] == '}') { if (menos) num = -num; r.push_back(num); num = 0; menos = false; } else if (s[i] == '-') menos = true; else num = 10 * num + s[i] - '0'; } return r; } int main() { ios::sync_with_stdio(false); //freopen("e.in", "r", stdin); cin >> n; while (n--) { cin >> k; int len = -1; bool sol = true; for (int i = 0; i < k; i++) { v[i].clear(); cin >> str; if (!sol) continue; v[i] = func(str); if (len == -1) len = v[i].size(); else if (len != v[i].size()) sol = false; } if (sol) { cout << '{'; for (int i = 0; i < len; i++) { int tmp = 0; for (int j = 0; j < k; j++) tmp += v[j][i]; cout << tmp; if (i < len - 1) cout << ','; } cout << "}\n"; } else cout << "No solution\n"; } }
[ "eliogovea1993@gmail.com" ]
eliogovea1993@gmail.com
67b7e078eb22ed69ef1fc432e7d9cca595a935f2
53d50ab7e5a6069f869aa8d78486a0878e7c4afb
/GameEngine/Shader.h
6f92cf7a9396f665236b4c8ba669a6f11a2f91e3
[]
no_license
adrset/schrod
8e67efb45d17d345d3cff9d09923e1e42a1d0f8b
e0d80a13b392ccd96c6f0acff9d9959e6b7dec27
refs/heads/master
2020-03-19T10:06:19.543846
2018-06-06T14:52:15
2018-06-06T14:52:15
136,343,482
1
0
null
null
null
null
UTF-8
C++
false
false
1,240
h
#ifndef SHADER_H #define SHADER_H #include <string> #include <fstream> #include <sstream> #include <iostream> #include <map> #include <glad/glad.h> #include <glm/matrix.hpp> #include <glm/gtc/type_ptr.hpp> #include "errors.h" namespace GameEngine { class Shader { public: // the program ID unsigned int ID; // constructor reads and builds the shader Shader(const char* vertexPath, const char* fragmentPath); Shader(){ fprintf(stderr, "%s\n", "Creating empt shader!");} // use/activate the shader void use(); // utility uniform functions void setBool(const std::string &name, bool value) const; void setInt(const std::string &name, int value) const; void setFloat(const std::string &name, float value) const; void setMat4(const std::string &name, const glm::mat4 &mat) const; void setVec4(const std::string &name, const glm::vec4 &value) const; void setVec3(const std::string &name, const glm::vec3 &value) const; void setVec3(const std::string &name, float x, float y, float z) const; void setVec2(const std::string &name, const glm::vec2 &value) const; private: int getUniformLocation(const std::string uniform) const; void checkCompileErrors(unsigned int shader, std::string type); }; } #endif
[ "274433@pw.edu.pl" ]
274433@pw.edu.pl
daaa82d00057ee6efe55790bef415791a9a9188b
6870ea7fa607e314737ed7e814f22537eeb0fd0f
/Binary tree/Inorder_traversal_to_specialtree_conversion.cpp
dc95594761f36a4098a0c79ead0f4cf49ad6bd36
[]
no_license
ranjansingh119/Programming-source-code
e65b332d602a45574899d61097a46e220a67e7f2
2029be1e38f6634d287b5901ebf17e65a46fde0c
refs/heads/master
2021-01-20T20:05:24.914852
2016-06-20T18:09:52
2016-06-20T18:09:52
46,512,213
0
0
null
null
null
null
UTF-8
C++
false
false
1,457
cpp
#include<iostream> #include<cstdio> #include<cstdlib> using namespace std; struct tnode{ int data; struct tnode* left; struct tnode* right; }; struct tnode* newnode(int data); int maximum(int array[], int s, int last); struct tnode* create_special_tree(int arr[], int start, int end){ if(start>end) return NULL; int max_element_index = maximum(arr, start, end); struct tnode* root = newnode(arr[max_element_index]); if(start==end) return root; root->left = create_special_tree(arr, start, max_element_index-1); root->right = create_special_tree(arr, max_element_index+1, end); return root; } int maximum(int array[], int s, int last){ int max = array[s]; int max_index = s; for(int i=s+1; i<=last; i++){ if(array[i]>max){ max = array[i]; max_index = i; } } return max_index; } struct tnode* newnode(int data){ struct tnode* new_node = (struct tnode*) malloc (sizeof(struct tnode)); new_node->data = data; new_node->left = new_node->right = NULL; return new_node; } void inorder_display(struct tnode* root){ if(root==NULL){ return; } inorder_display(root->left); cout<<root->data<<" "; inorder_display(root->right); } int main(){ int arr[] = {5, 10, 40, 30, 28}; int size = sizeof(arr)/ sizeof(arr[0]); struct tnode* root = create_special_tree(arr, 0, size-1); cout<<"The inorder traversal of the given tree :"<<endl; inorder_display(root); return 0; }
[ "ranjansingh119@gmail.com" ]
ranjansingh119@gmail.com
38efcb5a7064e60f0157f8a2a3cf9010dab0bc1b
b2fd89d5d9fecf54ff8fd9cf4405339e54840315
/Source/MyProject2/BPLib.h
868a02b10b3b8806f7cb1b8ecf9b65114ba82108
[]
no_license
ethosium/MyProject2
0454627d1187dd6bfbcf59377669f070418ec9bd
313aad2b31156385b0b0b95ed9170d04b077321e
refs/heads/master
2021-01-18T22:15:54.619793
2016-01-15T00:33:46
2016-01-15T00:33:46
49,684,227
0
0
null
null
null
null
UTF-8
C++
false
false
448
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "Kismet/BlueprintFunctionLibrary.h" #include "BPLib.generated.h" /** * */ UCLASS() class MYPROJECT2_API UBPLib : public UBlueprintFunctionLibrary { public: GENERATED_BODY() UFUNCTION(BlueprintCallable, meta = (FriendlyName = "md5", CompactNodeTitle = "md5", Keywords = "md5"), Category = Crypto) static FString md5(FString s); };
[ "ethosium@gmail.com" ]
ethosium@gmail.com
e252637543b25d0b952002080ddcf88bb91f7c2f
4bf2c33b5d25dc73e89a2a06c73cb3b2a911bee6
/smartweddingreception2A4/bague.cpp
10f7c8d042d359f3a364899e3bc00f9865caa659
[]
no_license
HaythemBenMechichi/smart_wedding_reception_2A4
ee15ec7271681935fb8407fb79e13851773cc2b4
07b7f88ecf532a5ac85df031321d06da05248666
refs/heads/master
2023-02-13T04:19:52.350588
2020-12-02T07:29:55
2020-12-02T07:29:55
316,033,206
1
0
null
null
null
null
UTF-8
C++
false
false
1,385
cpp
#include "bague.h" bague::bague() { } bague::bague(int idb,QString nom,QString commentaire,int prix) { this->nom=nom; this->commentaire=commentaire; this->idb=idb; this->prix=prix; } bool bague::ajouter() { QSqlQuery query; query.prepare("insert into bague(nom,commentaire,idb,prix)" "values(:nom,:commentaire,:idb,:prix)"); query.bindValue(":nom",nom); query.bindValue(":commentaire",commentaire); query.bindValue(":idb",idb); query.bindValue(":prix",prix); return query.exec(); } bool bague::supprimer(QString nom) { QSqlQuery query; query.prepare("Delete from bague where nom= :nom"); query.bindValue(":nom",nom); return query.exec(); } QSqlQueryModel * bague::afficher() { QSqlQueryModel * model= new QSqlQueryModel(); model->setQuery("select * where nom= :nom from bague"); model->setHeaderData(0,Qt::Vertical,QObject::tr("nom")); model->setHeaderData(1,Qt::Vertical,QObject::tr("commentaire")); model->setHeaderData(2,Qt::Vertical,QObject::tr("prix")); return model; } /*bool bague::update() { QSqlQuery query; query.prepare("insert into bague where nom= :nom nom,commentaire,prix)" "values(:nom,:commentaire,:prix)"); query.bindValue(":nom",nom); query.bindValue(":commentaire",commentaire); query.bindValue(":prix",prix); return query.exec(); }*/
[ "youssefriahi63@yahoo.fr" ]
youssefriahi63@yahoo.fr
e521b7282ed0e84ac7a35dd95e418ac737778a00
a22d607128a696c652f47c8f98dc83fb0b541a1d
/contest 7 dslk va ngan xep/8.cpp
ea193fe9749628d4935d8b26d7c0bfb8ebc6ba4e
[]
no_license
nguyenvanhieu99/giai-thuat-
e4c4934a1eb35584b337130c80c2903ea647648d
917dcd507548a6d42eafd9f6341dcde13454a098
refs/heads/master
2022-12-24T07:47:30.319207
2020-10-01T15:00:41
2020-10-01T15:00:41
285,477,500
0
0
null
null
null
null
UTF-8
C++
false
false
775
cpp
#include<iostream> #include<algorithm> //#include<bits/stdc++.h> #include<stack> using namespace std; char *chuan(string s){ int n=s.length(); int ind=0; char *t=new char(n); stack <int>a; a.push(0); for(int i=0;i<n;i++){ if(s[i]=='+'){ if(a.top()==1) t[ind++]='-'; if(a.top()==0) t[ind++]='+'; } else if(s[i]=='-'){ if(a.top()== 1 ) t[ind++]='+'; if(a.top()== 0 ) t[ind++]='-'; } else if(s[i]=='('&&i>0){ if(s[i-1]=='-'){ int x=(a.top()==1)?0:1; a.push(x); } else if(s[i-1]=='+') a.push(a.top()); } else if(s[i]==')'){ a.pop(); } else t[ind++]=s[i]; } return t; } int main(){ int bo;cin>>bo; string s; cin.ignore(); while(bo--){ getline(cin,s); cout<<chuan(s)<<endl; } return 0; }
[ "nvhieu.dev@gmail.com" ]
nvhieu.dev@gmail.com
01ef36b542710e26230b8d8072ea12b6deb125b6
942b7b337019aa52862bce84a782eab7111010b1
/xray/utils/xrAI/graph_engine_inline.h
3cdef1b883ecd6f2c3f910c0849061946d33544a
[]
no_license
galek/xray15
338ad7ac5b297e9e497e223e0fc4d050a4a78da8
015c654f721e0fbed1ba771d3c398c8fa46448d9
refs/heads/master
2021-11-23T12:01:32.800810
2020-01-10T15:52:45
2020-01-10T15:52:45
168,657,320
0
0
null
2019-02-01T07:11:02
2019-02-01T07:11:01
null
UTF-8
C++
false
false
4,722
h
//////////////////////////////////////////////////////////////////////////// // Module : graph_engine_inline.h // Created : 21.03.2002 // Modified : 03.03.2004 // Author : Dmitriy Iassenev // Description : Graph engine inline functions //////////////////////////////////////////////////////////////////////////// #pragma once IC CGraphEngine::CGraphEngine (u32 max_vertex_count) { m_algorithm = xr_new<CAlgorithm> (max_vertex_count); m_algorithm->data_storage().set_min_bucket_value (_dist_type(0)); m_algorithm->data_storage().set_max_bucket_value (_dist_type(2000)); #ifndef AI_COMPILER m_solver_algorithm = xr_new<CSolverAlgorithm> (16*1024); #endif // AI_COMPILER } IC CGraphEngine::~CGraphEngine () { xr_delete (m_algorithm); #ifndef AI_COMPILER xr_delete (m_solver_algorithm); #endif // AI_COMPILER } #ifndef AI_COMPILER IC const CGraphEngine::CSolverAlgorithm &CGraphEngine::solver_algorithm() const { return (*m_solver_algorithm); } #endif // AI_COMPILER template < typename _Graph, typename _Parameters > IC bool CGraphEngine::search ( const _Graph &graph, const _index_type &start_node, const _index_type &dest_node, xr_vector<_index_type> *node_path, const _Parameters &parameters ) { #ifndef AI_COMPILER Statistic.AI_Path.Begin(); START_PROFILE("graph_engine") START_PROFILE("graph_engine/search") #endif typedef CPathManager<_Graph, CAlgorithm::CDataStorage, _Parameters, _dist_type,_index_type,_iteration_type> CPathManagerGeneric; CPathManagerGeneric path_manager; path_manager.setup ( &graph, &m_algorithm->data_storage(), node_path, start_node, dest_node, parameters ); bool successfull = m_algorithm->find(path_manager); #ifndef AI_COMPILER Statistic.AI_Path.End(); #endif return (successfull); #ifndef AI_COMPILER STOP_PROFILE STOP_PROFILE #endif } template < typename _Graph, typename _Parameters > IC bool CGraphEngine::search ( const _Graph &graph, const _index_type &start_node, const _index_type &dest_node, xr_vector<_index_type> *node_path, _Parameters &parameters ) { #ifndef AI_COMPILER Statistic.AI_Path.Begin(); START_PROFILE("graph_engine") START_PROFILE("graph_engine/search") #endif typedef CPathManager<_Graph, CAlgorithm::CDataStorage, _Parameters, _dist_type,_index_type,_iteration_type> CPathManagerGeneric; CPathManagerGeneric path_manager; path_manager.setup ( &graph, &m_algorithm->data_storage(), node_path, start_node, dest_node, parameters ); bool successfull = m_algorithm->find(path_manager); #ifndef AI_COMPILER Statistic.AI_Path.End(); #endif return (successfull); #ifndef AI_COMPILER STOP_PROFILE STOP_PROFILE #endif } template < typename _Graph, typename _Parameters, typename _PathManager > IC bool CGraphEngine::search ( const _Graph &graph, const _index_type &start_node, const _index_type &dest_node, xr_vector<_index_type> *node_path, const _Parameters &parameters, _PathManager &path_manager ) { #ifndef AI_COMPILER Statistic.AI_Path.Begin(); START_PROFILE("graph_engine") START_PROFILE("graph_engine/search") #endif path_manager.setup ( &graph, &m_algorithm->data_storage(), node_path, start_node, dest_node, parameters ); bool successfull = m_algorithm->find(path_manager); #ifndef AI_COMPILER Statistic.AI_Path.End(); #endif return (successfull); #ifndef AI_COMPILER STOP_PROFILE STOP_PROFILE #endif } #ifndef AI_COMPILER template < typename T1, typename T2, typename T3, typename T4, typename T5, bool T6, typename T7, typename T8, typename _Parameters > IC bool CGraphEngine::search( const CProblemSolver< T1, T2, T3, T4, T5, T6, T7, T8 > &graph, const _solver_index_type &start_node, const _solver_index_type &dest_node, xr_vector<_solver_edge_type> *node_path, const _Parameters &parameters ) { #ifndef AI_COMPILER Statistic.AI_Path.Begin(); START_PROFILE("graph_engine") START_PROFILE("graph_engine/proble_solver") #endif typedef CProblemSolver<T1,T2,T3,T4,T5,T6,T7,T8> CSProblemSolver; typedef CPathManager<CSProblemSolver,CSolverAlgorithm::CDataStorage,_Parameters,_solver_dist_type,_solver_index_type,GraphEngineSpace::_iteration_type> CSolverPathManager; CSolverPathManager path_manager; path_manager.setup ( &graph, &m_solver_algorithm->data_storage(), node_path, start_node, dest_node, parameters ); bool successfull = m_solver_algorithm->find(path_manager); #ifndef AI_COMPILER Statistic.AI_Path.End(); #endif return (successfull); #ifndef AI_COMPILER STOP_PROFILE STOP_PROFILE #endif } #endif // AI_COMPILER
[ "abramcumner@yandex.ru" ]
abramcumner@yandex.ru
8c2ca5c460924b0a2242cf86395876a5eea9cfc7
b41db21e54e088200157105345070f01e9557ced
/AtCoderRegularContest/37/b.cpp
f208f0f833ccbc330a0fc640f134540ff09e0a78
[]
no_license
tsugupoyo/AtCoder
e6ce8692e133028264eb8f85f765d988306feb97
3b1cd63097c47bf039de87f943346fc0d787cc83
refs/heads/main
2023-06-02T06:40:34.981731
2021-06-21T02:56:36
2021-06-21T02:56:36
378,789,517
0
0
null
null
null
null
UTF-8
C++
false
false
773
cpp
#include <bits/stdc++.h> using namespace std; using ll=long long; using P = pair<int,int>; #define rep(i,n) for(int i=0;i<(int)(n);i++) const int INF =1001001001; bool graph[100][100]; bool visit[100]; int n, m; bool ok; void dfs(int v, int prev) { visit[v] = true; if(prev != -1){ } rep(i,n) { if(graph[v][i] == false) continue; if(visit[i]) { if(i != prev) ok = false; continue; } dfs(i,v); } } int main() { cin >> n >> m; rep(i, m) { int a, b; cin >> a >> b; --a;--b; graph[a][b] = true; graph[b][a] = true; } int ans =0; rep(i,n) { if(visit[i]) continue; ok = true; dfs(i, -1); if(ok) ans++; } cout << ans << endl; }
[ "fujiwaratakatsugu@fujiwaratakashinoMacBook-puro.local" ]
fujiwaratakatsugu@fujiwaratakashinoMacBook-puro.local
6a50ad23e7d90a03ce7c311de07e1aec04b0d5d3
c115b2799014dc2ab63ca2626b3f0263b1339e7a
/NosePoke_Adquisicion_RA/NosePoke_Adquisicion_RA.ino
cf2094a528a52c122850e4fc468964e5100ce919
[]
no_license
Traintain/NosePoke
6409deb47072fc77aa92b30e8b3363cd1200b87c
7cf0564199464eed976851ccff136a52c097635a
refs/heads/master
2023-06-23T03:38:28.631037
2023-06-13T09:04:54
2023-06-13T09:04:54
220,561,332
0
0
null
null
null
null
UTF-8
C++
false
false
13,612
ino
//This library allows to control the stepper motor //Pin conections //Infrared sensors on the holes const int IR_Right=4; const int IR_Left=3; const int MOTOR=8; //Contecions for the LED lights const int LED_Right=6; const int LED_Left=5; const int LED_center=7; //Motor constants //120 steps per turn dispense 0.017 ml aprox. Above 120 RPM the motor get clumsy int nSpeed=120; int nSteps=150; //Number of blocks const int nBlocks=1; //Number of trials per block const int nTrials=50; //Inter trial interval, in miliseconds const int ITI=5000; int ITIsec=ITI/1000; //Maximum duration of each trial, in milisencods const int durTrial=10000; //Reward period, in case the nose enters while the trial, in miliseconds const int durReward=3000; //Output constants //Number of successful trials. Can be up to 50 por block. int success; //Time spend on impulsive responses. An impulsive response is when the animal inserts its nose during the ITI unsigned long impulsive; //Number of omissions. An omision response is when the animal doesn't inster its nose during a trial int omission; //Number of categories. A category is when a animal has 3 successes in a row. int category; //Number of right correct choices int goodRight; //Number of left correct choices int goodLeft; //mean of the latency of each block unsigned long latency; //temporal number for math double temp; //Error de seleccion: numero de errores antes del primer acierto int errSelec; //Perseveracion primaria int EPP; //Perseveracion secundaria int EPS; //Aciertos por segmento int aciertoTemprano; int aciertoIntermedio; int aciertoFinal; //Global max continious correct responses int globalMax; //Local max continious correct responses int localMax; int right; int left; int COM=-1; //Integer that counts the number of consecutives succeses int sucesiveSuccess; bool metioNariz; unsigned long tIni; unsigned long tInterm; unsigned long tLog; String msg=""; //Number between 0 and 2, that indicates the side where the animal should drink long randomSide; bool isRight; int firstCorrect; void setup() { //Setup of the different pins pinMode(IR_Right, INPUT); pinMode(IR_Left, INPUT); pinMode(LED_Right, OUTPUT); pinMode(LED_Left, OUTPUT); pinMode(LED_center, OUTPUT); pinMode(MOTOR, OUTPUT); digitalWrite(MOTOR,HIGH); randomSeed(analogRead(0)); Serial.begin(9600); //Comprobar comunicación con PC Serial.println("Transmitiendo"); //while(COM==-1){ // COM=Serial.read(); //} //To check the serial comunication the PC sends a number 6. //if(COM!=54){ //Error en caso de que no haya comunicación // Serial.println("Error"); //}else{ //Todo va bien // Serial.println("Ok"); //} } //Method to make the motor turn void motor(){ //Serial.println("Iniciando un ciclo del motor"); digitalWrite(LED_center,HIGH); digitalWrite(MOTOR,LOW); //Poner en 1000 al inicio para que llene la sonda rapidamente //Poner en 20 para dispensar una gota delay(20); digitalWrite(MOTOR,HIGH); delay(durReward); digitalWrite(LED_center,LOW); } //To initiate the protocol the PC must send a number 9 void loop() { //while(COM!=57){ // COM=Serial.read(); //} //Run two blocks for(int j=0; j<nBlocks;j++){ //Reset the output counters success=0; impulsive=0; omission=0; category=0; sucesiveSuccess=0; temp=0; goodLeft=0; goodRight=0; latency=0; firstCorrect=0; errSelec=0; EPP=0; EPS=0; aciertoTemprano=0; aciertoIntermedio=0; aciertoFinal=0; localMax=0; globalMax=0; Serial.print("Van a empezar los "); Serial.print(nTrials); Serial.println(" ensayos"); //Wait 5 seconds for habituation delay(ITI); Serial.println("Ensayo,Aciertos,Porcentaje aciertos,Tiempo total en Respuestas impulsivas,Omisiones,Porcentaje omisiones,Categorias,Latencia promedio,Errores de perseveración primarios,Porcentaje errores de perseveración primarios,Errores de perseveración secundarios,Porcentaje errores de perseveración secundarios,Errores de seleccion,Porcentaje errores de selección,Adquisicion de reglas,Establecimiento de reglas,Mantenimiento de reglas,Maximo de aciertos seguidos"); //Begin 50 trials for(int i=0; i<nTrials; i++){ trial(i); //Imprime el ensayo temp=i+1; Serial.print(temp); Serial.print(","); //Imprime los aciertos Serial.print(success); Serial.print(","); //Imprime el porcentaje de aciertos temp=(success*100/nTrials); Serial.print(temp); Serial.print(","); //Imprime el tiempo total de respuestas impulsivas temp=impulsive/1000; Serial.print(temp); Serial.print(","); //Imprime las omisiones Serial.print(omission); Serial.print(","); //Imprime el porcentaje de omisiones temp=(omission*100/nTrials); Serial.print(temp); Serial.print(","); //Imprime las categorias Serial.print(category); Serial.print(","); //Imprime la latencia promedio if(success!=0 || EPP !=0 || EPS != 0){ temp=latency/(success+EPP+EPS); }else{ temp=0; } Serial.print(temp); Serial.print(","); //Errores de perseveración primarios Serial.print(EPP); Serial.print(","); //Porcentaje errores de perseveración primarios if(success!=0){ temp=(EPP*100/success); }else{ temp=0; } Serial.print(temp); Serial.print(","); //Errores de perseveración secundarios Serial.print(EPS); Serial.print(","); //Porcentaje errores de perseveración secundarios if(EPS!=0){ temp=(EPP*100/EPS); }else{ temp=0; } Serial.print(temp); Serial.print(","); //Errores de seleccion Serial.print(errSelec); Serial.print(","); //Porcentaje errores de selección if(firstCorrect!=0){ temp=(errSelec*100/firstCorrect); }else{ temp=0; } Serial.print(temp); Serial.print(","); //Imprime las adquisiciones de reglas temp=(aciertoTemprano*100)/17; Serial.print(temp); Serial.print(","); //Imprime el establecimiento de reglas temp=(aciertoIntermedio*100)/16; Serial.print(temp); Serial.print(","); //Imprime el mantenimiento de reglas temp=(aciertoFinal*100)/17; Serial.print(temp); Serial.print(","); //Imprime el maximo de aciertos seguidos Serial.println(globalMax); if(i==49){ Serial.println(); Serial.println("***********************************"); Serial.print("Aciertos: "); Serial.println(success); Serial.print("Porcentaje aciertos: "); temp=(success*100/nTrials); Serial.print(temp); Serial.println("%"); Serial.print("Tiempo total en Respuestas impulsivas: "); temp=impulsive/1000; Serial.print(temp); Serial.println(" s"); Serial.print("Omisiones: "); Serial.println(omission); Serial.print("Porcentaje omisiones: "); temp=(omission*100/nTrials); Serial.print(temp); Serial.println("%"); Serial.print("Categorias: "); Serial.println(category); Serial.print("La latencia promedio es de: "); if(success!=0 || EPP !=0 || EPS != 0){ temp=latency/(success+EPP+EPS); }else{ temp=0; } Serial.print(temp); Serial.println(" ms"); Serial.print("Errores de perseveración primarios: "); Serial.println(EPP); Serial.print("Porcentaje errores de perseveración primarios: "); if(success!=0){ temp=(EPP*100/success); }else{ temp=0; } Serial.print(temp); Serial.println("%"); Serial.print("Errores de perseveración secundarios: "); Serial.println(EPS); Serial.print("Porcentaje errores de perseveración secundarios: "); if(EPS!=0){ temp=(EPP*100/EPS); }else{ temp=0; } Serial.print(temp); Serial.println("%"); Serial.print("Errores de seleccion: "); Serial.println(errSelec); Serial.print("Porcentaje errores de selección: "); if(firstCorrect!=0){ temp=(errSelec*100/firstCorrect); }else{ temp=0; } Serial.print(temp); Serial.println("%"); Serial.print("Adquisicion de reglas: "); temp=(aciertoTemprano*100)/17; Serial.println(temp); Serial.print("Establecimiento de reglas: "); temp=(aciertoIntermedio*100)/16; Serial.println(temp); Serial.print("Mantenimiento de reglas: "); temp=(aciertoFinal*100)/17; Serial.println(temp); Serial.print("Maximo de aciertos seguidos: "); Serial.println(globalMax); if(firstCorrect!=0){ Serial.print("El primer acierto fue en el intento: "); Serial.println(firstCorrect); } } } Serial.println("Terminan bloque de 50 ensayos"); } while(true); } //The instructions for each trial void trial(int i){ metioNariz=false; randomSide=random(0,2); isRight=randomSide<1; //Serial.println("Inicia ensayo"); tIni=millis(); if(isRight){ digitalWrite(LED_Right,HIGH); //Serial.println("Se enciende la luz derecha"); }else{ digitalWrite(LED_Left,HIGH); //Serial.println("Se enciende la luz izquierda"); } //Check fot 10 seconds if the animal inserts its nose while(( (millis()-tIni) < durTrial) && metioNariz==false){ right=digitalRead(IR_Right); left=digitalRead(IR_Left); if(right==LOW){ tLog=millis()-tIni; //Serial.print("Metio la nariz en la derecha a los: "); //Serial.println(tLog); if(isRight){ digitalWrite(LED_Right,LOW); motor(); //Exito if(firstCorrect==0){ firstCorrect=i+1; //Serial.print("Primer acierto en el intento: "); //Serial.println(firstCorrect); } success++; if(i<=16){ aciertoTemprano++; }else if(i<=32 && i>16){ aciertoIntermedio++; }else{ aciertoFinal++; } if((sucesiveSuccess%3)==2)category++; sucesiveSuccess++; localMax++; if(localMax > globalMax) globalMax = localMax; }else{ //Fallo digitalWrite(LED_Left,LOW); if(firstCorrect==0){ errSelec++; //Serial.println("Error de selección"); }else{ if(sucesiveSuccess!=0){ EPP++; //Serial.println("Error de perseveración primaria"); sucesiveSuccess=0; }else{ EPS++; //Serial.println("Error de perseveración secundaria"); } } sucesiveSuccess=0; localMax=0; } while(right==LOW){ right=digitalRead(IR_Right); } latency+=tLog; metioNariz=true; } if(left==LOW){ tLog=millis()-tIni; //Serial.print("Metio la nariz en la izquierda a los: "); //Serial.println(tLog); if(isRight){ //Fallo digitalWrite(LED_Right,LOW); if(firstCorrect==0){ errSelec++; //Serial.println("Error de selección"); }else{ if(sucesiveSuccess!=0){ EPP++; //Serial.println("Error de perseveración primaria"); sucesiveSuccess=0; }else{ EPS++; //Serial.println("Error de perseveración secundaria"); } } sucesiveSuccess=0; localMax=0; }else{ //Exito digitalWrite(LED_Left,LOW); motor(); //Exito if(firstCorrect==0){ firstCorrect=i+1; //Serial.print("Primer acierto en el intento: "); //Serial.println(firstCorrect); } success++; if(i<=16){ aciertoTemprano++; }else if(i<=32 && i>16){ aciertoIntermedio++; }else{ aciertoFinal++; } if((sucesiveSuccess%3)==2)category++; sucesiveSuccess++; localMax++; if(localMax > globalMax) globalMax = localMax; } while(left==LOW){ left=digitalRead(IR_Left); } latency+=tLog; metioNariz=true; } } //------------------------ if(metioNariz==false){ digitalWrite(LED_Right,LOW); digitalWrite(LED_Left,LOW); omission++; //Serial.print("Omision numero:"); //Serial.println(omission); sucesiveSuccess=0; } //------------------------ //El animal debe esperar 10 segundos antes de volver a meter la nariz //Si la mete antes se reinicia la cuenta //Serial.print("Fin ensayo, inician "); //Serial.print(ITIsec); //Serial.println(" s de intervalo entre estímulos"); tInterm=millis(); while((millis()-tInterm) < ITI){ right=digitalRead(IR_Right); left=digitalRead(IR_Left); if(right==LOW || left==LOW){ //impulsive++; tIni=millis(); //Serial.println("Inicio de respuesta impulsiva"); while(right==LOW || left==LOW){ right=digitalRead(IR_Right); left=digitalRead(IR_Left); } impulsive+=millis()-tIni; tInterm = millis(); //Serial.println("Inician de nuevo "); //Serial.print(ITIsec); //Serial.println(" s de espera"); } } }
[ "jm.rivera@uniandes.edu.co" ]
jm.rivera@uniandes.edu.co
6b3baeeca3ca9a3602a9e203e66fdfea080683cb
494fc35b2dbe5705bdf81e6b5d2615d1198c8559
/Mu2eG4/inc/nestPolyhedra.hh
7e1854e300006ff28fdfe2f47eee5fafe6198f2a
[ "Apache-2.0" ]
permissive
shadowbehindthebread/Offline
36f71913ac789b9381db5143b0fc0bd7349c155e
57b5055641a4c626a695f3d83237c79758956b6a
refs/heads/master
2022-11-05T17:44:25.761755
2020-06-15T18:07:16
2020-06-15T18:07:16
273,599,835
1
0
Apache-2.0
2020-06-19T22:48:25
2020-06-19T22:48:24
null
UTF-8
C++
false
false
1,921
hh
#ifndef Mu2eG4_nestPolyhedra_hh #define Mu2eG4_nestPolyhedra_hh // // Free function to create and place a new G4Polyhedra, place inside a logical volume. // // $Id: nestPolyhedra.hh,v 1.3 2014/09/19 19:14:55 knoepfel Exp $ // $Author: knoepfel $ // $Date: 2014/09/19 19:14:55 $ // // Original author Rob Kutschke // #include <string> #include <vector> #include "G4Helper/inc/VolumeInfo.hh" class G4CSGSolid; class G4LogicalVolume; class G4Material; class G4VPhysicalVolume; // G4 includes #include "G4Polyhedra.hh" #include "G4Colour.hh" #include "G4RotationMatrix.hh" #include "G4ThreeVector.hh" namespace mu2e { class Polyhedra; class PolyhedraParams; VolumeInfo nestPolyhedra ( std::string const& name, PolyhedraParams const & polyObj, G4Material* material, G4RotationMatrix const* rot, G4ThreeVector const & offset, VolumeInfo const & parent, int copyNo, bool const isVisible, G4Colour const color, bool const forceSolid, bool const forceAuxEdgeVisible, bool const placePV, bool const doSurfaceCheck ); VolumeInfo nestPolyhedra ( std::string const& name, PolyhedraParams const & polyObj, G4Material* material, G4RotationMatrix const* rot, G4ThreeVector const & offset, VolumeInfo const & parent, int copyNo, G4Colour const color, std::string const& lookupToken ); } #endif /* Mu2eG4_nestPolyhedra_hh */
[ "david.brown@louisville.edu" ]
david.brown@louisville.edu
1838471a6af62b44930c1a1379f6c703e74261c2
1786f51414ac5919b4a80c7858e11f7eb12cb1a9
/USST/UF9div3/E.cpp
15af7f6a8d57cb6560f9f580eddfe02408e0b04b
[]
no_license
SetsunaChyan/OI_source_code
206c4d7a0d2587a4d09beeeb185765bca0948f27
bb484131e02467cdccd6456ea1ecb17a72f6e3f6
refs/heads/master
2020-04-06T21:42:44.429553
2019-12-02T09:18:54
2019-12-02T09:18:54
157,811,588
0
0
null
null
null
null
UTF-8
C++
false
false
1,045
cpp
#include <bits/stdc++.h> using namespace std; typedef pair<int,int> pii; char s[10][10]; int l,qaq[10][10][10],ans; void bfs() { queue<pii> q; q.emplace(0,0); while(!q.empty()) { pii p=q.front();q.pop(); if(p.second==8) { ans=1; return; } if(p.first&&qaq[p.second+1][7][p.first-1]==0&&qaq[p.second][7][p.first-1]==0) q.emplace(p.first-1,p.second+1); if(qaq[p.second+1][7][p.first]==0&&qaq[p.second][7][p.first]==0) q.emplace(p.first,p.second+1); if(p.first<7&&qaq[p.second+1][7][p.first+1]==0&&qaq[p.second][7][p.first+1]==0) q.emplace(p.first+1,p.second+1); } } int main() { for(int i=0;i<8;i++) scanf("%s",s[i]); for(int i=0;i<8;i++) for(int j=0;j<8;j++) if(s[i][j]=='S') qaq[0][i][j]=1; for(int i=1;i<9;i++) for(int j=1;j<8;j++) for(int k=0;k<8;k++) if(qaq[i-1][j-1][k]) qaq[i][j][k]=1; bfs(); if(ans) printf("WIN"); else printf("LOSE"); return 0; }
[ "ctzguozi@163.com" ]
ctzguozi@163.com
f9204b95cd2c99a295f60f01d4ba103784b97739
e3d4d464c13605f58b0512003d9e2a23c2ae2ef9
/Dllmain.cpp
5d79f4d318d1412f47840932cfae4bfc778ff0bc
[]
no_license
testcc2c/FakeImGuiCheatLoverzSource
1c76775774890102fa5927f018ecf8909c4528c1
cc03a618a177cd647ef2e432e84356080d721ebf
refs/heads/main
2023-07-01T00:04:01.362137
2021-08-09T22:44:16
2021-08-09T22:44:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,855
cpp
#include "RenderHelper.h" void HOOKInitalize() { L::MainGay(); HWND window = FindWindow(0, (L"Fortnite ")); IDXGISwapChain* swapChain = nullptr; ID3D11Device* device = nullptr; ID3D11DeviceContext* context = nullptr; auto featureLevel = D3D_FEATURE_LEVEL_11_0; DXGI_SWAP_CHAIN_DESC sd = { 0 }; sd.BufferCount = 1; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; sd.OutputWindow = window; sd.SampleDesc.Count = 1; sd.Windowed = TRUE; if (FAILED(D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_HARDWARE, 0, 0, &featureLevel, 1, D3D11_SDK_VERSION, &sd, &swapChain, &device, nullptr, &context))) { MessageBox(0, (L"dx11 fatal error"), (L"fatal error"), MB_ICONERROR); return; } auto table = *reinterpret_cast<PVOID**>(swapChain); auto present = table[8]; auto resize = table[13]; context->Release(); device->Release(); swapChain->Release(); MH_Initialize(); auto addr = SDK::Utilities::Scanners::PatternScan(xorthis("48 8B C4 48 89 58 18 55 56 57 41 54 41 55 41 56 41 57 48 8D A8 ? ? ? ? 48 81 EC ? ? ? ? 0F 29 70 B8 0F 29 78 A8 44 0F 29 40 ? 44 0F 29 48 ? 44 0F 29 90 ? ? ? ? 44 0F 29 98 ? ? ? ? 44 0F 29 A0 ? ? ? ? 44 0F 29 A8 ? ? ? ? 48 8B 05 ? ? ? ? 48 33 C4 48 89 85 ? ? ? ? 48 8B F1")); MH_CreateHook((LPVOID)addr, (LPVOID)CalculateShotHook, (LPVOID*)&CalculateShot); MH_EnableHook((LPVOID)addr); MH_CreateHook(present, present_hk, reinterpret_cast<PVOID*>(&presenth)); MH_EnableHook(present); MH_CreateHook(resize, resize_hk, reinterpret_cast<PVOID*>(&resizeh)); MH_EnableHook(resize); oriWndProc = (WNDPROC)SetWindowLongPtr(window, GWLP_WNDPROC, (LONG_PTR)WndProc); } HANDLE(WINAPI* Real_CreateFileW) (LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) = CreateFileW; BOOL(WINAPI* Real_CreateDirectoryW) (LPCWSTR lpPathName, LPSECURITY_ATTRIBUTES lpSecurityAttributes) = CreateDirectoryW; HANDLE WINAPI _CreateFileW(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) { if (wcsstr(lpFileName, L".pak") || wcsstr(lpFileName, L".sig") || wcsstr(lpFileName, L"Fortnite") || wcsstr(lpFileName, L"\\.\\")) return Real_CreateFileW(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); else return Real_CreateFileW(L"C:\\Windows\\a", dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); } BOOL WINAPI _CreateDirectoryW(LPCWSTR lpPathName, LPSECURITY_ATTRIBUTES lpSecurityAttributes) { if (wcsstr(lpPathName, L"Fortnite")) return Real_CreateDirectoryW(lpPathName, lpSecurityAttributes); else return Real_CreateDirectoryW(L"C:\\Windows\\a", lpSecurityAttributes); } VOID InitAntiTracesFiles() { DetourTransactionBegin(); DetourAttach(&(PVOID&)Real_CreateFileW, _CreateFileW); DetourAttach(&(PVOID&)Real_CreateDirectoryW, _CreateDirectoryW); } void CheatInitialize() { InitAntiTracesFiles(); HOOKInitalize(); Details.UWORLD = SDK::Utilities::Scanners::PatternScan(xorthis("48 8B 05 ? ? ? ? 4D 8B C2")); Details.UWORLD = RELATIVE_ADDR(Details.UWORLD, 7); LineOfS = SDK::Utilities::Scanners::PatternScan(xorthis("E8 ? ? ? ? 48 8B 0D ? ? ? ? 33 D2 40 8A F8")); LineOfS = RELATIVE_ADDR(LineOfS, 5); } BOOL APIENTRY DllMain(HMODULE module, DWORD reason, LPVOID reserved) { if (reason == DLL_PROCESS_ATTACH) { //HOOKInitalize(); CheatInitialize(); } return TRUE; }
[ "noreply@github.com" ]
testcc2c.noreply@github.com
65bd002eba5760fb3eed8e448c9426d54f57bc5f
8134e49b7c40c1a489de2cd4e7b8855f328b0fac
/3rdparty/libbitcoin/include/bitcoin/bitcoin/message/get_blocks.hpp
5131c6e04c3eb07338b250da839787b0cc1455b5
[ "Apache-2.0" ]
permissive
BeamMW/beam
3efa193b22965397da26c1af2aebb2c045194d4d
956a71ad4fedc5130cbbbced4359d38534f8a7a5
refs/heads/master
2023-09-01T12:00:09.204471
2023-08-31T09:22:40
2023-08-31T09:22:40
125,412,400
671
233
Apache-2.0
2023-08-18T12:47:41
2018-03-15T18:49:06
C++
UTF-8
C++
false
false
3,206
hpp
/** * Copyright (c) 2011-2017 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LIBBITCOIN_MESSAGE_GET_BLOCKS_HPP #define LIBBITCOIN_MESSAGE_GET_BLOCKS_HPP #include <istream> #include <memory> #include <string> #include <vector> #include <bitcoin/bitcoin/define.hpp> #include <bitcoin/bitcoin/math/hash.hpp> #include <bitcoin/bitcoin/utility/data.hpp> #include <bitcoin/bitcoin/utility/reader.hpp> #include <bitcoin/bitcoin/utility/writer.hpp> namespace libbitcoin { namespace message { class BC_API get_blocks { public: typedef std::shared_ptr<get_blocks> ptr; typedef std::shared_ptr<const get_blocks> const_ptr; static get_blocks factory_from_data(uint32_t version, const data_chunk& data); static get_blocks factory_from_data(uint32_t version, std::istream& stream); static get_blocks factory_from_data(uint32_t version, reader& source); get_blocks(); get_blocks(const hash_list& start, const hash_digest& stop); get_blocks(hash_list&& start, hash_digest&& stop); get_blocks(const get_blocks& other); get_blocks(get_blocks&& other); hash_list& start_hashes(); const hash_list& start_hashes() const; void set_start_hashes(const hash_list& value); void set_start_hashes(hash_list&& value); hash_digest& stop_hash(); const hash_digest& stop_hash() const; void set_stop_hash(const hash_digest& value); void set_stop_hash(hash_digest&& value); virtual bool from_data(uint32_t version, const data_chunk& data); virtual bool from_data(uint32_t version, std::istream& stream); virtual bool from_data(uint32_t version, reader& source); data_chunk to_data(uint32_t version) const; void to_data(uint32_t version, std::ostream& stream) const; void to_data(uint32_t version, writer& sink) const; bool is_valid() const; void reset(); size_t serialized_size(uint32_t version) const; // This class is move assignable but not copy assignable. get_blocks& operator=(get_blocks&& other); void operator=(const get_blocks&) = delete; bool operator==(const get_blocks& other) const; bool operator!=(const get_blocks& other) const; static const std::string command; static const uint32_t version_minimum; static const uint32_t version_maximum; private: // 10 sequential hashes, then exponential samples until reaching genesis. hash_list start_hashes_; hash_digest stop_hash_; }; } // namespace message } // namespace libbitcoin #endif
[ "strylets@gmail.com" ]
strylets@gmail.com
4e9462bfd4f431e23a6c242cf7d2832d66c36f99
30cd1a7af92fb1243c33f9b8dde445c29118bd1a
/third_party/allwpilib_2016/wpilibc/shared/src/HLUsageReporting.cpp
bcbc6b6a34d4da7e4a6882abc83df2d2783d4fa9
[ "BSD-2-Clause" ]
permissive
FRC1296/CheezyDriver2016
3907a34fd5f8ccd2c90ab1042782106c0947c0cb
4aa95b16bb63137250d2ad2529b03b2bd56c78c0
refs/heads/master
2016-08-12T23:22:00.077919
2016-03-19T05:56:18
2016-03-19T05:56:18
51,854,487
2
0
null
2016-02-29T10:10:27
2016-02-16T17:27:07
C++
UTF-8
C++
false
false
399
cpp
#include "HLUsageReporting.h" HLUsageReportingInterface* HLUsageReporting::impl = nullptr; void HLUsageReporting::SetImplementation(HLUsageReportingInterface* i) { impl = i; } void HLUsageReporting::ReportScheduler() { if (impl != nullptr) { impl->ReportScheduler(); } } void HLUsageReporting::ReportSmartDashboard() { if (impl != nullptr) { impl->ReportSmartDashboard(); } }
[ "tkb@cheezy.usfluidtech.com" ]
tkb@cheezy.usfluidtech.com
24ae0e4e28f19ffef83bd74d78153ebd1502da6b
4d99749aaaf023abff4c30d4d113e63fadbb2419
/origin/math/matrix/matrix.test/matrix_1.cpp
9d1e792aa209dc1ffe585cb06a7e64c6af70f323
[ "MIT" ]
permissive
asutton/origin-google
6b6a6dd33c9677f5f5fb326f75620f4e419927b6
516482c081a357a06402e5f288d645d3e18f69fa
refs/heads/master
2021-07-24T23:00:57.341960
2017-11-03T13:24:00
2017-11-03T13:24:00
109,394,139
7
1
null
null
null
null
UTF-8
C++
false
false
2,887
cpp
// Copyright (c) 2008-2010 Kent State University // Copyright (c) 2011-2012 Texas A&M University // // This file is distributed under the MIT License. See the accompanying file // LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms // and conditions. #include <iostream> #include <origin/math/matrix/matrix.hpp> using namespace std; using namespace origin; // Tests for 1D use of matrices: void test_init() { // Value initialization matrix<int, 1> m1 { 1, 2, 3, 4 }; assert(m1.extent(0) == 4); assert(m1.size() == 4); cout << m1 << '\n'; // Check initialization patterns for 1D matrices (vectors). // Using parens calls the size initializer. matrix<int, 1> m2(5); assert(m2.extent(0) == 5); cout << m2 << '\n'; // Make sure that we can be completely ambiguous and still get the right // thing. That is, 3 is interpreted as a dimension and not a value. matrix<std::size_t, 1> m3(3); assert(m3.extent(0) == 3); cout << m3 << '\n'; // Using parens *always* is always a bounds initializer. matrix<std::size_t, 1> m4(2ul); cout << m4 << '\n'; // Using braces is always a value initializer. // This should emit a deleted function error since it would require // narrowing (the deleted constructor is selected). // matrix<std::size_t, 1> m5{1, 2, 3}; // But this needs to be ok since we have an exact match for value // initialization. matrix<std::size_t, 1> m6{1ul, 2ul}; cout << m6 << '\n'; } void test_access() { // Test element access. matrix<int, 1> m {0, 1, 2, 3}; assert(m(0) == 0); // Test slicing. Note that slices in 1D are proxies. assert(m[0] == 0); assert(m.row(0) == 0); // Iterators increase monotonically. auto i = m.begin(); int n = 0; for ( ; i != m.end(); ++i, ++n) assert(*i == n); } void test_slice() { cout << "--- slice ---\n"; matrix<int, 1> m {0, 1, 2, 3, 4, 5}; auto s1 = m(2); assert(s1 == 2); // FIXME: Actually implement these checks. auto s2 = m(slice(1, 3)); cout << s2 << '\n'; // 1 2 3 auto s3 = m(slice(1, 5)); // Check at the boundary. cout << s3 << '\n'; // 1 2 3 4 5 // Some identities assert(m(slice(0)) == m); assert(m(slice::all) == m); cout << "----------\n"; } void test_ops() { // Test operations matrix<int, 1> m {0, 1, 2, 3}; m[0] = 1; assert(m(0) == 1); m[0] += 1; assert(m(0) == 2); m[0] -= 1; assert(m(0) == 1); m[0] *= 10; assert(m(0) == 10); m[0] /= 5; assert(m(0) == 2); m[0] %= 2; assert(m(0) == 0); matrix<int, 1> m2 {4, 3, 2, 1}; m += m2; // 4, 4, 4, 4 cout << m << '\n'; m -= m2; // 0, 1, 2, 3 cout << m << '\n'; } int main() { test_init(); test_access(); test_slice(); test_ops(); matrix<int, 1> m {0, 1, 2, 3, 4, 5, 6 }; for (int i = 0; i != 7; ++i) { // assert(&m.s(i) == m.data() + i); } m(0); m(slice(1, 2)); }
[ "andrew.n.sutton@gmail.com" ]
andrew.n.sutton@gmail.com
1d84795b439d4e2ba2b7dbc97628d1466d024003
21ede326b6cfcf5347ca6772d392d3acca80cfa0
/ash/shell_port_mash.cc
3c952fb8fc1eeccc1e9459693fd35706b01d1578
[ "BSD-3-Clause" ]
permissive
csagan5/kiwi
6eaab0ab4db60468358291956506ad6f889401f8
eb2015c28925be91b4a3130b3c2bee2f5edc91de
refs/heads/master
2020-04-04T17:06:54.003121
2018-10-24T08:20:01
2018-10-24T08:20:01
156,107,399
2
0
null
null
null
null
UTF-8
C++
false
false
10,192
cc
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/shell_port_mash.h" #include <memory> #include <utility> #include "ash/accelerators/accelerator_controller.h" #include "ash/accelerators/accelerator_controller_registrar.h" #include "ash/display/display_synchronizer.h" #include "ash/host/ash_window_tree_host_init_params.h" #include "ash/host/ash_window_tree_host_mus.h" #include "ash/keyboard/keyboard_ui_mash.h" #include "ash/public/cpp/config.h" #include "ash/public/cpp/immersive/immersive_fullscreen_controller.h" #include "ash/public/cpp/shell_window_ids.h" #include "ash/shell.h" #include "ash/touch/touch_transform_setter_mus.h" #include "ash/window_manager.h" #include "ash/wm/drag_window_resizer_mash.h" #include "ash/wm/immersive_handler_factory_mash.h" #include "ash/wm/tablet_mode/tablet_mode_event_handler.h" #include "ash/wm/window_cycle_event_filter.h" #include "ash/wm/window_resizer.h" #include "ash/wm/window_util.h" #include "ash/wm/workspace/workspace_event_handler_mash.h" #include "services/ui/public/interfaces/constants.mojom.h" #include "services/ui/public/interfaces/video_detector.mojom.h" #include "ui/aura/env.h" #include "ui/aura/mus/window_tree_host_mus_init_params.h" #include "ui/aura/window.h" #include "ui/display/display.h" #include "ui/display/manager/display_manager.h" #include "ui/display/manager/forwarding_display_delegate.h" #include "ui/display/mojo/native_display_delegate.mojom.h" #include "ui/views/mus/pointer_watcher_event_router.h" namespace ash { ShellPortMash::ShellPortMash( WindowManager* window_manager, views::PointerWatcherEventRouter* pointer_watcher_event_router) : window_manager_(window_manager), pointer_watcher_event_router_(pointer_watcher_event_router), immersive_handler_factory_( std::make_unique<ImmersiveHandlerFactoryMash>()) { DCHECK(window_manager_); DCHECK(pointer_watcher_event_router_); DCHECK_EQ(Config::MASH, GetAshConfig()); } ShellPortMash::~ShellPortMash() = default; // static ShellPortMash* ShellPortMash::Get() { const ash::Config config = ShellPort::Get()->GetAshConfig(); CHECK_EQ(Config::MASH, config); return static_cast<ShellPortMash*>(ShellPort::Get()); } void ShellPortMash::Shutdown() { display_synchronizer_.reset(); ShellPort::Shutdown(); } Config ShellPortMash::GetAshConfig() const { return Config::MASH; } std::unique_ptr<display::TouchTransformSetter> ShellPortMash::CreateTouchTransformDelegate() { return std::make_unique<TouchTransformSetterMus>( window_manager_->connector()); } void ShellPortMash::LockCursor() { // When we are running in mus, we need to keep track of state not just in the // window server, but also locally in ash because ash treats the cursor // manager as the canonical state for now. NativeCursorManagerAsh will keep // this state, while also forwarding it to the window manager for us. window_manager_->window_manager_client()->LockCursor(); } void ShellPortMash::UnlockCursor() { window_manager_->window_manager_client()->UnlockCursor(); } void ShellPortMash::ShowCursor() { window_manager_->window_manager_client()->SetCursorVisible(true); } void ShellPortMash::HideCursor() { window_manager_->window_manager_client()->SetCursorVisible(false); } void ShellPortMash::SetCursorSize(ui::CursorSize cursor_size) { window_manager_->window_manager_client()->SetCursorSize(cursor_size); } void ShellPortMash::SetGlobalOverrideCursor( base::Optional<ui::CursorData> cursor) { window_manager_->window_manager_client()->SetGlobalOverrideCursor( std::move(cursor)); } bool ShellPortMash::IsMouseEventsEnabled() { return cursor_touch_visible_; } void ShellPortMash::SetCursorTouchVisible(bool enabled) { window_manager_->window_manager_client()->SetCursorTouchVisible(enabled); } void ShellPortMash::OnCursorTouchVisibleChanged(bool enabled) { cursor_touch_visible_ = enabled; } std::unique_ptr<WindowResizer> ShellPortMash::CreateDragWindowResizer( std::unique_ptr<WindowResizer> next_window_resizer, wm::WindowState* window_state) { return std::make_unique<ash::DragWindowResizerMash>( std::move(next_window_resizer), window_state); } std::unique_ptr<WindowCycleEventFilter> ShellPortMash::CreateWindowCycleEventFilter() { // TODO: implement me, http://crbug.com/629191. return nullptr; } std::unique_ptr<wm::TabletModeEventHandler> ShellPortMash::CreateTabletModeEventHandler() { // TODO: need support for window manager to get events before client: // http://crbug.com/624157. NOTIMPLEMENTED_LOG_ONCE(); return nullptr; } std::unique_ptr<WorkspaceEventHandler> ShellPortMash::CreateWorkspaceEventHandler(aura::Window* workspace_window) { return std::make_unique<WorkspaceEventHandlerMash>(workspace_window); } std::unique_ptr<KeyboardUI> ShellPortMash::CreateKeyboardUI() { return KeyboardUIMash::Create(window_manager_->connector()); } void ShellPortMash::AddPointerWatcher(views::PointerWatcher* watcher, views::PointerWatcherEventTypes events) { // TODO: implement drags for mus pointer watcher, http://crbug.com/641164. // NOTIMPLEMENTED_LOG_ONCE drags for mus pointer watcher. pointer_watcher_event_router_->AddPointerWatcher( watcher, events == views::PointerWatcherEventTypes::MOVES); } void ShellPortMash::RemovePointerWatcher(views::PointerWatcher* watcher) { pointer_watcher_event_router_->RemovePointerWatcher(watcher); } bool ShellPortMash::IsTouchDown() { // TODO: implement me, http://crbug.com/634967. return false; } void ShellPortMash::ToggleIgnoreExternalKeyboard() { NOTIMPLEMENTED_LOG_ONCE(); } void ShellPortMash::CreatePointerWatcherAdapter() { // In Config::CLASSIC PointerWatcherAdapterClassic must be created when this // function is called (it is order dependent), that is not the case with // Config::MASH. } std::unique_ptr<AshWindowTreeHost> ShellPortMash::CreateAshWindowTreeHost( const AshWindowTreeHostInitParams& init_params) { auto display_params = std::make_unique<aura::DisplayInitParams>(); display_params->viewport_metrics.bounds_in_pixels = init_params.initial_bounds; display_params->viewport_metrics.device_scale_factor = init_params.device_scale_factor; display_params->viewport_metrics.ui_scale_factor = init_params.ui_scale_factor; display::DisplayManager* display_manager = Shell::Get()->display_manager(); display::Display mirrored_display = display_manager->GetMirroringDisplayById(init_params.display_id); if (mirrored_display.is_valid()) { display_params->display = std::make_unique<display::Display>(mirrored_display); } display_params->is_primary_display = true; display_params->mirrors = display_manager->software_mirroring_display_list(); aura::WindowTreeHostMusInitParams aura_init_params = window_manager_->window_manager_client()->CreateInitParamsForNewDisplay(); aura_init_params.display_id = init_params.display_id; aura_init_params.display_init_params = std::move(display_params); aura_init_params.use_classic_ime = !Shell::ShouldUseIMEService(); return std::make_unique<AshWindowTreeHostMus>(std::move(aura_init_params)); } void ShellPortMash::OnCreatedRootWindowContainers( RootWindowController* root_window_controller) { // TODO: To avoid lots of IPC AddActivationParent() should take an array. // http://crbug.com/682048. aura::Window* root_window = root_window_controller->GetRootWindow(); for (size_t i = 0; i < kNumActivatableShellWindowIds; ++i) { window_manager_->window_manager_client()->AddActivationParent( root_window->GetChildById(kActivatableShellWindowIds[i])); } UpdateSystemModalAndBlockingContainers(); } void ShellPortMash::UpdateSystemModalAndBlockingContainers() { std::vector<aura::BlockingContainers> all_blocking_containers; for (RootWindowController* root_window_controller : Shell::GetAllRootWindowControllers()) { aura::BlockingContainers blocking_containers; wm::GetBlockingContainersForRoot( root_window_controller->GetRootWindow(), &blocking_containers.min_container, &blocking_containers.system_modal_container); all_blocking_containers.push_back(blocking_containers); } window_manager_->window_manager_client()->SetBlockingContainers( all_blocking_containers); } void ShellPortMash::OnHostsInitialized() { display_synchronizer_ = std::make_unique<DisplaySynchronizer>( window_manager_->window_manager_client()); } std::unique_ptr<display::NativeDisplayDelegate> ShellPortMash::CreateNativeDisplayDelegate() { display::mojom::NativeDisplayDelegatePtr native_display_delegate; if (window_manager_->connector()) { window_manager_->connector()->BindInterface(ui::mojom::kServiceName, &native_display_delegate); } return std::make_unique<display::ForwardingDisplayDelegate>( std::move(native_display_delegate)); } std::unique_ptr<AcceleratorController> ShellPortMash::CreateAcceleratorController() { uint16_t accelerator_namespace_id = 0u; const bool add_result = window_manager_->GetNextAcceleratorNamespaceId(&accelerator_namespace_id); // ShellPortMash is created early on, so that GetNextAcceleratorNamespaceId() // should always succeed. DCHECK(add_result); accelerator_controller_registrar_ = std::make_unique<AcceleratorControllerRegistrar>( window_manager_, accelerator_namespace_id); return std::make_unique<AcceleratorController>( accelerator_controller_registrar_.get()); } void ShellPortMash::AddVideoDetectorObserver( viz::mojom::VideoDetectorObserverPtr observer) { // We may not have access to the connector in unit tests. if (!window_manager_->connector()) return; ui::mojom::VideoDetectorPtr video_detector; window_manager_->connector()->BindInterface(ui::mojom::kServiceName, &video_detector); video_detector->AddObserver(std::move(observer)); } } // namespace ash
[ "team@geometry.ee" ]
team@geometry.ee
5a39832290e98aa8d43198b3c94c512c533fc812
30ddfa3cae3743090df23df96c4bfec8e757d418
/BlackJack1/BlackJack1/Card.cpp
67405d15a674d5887a4cc16fff700d1f1b9ceb6b
[]
no_license
Reza-Amani/BlackJack-Cpp
5c4c3f49ecb5fa36925a4cb532c9d39c4ab2ad8f
8ae8d3c653a47da991dcea9364faaebff1c5d55b
refs/heads/master
2020-03-31T04:26:06.062478
2018-10-21T09:55:34
2018-10-21T09:55:34
151,904,907
0
0
null
null
null
null
UTF-8
C++
false
false
197
cpp
#include "stdafx.h" #include "Card.h" Card::Card(Suits s, Ranks r) { suit = s; rank = r; rule = rule } int Card::get_value(Irule& rule) { return rule.card_value(this); } Card::~Card() { }
[ "reza.amani@gmail.com" ]
reza.amani@gmail.com
c3aa1fdb85bc7db2936ac7ae0062bd7528e09d30
65702ad9670aaf0ac9da4d20477d636029d8277a
/cosim/bfmTests/srotKeyTest/c_module.cc
adafb0ded89e437897e054f6a37623f2fe1b40d7
[ "BSD-2-Clause-Views", "BSD-2-Clause" ]
permissive
animeshbchowdhury/CEP
87f3cc7c1fdf2c7b4ee2c8ce1982ec67385245e2
0eb7170a5f31aa44b6590b706d0daf0c50a49a27
refs/heads/master
2023-05-11T05:52:48.811207
2021-05-24T14:13:01
2021-05-24T14:13:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,233
cc
//************************************************************************ // Copyright 2021 Massachusetts Institute of Technology // SPDX License Identifier: MIT // // File Name: // Program: Common Evaluation Platform (CEP) // Description: // Notes: // //************************************************************************ #include "v2c_cmds.h" #include "simPio.h" // #include "shMem.h" #include "c_module.h" #include <unistd.h> #include "random48.h" #include "cep_apis.h" #include "simdiag_global.h" #include "cepSrotTest.h" // void *c_module(void *arg) { // ====================================== // Set up // ====================================== pthread_parm_t *tParm = (pthread_parm_t *)arg; int errCnt = 0; int slotId = tParm->slotId; int cpuId = tParm->cpuId; int verbose = tParm->verbose; Int32U seed = tParm->seed; int restart = tParm->restart; int offset = GET_OFFSET(slotId,cpuId); GlobalShMemory.getSlotCpuId(offset,&slotId,&cpuId); //printf("offset=%x seed=%x verbose=%x GlobalShMemory=%x\n",offset,seed, verbose,(unsigned long) &GlobalShMemory); // notify I am Alive!!! shIpc *ptr = GlobalShMemory.getIpcPtr(offset); ptr->SetAliveStatus(); sleep(1); // ====================================== // Test is Here // ====================================== simPio pio; pio.MaybeAThread(); // chec pio.EnableShIpc(1); pio.SetVerbose(verbose); // // ====================================== // Test starts here // ====================================== // MUST // wait until Calibration is done.. //int calibDone = calibrate_ddr3(50); pio.RunClk(1000); // int mask = seed; // seed is used as cpuActiveMask from c_displatch if (!errCnt) { errCnt = cepSrotTest_maxKeyTest(cpuId, verbose); } // pio.RunClk(100); // // ====================================== // Exit // ====================================== cleanup: if (errCnt != 0) { LOGI("======== TEST FAIL ========== %x\n",errCnt); } else { LOGI("======== TEST PASS ========== \n"); } // shIpc *ptr = GlobalShMemory.getIpcPtr(offset); ptr->SetError(errCnt); ptr->SetThreadDone(); pthread_exit(NULL); return ((void *)NULL); }
[ "pa25523@561195-mitll.llan.ll.mit.edu" ]
pa25523@561195-mitll.llan.ll.mit.edu
e64fb11fa157eef645cc9f60471d1167aa1c820f
c9ea4b7d00be3092b91bf157026117bf2c7a77d7
/比赛/雅礼集训/20190107/sum_bf.cpp
2e0c8d31dcf67360aaaadaffa07f0fe4df31e9a6
[]
no_license
Jerry-Terrasse/Programming
dc39db2259c028d45c58304e8f29b2116eef4bfd
a59a23259d34a14e38a7d4c8c4d6c2b87a91574c
refs/heads/master
2020-04-12T08:31:48.429416
2019-04-20T00:32:55
2019-04-20T00:32:55
162,387,499
3
0
null
null
null
null
UTF-8
C++
false
false
862
cpp
#include<iostream> #include<algorithm> #include<cstdlib> #define int long long #define MAXN 77 using namespace std; int f[MAXN],fc=0,n=1,now=0,ans=0,ansnow=0; inline void judge(); signed main() { register int i=0; if(n>30) { exit(0); } for(now=0;now<(1LL<<n);++now) { judge(); } cout<<ans<<':'; for(i=0;i<n;++i) { if(ansnow>>i&1) { cout<<i+1<<' '; } } cout<<endl; ++n; main(); return 0; } inline void judge() { register int i=0,j=0; for(i=fc=0;i<n;++i) { if(now>>i&1) { f[++fc]=i+1; } } for(i=1;i<=fc;++i) { for(j=i+1;j<=fc;++j) { if(__gcd(f[i],f[j])>1) { return; } } } for(i=1,j=0;i<=fc;++i) { j+=f[i]; } if(j>ans) { ans=j; ansnow=now; } return; }
[ "3305049949@qq.com" ]
3305049949@qq.com
81c684ac8c56f710e42c58b0b4e3662bdbef547c
1d6f19ced2319e0674ca954a6a4d1994da32b854
/aqcore/mixcomp.h
61b36fc2af16bf0fc6b9f3e8d2d614841fe3a44f
[]
no_license
yojiyojiyoji/AQUASIM
33096096ad81cf84d7adca1afc0fad179ba3f354
83dbdfe625a428c18d1a6ec8672d8146ea2ff0e7
refs/heads/master
2023-07-13T11:58:27.884332
2018-05-09T12:20:01
2018-05-09T12:20:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,127
h
/////////////////////////////// mixcomp.h //////////////////////////////// // // date: person: comments: // // creation: 10.12.91 Peter Reichert // revisions: 26.10.92 Peter Reichert redesign of links // 11.12.92 Peter Reichert variable volume added // 17.05.04 Peter Reichert converted to ANSI C++ // ////////////////////////////////////////////////////////////////////////////// // // "mixcomp" implements a class for mixed reactor compartments // =========================================================== // ////////////////////////////////////////////////////////////////////////////// // // Concepts // ======== // // // // ////////////////////////////////////////////////////////////////////////////// // // Class hierarchy // =============== // // NODE // | // +------+ // | // FILEIO | // | | // +------+----SYMBOL // | // +----AQCOMP // | // +----MIXCOMP // ////////////////////////////////////////////////////////////////////////////// // // Classes // ======= // // The following class is implemented in this file: // // MIXCOMP: class for mixed compartments // -------- // // ////////////////////////////////////////////////////////////////////////////// // // Methods of the class MIXCOMP // ============================ // // // // // // ////////////////////////////////////////////////////////////////////////////// #ifndef MIXCOMP_H #define MIXCOMP_H #include "aqcomp.h" ////////////////////////////////////////////////////////////////////////////// class MIXCOMP : public AQCOMP { friend class COMPSYS; public: MIXCOMP(); MIXCOMP(const MIXCOMP& com); MIXCOMP(const AQCOMP* com); ~MIXCOMP(); AQCOMPTYPE Type() const { return MixComp; } const char* TypeName() const; AQVAR* SpaceVar(const VARSYS*) const { return 0; } BOOLEAN AllowedSpaceVal(REAL) const { return TRUE; } BOOLEAN AllowedProgVarType(PROGVARTYPE type) const; BOOLEAN AllowedReplaceVar(const AQVAR* oldvar, const AQVAR* newvar) const; BOOLEAN AllowedExchangeVar(const AQVAR* var1, const AQVAR* var2) const; BOOLEAN AllowedComp() const; BOOLEAN AddInitCond(const VARLIST* varlist, CARDINAL zone, AQVAR* var, const char* inpline, char* errorline, CARDINAL& numparseerrors, CARDINAL pos=CARDINAL_MAX); BOOLEAN ReplaceInitCond(const VARLIST* varlist, CARDINAL zone, AQVAR* var, const char* inpline, char* errorline, CARDINAL& numparseerrors, CARDINAL pos); BOOLEAN DeleteInitCond(CARDINAL pos); CARDINAL NumInitCond() const { return numinit; } CARDINAL InitZone(CARDINAL index) const; AQVAR* InitVar(CARDINAL index) const; const FORMVAR* InitVal(CARDINAL index) const; BOOLEAN Inflow(const VARLIST* varlist, const char* inpline, char* errorline); const FORMVAR* Inflow() const { return inflow; } BOOLEAN AddInput(const VARLIST* varlist, AQVAR* var, const char* inpline, char* errorline, CARDINAL& numparseerrors, CARDINAL pos=CARDINAL_MAX); BOOLEAN ReplaceInput(const VARLIST* varlist, AQVAR* var, const char* inpline, char* errorline, CARDINAL& numparseerrors, CARDINAL pos); BOOLEAN DeleteInput(CARDINAL pos); CARDINAL NumInput() const { return numinput; } AQVAR* InputVar(CARDINAL index) const; const FORMVAR* InputFlux(CARDINAL index) const; CARDINAL NumGridPts() const { return 1; } BOOLEAN NumGridPts(CARDINAL n); REAL GridPt(const REAL* Y, CARDINAL index); CARDINAL NumZoneGridPts(CARDINAL zone); REAL ZoneGridPt(const REAL* Y, CARDINAL zone, CARDINAL index); CARDINAL NumEq() const; REAL RelAcc(CARDINAL i) const; REAL AbsAcc(CARDINAL i) const; EQTYPE EqType(CARDINAL i) const; BOOLEAN InitCond(VARSYS* varsys, REAL* Y, CARDINAL callnum); BOOLEAN Delta(const NUMPAR& numpar, VARSYS* varsys, const REAL* Y, const REAL* YT, REAL* DELTA); BOOLEAN GridValue(VARSYS* varsys, CARDINAL* calcnum_ptr, REAL* t_ptr, const REAL* Y, CARDINAL zone, CARDINAL pt, AQVAR* var, REAL& value); BOOLEAN SpaceValue(VARSYS* varsys, CARDINAL* calcnum_ptr, REAL* t_ptr, const REAL* Y, CARDINAL zone, REAL x, BOOLEAN xrel, AQVAR* var, REAL& value); BOOLEAN FixedVol() const { return fixedvol; } BOOLEAN FixedVol(BOOLEAN b); REAL Vol() const { return vol; } BOOLEAN Vol(REAL v); BOOLEAN Outflow(const char* inpline, const VARLIST* varlist, char* errorline, CARDINAL& numparseerrors); const FORMVAR* Outflow() { return Qout; } CARDINAL NumZones() const; const char* ZoneName(CARDINAL index) const; const char* AdvInName(CARDINAL conn) const; const char* AdvOutName(CARDINAL conn) const; const char* DiffName(CARDINAL conn) const; BOOLEAN AdvInExZ(CARDINAL conn) const; REAL AdvInZ(const REAL* Y, CARDINAL conn) const; REAL AdvOutQ(VARSYS* varsys, const REAL* Y, CARDINAL conn); REAL AdvOutJ(VARSYS* varsys, const REAL* Y, CARDINAL conn, const AQVAR* var); REAL DiffC(const REAL* Y, CARDINAL conn, const AQVAR* var) const; BOOLEAN AccQ(REAL relacc, REAL absacc); BOOLEAN AccV(REAL relacc, REAL absacc); REAL RelAccQ() const { return relaccQ; } REAL AbsAccQ() const { return absaccQ; } REAL RelAccV() const { return relaccV; } REAL AbsAccV() const { return absaccV; } JOBSTATUS Load(std::istream& in,const VARLIST* varlist, const PROCLIST* proclist); JOBSTATUS Save(std::ostream& out); JOBSTATUS Write(std::ostream& out, BOOLEAN sh=FALSE); private: CARDINAL numinit; CARDINAL* initzone; AQVAR** initvar; FORMVAR** initval; FORMVAR* inflow; CARDINAL numinput; AQVAR** inputvar; FORMVAR** inputflux; BOOLEAN fixedvol; REAL vol; FORMVAR* Qout; REAL* Cout; CARDINAL numCout; REAL relaccQ; REAL absaccQ; REAL relaccV; REAL absaccV; void ReplVar(AQVAR* oldvar, AQVAR* newvar); void ExchVar(AQVAR* var1, AQVAR* var2); BOOLEAN SetGridPts(CARDINAL n); void CalcArg(); void init(); void del(); }; ////////////////////////////////////////////////////////////////////////////// #endif //////////////////////////////////////////////////////////////////////////////
[ "jstachelek@utexas.edu" ]
jstachelek@utexas.edu
e811e994c26fb180a2a00e2603351cb1258dc10b
6d6b2ad24779426fcee731602dfcff99d90bd3f8
/thrift/thrift/lib/cpp/test/gen-cpp/AnnotationTest_constants.cpp
496996a6b952f1aac746b156c146b7282e47fe52
[ "Apache-2.0" ]
permissive
XiongWD/RPC-CPP-PHP
e050dd95a06c684f4b16fab906eb15be04eb38fe
2573f240a26d3b27e6aea101171eceb9f7cfe8d9
refs/heads/master
2021-01-20T16:38:53.858121
2017-05-10T10:27:05
2017-05-10T10:27:05
90,845,780
0
0
null
null
null
null
UTF-8
C++
false
true
300
cpp
/** * Autogenerated by Thrift Compiler (1.0.0-dev) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #include "AnnotationTest_constants.h" const AnnotationTestConstants g_AnnotationTest_constants; AnnotationTestConstants::AnnotationTestConstants() { }
[ "hbuedxw@163.com" ]
hbuedxw@163.com
de3512ab95206c37c843ccfe9be0143f7396947c
63ade4b3fde43919e649929a8331c153d9ed7e19
/unittests/common/split.hpp
f94b9bda52d94a54fbe5eb83bd1011671baee207
[ "LLVM-exception", "Apache-2.0" ]
permissive
paulhuggett/pstore
ff33c91e953cbdf37a6f6d7874e03913788bf6e7
e6465e0d49ad317cdca9aa0914cd91a6ea9a94ee
refs/heads/main
2023-08-15T06:47:19.934465
2023-07-28T14:55:10
2023-07-28T14:55:10
321,625,810
0
0
NOASSERTION
2021-03-09T21:30:51
2020-12-15T10:00:51
C++
UTF-8
C++
false
false
1,868
hpp
//===- unittests/common/split.hpp -------------------------*- mode: C++ -*-===// //* _ _ _ * //* ___ _ __ | (_) |_ * //* / __| '_ \| | | __| * //* \__ \ |_) | | | |_ * //* |___/ .__/|_|_|\__| * //* |_| * //===----------------------------------------------------------------------===// // // Part of the pstore project, under the Apache License v2.0 with LLVM Exceptions. // See https://github.com/paulhuggett/pstore/blob/master/LICENSE.txt for license // information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef SPLIT_HPP #define SPLIT_HPP #include <algorithm> #include <cctype> #include <cwctype> #include <iterator> #include <string> #include <vector> #include "pstore/support/ctype.hpp" template <typename StringType> std::vector<StringType> split_lines (StringType const & s) { std::vector<StringType> result; typename StringType::size_type pos = 0; for (;;) { auto const cr_pos = s.find_first_of ('\n', pos); auto count = (cr_pos == StringType::npos) ? StringType::npos : cr_pos - pos; result.emplace_back (s, pos, count); if (count == StringType::npos) { break; } pos = cr_pos + 1; } return result; } template <typename StringType> std::vector<StringType> split_tokens (StringType const & s) { std::vector<StringType> result; using char_type = typename StringType::value_type; auto is_space = [] (char_type c) { return pstore::isspace (c); }; auto it = std::begin (s); auto end = std::end (s); while (it != end) { it = std::find_if_not (it, end, is_space); // skip leading whitespace auto start = it; it = std::find_if (it, end, is_space); if (start != it) { result.emplace_back (start, it); } } return result; } #endif // SPLIT_HPP
[ "paulhuggett@mac.com" ]
paulhuggett@mac.com
65f37ac1e86955a2286503879fe6c90954a1784c
1eb36ccc0aa5c470ed062a82953b7c2677d9d2ac
/c_and_cpp/other_projects/computer_graphics_module_labs/week07/bezier.cc
7fe269ec3d9026b9c3e12419dcf8464cce0321a5
[]
no_license
carlawarde/projects
ffaaa85fd30d64e445294af947225c839ef33f55
f11ca63ef9921530322c323bace99f834b5947b8
refs/heads/master
2021-08-03T06:45:54.409835
2021-07-30T19:04:46
2021-07-30T19:04:46
191,652,705
2
1
null
2021-07-30T19:04:47
2019-06-12T22:23:55
HTML
UTF-8
C++
false
false
6,108
cc
#include <GL/glut.h> #include <stdlib.h> #include <math.h> #include <iostream> #if !defined(GLUT_WHEEL_UP) # define GLUT_WHEEL_UP 3 # define GLUT_WHEEL_DOWN 4 #endif /* Set initial size of the display window. */ GLsizei winWidth = 600, winHeight = 600; GLsizei newWidth, newHeight; /* Set size of world-coordinate clipping window. */ GLfloat xwcMin = -50.0, xwcMax = 50.0; GLfloat ywcMin = -50.0, ywcMax = 50.0; bool leftButton = false, middleButton = false; int downX, downY; int startMouseX, startMouseY, startTransX, startTransY, curTransX, curTransY; float zoom = 1.0; class wcPt3D { public: GLfloat x, y, z; }; void init (void) { /* Set color of display window to white. */ glClearColor (1.0, 1.0, 1.0, 0.0); } void plotPoint (wcPt3D bezCurvePt) { glBegin (GL_POINTS); glVertex2f (bezCurvePt.x, bezCurvePt.y); glEnd ( ); } /* Compute binomial coefficients C for given value of n. */ void binomialCoeffs (GLint n, GLint * C) { GLint k, j; for (k = 0; k <= n; k++) { /* Compute n!/(k!(n - k)!). */ C [k] = 1; for (j = n; j >= k + 1; j--) C [k] *= j; for (j = n - k; j >= 2; j--) C [k] /= j; } } void computeBezPt (GLfloat t, wcPt3D * bezPt, GLint nCtrlPts, wcPt3D * ctrlPts, GLint * C) { GLint k, n = nCtrlPts - 1; GLfloat bezBlendFcn; bezPt->x = bezPt->y = bezPt->z = 0.0; /* Compute blending functions and blend control points. */ for (k = 0; k < nCtrlPts; k++) { bezBlendFcn = C [k] * pow (t, k) * pow (1 - t, n - k); bezPt->x += ctrlPts [k].x * bezBlendFcn; bezPt->y += ctrlPts [k].y * bezBlendFcn; bezPt->z += ctrlPts [k].z * bezBlendFcn; } } void bezier (wcPt3D * ctrlPts, GLint nCtrlPts, GLint nBezCurvePts) { wcPt3D bezCurvePt; GLfloat t; GLint *C; /* Allocate space for binomial coefficients */ C = new GLint [nCtrlPts]; binomialCoeffs (nCtrlPts - 1, C); for (int i = 0; i <= nBezCurvePts; i++) { t = GLfloat (i) / GLfloat (nBezCurvePts); computeBezPt (t, &bezCurvePt, nCtrlPts, ctrlPts, C); plotPoint (bezCurvePt); } delete [ ] C; } void displayFcn (void) { glClear (GL_COLOR_BUFFER_BIT); // Clear display window. if(leftButton){ glMatrixMode (GL_PROJECTION); glLoadIdentity ( ); double w = glutGet( GLUT_WINDOW_WIDTH ); double h = glutGet( GLUT_WINDOW_HEIGHT ); glTranslatef( curTransX / w * 2, curTransY / h * 2, 0 ); gluOrtho2D (xwcMin, xwcMax, ywcMin, ywcMax); glMatrixMode (GL_MODELVIEW); glLoadIdentity(); } /* Set example number of control points and number of * curve positions to be plotted along the Bezier curve. */ GLint nCtrlPts = 4, nBezCurvePts = 1000; wcPt3D ctrlPts [4] = { {-40.0, -40.0, 0.0}, {-10.0, 200.0, 0.0}, {10.0, -200.0, 0.0}, {40.0, 40.0, 0.0} }; glPointSize (4); glColor3f (1.0, 0.0, 0.0); // Set point color to red. bezier (ctrlPts, nCtrlPts, nBezCurvePts); glutSwapBuffers(); } void winReshapeFcn (GLint newWidth, GLint newHeight) { /* Maintain an aspect ratio of 1.0. */ // glViewport (0, 0, newHeight, newHeight); if(newWidth >= newHeight) glViewport(0,0, newHeight, newHeight); else glViewport(0,0, newWidth, newWidth); glMatrixMode (GL_PROJECTION); glLoadIdentity ( ); gluOrtho2D (xwcMin, xwcMax, ywcMin, ywcMax); glutPostRedisplay(); } void MouseCallback(int button, int state, int x, int y) { downX = x; downY = y; int mod; leftButton = ((button == GLUT_LEFT_BUTTON) && (state == GLUT_DOWN)); mod = glutGetModifiers(); if(leftButton) { startMouseX = x; startMouseY = glutGet(GLUT_WINDOW_HEIGHT) - y; startTransX = curTransX; startTransY = curTransY; } if(mod == GLUT_ACTIVE_CTRL && button == 3) { zoom = zoom * 0.75; glLoadIdentity ( ); if(winWidth >= winHeight) gluOrtho2D ((newHeight/2) - zoom,(newHeight/2) + zoom, (newHeight/2) - zoom, (newHeight/2) + zoom); else gluOrtho2D ((newWidth/2) - zoom,(newWidth/2) + zoom, (newWidth/2) - zoom, (newWidth/2) + zoom); glutPostRedisplay(); } else if(mod == GLUT_ACTIVE_CTRL && button == 4) { zoom = zoom * 1.5; glLoadIdentity ( ); if(winWidth >= winHeight) gluOrtho2D ((newHeight/2) - zoom,(newHeight/2) + zoom, (newHeight/2) - zoom, (newHeight/2) + zoom); else gluOrtho2D ((newWidth/2) - zoom,(newWidth/2) + zoom, (newWidth/2) - zoom, (newWidth/2) + zoom); glutPostRedisplay(); } } void MotionCallback(int x, int y) { downX = x; downY = y; int curMouseX = x; int curMouseY = glutGet( GLUT_WINDOW_HEIGHT) - y; if (leftButton) { curTransX = startTransX + (curMouseX - startMouseX ); curTransY = startTransY + (curMouseY - startMouseY ); } glutPostRedisplay(); } void keyPress(unsigned char key, int x, int y) { if(key == 'z') { zoom = zoom * 0.75; glLoadIdentity ( ); if(winWidth >= winHeight) gluOrtho2D ((newHeight/2) - zoom,(newHeight/2) + zoom, (newHeight/2) - zoom, (newHeight/2) + zoom); else gluOrtho2D ((newWidth/2) - zoom,(newWidth/2) + zoom, (newWidth/2) - zoom, (newWidth/2) + zoom); glutPostRedisplay(); } else if(key == 'Z') { zoom = zoom * 1.5; glLoadIdentity ( ); if(winWidth >= winHeight) gluOrtho2D ((newHeight/2) - zoom,(newHeight/2) + zoom, (newHeight/2) - zoom, (newHeight/2) + zoom); else gluOrtho2D ((newWidth/2) - zoom,(newWidth/2) + zoom, (newWidth/2) - zoom, (newWidth/2) + zoom); glutPostRedisplay(); } } int main (int argc, char** argv) { glutInit (&argc, argv); glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB); glutInitWindowPosition (50, 50); glutInitWindowSize (winWidth, winHeight); glutCreateWindow ("Bezier Curve"); init ( ); glutDisplayFunc (displayFcn); glutReshapeFunc (winReshapeFcn); glutKeyboardFunc(keyPress); glutMouseFunc(MouseCallback); glutMotionFunc(MotionCallback); glutMainLoop ( ); }
[ "carla.warde98@gmail.com" ]
carla.warde98@gmail.com
18d0670eab4b1f80eda0ee1ba12603de101f3b5d
750395d2f5d37b1f30b8b1920e11e040cbe401c4
/FHE/Random_Coins.h
24b9b8d7ff461ac2da1f4b6240bc5741307ef578
[ "MIT", "BSD-2-Clause" ]
permissive
AlexanderViand/MP-SPDZ
b4c920e45143f710c9371cab4c37b63da5420ed7
d26a62efe496946d721b0ab49710494cea5c9652
refs/heads/master
2020-05-19T08:10:28.857168
2019-05-03T08:03:13
2019-05-03T08:03:50
184,914,569
1
0
NOASSERTION
2019-05-04T15:48:59
2019-05-04T15:48:59
null
UTF-8
C++
false
false
2,753
h
#ifndef _Random_Coins #define _Random_Coins /* Randomness used to encrypt */ #include "FHE/FHE_Params.h" #include "FHE/Rq_Element.h" #include "FHE/AddableVector.h" class FHE_PK; class Int_Random_Coins : public AddableMatrix<bigint> { const FHE_Params* params; public: Int_Random_Coins(const FHE_Params& params) : params(&params) { resize(3, params.phi_m()); } Int_Random_Coins(const FHE_PK& pk); void sample(PRNG& G) { (*this)[0].from(HalfGenerator(G)); for (int i = 1; i < 3; i++) (*this)[i].from(GaussianGenerator(params->get_DG(), G)); } }; class Random_Coins { Rq_Element uu,vv,ww; const FHE_Params *params; public: const FHE_Params& get_params() const { return *params; } Random_Coins(const FHE_Params& p) : uu(p.FFTD(),evaluation,evaluation), vv(p.FFTD(),evaluation,evaluation), ww(p.FFTD(),polynomial,polynomial) { params=&p; } Random_Coins(const FHE_PK& pk); ~Random_Coins() { ; } // Rely on default copy assignment/constructor const Rq_Element& u() const { return uu; } const Rq_Element& v() const { return vv; } const Rq_Element& w() const { return ww; } void assign(const Rq_Element& u,const Rq_Element& v,const Rq_Element& w) { uu=u; vv=v; ww=w; } template <class T> void assign(const vector<T>& u,const vector<T>& v,const vector<T>& w) { uu.from_vec(u); vv.from_vec(v); ww.from_vec(w); } void assign(const Int_Random_Coins& rc) { uu.from_vec(rc[0]); vv.from_vec(rc[1]); ww.from_vec(rc[2]); } /* Generate a standard distribution */ void generate(PRNG& G) { uu.from(HalfGenerator(G)); vv.from(GaussianGenerator(params->get_DG(), G)); ww.from(GaussianGenerator(params->get_DG(), G)); } // Generate all from Uniform in range (-B,...B) void generateUniform(PRNG& G,const bigint& B1,const bigint& B2,const bigint& B3) { if (B1 == 0) uu.assign_zero(); else uu.from(UniformGenerator(G,numBits(B1))); vv.from(UniformGenerator(G,numBits(B2))); ww.from(UniformGenerator(G,numBits(B3))); } // ans,x and y must have same params otherwise error friend void add(Random_Coins& ans, const Random_Coins& x,const Random_Coins& y); // Don't bother outputing params, assumes these are implicitly known friend ostream& operator<<(ostream& s,const Random_Coins& rc) { s << rc.uu << " " << rc.vv << " " << rc.ww; return s; } void pack(octetStream& o) const { uu.pack(o); vv.pack(o); ww.pack(o); } size_t report_size(ReportType type) { return uu.report_size(type) + vv.report_size(type) + ww.report_size(type); } }; #endif
[ "m.keller@bristol.ac.uk" ]
m.keller@bristol.ac.uk
081202f0cee55f7f8d66a4ce480d30d66500133a
649d61a64e19cc44892ecad0dd8fe6164ce594a7
/Student_Cuda_Image/src/cpp/core/01_Rippling/02_provider/RipplingProvider.h
7318cf1686f1560eb58bdc2f1b388612ec7ea007
[]
no_license
thegazou/CUDA
ec2cebb4ba89679cf06d61af758d650c20508407
e2b3828cbd63314e7ddcb9d1ebb0b87f3eb4af7f
refs/heads/master
2021-01-17T21:22:16.519938
2017-05-02T15:33:19
2017-05-02T15:33:19
84,175,648
0
1
null
null
null
null
UTF-8
C++
false
false
909
h
#pragma once #include "cudaTools.h" #include "Provider_I_GPU.h" using namespace gpu; /*----------------------------------------------------------------------*\ |* Declaration *| \*---------------------------------------------------------------------*/ /*--------------------------------------*\ |* Public *| \*-------------------------------------*/ class RipplingProvider: public Provider_I<uchar4> { public: virtual ~RipplingProvider() { // Rien } /*--------------------------------------*\ |* Override *| \*-------------------------------------*/ virtual Animable_I<uchar4>* createAnimable(void); virtual Image_I* createImageGL(void); }; /*----------------------------------------------------------------------*\ |* End *| \*---------------------------------------------------------------------*/
[ "thegazou@romandie.com" ]
thegazou@romandie.com
6c3759a0dcfe688e967003b428f26078ab029b4f
fec3a741c8451d230ffc698880af1cba4c8f5293
/Cards.h
709c80cef121679e2f4ffdba660970d4dfc27f34
[]
no_license
kchandre/GinRummy
536513b58bbcade2c8e56b18704d908842589441
58eb28424ef00d48cfeb699c3e927a167c8fd62b
refs/heads/master
2020-03-15T17:35:58.008953
2018-05-05T17:13:49
2018-05-05T17:13:49
132,265,326
0
2
null
2018-05-05T17:11:14
2018-05-05T16:28:03
C++
UTF-8
C++
false
false
1,422
h
#pragma once #include <iostream> #include <vector> #include <string> #include <algorithm> #include <ctime> using namespace std; #define DECK_SIZE 52 #define CARDS_PER_PLAYER 7 #define NumRanks 13 #define Numsuits 4 #define OffsetR 2 #define ONE 1 #define TEN "10" #define JACK "11" #define QUEEN "12" #define KING "13" #define ACE "14" #define DIAMOND "-D" #define SPADE "-S" #define CLUB "-C" #define HEART "-H" //enumerate rank for card generation //TODO change enum Rank{ Two,Three,Four,Five, Six,Seven,Eight,Nine,Ten, Jack,Queen,King,Ace }; //enumerate suit enum Suit{ D,H,S,C }; //changed function order class Cards { public: void InitializeDeck(); //generate deck void DeckShuffle(); //shuffle deck void CardPop(); //pulls card off top of deck int DeckSize() const; //return size of deck int GetPFromPile() const; //return size of pick up stack void AdjPick(); //generate pick up from stack void PopPick(); //pop off pick up pile string TopCard () const; //return top card from deck void DispAvailCards() const; //display cards string RetCard(const int& number) const; //get card in deck at number string pickFromPile(const int& number) const; //return card @ number void InsertPick(const string& card); //insert card at end of pick pile private: vector<string> Deck; vector<string> FromPile; };
[ "noreply@github.com" ]
kchandre.noreply@github.com
6e37e88e6e31bc0df0a7b7de780561fd3e60dd2a
a7764174fb0351ea666faa9f3b5dfe304390a011
/drv/MoniTool/MoniTool_CaseData.ixx
5b106e74fc341c93fbef8777f1191f6f2fb5ea6f
[]
no_license
uel-dataexchange/Opencascade_uel
f7123943e9d8124f4fa67579e3cd3f85cfe52d91
06ec93d238d3e3ea2881ff44ba8c21cf870435cd
refs/heads/master
2022-11-16T07:40:30.837854
2020-07-08T01:56:37
2020-07-08T01:56:37
276,290,778
0
0
null
null
null
null
UTF-8
C++
false
false
721
ixx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #include <MoniTool_CaseData.jxx> #ifndef _Standard_Type_HeaderFile #include <Standard_Type.hxx> #endif IMPLEMENT_STANDARD_TYPE(MoniTool_CaseData) IMPLEMENT_STANDARD_SUPERTYPE_ARRAY() STANDARD_TYPE(MMgt_TShared), STANDARD_TYPE(Standard_Transient), IMPLEMENT_STANDARD_SUPERTYPE_ARRAY_END() IMPLEMENT_STANDARD_TYPE_END(MoniTool_CaseData) IMPLEMENT_DOWNCAST(MoniTool_CaseData,Standard_Transient) IMPLEMENT_STANDARD_RTTI(MoniTool_CaseData)
[ "shoka.sho2@excel.co.jp" ]
shoka.sho2@excel.co.jp
0ae2413fc84c339218866a79093d55e70b7b9970
6a57649f5af3e5d4b9b92b0a622f43664643a073
/5/11.cpp
1180abc1774764359dabeecc0286445bf93a4e26
[]
no_license
snull/CTU-CE-BP
1602e8fcf7dc0a82a71477ce279ce3e9519f564f
3baa344f995b1fc7b80495da883cd8872b52668b
refs/heads/master
2023-03-02T08:44:10.567498
2021-02-06T00:11:41
2021-02-06T07:12:38
334,291,849
3
0
null
null
null
null
UTF-8
C++
false
false
171
cpp
#include <iostream> using namespace std; int main(){ for(int i=1 ; i<7 ; i++ ){ for(int j=1 ; j<=i ; j++){ cout<<"* "; } cout<<endl; } return 0; }
[ "shayan.mpm@gmail.com" ]
shayan.mpm@gmail.com
714da659bc1678268821a5276d595b767e53a7ea
eee88a0c318799bd5ddc5bde0c3d03e989575251
/qsort.cpp
b0243f05b757bea8b5e3fdc1672459e069cb5146
[]
no_license
CATQ/Hello-world2
778f21a4bea7436d91165c6f709c1c22bc0745b6
3fdadbbc87a5f838fe7149f2e8b10a23de49de7b
refs/heads/master
2021-05-16T10:43:53.180862
2018-01-05T14:51:37
2018-01-05T14:51:37
104,815,929
0
0
null
null
null
null
UTF-8
C++
false
false
438
cpp
#include<stdio.h> int a[200]; int qsort(int r, int l) { int mid, t; int x = r; int y = l; mid = (x+y)/2; while (x < y) { while (a[x]<a[mid]) x++; while (a[y]>a[mid]) y--; if (x<=y) { t= a[x];a[x] = a[y];a[y] = t; x++;y--; } } if (x<l) qsort(x,l); if (y>r) qsort(r,y); } int main() { int i, n; scanf("%d", &n); for (i=1; i<=n; i++) scanf("%d", &a[i]); qsort(1,n); for (i=1; i<=n; i++) printf("%d ", a[i]); }
[ "819735890@qq.com" ]
819735890@qq.com
3d1116de5c6887368201f3e3b5145addecd4204c
295710c5c59ba965149c1183b8e39ea28e195738
/ToirPlus_Old_Src/LoLBot/TabTwo.cpp
bb703dc8b26e121ab7d518bd2b9022c0914bb338
[]
no_license
PrtectInt3/ToirPlus_SRC
cfeee7e10eb9a4ba415d63511c4703f887c581fb
7f2084580caffd4f0e580b55cf59ec1e07ed523c
refs/heads/main
2023-02-25T17:43:47.771388
2021-01-28T21:11:07
2021-01-28T21:11:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
873
cpp
// TabTwo.cpp : implementation file // #include "stdafx.h" #include "LoLBot.h" #include "TabTwo.h" // CTabTwo dialog IMPLEMENT_DYNAMIC(CTabTwo, CDialog) CTabTwo::CTabTwo(CWnd* pParent /*=NULL*/) : CDialog(CTabTwo::IDD, pParent) { } CTabTwo::~CTabTwo() { } void CTabTwo::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CTabTwo, CDialog) ON_CONTROL_RANGE(BN_CLICKED, LOLBOT_TAT_BAT_VE, LOLBOT_VE_ENEMY_SKILL_R, OnTab2ChecBoxStatusChanged) END_MESSAGE_MAP() // CTabTwo message handlers //#include "Commons.h" //extern HWND g_hWinAPP; void CTabTwo::OnTab2ChecBoxStatusChanged(UINT nID) { CButton *pCheckBox = (CButton *)GetDlgItem(nID); ::PostMessage(g_hWinAPP, WM_HOOK_WRITE, nID, pCheckBox->GetCheck()); //__oMsg("--------------->[%s][%d]haint--->stt check:%d;ID=%d", __FILE__, __LINE__, pCheckBox->GetCheck(), nID); }
[ "michuelhack@gmail.com" ]
michuelhack@gmail.com
0e115863a7a2a9339c80a116d758ce7717d5c2e2
f9d7775bef11d1621c5e8417046b9161e63eacb7
/include/ipv6_address.h
25357512455b7e2133bbe532f7895a0730393d0f
[]
no_license
sdeming/spirit-parsers
43d6269402a99eae1119d00d2bdc97201ce435ab
98b4b6f671b59d0d33af6bc68091b61ce33714c5
refs/heads/master
2020-05-19T10:34:49.890303
2016-08-25T14:32:13
2016-08-25T14:32:13
546,967
1
0
null
null
null
null
UTF-8
C++
false
false
2,684
h
#ifndef __ipv6_parser_h__ #define __ipv6_parser_h__ #include <boost/config/warning_disable.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_object.hpp> #include "ipv4_address.h" #include <iostream> #include <string> namespace uri { namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::ascii; namespace phoenix = boost::phoenix; /** * Implementation of an ipv6 IP address parser */ template <typename Iterator> struct ipv6_address : qi::grammar<Iterator, std::string()> { ipv6_address() : ipv6_address::base_type(start) { using qi::repeat; using qi::raw; using ascii::xdigit; qi::on_error<qi::fail> ( start, std::cerr << phoenix::val("Error! Expecting") << qi::_4 << phoenix::val(" here: \"") << phoenix::construct<std::string>(qi::_3, qi::_2) << phoenix::val("\"") << std::endl ); h16 = repeat(1,4)[xdigit]; ls32 = h16 >> ':' >> h16 | ipv4 ; ipv6_attr = repeat(6)[h16 >> ':'] >> ls32 | "::" >> repeat(5)[h16 >> ':'] >> ls32 | - h16 >> "::" >> repeat(4)[h16 >> ':'] >> ls32 | -(h16 >> -( ':' >> h16) ) >> "::" >> repeat(3)[h16 >> ':'] >> ls32 | -(h16 >> -repeat(1,2)[':' >> h16] ) >> "::" >> repeat(2)[h16 >> ':'] >> ls32 | -(h16 >> -repeat(1,3)[':' >> h16] ) >> "::" >> h16 >> ':' >> ls32 | -(h16 >> -repeat(1,4)[':' >> h16] ) >> "::" >> ls32 | -(h16 >> -repeat(1,5)[':' >> h16] ) >> "::" >> h16 | -(h16 >> -repeat(1,6)[':' >> h16] ) >> "::" ; start = raw[ipv6_attr]; h16.name("h16"); ls32.name("ls32"); ipv6_attr.name("ipv6_attr"); start.name("start"); } ipv4_address<Iterator> ipv4; qi::rule<Iterator> h16, ls32; qi::rule<Iterator, std::string()> ipv6_attr; qi::rule<Iterator, std::string()> start; }; } // namespace uri #endif // __ipv6_parser_h__
[ "sdeming@makefile.com" ]
sdeming@makefile.com
1366051be1fdb834c2a85b2f3b70cbab264c8ef2
f4bc983c8ac2fe093f90c78967a04f5bf4f0c0fd
/Final/MyWin32.cpp
556d71762bdc53a6d3c4736ea3b5bd96167755c0
[]
no_license
wyattwhiting/CS271
214be4cd1bea95cfdc42a185cf91429f6f50058f
29e2cb579aa86f49a7fa6e376bd0a31e3f88d304
refs/heads/main
2023-03-04T02:14:09.078174
2021-02-14T04:10:41
2021-02-14T04:10:41
338,722,847
0
0
null
null
null
null
UTF-8
C++
false
false
165
cpp
//MyWin32 - CS271 F2020 - Wyatt Whiting #include <Windows.h> int main() { MessageBoxA(NULL, "Hello, Win32.", "Ebic :DD", MB_ICONEXCLAMATION); return 0; }
[ "wyatt.d.whiting@gmail.com" ]
wyatt.d.whiting@gmail.com
eeb944f352166d9fa76f2aec33901ba3d9921998
2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0
/fuzzedpackages/gee4/src/linesearch.h
29452f6b3f8a6e29341a4a6d5e2b5d97eb941faf
[]
no_license
akhikolla/testpackages
62ccaeed866e2194652b65e7360987b3b20df7e7
01259c3543febc89955ea5b79f3a08d3afe57e95
refs/heads/master
2023-02-18T03:50:28.288006
2021-01-18T13:23:32
2021-01-18T13:23:32
329,981,898
7
1
null
null
null
null
UTF-8
C++
false
false
1,534
h
/* Copyright 2016 The University of Manchester. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Written by Yi Pan - ypan1988@gmail.com ==============================================================================*/ #ifndef LINESEARCH_H_ // NOLINT #define LINESEARCH_H_ #include <RcppArmadillo.h> #include <cmath> #include <algorithm> #include <limits> namespace dragonwell { // Line Searches and Backtracking template <typename T> class LineSearch { public: LineSearch() {} // Constructor ~LineSearch() {} // Destructor bool GetStep(T &func, double *f, arma::vec *x, const arma::vec &g, const arma::vec &p, const double stepmax); void set_message(bool message) { message_ = message; } protected: bool message_; bool IsInfOrNaN(double x); }; // class LineSearch #include "linesearch_impl.h" // NOLINT } // namespace dragonwell #endif // LINESEARCH_H_ NOLINT
[ "akhilakollasrinu424jf@gmail.com" ]
akhilakollasrinu424jf@gmail.com
b52d6a1c29108ecd018b55ce4d32f9a4bcd3ab1a
20d024bd04ace59987ba05f864d6d9dece72fbab
/CQU Summer/西南弱校联萌训练赛(1)/G - Problem G.cpp
9974244ba0fe5231af5c5e6bbd61c7919fa74942
[]
no_license
Yeluorag/ACM-ICPC-Code-Library
8837688c23bf487d4374a76cf0656cb7adc751b0
77751c79549ea8ab6f790d55fac3738d5b615488
refs/heads/master
2021-01-20T20:18:43.366920
2016-08-12T08:08:38
2016-08-12T08:08:38
64,487,659
0
0
null
null
null
null
UTF-8
C++
false
false
1,238
cpp
// Header. #include <set> #include <map> #include <queue> #include <stack> #include <cmath> #include <cstdio> #include <vector> #include <string> #include <sstream> #include <cstring> #include <iostream> #include <algorithm> using namespace std; // Macro typedef long long LL; #define mem(a, n) memset(a, n, sizeof(a)) #define rep(i, n) for(int i = 0; i < (n); i ++) #define REP(i, t, n) for(int i = (t); i < (n); i ++) #define FOR(i, t, n) for(int i = (t); i <= (n); i ++) #define ALL(v) v.begin(), v.end() #define Min(a, b) a = min(a, b) #define Max(a, b) a = max(a, b) #define put(a) printf("%d\n", a) #define ss(a) scanf("%s", a) #define si(a) scanf("%d", &a) #define sii(a, b) scanf("%d%d", &a, &b) #define siii(a, b, c) scanf("%d%d%d", &a, &b, &c) #define VI vector<int> #define pb push_back const int inf = 0x3f3f3f3f, N = 3e5 + 5, MOD = 1e9 + 7; // Macro end int T, cas = 0; int n, m, a[N]; // Imp #define LOCAL int main(){ #ifdef LOCAL freopen("/Users/apple/input.txt", "r", stdin); // freopen("/Users/apple/out.txt", "w", stdout); #endif si(n); FOR(i, 1, n) si(a[i]); int l, r, dv = inf; FOR(i, 1, n) { int tmp = dv; Min(tmp, a[i]); if(a[i] % tmp) } return 0; }
[ "yeluorag@gmail.com" ]
yeluorag@gmail.com
e65f99eb47f280a3f45fc11006b8469207d57fbf
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/squid/old_hunk_919.cpp
16540e7b9b94419496dceaa6350108cf22f3d561
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
162
cpp
case 'm': if (building_deny_info_url) break; #if USE_AUTH p = auth_user_request->denyMessage("[not available]"); #else p = "-"; #endif
[ "993273596@qq.com" ]
993273596@qq.com
3baad681e6b02de3aeb7ee83b29a16f2ef769408
f98049b004e5e452f9a5043162a1ef596870fba6
/class/car.cpp
b4664570a3304432e38d215598fc94135d403ab1
[]
no_license
JinKyuGit/CPlusPlus
3525319574373ade20a85353df2519e4969850fb
d5b14f1ab8211eab3468353a5bb48215a6e3aa58
refs/heads/master
2021-05-11T23:46:34.049510
2018-02-07T04:21:03
2018-02-07T04:21:03
117,518,786
0
0
null
null
null
null
UTF-8
C++
false
false
435
cpp
#include<iostream> #include"car.h" using namespace std; void Car::Show(){ cout<<"\n == 현재상태 ==\n"; cout<<"속도 : "<<this->speed<<endl; cout<<"연료 : "<<this->fuel<<endl; cout<<" ========= \n"; cout<<"1. 가속\n"; cout<<"2. 감속\n"; } void Car::Accel(){ this->speed+=10; this->fuel-=5; } void Car::Break(){ if(this->speed < 10){ this->speed=0; cout<<" stop\n"; return; } this->speed-=10; }
[ "wlsrb8993@gmail.com" ]
wlsrb8993@gmail.com
0cf92815def0c9ca8cd64b870932481355252b52
b9623c82dc51f398b57dde08cf223342093f2af0
/4/4.cpp
c7144a99e0d4397a02b0056a0d443539ed241a47
[]
no_license
irinamrk02/Laba-10
b8d75237c582dc30cee17c34c3ba96cf1b5d2144
cd2ebb4092e2a547cea5b7fcaebe32ba3cbb3dc7
refs/heads/master
2023-01-31T16:37:21.747375
2020-12-08T19:44:46
2020-12-08T19:44:46
319,743,758
0
0
null
null
null
null
UTF-8
C++
false
false
634
cpp
// 4.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы. // #include "string" #include "iostream" #include "fstream" using namespace std; int main() { setlocale(0, ""); ifstream in("f.txt"); string s, r; while (in.peek() != EOF) { getline(in, s); if (s.size() > r.size()) { r = s; } } cout << "Длина максимальной строки = " << r.size() << ". Сама строка: " << r << endl; in.close(); return 0; }
[ "irinamrk02@mail.ru" ]
irinamrk02@mail.ru
f941f8877abd3f27028b006fb49d212fcc0dd30c
1d1f79a08c9c23582501f0afaff3e98952a731be
/Runtime/Src/External.hpp
8be537ab9fe1d1559c75ed4691d2214f3f47fdd4
[]
no_license
smorel/Cheezy
65fab8dc9f05d6a7d4f92369a86f048507d90d27
9cab8f0165f3cb1681472317190db0984e1ffe9b
refs/heads/master
2021-01-20T10:10:55.200685
2019-01-16T23:33:30
2019-01-16T23:33:30
2,325,685
0
0
null
null
null
null
UTF-8
C++
false
false
79
hpp
#pragma once #include "Core/Src/Public.hpp" #include "UnitTest/Src/Public.hpp"
[ "sebastien.morel@autodesk.com" ]
sebastien.morel@autodesk.com
9f7903f6fb0b82c341bb4a457f38566ebe991d06
3cb46d380d4f6fe801d4a7434f74a389b67fe093
/openFrameworks-GUIs-and-APIs/Examples/classObjects/src/Circle.cpp
1e9c25644aff6bac24dd6b7924d1fa9c701c3769
[]
no_license
tabi-marc/assessment1-skillsportfolio-tabitha-marcial
4ef9d1c2e772b66541ba68171b50b305ff701477
da71a091e7ec2c023d35ebb43785b48b5dab2500
refs/heads/master
2023-02-04T12:32:27.014300
2020-12-18T17:12:16
2020-12-18T17:12:16
312,268,605
0
0
null
null
null
null
UTF-8
C++
false
false
486
cpp
// // Circle.cpp // classObjects // // Created by Jake Hobbs on 13/08/2020. // #include "Circle.hpp" void Circle::setup(float x, float y){ //set x and y position to value passed in //value passed in will be set by mouse click xPos = x; yPos = y; //set random radius between 10 and 50 radius = ofRandom(10, 50); } void Circle::update(){ //make circle fall yPos += 5; } void Circle::draw(){ //draw the circle ofDrawCircle(xPos, yPos, radius); }
[ "noreply@github.com" ]
tabi-marc.noreply@github.com
7799c1916b8a5834d3be6ecbb6374bde9a0893b7
dc1b29c1041ee98d882751a53c49c1044ea272eb
/src/blockchain_utilities/blockchain_export.cpp
8db4fe5e6cf2cc648b0d9b4b44d55bd5750aea9c
[ "BSD-3-Clause" ]
permissive
XtendCash/XtendCash
ed3bcf5fd52eff151821f33f63b47de55792f2ff
f82de0b9e0f0ba4893713dc5021ff87de9943212
refs/heads/master
2020-05-05T00:16:17.280894
2019-09-15T03:03:13
2019-09-15T03:03:13
179,569,723
3
3
NOASSERTION
2019-08-25T23:41:29
2019-04-04T20:10:26
C++
UTF-8
C++
false
false
7,369
cpp
// Copyright (c) 2014-2018, The Monero Project // Copyright (c) 2018, The Loki Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER 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 "bootstrap_file.h" #include "blocksdat_file.h" #include "common/command_line.h" #include "cryptonote_core/cryptonote_core.h" #include "blockchain_objects.h" #include "blockchain_db/db_types.h" #include "version.h" #undef XTEND_DEFAULT_LOG_CATEGORY #define XTEND_DEFAULT_LOG_CATEGORY "bcutil" namespace po = boost::program_options; using namespace epee; int main(int argc, char* argv[]) { TRY_ENTRY(); epee::string_tools::set_module_name_and_folder(argv[0]); std::string default_db_type = "lmdb"; std::string available_dbs = cryptonote::blockchain_db_types(", "); available_dbs = "available: " + available_dbs; uint32_t log_level = 0; uint64_t block_stop = 0; bool blocks_dat = false; tools::on_startup(); boost::filesystem::path output_file_path; po::options_description desc_cmd_only("Command line options"); po::options_description desc_cmd_sett("Command line options and settings options"); const command_line::arg_descriptor<std::string> arg_output_file = {"output-file", "Specify output file", "", true}; const command_line::arg_descriptor<std::string> arg_log_level = {"log-level", "0-4 or categories", ""}; const command_line::arg_descriptor<uint64_t> arg_block_stop = {"block-stop", "Stop at block number", block_stop}; const command_line::arg_descriptor<std::string> arg_database = { "database", available_dbs.c_str(), default_db_type }; const command_line::arg_descriptor<bool> arg_blocks_dat = {"blocksdat", "Output in blocks.dat format", blocks_dat}; command_line::add_arg(desc_cmd_sett, cryptonote::arg_data_dir); command_line::add_arg(desc_cmd_sett, arg_output_file); command_line::add_arg(desc_cmd_sett, cryptonote::arg_testnet_on); command_line::add_arg(desc_cmd_sett, cryptonote::arg_stagenet_on); command_line::add_arg(desc_cmd_sett, arg_log_level); command_line::add_arg(desc_cmd_sett, arg_database); command_line::add_arg(desc_cmd_sett, arg_block_stop); command_line::add_arg(desc_cmd_sett, arg_blocks_dat); command_line::add_arg(desc_cmd_only, command_line::arg_help); po::options_description desc_options("Allowed options"); desc_options.add(desc_cmd_only).add(desc_cmd_sett); po::variables_map vm; bool r = command_line::handle_error_helper(desc_options, [&]() { po::store(po::parse_command_line(argc, argv, desc_options), vm); po::notify(vm); return true; }); if (! r) return 1; if (command_line::get_arg(vm, command_line::arg_help)) { std::cout << "Xtend '" << XTEND_RELEASE_NAME << "' (v" << XTEND_VERSION_FULL << ")" << ENDL << ENDL; std::cout << desc_options << std::endl; return 1; } mlog_configure(mlog_get_default_log_path("xtend-blockchain-export.log"), true); if (!command_line::is_arg_defaulted(vm, arg_log_level)) mlog_set_log(command_line::get_arg(vm, arg_log_level).c_str()); else mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str()); block_stop = command_line::get_arg(vm, arg_block_stop); LOG_PRINT_L0("Starting..."); bool opt_testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on); bool opt_stagenet = command_line::get_arg(vm, cryptonote::arg_stagenet_on); if (opt_testnet && opt_stagenet) { std::cerr << "Can't specify more than one of --testnet and --stagenet" << std::endl; return 1; } bool opt_blocks_dat = command_line::get_arg(vm, arg_blocks_dat); std::string m_config_folder; m_config_folder = command_line::get_arg(vm, cryptonote::arg_data_dir); std::string db_type = command_line::get_arg(vm, arg_database); if (!cryptonote::blockchain_valid_db_type(db_type)) { std::cerr << "Invalid database type: " << db_type << std::endl; return 1; } if (command_line::has_arg(vm, arg_output_file)) output_file_path = boost::filesystem::path(command_line::get_arg(vm, arg_output_file)); else output_file_path = boost::filesystem::path(m_config_folder) / "export" / BLOCKCHAIN_RAW; LOG_PRINT_L0("Export output file: " << output_file_path.string()); LOG_PRINT_L0("Initializing source blockchain (BlockchainDB)"); blockchain_objects_t blockchain_objects = {}; Blockchain *core_storage = &blockchain_objects.m_blockchain; BlockchainDB *db = new_db(db_type); if (db == NULL) { LOG_ERROR("Attempted to use non-existent database type: " << db_type); throw std::runtime_error("Attempting to use non-existent database type"); } LOG_PRINT_L0("database: " << db_type); boost::filesystem::path folder(m_config_folder); folder /= db->get_db_name(); const std::string filename = folder.string(); LOG_PRINT_L0("Loading blockchain from folder " << filename << " ..."); try { db->open(filename, DBF_RDONLY); } catch (const std::exception& e) { LOG_PRINT_L0("Error opening database: " << e.what()); return 1; } r = core_storage->init(db, opt_testnet ? cryptonote::TESTNET : opt_stagenet ? cryptonote::STAGENET : cryptonote::MAINNET); if (core_storage->get_blockchain_pruning_seed()) { LOG_PRINT_L0("Blockchain is pruned, cannot export"); return 1; } CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize source blockchain storage"); LOG_PRINT_L0("Source blockchain storage initialized OK"); LOG_PRINT_L0("Exporting blockchain raw data..."); if (opt_blocks_dat) { BlocksdatFile blocksdat; r = blocksdat.store_blockchain_raw(core_storage, NULL, output_file_path, block_stop); } else { BootstrapFile bootstrap; r = bootstrap.store_blockchain_raw(core_storage, NULL, output_file_path, block_stop); } CHECK_AND_ASSERT_MES(r, 1, "Failed to export blockchain raw data"); LOG_PRINT_L0("Blockchain raw data exported OK"); return 0; CATCH_ENTRY("Export error", 1); }
[ "49289946+XtendCash@users.noreply.github.com" ]
49289946+XtendCash@users.noreply.github.com
33d6d39702b6f9e7b88ea94c3b5a7e940db0fd79
88a3eb724ad1a758628a9a73660b177d6dca8d40
/QT_2_4/main.cpp
a82606f71dcebe093b1970152f7ef7d076bef385
[]
no_license
TomislavBak/QTAssigments
cbdeb29691d4727f46551425d1ec27499013f9fa
e9ea5a36948103c84017e65dd4db16ae94dede4b
refs/heads/master
2022-11-06T14:42:32.874533
2020-06-18T15:56:53
2020-06-18T15:56:53
252,579,015
0
0
null
null
null
null
UTF-8
C++
false
false
179
cpp
#include "gui_prob.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); GUI_PROB w; w.show(); return a.exec(); }
[ "noreply@github.com" ]
TomislavBak.noreply@github.com
a02b0f3f2b2f2c94424a5a3e5503bb1909105a22
6cabb3a28013758e71c3cfab530762d49b89785b
/贪心/F - 1838 鎕鎕鎕(构造法).cpp
19d563c32b941fcb8000b0890758268bba48ae32
[]
no_license
TreeYD/Code
2caeccbebd1330fd51373fc46aafd6804c9446bf
1e16ccc80cf36af3728f3ca172e4ab86402e4d8e
refs/heads/master
2020-04-01T22:47:06.318221
2018-10-31T11:37:19
2018-10-31T11:37:19
153,726,191
0
0
null
null
null
null
UTF-8
C++
false
false
454
cpp
#include<bits/stdc++.h> using namespace std; #define M 200005 struct Node{ int a,b,id; bool operator<(const Node &x)const{ return a<x.a; } }A[M<<1]; int n; int main(){ scanf("%d",&n); for(int i=1;i<=n*2+1;i++){ scanf("%d%d",&A[i].a,&A[i].b); A[i].id=i; } sort(A+1,A+1+n*2+1); for(int i=1;i<=n;i++){ int a=2*i-1,b=2*i; if(A[a].b>A[b].b)printf("%d\n",A[a].id); else printf("%d\n",A[b].id); } printf("%d\n",A[n*2+1].id); return 0; }
[ "treeYd@qq.com" ]
treeYd@qq.com
b1b0cfa63a2336709ab9b95b7c3df22351be0d32
7f931e20074f464277a551ac6162aec42f9b96fb
/tva/TVS/slnTva/prjShell/shell.h
8678e2d497f98c6deda14d4093d4f43f73cb09ec
[]
no_license
yetanother/tvaSoft
6ee5c7c34ba7aaca68721c7fce29bdc4e6b054f5
41b416ec27f4c706febd96b7d2a3aff1bab64e6b
refs/heads/master
2021-01-01T16:05:53.390398
2013-07-15T13:14:43
2013-07-15T13:14:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
516
h
#pragma once #include "..\src\corelib\kernel\qobject.h" #include "..\..\slnPreProc\tvaModel.h" class MainWindow; namespace tva { class Logger; // class Shell: public QObject { Q_OBJECT private: MainWindow *mw_; Logger* logger_; tva::Model model; public: Shell():mw_(nullptr){} void setMainWnd(MainWindow*mw){mw_= mw;} void setLogger(Logger* logger){logger_=logger;} tva::Model& getModel(){return model;} public slots: void show(); void addLineToLogger(const QString& str)const; }; }
[ "std.approach@gmail.com" ]
std.approach@gmail.com
c8af84780cccdc8726895641df40b633f2a4c755
606d4d74b1951b85605d29a8e41106c960619635
/Assignment 4/to add two arrays.cpp
562a1c425cf1db01591edbe86932195de340f137
[]
no_license
AishwaryaManjalekar/PQJQP_Aishwarya
2a0bce47360812a01abe1f9981f29ca3749096c9
178132097fc1d0178503c03169497628ff4baa26
refs/heads/main
2023-03-22T06:06:59.827981
2021-03-08T08:44:29
2021-03-08T08:44:29
311,329,804
0
0
null
null
null
null
UTF-8
C++
false
false
790
cpp
#include<iostream> using namespace std; class ArrayExample { int n,arr1[20],arr2[20],sum[20]; int i,j; public:void accept() { cout<<"enter the size of an array:"; cin>>n; cout<<"Enter the elements in an array 1:"; for(int i=0;i<n;i++) { cin>>arr1[i]; } cout<<"Enter the elements in an array 2:"; for(int j=0;j<n;j++) { cin>>arr2[i]; } } void display() { cout<<"The sum of the array are:"; for(int i=0;i<n;i++) { sum[i]=arr1[i]+arr2[i]; cout<<sum[i]<<"\n"; } } }; int main() { ArrayExample v1; v1.accept(); v1.display(); }
[ "noreply@github.com" ]
AishwaryaManjalekar.noreply@github.com
af7baadd90bb94ec036d0118f457cabd3f856347
5afb8bcb3c0edcc0266d1811d7aede7895c835f3
/src/qt/walletmodel.cpp
3aa87a397b30658edc28cb9b1afebb149ceed57d
[ "MIT" ]
permissive
CryptoHours/cryptohours
7a6b5b6a0dcffffe1c8a03aa8a348e75b7811505
b45d71bb7f34a6e39ee60024318487db2ae6573e
refs/heads/master
2021-09-03T06:14:31.357128
2018-01-06T08:29:51
2018-01-06T08:29:51
113,479,293
0
0
null
null
null
null
UTF-8
C++
false
false
25,568
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "walletmodel.h" #include "addresstablemodel.h" #include "guiconstants.h" #include "recentrequeststablemodel.h" #include "transactiontablemodel.h" #include "base58.h" #include "db.h" #include "keystore.h" #include "main.h" #include "spork.h" #include "sync.h" #include "ui_interface.h" #include "wallet.h" #include "walletdb.h" // for BackupWallet #include <stdint.h> #include <QDebug> #include <QSet> #include <QTimer> using namespace std; WalletModel::WalletModel(CWallet* wallet, OptionsModel* optionsModel, QObject* parent) : QObject(parent), wallet(wallet), optionsModel(optionsModel), addressTableModel(0), transactionTableModel(0), recentRequestsTableModel(0), cachedBalance(0), cachedUnconfirmedBalance(0), cachedImmatureBalance(0), cachedZerocoinBalance(0), cachedEncryptionStatus(Unencrypted), cachedNumBlocks(0) { fHaveWatchOnly = wallet->HaveWatchOnly(); fForceCheckBalanceChanged = false; addressTableModel = new AddressTableModel(wallet, this); transactionTableModel = new TransactionTableModel(wallet, this); recentRequestsTableModel = new RecentRequestsTableModel(wallet, this); // This timer will be fired repeatedly to update the balance pollTimer = new QTimer(this); connect(pollTimer, SIGNAL(timeout()), this, SLOT(pollBalanceChanged())); pollTimer->start(MODEL_UPDATE_DELAY); subscribeToCoreSignals(); } WalletModel::~WalletModel() { unsubscribeFromCoreSignals(); } CAmount WalletModel::getBalance(const CCoinControl* coinControl) const { if (coinControl) { CAmount nBalance = 0; std::vector<COutput> vCoins; wallet->AvailableCoins(vCoins, true, coinControl); BOOST_FOREACH (const COutput& out, vCoins) if (out.fSpendable) nBalance += out.tx->vout[out.i].nValue; return nBalance; } return wallet->GetBalance(); } CAmount WalletModel::getZerocoinBalance() const { return wallet->GetZerocoinBalance(); } CAmount WalletModel::getUnconfirmedBalance() const { return wallet->GetUnconfirmedBalance(); } CAmount WalletModel::getImmatureBalance() const { return wallet->GetImmatureBalance(); } bool WalletModel::haveWatchOnly() const { return fHaveWatchOnly; } CAmount WalletModel::getWatchBalance() const { return wallet->GetWatchOnlyBalance(); } CAmount WalletModel::getWatchUnconfirmedBalance() const { return wallet->GetUnconfirmedWatchOnlyBalance(); } CAmount WalletModel::getWatchImmatureBalance() const { return wallet->GetImmatureWatchOnlyBalance(); } void WalletModel::updateStatus() { EncryptionStatus newEncryptionStatus = getEncryptionStatus(); if (cachedEncryptionStatus != newEncryptionStatus) emit encryptionStatusChanged(newEncryptionStatus); } void WalletModel::pollBalanceChanged() { // Get required locks upfront. This avoids the GUI from getting stuck on // periodical polls if the core is holding the locks for a longer time - // for example, during a wallet rescan. TRY_LOCK(cs_main, lockMain); if (!lockMain) return; TRY_LOCK(wallet->cs_wallet, lockWallet); if (!lockWallet) return; if (fForceCheckBalanceChanged || chainActive.Height() != cachedNumBlocks || nZeromintPercentage != cachedZeromintPercentage || cachedTxLocks != nCompleteTXLocks) { fForceCheckBalanceChanged = false; // Balance and number of transactions might have changed cachedNumBlocks = chainActive.Height(); cachedZeromintPercentage = nZeromintPercentage; checkBalanceChanged(); if (transactionTableModel) { transactionTableModel->updateConfirmations(); } } } void WalletModel::checkBalanceChanged() { TRY_LOCK(cs_main, lockMain); if (!lockMain) return; CAmount newBalance = getBalance(); CAmount newUnconfirmedBalance = getUnconfirmedBalance(); CAmount newImmatureBalance = getImmatureBalance(); CAmount newZerocoinBalance = getZerocoinBalance(); CAmount newWatchOnlyBalance = 0; CAmount newWatchUnconfBalance = 0; CAmount newWatchImmatureBalance = 0; if (haveWatchOnly()) { newWatchOnlyBalance = getWatchBalance(); newWatchUnconfBalance = getWatchUnconfirmedBalance(); newWatchImmatureBalance = getWatchImmatureBalance(); } if (cachedBalance != newBalance || cachedUnconfirmedBalance != newUnconfirmedBalance || cachedImmatureBalance != newImmatureBalance || cachedZerocoinBalance != newZerocoinBalance || cachedTxLocks != nCompleteTXLocks || cachedWatchOnlyBalance != newWatchOnlyBalance || cachedWatchUnconfBalance != newWatchUnconfBalance || cachedWatchImmatureBalance != newWatchImmatureBalance) { cachedBalance = newBalance; cachedUnconfirmedBalance = newUnconfirmedBalance; cachedImmatureBalance = newImmatureBalance; cachedZerocoinBalance = newZerocoinBalance; cachedTxLocks = nCompleteTXLocks; cachedWatchOnlyBalance = newWatchOnlyBalance; cachedWatchUnconfBalance = newWatchUnconfBalance; cachedWatchImmatureBalance = newWatchImmatureBalance; emit balanceChanged(newBalance, newUnconfirmedBalance, newImmatureBalance, newZerocoinBalance, newWatchOnlyBalance, newWatchUnconfBalance, newWatchImmatureBalance); } } void WalletModel::updateTransaction() { // Balance and number of transactions might have changed fForceCheckBalanceChanged = true; } void WalletModel::updateAddressBook(const QString& address, const QString& label, bool isMine, const QString& purpose, int status) { if (addressTableModel) addressTableModel->updateEntry(address, label, isMine, purpose, status); } void WalletModel::updateAddressBook(const QString &pubCoin, const QString &isUsed, int status) { if(addressTableModel) addressTableModel->updateEntry(pubCoin, isUsed, status); } void WalletModel::updateWatchOnlyFlag(bool fHaveWatchonly) { fHaveWatchOnly = fHaveWatchonly; emit notifyWatchonlyChanged(fHaveWatchonly); } bool WalletModel::validateAddress(const QString& address) { CBitcoinAddress addressParsed(address.toStdString()); return addressParsed.IsValid(); } WalletModel::SendCoinsReturn WalletModel::prepareTransaction(WalletModelTransaction& transaction, const CCoinControl* coinControl) { CAmount total = 0; QList<SendCoinsRecipient> recipients = transaction.getRecipients(); std::vector<std::pair<CScript, CAmount> > vecSend; if (recipients.empty()) { return OK; } if (isAnonymizeOnlyUnlocked()) { return AnonymizeOnlyUnlocked; } QSet<QString> setAddress; // Used to detect duplicates int nAddresses = 0; // Pre-check input data for validity foreach (const SendCoinsRecipient& rcp, recipients) { if (rcp.paymentRequest.IsInitialized()) { // PaymentRequest... CAmount subtotal = 0; const payments::PaymentDetails& details = rcp.paymentRequest.getDetails(); for (int i = 0; i < details.outputs_size(); i++) { const payments::Output& out = details.outputs(i); if (out.amount() <= 0) continue; subtotal += out.amount(); const unsigned char* scriptStr = (const unsigned char*)out.script().data(); CScript scriptPubKey(scriptStr, scriptStr + out.script().size()); vecSend.push_back(std::pair<CScript, CAmount>(scriptPubKey, out.amount())); } if (subtotal <= 0) { return InvalidAmount; } total += subtotal; } else { // User-entered pivx address / amount: if (!validateAddress(rcp.address)) { return InvalidAddress; } if (rcp.amount <= 0) { return InvalidAmount; } setAddress.insert(rcp.address); ++nAddresses; CScript scriptPubKey = GetScriptForDestination(CBitcoinAddress(rcp.address.toStdString()).Get()); vecSend.push_back(std::pair<CScript, CAmount>(scriptPubKey, rcp.amount)); total += rcp.amount; } } if (setAddress.size() != nAddresses) { return DuplicateAddress; } CAmount nBalance = getBalance(coinControl); if (total > nBalance) { return AmountExceedsBalance; } { LOCK2(cs_main, wallet->cs_wallet); transaction.newPossibleKeyChange(wallet); CAmount nFeeRequired = 0; std::string strFailReason; CWalletTx* newTx = transaction.getTransaction(); CReserveKey* keyChange = transaction.getPossibleKeyChange(); if (recipients[0].useSwiftTX && total > GetSporkValue(SPORK_5_MAX_VALUE) * COIN) { emit message(tr("Send Coins"), tr("SwiftTX doesn't support sending values that high yet. Transactions are currently limited to %1 PIV.").arg(GetSporkValue(SPORK_5_MAX_VALUE)), CClientUIInterface::MSG_ERROR); return TransactionCreationFailed; } bool fCreated = wallet->CreateTransaction(vecSend, *newTx, *keyChange, nFeeRequired, strFailReason, coinControl, recipients[0].inputType, recipients[0].useSwiftTX); transaction.setTransactionFee(nFeeRequired); if (recipients[0].useSwiftTX && newTx->GetValueOut() > GetSporkValue(SPORK_5_MAX_VALUE) * COIN) { emit message(tr("Send Coins"), tr("SwiftTX doesn't support sending values that high yet. Transactions are currently limited to %1 PIV.").arg(GetSporkValue(SPORK_5_MAX_VALUE)), CClientUIInterface::MSG_ERROR); return TransactionCreationFailed; } if (!fCreated) { if ((total + nFeeRequired) > nBalance) { return SendCoinsReturn(AmountWithFeeExceedsBalance); } emit message(tr("Send Coins"), QString::fromStdString(strFailReason), CClientUIInterface::MSG_ERROR); return TransactionCreationFailed; } // reject insane fee if (nFeeRequired > ::minRelayTxFee.GetFee(transaction.getTransactionSize()) * 10000) return InsaneFee; } return SendCoinsReturn(OK); } WalletModel::SendCoinsReturn WalletModel::sendCoins(WalletModelTransaction& transaction) { QByteArray transaction_array; /* store serialized transaction */ if (isAnonymizeOnlyUnlocked()) { return AnonymizeOnlyUnlocked; } { LOCK2(cs_main, wallet->cs_wallet); CWalletTx* newTx = transaction.getTransaction(); QList<SendCoinsRecipient> recipients = transaction.getRecipients(); // Store PaymentRequests in wtx.vOrderForm in wallet. foreach (const SendCoinsRecipient& rcp, recipients) { if (rcp.paymentRequest.IsInitialized()) { std::string key("PaymentRequest"); std::string value; rcp.paymentRequest.SerializeToString(&value); newTx->vOrderForm.push_back(make_pair(key, value)); } else if (!rcp.message.isEmpty()) // Message from normal pivx:URI (pivx:XyZ...?message=example) { newTx->vOrderForm.push_back(make_pair("Message", rcp.message.toStdString())); } } CReserveKey* keyChange = transaction.getPossibleKeyChange(); transaction.getRecipients(); if (!wallet->CommitTransaction(*newTx, *keyChange, (recipients[0].useSwiftTX) ? "ix" : "tx")) return TransactionCommitFailed; CTransaction* t = (CTransaction*)newTx; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << *t; transaction_array.append(&(ssTx[0]), ssTx.size()); } // Add addresses / update labels that we've sent to to the address book, // and emit coinsSent signal for each recipient foreach (const SendCoinsRecipient& rcp, transaction.getRecipients()) { // Don't touch the address book when we have a payment request if (!rcp.paymentRequest.IsInitialized()) { std::string strAddress = rcp.address.toStdString(); CTxDestination dest = CBitcoinAddress(strAddress).Get(); std::string strLabel = rcp.label.toStdString(); { LOCK(wallet->cs_wallet); std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(dest); // Check if we have a new address or an updated label if (mi == wallet->mapAddressBook.end()) { wallet->SetAddressBook(dest, strLabel, "send"); } else if (mi->second.name != strLabel) { wallet->SetAddressBook(dest, strLabel, ""); // "" means don't change purpose } } } emit coinsSent(wallet, rcp, transaction_array); } checkBalanceChanged(); // update balance immediately, otherwise there could be a short noticeable delay until pollBalanceChanged hits return SendCoinsReturn(OK); } OptionsModel* WalletModel::getOptionsModel() { return optionsModel; } AddressTableModel* WalletModel::getAddressTableModel() { return addressTableModel; } TransactionTableModel* WalletModel::getTransactionTableModel() { return transactionTableModel; } RecentRequestsTableModel* WalletModel::getRecentRequestsTableModel() { return recentRequestsTableModel; } WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const { if (!wallet->IsCrypted()) { return Unencrypted; } else if (wallet->fWalletUnlockAnonymizeOnly) { return UnlockedForAnonymizationOnly; } else if (wallet->IsLocked()) { return Locked; } else { return Unlocked; } } bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString& passphrase) { if (encrypted) { // Encrypt return wallet->EncryptWallet(passphrase); } else { // Decrypt -- TODO; not supported yet return false; } } bool WalletModel::setWalletLocked(bool locked, const SecureString& passPhrase, bool anonymizeOnly) { if (locked) { // Lock wallet->fWalletUnlockAnonymizeOnly = false; return wallet->Lock(); } else { // Unlock return wallet->Unlock(passPhrase, anonymizeOnly); } } bool WalletModel::isAnonymizeOnlyUnlocked() { return wallet->fWalletUnlockAnonymizeOnly; } bool WalletModel::changePassphrase(const SecureString& oldPass, const SecureString& newPass) { bool retval; { LOCK(wallet->cs_wallet); wallet->Lock(); // Make sure wallet is locked before attempting pass change retval = wallet->ChangeWalletPassphrase(oldPass, newPass); } return retval; } bool WalletModel::backupWallet(const QString& filename) { return BackupWallet(*wallet, filename.toLocal8Bit().data()); } // Handlers for core signals static void NotifyKeyStoreStatusChanged(WalletModel* walletmodel, CCryptoKeyStore* wallet) { qDebug() << "NotifyKeyStoreStatusChanged"; QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection); } static void NotifyAddressBookChanged(WalletModel* walletmodel, CWallet* wallet, const CTxDestination& address, const std::string& label, bool isMine, const std::string& purpose, ChangeType status) { QString strAddress = QString::fromStdString(CBitcoinAddress(address).ToString()); QString strLabel = QString::fromStdString(label); QString strPurpose = QString::fromStdString(purpose); qDebug() << "NotifyAddressBookChanged : " + strAddress + " " + strLabel + " isMine=" + QString::number(isMine) + " purpose=" + strPurpose + " status=" + QString::number(status); QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection, Q_ARG(QString, strAddress), Q_ARG(QString, strLabel), Q_ARG(bool, isMine), Q_ARG(QString, strPurpose), Q_ARG(int, status)); } // queue notifications to show a non freezing progress dialog e.g. for rescan static bool fQueueNotifications = false; static std::vector<std::pair<uint256, ChangeType> > vQueueNotifications; static void NotifyTransactionChanged(WalletModel* walletmodel, CWallet* wallet, const uint256& hash, ChangeType status) { if (fQueueNotifications) { vQueueNotifications.push_back(make_pair(hash, status)); return; } QString strHash = QString::fromStdString(hash.GetHex()); qDebug() << "NotifyTransactionChanged : " + strHash + " status= " + QString::number(status); QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection /*, Q_ARG(QString, strHash), Q_ARG(int, status)*/); } static void ShowProgress(WalletModel* walletmodel, const std::string& title, int nProgress) { // emits signal "showProgress" QMetaObject::invokeMethod(walletmodel, "showProgress", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(title)), Q_ARG(int, nProgress)); } static void NotifyWatchonlyChanged(WalletModel* walletmodel, bool fHaveWatchonly) { QMetaObject::invokeMethod(walletmodel, "updateWatchOnlyFlag", Qt::QueuedConnection, Q_ARG(bool, fHaveWatchonly)); } static void NotifyZerocoinChanged(WalletModel* walletmodel, CWallet* wallet, const std::string& hexString, const std::string& isUsed, ChangeType status) { QString HexStr = QString::fromStdString(hexString); QString isUsedStr = QString::fromStdString(isUsed); qDebug() << "NotifyZerocoinChanged : " + HexStr + " " + isUsedStr + " status= " + QString::number(status); QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection, Q_ARG(QString, HexStr), Q_ARG(QString, isUsedStr), Q_ARG(int, status)); } void WalletModel::subscribeToCoreSignals() { // Connect signals to wallet wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1)); wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5, _6)); wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); wallet->ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2)); wallet->NotifyWatchonlyChanged.connect(boost::bind(NotifyWatchonlyChanged, this, _1)); wallet->NotifyZerocoinChanged.connect(boost::bind(NotifyZerocoinChanged, this, _1, _2, _3, _4)); } void WalletModel::unsubscribeFromCoreSignals() { // Disconnect signals from wallet wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1)); wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5, _6)); wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); wallet->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); wallet->NotifyWatchonlyChanged.disconnect(boost::bind(NotifyWatchonlyChanged, this, _1)); wallet->NotifyZerocoinChanged.disconnect(boost::bind(NotifyZerocoinChanged, this, _1, _2, _3, _4)); } // WalletModel::UnlockContext implementation WalletModel::UnlockContext WalletModel::requestUnlock(bool relock) { bool was_locked = getEncryptionStatus() == Locked; if (!was_locked && isAnonymizeOnlyUnlocked()) { setWalletLocked(true); wallet->fWalletUnlockAnonymizeOnly = false; was_locked = getEncryptionStatus() == Locked; } if (was_locked) { // Request UI to unlock wallet emit requireUnlock(); } // If wallet is still locked, unlock was failed or cancelled, mark context as invalid bool valid = getEncryptionStatus() != Locked; return UnlockContext(valid, relock); // return UnlockContext(this, valid, was_locked && !isAnonymizeOnlyUnlocked()); } WalletModel::UnlockContext::UnlockContext(bool valid, bool relock) : valid(valid), relock(relock) { } WalletModel::UnlockContext::~UnlockContext() { /* if (valid && relock) { wallet->setWalletLocked(true); } */ } void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs) { // Transfer context; old object no longer relocks wallet *this = rhs; rhs.relock = false; } bool WalletModel::getPubKey(const CKeyID& address, CPubKey& vchPubKeyOut) const { return wallet->GetPubKey(address, vchPubKeyOut); } // returns a list of COutputs from COutPoints void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs) { LOCK2(cs_main, wallet->cs_wallet); BOOST_FOREACH (const COutPoint& outpoint, vOutpoints) { if (!wallet->mapWallet.count(outpoint.hash)) continue; int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain(); if (nDepth < 0) continue; COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth, true); vOutputs.push_back(out); } } bool WalletModel::isSpent(const COutPoint& outpoint) const { LOCK2(cs_main, wallet->cs_wallet); return wallet->IsSpent(outpoint.hash, outpoint.n); } // AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address) void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const { std::vector<COutput> vCoins; wallet->AvailableCoins(vCoins); LOCK2(cs_main, wallet->cs_wallet); // ListLockedCoins, mapWallet std::vector<COutPoint> vLockedCoins; wallet->ListLockedCoins(vLockedCoins); // add locked coins BOOST_FOREACH (const COutPoint& outpoint, vLockedCoins) { if (!wallet->mapWallet.count(outpoint.hash)) continue; int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain(); if (nDepth < 0) continue; COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth, true); if (outpoint.n < out.tx->vout.size() && wallet->IsMine(out.tx->vout[outpoint.n]) == ISMINE_SPENDABLE) vCoins.push_back(out); } BOOST_FOREACH (const COutput& out, vCoins) { COutput cout = out; while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0])) { if (!wallet->mapWallet.count(cout.tx->vin[0].prevout.hash)) break; cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0, true); } CTxDestination address; if (!out.fSpendable || !ExtractDestination(cout.tx->vout[cout.i].scriptPubKey, address)) continue; mapCoins[QString::fromStdString(CBitcoinAddress(address).ToString())].push_back(out); } } bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const { LOCK2(cs_main, wallet->cs_wallet); return wallet->IsLockedCoin(hash, n); } void WalletModel::lockCoin(COutPoint& output) { LOCK2(cs_main, wallet->cs_wallet); wallet->LockCoin(output); } void WalletModel::unlockCoin(COutPoint& output) { LOCK2(cs_main, wallet->cs_wallet); wallet->UnlockCoin(output); } void WalletModel::listLockedCoins(std::vector<COutPoint>& vOutpts) { LOCK2(cs_main, wallet->cs_wallet); wallet->ListLockedCoins(vOutpts); } void WalletModel::listZerocoinMints(std::list<CZerocoinMint>& listMints, bool fUnusedOnly, bool fMaturedOnly, bool fUpdateStatus) { listMints.clear(); CWalletDB walletdb(wallet->strWalletFile); listMints = walletdb.ListMintedCoins(fUnusedOnly, fMaturedOnly, fUpdateStatus); } void WalletModel::loadReceiveRequests(std::vector<std::string>& vReceiveRequests) { LOCK(wallet->cs_wallet); BOOST_FOREACH (const PAIRTYPE(CTxDestination, CAddressBookData) & item, wallet->mapAddressBook) BOOST_FOREACH (const PAIRTYPE(std::string, std::string) & item2, item.second.destdata) if (item2.first.size() > 2 && item2.first.substr(0, 2) == "rr") // receive request vReceiveRequests.push_back(item2.second); } bool WalletModel::saveReceiveRequest(const std::string& sAddress, const int64_t nId, const std::string& sRequest) { CTxDestination dest = CBitcoinAddress(sAddress).Get(); std::stringstream ss; ss << nId; std::string key = "rr" + ss.str(); // "rr" prefix = "receive request" in destdata LOCK(wallet->cs_wallet); if (sRequest.empty()) return wallet->EraseDestData(dest, key); else return wallet->AddDestData(dest, key, sRequest); } bool WalletModel::isMine(CBitcoinAddress address) { return IsMine(*wallet, address.Get()); }
[ "ivan.helmot@yahoo.com" ]
ivan.helmot@yahoo.com
9347605b8c0ffd6857fe85c8efd69bf9fec2568e
ed91c77afaeb0e075da38153aa89c6ee8382d3fc
/mediasoup-client/deps/webrtc/src/pc/dtls_transport_unittest.cc
f80d99b05ec7525b7bf5d10e5afa8e79a8baa20f
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-google-patent-license-webrtc", "LicenseRef-scancode-google-patent-license-webm", "MIT" ]
permissive
whatisor/mediasoup-client-android
37bf1aeaadc8db642cff449a26545bf15da27539
dc3d812974991d9b94efbc303aa2deb358928546
refs/heads/master
2023-04-26T12:24:18.355241
2023-01-02T16:55:19
2023-01-02T16:55:19
243,833,549
0
0
MIT
2020-02-28T18:56:36
2020-02-28T18:56:36
null
UTF-8
C++
false
false
5,756
cc
/* * Copyright 2018 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "pc/dtls_transport.h" #include <utility> #include <vector> #include "absl/memory/memory.h" #include "p2p/base/fake_dtls_transport.h" #include "rtc_base/gunit.h" #include "test/gmock.h" #include "test/gtest.h" constexpr int kDefaultTimeout = 1000; // milliseconds constexpr int kNonsenseCipherSuite = 1234; using cricket::FakeDtlsTransport; using ::testing::ElementsAre; namespace webrtc { class TestDtlsTransportObserver : public DtlsTransportObserverInterface { public: void OnStateChange(DtlsTransportInformation info) override { state_change_called_ = true; states_.push_back(info.state()); info_ = info; } void OnError(RTCError error) override {} DtlsTransportState state() { if (states_.size() > 0) { return states_[states_.size() - 1]; } else { return DtlsTransportState::kNew; } } bool state_change_called_ = false; DtlsTransportInformation info_; std::vector<DtlsTransportState> states_; }; class DtlsTransportTest : public ::testing::Test { public: DtlsTransport* transport() { return transport_.get(); } DtlsTransportObserverInterface* observer() { return &observer_; } void CreateTransport(rtc::FakeSSLCertificate* certificate = nullptr) { auto cricket_transport = std::make_unique<FakeDtlsTransport>( "audio", cricket::ICE_CANDIDATE_COMPONENT_RTP); if (certificate) { cricket_transport->SetRemoteSSLCertificate(certificate); } cricket_transport->SetSslCipherSuite(kNonsenseCipherSuite); transport_ = rtc::make_ref_counted<DtlsTransport>(std::move(cricket_transport)); } void CompleteDtlsHandshake() { auto fake_dtls1 = static_cast<FakeDtlsTransport*>(transport_->internal()); auto fake_dtls2 = std::make_unique<FakeDtlsTransport>( "audio", cricket::ICE_CANDIDATE_COMPONENT_RTP); auto cert1 = rtc::RTCCertificate::Create( rtc::SSLIdentity::Create("session1", rtc::KT_DEFAULT)); fake_dtls1->SetLocalCertificate(cert1); auto cert2 = rtc::RTCCertificate::Create( rtc::SSLIdentity::Create("session1", rtc::KT_DEFAULT)); fake_dtls2->SetLocalCertificate(cert2); fake_dtls1->SetDestination(fake_dtls2.get()); } rtc::scoped_refptr<DtlsTransport> transport_; TestDtlsTransportObserver observer_; }; TEST_F(DtlsTransportTest, CreateClearDelete) { auto cricket_transport = std::make_unique<FakeDtlsTransport>( "audio", cricket::ICE_CANDIDATE_COMPONENT_RTP); auto webrtc_transport = rtc::make_ref_counted<DtlsTransport>(std::move(cricket_transport)); ASSERT_TRUE(webrtc_transport->internal()); ASSERT_EQ(DtlsTransportState::kNew, webrtc_transport->Information().state()); webrtc_transport->Clear(); ASSERT_FALSE(webrtc_transport->internal()); ASSERT_EQ(DtlsTransportState::kClosed, webrtc_transport->Information().state()); } TEST_F(DtlsTransportTest, EventsObservedWhenConnecting) { CreateTransport(); transport()->RegisterObserver(observer()); CompleteDtlsHandshake(); ASSERT_TRUE_WAIT(observer_.state_change_called_, kDefaultTimeout); EXPECT_THAT( observer_.states_, ElementsAre( // FakeDtlsTransport doesn't signal the "connecting" state. // TODO(hta): fix FakeDtlsTransport or file bug on it. // DtlsTransportState::kConnecting, DtlsTransportState::kConnected)); } TEST_F(DtlsTransportTest, CloseWhenClearing) { CreateTransport(); transport()->RegisterObserver(observer()); CompleteDtlsHandshake(); ASSERT_TRUE_WAIT(observer_.state() == DtlsTransportState::kConnected, kDefaultTimeout); transport()->Clear(); ASSERT_TRUE_WAIT(observer_.state() == DtlsTransportState::kClosed, kDefaultTimeout); } TEST_F(DtlsTransportTest, CertificateAppearsOnConnect) { rtc::FakeSSLCertificate fake_certificate("fake data"); CreateTransport(&fake_certificate); transport()->RegisterObserver(observer()); CompleteDtlsHandshake(); ASSERT_TRUE_WAIT(observer_.state() == DtlsTransportState::kConnected, kDefaultTimeout); EXPECT_TRUE(observer_.info_.remote_ssl_certificates() != nullptr); } TEST_F(DtlsTransportTest, CertificateDisappearsOnClose) { rtc::FakeSSLCertificate fake_certificate("fake data"); CreateTransport(&fake_certificate); transport()->RegisterObserver(observer()); CompleteDtlsHandshake(); ASSERT_TRUE_WAIT(observer_.state() == DtlsTransportState::kConnected, kDefaultTimeout); EXPECT_TRUE(observer_.info_.remote_ssl_certificates() != nullptr); transport()->Clear(); ASSERT_TRUE_WAIT(observer_.state() == DtlsTransportState::kClosed, kDefaultTimeout); EXPECT_FALSE(observer_.info_.remote_ssl_certificates()); } TEST_F(DtlsTransportTest, CipherSuiteVisibleWhenConnected) { CreateTransport(); transport()->RegisterObserver(observer()); CompleteDtlsHandshake(); ASSERT_TRUE_WAIT(observer_.state() == DtlsTransportState::kConnected, kDefaultTimeout); ASSERT_TRUE(observer_.info_.ssl_cipher_suite()); EXPECT_EQ(kNonsenseCipherSuite, *observer_.info_.ssl_cipher_suite()); transport()->Clear(); ASSERT_TRUE_WAIT(observer_.state() == DtlsTransportState::kClosed, kDefaultTimeout); EXPECT_FALSE(observer_.info_.ssl_cipher_suite()); } } // namespace webrtc
[ "wuhaiyang1213@gmail.com" ]
wuhaiyang1213@gmail.com
5c3d69a602773d6ae6795969fe1bce3709c93fb2
eff63d54d63acf878b013342fc43c222be535164
/maths/euler_tot.cpp
9661882e4a94f8277f2e5d2ab7ac9ec03df733da
[]
no_license
viv-india/Viv_lib
526753e0fbf0143fe2fea9ac5bf2c848eb09b4fb
360515ca3a009521e55d258d299fb28789545855
refs/heads/master
2023-05-15T08:12:39.313302
2023-05-03T16:48:43
2023-05-03T16:48:43
85,391,925
0
0
null
null
null
null
UTF-8
C++
false
false
712
cpp
/*************What doesn't kills you makes you stronger************************/ #include<bits/stdc++.h> #include<algorithm> using namespace std; #define ld long double #define ll long long #define mod 1000000007 #define f(i,n) for( ll (i)= 0;(i)<(n);(i)++) #define faster ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0) #define lp pair<ll,ll> #define maxn 1000000 //ll gcd(ll a ,ll b) {return(a==0?b:gcd(b%a,a));} ll tot(ll n) {ll ans=n; if(n%2==0) ans=(n/2); while(n%2==0) {n/=2;} ll sq=sqrt(n); for(ll i=3;i<=sq;i+=2) { if(n%i==0) ans=(ans/i)*(i-1); while(n%i==0) {n/=i;} } if(n>1) ans=(ans/n)*(n-1); return ans;} int main() {faster; ll n,x; cin>>n; while(n--) {cin>>x;cout<<tot(x)<<endl;} }
[ "vivek.singh9022@gmail.com" ]
vivek.singh9022@gmail.com
2efd53f5a1010222a98ad3e82893066d90a3fc41
2ed96334b80d8aada5026e9ee8b3633e42d7064c
/Platformer/src/game/state_stack.cpp
870e922409b9e759bce632afe91dddc940f9c1c5
[]
no_license
matt4682/platformer
0e0c8a9f667d482e2752c62afa09a7e66880d819
2b756ee9a2d4b04e0106463ace46fa2a8ae818e6
refs/heads/master
2021-01-23T06:21:04.311802
2017-03-27T17:18:26
2017-03-27T17:18:26
86,359,806
0
0
null
null
null
null
UTF-8
C++
false
false
3,355
cpp
#include "./state_stack.h" #include "../ui/states/play_state.h" #include "../ui/states/pause_state.h" #include "../ui/states/level_select_state.h" #include "../ui/states/world_select_state.h" #include "../ui/states/level_loading_state.h" #include "../ui/states/level_completion_state.h" #include "../ui/states/menu_state.h" #include "../ui/states/option_state.h" #include "../ui/states/help_state.h" StateStack::StateStack(State::Context context) : mContext(context) {} void StateStack::update(sf::Time deltaTime) { for (auto i = mStack.rbegin(); i != mStack.rend(); ++i) { if (!i->get()->update(deltaTime)) break; } applyPendingChanges(); } void StateStack::draw() { for (auto i = mStack.begin(); i != mStack.end(); ++i) { i->get()->draw(); } } void StateStack::handleEvent(const sf::Event &event) { for (auto i = mStack.rbegin(); i != mStack.rend(); ++i) { if (!i->get()->handleEvent(event)) break; } } State::Ptr StateStack::createState(State::ID stateID, const std::string &map) { switch (stateID) { case(State::ID::Play) : return std::unique_ptr<PlayState>(new PlayState(*this, mContext, map)); case(State::ID::Pause) : return std::unique_ptr<PauseState>(new PauseState(*this, mContext, map)); case(State::ID::WorldSelect) : return std::unique_ptr<WorldSelectState>(new WorldSelectState(*this, mContext, map)); case(State::ID::LevelSelect) : return std::unique_ptr<LevelSelectState>(new LevelSelectState(*this, mContext, map)); case(State::ID::LevelCompletion) : return std::unique_ptr<LevelCompletionState>(new LevelCompletionState(*this, mContext)); case(State::ID::LoadingWorld) : return std::unique_ptr<LevelSelectState>(new LevelSelectState(*this, mContext, map)); case(State::ID::Loading) : return std::unique_ptr<LevelLoadingState>(new LevelLoadingState(*this, mContext, map)); case(State::ID::Menu) : return std::unique_ptr<MenuState>(new MenuState(*this, mContext)); case(State::ID::Option) : return std::unique_ptr<OptionState>(new OptionState(*this, mContext)); case(State::ID::Help) : return std::unique_ptr<HelpState>(new HelpState(*this, mContext)); default: return std::unique_ptr<MenuState>(new MenuState(*this, mContext)); } } void StateStack::pushState(State::ID stateID, const std::string &map) { mPendingList.push_back(PendingChange(Push, stateID, map)); } void StateStack::popState() { mPendingList.push_back(PendingChange(Pop)); } void StateStack::clearStates() { mPendingList.push_back(PendingChange(Clear)); } void StateStack::onResolutionChange() { mPendingList.push_back(PendingChange(Resolution)); } bool StateStack::isEmpty() const { return mStack.empty(); } void StateStack::applyPendingChanges() { for (auto &change : mPendingList) { switch (change.action) { case(Action::Push) : mStack.push_back(std::move(createState(change.stateID, change.map))); break; case(Action::Pop) : mStack.pop_back(); break; case(Action::Clear) : mStack.clear(); break; case(Action::Resolution) : for (auto &state : mStack) state->onResolutionChange(); break; } } mPendingList.clear(); } State::Context StateStack::getContext() const { return mContext; }
[ "m_wilmink@fanshaweonline.ca" ]
m_wilmink@fanshaweonline.ca
cd8615af3009ae01419d82014abbf06c1c90160a
ca334a387940ab68fea3eef4aa9705540d725ec4
/homework3/bt10+11.cpp
6716f988c1cc8399a25483f0c851eba5280de02d
[]
no_license
minhtblaser/homeworkcodeC
878330e90b1306b3f867da542bbc72ccc775763f
c31d22c128eb78ed634254ea2e1d6490ac5564f6
refs/heads/main
2023-02-06T03:54:25.008790
2020-12-30T14:21:36
2020-12-30T14:21:36
315,014,739
0
0
null
null
null
null
UTF-8
C++
false
false
1,820
cpp
#include <stdio.h> #define MAX 1000 void NhapMang(int a[], int n){ for(int i = 0;i < n; i++){ printf("Nhap so thu %d: ", i); scanf("%d", &a[i]); } } void XuatMang(int a[], int n){ for(int i = 0;i < n; i++){ printf("%4d", a[i]); } } void ThemPhanTu(int a[], int &n, int val, int pos){ // Mang da day, khong the them. if(n >= MAX){ return; } // Neu pos <= 0 => Them vao dau if(pos < 0){ pos = 0; } // Neu pos >= n => Them vao cuoi else if(pos > n){ pos = n; } // Dich chuyen mang de tao o trong truoc khi them. for(int i = n; i > pos; i--){ a[i] = a[i-1]; } // Chen val tai pos a[pos] = val; // Tang so luong phan tu sau khi chen. ++n; } void XoaPhanTu(int a[], int &n, int pos){ // Mang rong, khong the xoa. if(n <= 0){ return; } // Neu pos <= 0 => Xoa dau if(pos < 0){ pos = 0; } // Neu pos >= n => Xoa cuoi else if(pos >= n){ pos = n-1; } // Dich chuyen mang for(int i = pos; i < n - 1; i++){ a[i] = a[i+1]; } // Giam so luong phan tu sau khi xoa. --n; } int main(){ int a[MAX]; int n; printf("\nNhap so luong phan tu: "); scanf("%d", &n); NhapMang(a, n); XuatMang(a, n); printf("\n=======THEM PHAN TU======\n"); int val, pos; printf("\nNhap so can them: "); scanf("%d", &val); printf("\nNhap vi tri muon chen: "); scanf("%d", &pos); ThemPhanTu(a, n, val, pos); printf("\nMang sau khi them: "); XuatMang(a, n); printf("\n=======XOA PHAN TU======\n"); printf("\nNhap vi tri muon xoa: "); scanf("%d", &pos); XoaPhanTu(a, n, pos); printf("\nMang sau khi xoa: "); XuatMang(a, n); printf("\nDone!"); }
[ "trinhngocminh,9a1@gmail.com" ]
trinhngocminh,9a1@gmail.com
393389b47bef5882dadfb34182e9d2b0145c9d36
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_patch_hunk_4960.cpp
bd1f9a440749066d5064028e6922712c3537d341
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
674
cpp
rv = file_cache_el_final(conf, &dobj->hdrs, r); } if (APR_SUCCESS == rv) { rv = file_cache_el_final(conf, &dobj->vary, r); } if (APR_SUCCESS == rv) { - rv = file_cache_el_final(conf, &dobj->data, r); + if (!dobj->disk_info.header_only) { + rv = file_cache_el_final(conf, &dobj->data, r); + } + else if (dobj->data.file){ + rv = apr_file_remove(dobj->data.file, dobj->data.pool); + } } /* remove the cached items completely on any failure */ if (APR_SUCCESS != rv) { remove_url(h, r); ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00736)
[ "993273596@qq.com" ]
993273596@qq.com
0a340b69167678d0f8b2318c987c570828022d1c
e7f4c25dc251fd6b74efa7014c3d271724536797
/test/encodings/unicode_group_Mn_u_encoding_policy_fail.re
823edc273b26407fa5143e2721172590a3905502
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain" ]
permissive
nightlark/re2c
163cc308e9023b290e08cc82cc704a8ae5b90114
96104a652622c63ca2cc0b1d2b1d3dad8c34aae6
refs/heads/master
2023-08-08T18:35:31.715463
2023-07-21T21:23:56
2023-07-21T21:29:45
100,122,233
1
0
null
2017-08-12T15:51:24
2017-08-12T15:51:24
null
UTF-8
C++
false
false
11,325
re
// re2c $INPUT -o $OUTPUT -u --encoding-policy fail #include <stdio.h> #define YYCTYPE unsigned int bool scan(const YYCTYPE * start, const YYCTYPE * const limit) { __attribute__((unused)) const YYCTYPE * YYMARKER; // silence compiler warnings when YYMARKER is not used # define YYCURSOR start Mn: /*!re2c re2c:yyfill:enable = 0; Mn = [\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf-\u05bf\u05c1-\u05c2\u05c4-\u05c5\u05c7-\u05c7\u0610-\u061a\u064b-\u065f\u0670-\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7-\u06e8\u06ea-\u06ed\u0711-\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u07fd-\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0902\u093a-\u093a\u093c-\u093c\u0941-\u0948\u094d-\u094d\u0951-\u0957\u0962-\u0963\u0981-\u0981\u09bc-\u09bc\u09c1-\u09c4\u09cd-\u09cd\u09e2-\u09e3\u09fe-\u09fe\u0a01-\u0a02\u0a3c-\u0a3c\u0a41-\u0a42\u0a47-\u0a48\u0a4b-\u0a4d\u0a51-\u0a51\u0a70-\u0a71\u0a75-\u0a75\u0a81-\u0a82\u0abc-\u0abc\u0ac1-\u0ac5\u0ac7-\u0ac8\u0acd-\u0acd\u0ae2-\u0ae3\u0afa-\u0aff\u0b01-\u0b01\u0b3c-\u0b3c\u0b3f-\u0b3f\u0b41-\u0b44\u0b4d-\u0b4d\u0b56-\u0b56\u0b62-\u0b63\u0b82-\u0b82\u0bc0-\u0bc0\u0bcd-\u0bcd\u0c00-\u0c00\u0c04-\u0c04\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55-\u0c56\u0c62-\u0c63\u0c81-\u0c81\u0cbc-\u0cbc\u0cbf-\u0cbf\u0cc6-\u0cc6\u0ccc-\u0ccd\u0ce2-\u0ce3\u0d00-\u0d01\u0d3b-\u0d3c\u0d41-\u0d44\u0d4d-\u0d4d\u0d62-\u0d63\u0dca-\u0dca\u0dd2-\u0dd4\u0dd6-\u0dd6\u0e31-\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1-\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0f18-\u0f19\u0f35-\u0f35\u0f37-\u0f37\u0f39-\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86-\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6-\u0fc6\u102d-\u1030\u1032-\u1037\u1039-\u103a\u103d-\u103e\u1058-\u1059\u105e-\u1060\u1071-\u1074\u1082-\u1082\u1085-\u1086\u108d-\u108d\u109d-\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752-\u1753\u1772-\u1773\u17b4-\u17b5\u17b7-\u17bd\u17c6-\u17c6\u17c9-\u17d3\u17dd-\u17dd\u180b-\u180d\u1885-\u1886\u18a9-\u18a9\u1920-\u1922\u1927-\u1928\u1932-\u1932\u1939-\u193b\u1a17-\u1a18\u1a1b-\u1a1b\u1a56-\u1a56\u1a58-\u1a5e\u1a60-\u1a60\u1a62-\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f-\u1a7f\u1ab0-\u1abd\u1b00-\u1b03\u1b34-\u1b34\u1b36-\u1b3a\u1b3c-\u1b3c\u1b42-\u1b42\u1b6b-\u1b73\u1b80-\u1b81\u1ba2-\u1ba5\u1ba8-\u1ba9\u1bab-\u1bad\u1be6-\u1be6\u1be8-\u1be9\u1bed-\u1bed\u1bef-\u1bf1\u1c2c-\u1c33\u1c36-\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced-\u1ced\u1cf4-\u1cf4\u1cf8-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u20d0-\u20dc\u20e1-\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f-\u2d7f\u2de0-\u2dff\u302a-\u302d\u3099-\u309a\ua66f-\ua66f\ua674-\ua67d\ua69e-\ua69f\ua6f0-\ua6f1\ua802-\ua802\ua806-\ua806\ua80b-\ua80b\ua825-\ua826\ua8c4-\ua8c5\ua8e0-\ua8f1\ua8ff-\ua8ff\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3-\ua9b3\ua9b6-\ua9b9\ua9bc-\ua9bd\ua9e5-\ua9e5\uaa29-\uaa2e\uaa31-\uaa32\uaa35-\uaa36\uaa43-\uaa43\uaa4c-\uaa4c\uaa7c-\uaa7c\uaab0-\uaab0\uaab2-\uaab4\uaab7-\uaab8\uaabe-\uaabf\uaac1-\uaac1\uaaec-\uaaed\uaaf6-\uaaf6\uabe5-\uabe5\uabe8-\uabe8\uabed-\uabed\ufb1e-\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\U000101fd-\U000101fd\U000102e0-\U000102e0\U00010376-\U0001037a\U00010a01-\U00010a03\U00010a05-\U00010a06\U00010a0c-\U00010a0f\U00010a38-\U00010a3a\U00010a3f-\U00010a3f\U00010ae5-\U00010ae6\U00010d24-\U00010d27\U00010f46-\U00010f50\U00011001-\U00011001\U00011038-\U00011046\U0001107f-\U00011081\U000110b3-\U000110b6\U000110b9-\U000110ba\U00011100-\U00011102\U00011127-\U0001112b\U0001112d-\U00011134\U00011173-\U00011173\U00011180-\U00011181\U000111b6-\U000111be\U000111c9-\U000111cc\U0001122f-\U00011231\U00011234-\U00011234\U00011236-\U00011237\U0001123e-\U0001123e\U000112df-\U000112df\U000112e3-\U000112ea\U00011300-\U00011301\U0001133b-\U0001133c\U00011340-\U00011340\U00011366-\U0001136c\U00011370-\U00011374\U00011438-\U0001143f\U00011442-\U00011444\U00011446-\U00011446\U0001145e-\U0001145e\U000114b3-\U000114b8\U000114ba-\U000114ba\U000114bf-\U000114c0\U000114c2-\U000114c3\U000115b2-\U000115b5\U000115bc-\U000115bd\U000115bf-\U000115c0\U000115dc-\U000115dd\U00011633-\U0001163a\U0001163d-\U0001163d\U0001163f-\U00011640\U000116ab-\U000116ab\U000116ad-\U000116ad\U000116b0-\U000116b5\U000116b7-\U000116b7\U0001171d-\U0001171f\U00011722-\U00011725\U00011727-\U0001172b\U0001182f-\U00011837\U00011839-\U0001183a\U000119d4-\U000119d7\U000119da-\U000119db\U000119e0-\U000119e0\U00011a01-\U00011a0a\U00011a33-\U00011a38\U00011a3b-\U00011a3e\U00011a47-\U00011a47\U00011a51-\U00011a56\U00011a59-\U00011a5b\U00011a8a-\U00011a96\U00011a98-\U00011a99\U00011c30-\U00011c36\U00011c38-\U00011c3d\U00011c3f-\U00011c3f\U00011c92-\U00011ca7\U00011caa-\U00011cb0\U00011cb2-\U00011cb3\U00011cb5-\U00011cb6\U00011d31-\U00011d36\U00011d3a-\U00011d3a\U00011d3c-\U00011d3d\U00011d3f-\U00011d45\U00011d47-\U00011d47\U00011d90-\U00011d91\U00011d95-\U00011d95\U00011d97-\U00011d97\U00011ef3-\U00011ef4\U00016af0-\U00016af4\U00016b30-\U00016b36\U00016f4f-\U00016f4f\U00016f8f-\U00016f92\U0001bc9d-\U0001bc9e\U0001d167-\U0001d169\U0001d17b-\U0001d182\U0001d185-\U0001d18b\U0001d1aa-\U0001d1ad\U0001d242-\U0001d244\U0001da00-\U0001da36\U0001da3b-\U0001da6c\U0001da75-\U0001da75\U0001da84-\U0001da84\U0001da9b-\U0001da9f\U0001daa1-\U0001daaf\U0001e000-\U0001e006\U0001e008-\U0001e018\U0001e01b-\U0001e021\U0001e023-\U0001e024\U0001e026-\U0001e02a\U0001e130-\U0001e136\U0001e2ec-\U0001e2ef\U0001e8d0-\U0001e8d6\U0001e944-\U0001e94a\U000e0100-\U000e01ef]; Mn { goto Mn; } * { return YYCURSOR == limit; } */ } static const unsigned int chars_Mn [] = {0x300,0x36f, 0x483,0x487, 0x591,0x5bd, 0x5bf,0x5bf, 0x5c1,0x5c2, 0x5c4,0x5c5, 0x5c7,0x5c7, 0x610,0x61a, 0x64b,0x65f, 0x670,0x670, 0x6d6,0x6dc, 0x6df,0x6e4, 0x6e7,0x6e8, 0x6ea,0x6ed, 0x711,0x711, 0x730,0x74a, 0x7a6,0x7b0, 0x7eb,0x7f3, 0x7fd,0x7fd, 0x816,0x819, 0x81b,0x823, 0x825,0x827, 0x829,0x82d, 0x859,0x85b, 0x8d3,0x8e1, 0x8e3,0x902, 0x93a,0x93a, 0x93c,0x93c, 0x941,0x948, 0x94d,0x94d, 0x951,0x957, 0x962,0x963, 0x981,0x981, 0x9bc,0x9bc, 0x9c1,0x9c4, 0x9cd,0x9cd, 0x9e2,0x9e3, 0x9fe,0x9fe, 0xa01,0xa02, 0xa3c,0xa3c, 0xa41,0xa42, 0xa47,0xa48, 0xa4b,0xa4d, 0xa51,0xa51, 0xa70,0xa71, 0xa75,0xa75, 0xa81,0xa82, 0xabc,0xabc, 0xac1,0xac5, 0xac7,0xac8, 0xacd,0xacd, 0xae2,0xae3, 0xafa,0xaff, 0xb01,0xb01, 0xb3c,0xb3c, 0xb3f,0xb3f, 0xb41,0xb44, 0xb4d,0xb4d, 0xb56,0xb56, 0xb62,0xb63, 0xb82,0xb82, 0xbc0,0xbc0, 0xbcd,0xbcd, 0xc00,0xc00, 0xc04,0xc04, 0xc3e,0xc40, 0xc46,0xc48, 0xc4a,0xc4d, 0xc55,0xc56, 0xc62,0xc63, 0xc81,0xc81, 0xcbc,0xcbc, 0xcbf,0xcbf, 0xcc6,0xcc6, 0xccc,0xccd, 0xce2,0xce3, 0xd00,0xd01, 0xd3b,0xd3c, 0xd41,0xd44, 0xd4d,0xd4d, 0xd62,0xd63, 0xdca,0xdca, 0xdd2,0xdd4, 0xdd6,0xdd6, 0xe31,0xe31, 0xe34,0xe3a, 0xe47,0xe4e, 0xeb1,0xeb1, 0xeb4,0xebc, 0xec8,0xecd, 0xf18,0xf19, 0xf35,0xf35, 0xf37,0xf37, 0xf39,0xf39, 0xf71,0xf7e, 0xf80,0xf84, 0xf86,0xf87, 0xf8d,0xf97, 0xf99,0xfbc, 0xfc6,0xfc6, 0x102d,0x1030, 0x1032,0x1037, 0x1039,0x103a, 0x103d,0x103e, 0x1058,0x1059, 0x105e,0x1060, 0x1071,0x1074, 0x1082,0x1082, 0x1085,0x1086, 0x108d,0x108d, 0x109d,0x109d, 0x135d,0x135f, 0x1712,0x1714, 0x1732,0x1734, 0x1752,0x1753, 0x1772,0x1773, 0x17b4,0x17b5, 0x17b7,0x17bd, 0x17c6,0x17c6, 0x17c9,0x17d3, 0x17dd,0x17dd, 0x180b,0x180d, 0x1885,0x1886, 0x18a9,0x18a9, 0x1920,0x1922, 0x1927,0x1928, 0x1932,0x1932, 0x1939,0x193b, 0x1a17,0x1a18, 0x1a1b,0x1a1b, 0x1a56,0x1a56, 0x1a58,0x1a5e, 0x1a60,0x1a60, 0x1a62,0x1a62, 0x1a65,0x1a6c, 0x1a73,0x1a7c, 0x1a7f,0x1a7f, 0x1ab0,0x1abd, 0x1b00,0x1b03, 0x1b34,0x1b34, 0x1b36,0x1b3a, 0x1b3c,0x1b3c, 0x1b42,0x1b42, 0x1b6b,0x1b73, 0x1b80,0x1b81, 0x1ba2,0x1ba5, 0x1ba8,0x1ba9, 0x1bab,0x1bad, 0x1be6,0x1be6, 0x1be8,0x1be9, 0x1bed,0x1bed, 0x1bef,0x1bf1, 0x1c2c,0x1c33, 0x1c36,0x1c37, 0x1cd0,0x1cd2, 0x1cd4,0x1ce0, 0x1ce2,0x1ce8, 0x1ced,0x1ced, 0x1cf4,0x1cf4, 0x1cf8,0x1cf9, 0x1dc0,0x1df9, 0x1dfb,0x1dff, 0x20d0,0x20dc, 0x20e1,0x20e1, 0x20e5,0x20f0, 0x2cef,0x2cf1, 0x2d7f,0x2d7f, 0x2de0,0x2dff, 0x302a,0x302d, 0x3099,0x309a, 0xa66f,0xa66f, 0xa674,0xa67d, 0xa69e,0xa69f, 0xa6f0,0xa6f1, 0xa802,0xa802, 0xa806,0xa806, 0xa80b,0xa80b, 0xa825,0xa826, 0xa8c4,0xa8c5, 0xa8e0,0xa8f1, 0xa8ff,0xa8ff, 0xa926,0xa92d, 0xa947,0xa951, 0xa980,0xa982, 0xa9b3,0xa9b3, 0xa9b6,0xa9b9, 0xa9bc,0xa9bd, 0xa9e5,0xa9e5, 0xaa29,0xaa2e, 0xaa31,0xaa32, 0xaa35,0xaa36, 0xaa43,0xaa43, 0xaa4c,0xaa4c, 0xaa7c,0xaa7c, 0xaab0,0xaab0, 0xaab2,0xaab4, 0xaab7,0xaab8, 0xaabe,0xaabf, 0xaac1,0xaac1, 0xaaec,0xaaed, 0xaaf6,0xaaf6, 0xabe5,0xabe5, 0xabe8,0xabe8, 0xabed,0xabed, 0xfb1e,0xfb1e, 0xfe00,0xfe0f, 0xfe20,0xfe2f, 0x101fd,0x101fd, 0x102e0,0x102e0, 0x10376,0x1037a, 0x10a01,0x10a03, 0x10a05,0x10a06, 0x10a0c,0x10a0f, 0x10a38,0x10a3a, 0x10a3f,0x10a3f, 0x10ae5,0x10ae6, 0x10d24,0x10d27, 0x10f46,0x10f50, 0x11001,0x11001, 0x11038,0x11046, 0x1107f,0x11081, 0x110b3,0x110b6, 0x110b9,0x110ba, 0x11100,0x11102, 0x11127,0x1112b, 0x1112d,0x11134, 0x11173,0x11173, 0x11180,0x11181, 0x111b6,0x111be, 0x111c9,0x111cc, 0x1122f,0x11231, 0x11234,0x11234, 0x11236,0x11237, 0x1123e,0x1123e, 0x112df,0x112df, 0x112e3,0x112ea, 0x11300,0x11301, 0x1133b,0x1133c, 0x11340,0x11340, 0x11366,0x1136c, 0x11370,0x11374, 0x11438,0x1143f, 0x11442,0x11444, 0x11446,0x11446, 0x1145e,0x1145e, 0x114b3,0x114b8, 0x114ba,0x114ba, 0x114bf,0x114c0, 0x114c2,0x114c3, 0x115b2,0x115b5, 0x115bc,0x115bd, 0x115bf,0x115c0, 0x115dc,0x115dd, 0x11633,0x1163a, 0x1163d,0x1163d, 0x1163f,0x11640, 0x116ab,0x116ab, 0x116ad,0x116ad, 0x116b0,0x116b5, 0x116b7,0x116b7, 0x1171d,0x1171f, 0x11722,0x11725, 0x11727,0x1172b, 0x1182f,0x11837, 0x11839,0x1183a, 0x119d4,0x119d7, 0x119da,0x119db, 0x119e0,0x119e0, 0x11a01,0x11a0a, 0x11a33,0x11a38, 0x11a3b,0x11a3e, 0x11a47,0x11a47, 0x11a51,0x11a56, 0x11a59,0x11a5b, 0x11a8a,0x11a96, 0x11a98,0x11a99, 0x11c30,0x11c36, 0x11c38,0x11c3d, 0x11c3f,0x11c3f, 0x11c92,0x11ca7, 0x11caa,0x11cb0, 0x11cb2,0x11cb3, 0x11cb5,0x11cb6, 0x11d31,0x11d36, 0x11d3a,0x11d3a, 0x11d3c,0x11d3d, 0x11d3f,0x11d45, 0x11d47,0x11d47, 0x11d90,0x11d91, 0x11d95,0x11d95, 0x11d97,0x11d97, 0x11ef3,0x11ef4, 0x16af0,0x16af4, 0x16b30,0x16b36, 0x16f4f,0x16f4f, 0x16f8f,0x16f92, 0x1bc9d,0x1bc9e, 0x1d167,0x1d169, 0x1d17b,0x1d182, 0x1d185,0x1d18b, 0x1d1aa,0x1d1ad, 0x1d242,0x1d244, 0x1da00,0x1da36, 0x1da3b,0x1da6c, 0x1da75,0x1da75, 0x1da84,0x1da84, 0x1da9b,0x1da9f, 0x1daa1,0x1daaf, 0x1e000,0x1e006, 0x1e008,0x1e018, 0x1e01b,0x1e021, 0x1e023,0x1e024, 0x1e026,0x1e02a, 0x1e130,0x1e136, 0x1e2ec,0x1e2ef, 0x1e8d0,0x1e8d6, 0x1e944,0x1e94a, 0xe0100,0xe01ef, 0x0,0x0}; static unsigned int encode_utf32 (const unsigned int * ranges, unsigned int ranges_count, unsigned int * s) { unsigned int * const s_start = s; for (unsigned int i = 0; i < ranges_count; i += 2) for (unsigned int j = ranges[i]; j <= ranges[i + 1]; ++j) *s++ = j; return s - s_start; } int main () { unsigned int * buffer_Mn = new unsigned int [1827]; YYCTYPE * s = (YYCTYPE *) buffer_Mn; unsigned int buffer_len = encode_utf32 (chars_Mn, sizeof (chars_Mn) / sizeof (unsigned int), buffer_Mn); /* convert 32-bit code units to YYCTYPE; reuse the same buffer */ for (unsigned int i = 0; i < buffer_len; ++i) s[i] = buffer_Mn[i]; if (!scan (s, s + buffer_len)) printf("test 'Mn' failed\n"); delete [] buffer_Mn; return 0; }
[ "skvadrik@gmail.com" ]
skvadrik@gmail.com
95b57abbe732ccc9f9df77b4cabadccc730feae7
84dd2490c7b5dda1fa01ba4bd5530dca00b3e8e7
/src/sick_reader/CSICK.h
dfad4defd062dcae7b7294ecf855aa45862733a8
[]
no_license
eglrp/laser_slam
2c6e58f7a8bbf5c94f7024d2aebae3eca69de4fa
83e980848e029a6addd937956b6e524b6d89c632
refs/heads/master
2020-04-07T04:52:49.104644
2017-04-15T20:55:23
2017-04-15T20:55:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,156
h
/* * CSICK.h * * Created on: Nov 26, 2012 * Author: liu */ #ifndef CSICK_H_ #define CSICK_H_ #include "CObs2DScan.h" #include "CClientSocket.h" #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <pthread.h> #define APPERTURE 4.712385 // in radian <=> 270° using namespace std; class CSICK { public: /** Constructor. * Note that there is default arguments, here you can customize IP Adress and TCP Port of your device. */ CSICK(std::string _ip=string("192.168.0.1"), unsigned int _port=2111); /** Destructor. * Close communcation with the device, and free memory. */ virtual ~CSICK(); /** This function acquire a laser scan from the device. If an error occured, hardwareError will be set to true. * The new laser scan will be stored in the outObservation argument. * * \exception This method throw exception if the frame received from the LMS 100 contain the following bad parameters : * * Status is not OK * * Data in the scan aren't DIST1 (may be RSSIx or DIST2). */ void doProcessSimple(bool &outThereIsObservation, CObs2DScan &outObservation, bool &hardwareError); //new for dual sick void doProcessSimple( ); bool setSick_A(string, unsigned int); bool setSick_B(string, unsigned int); void runSick_A(); void runSick_B(); //static int getScan_A(float* , TTimeStamp& ); static int getScan_A_SLAM(float* , TTimeStamp& ); static int getScan_A_OD(float* , TTimeStamp& ); //static int getScan_B(float* , TTimeStamp& ); static int getScan_B_SLAM(float* , TTimeStamp& ); static int getScan_B_OD(float* , TTimeStamp& ); CObs2DScan m_scan_A; CObs2DScan m_scan_B; CClientSocket m_client_A; CClientSocket m_client_B; bool m_connected_A; bool m_connected_B; pthread_mutex_t mutex_read_A_SLAM; pthread_mutex_t mutex_read_A_OD; pthread_mutex_t mutex_read_B_SLAM; pthread_mutex_t mutex_read_B_OD; float* m_pScan_A_SLAM; // for SLAM float* m_pScan_A_OD; // for obstacle detection float* m_pScan_B_SLAM; // for SLAM float* m_pScan_B_OD; // for obstacle detection bool bFirst_A; bool bFirst_B; int scan_A_num; int scan_B_num; bool scan_A_Ready_SLAM; bool scan_A_Ready_OD; bool scan_B_Ready_SLAM; bool scan_B_Ready_OD; TTimeStamp scan_A_t_SLAM; TTimeStamp scan_A_t_OD; TTimeStamp scan_B_t_SLAM; TTimeStamp scan_B_t_OD; /** This method must be called before trying to get a laser scan. */ bool turnOn(); /** This method could be called manually to stop communication with the device. Method is also called by destructor. */ bool turnOff(); /** A method to set the sensor pose on the robot. * Equivalent to setting the sensor pose via loading it from a config file. */ void setSensorPose(const CPose3D& _pose); void setSensorLabel(string ); /** This method should be called periodically. Period depend on the process_rate in the configuration file. */ void doProcess(); /** Initialize the sensor according to the parameters previously read in the configuration file. */ void initialize(); static CSICK * m_pCSICK; private : string m_ip; unsigned int m_port; CClientSocket m_client; bool m_turnedOn; string m_cmd; bool m_connected; unsigned int m_scanFrequency; // en hertz double m_angleResolution; // en degrés double m_startAngle; // degrés double m_stopAngle; // degrés //CPose3D m_sensorPose; double m_maxRange; double m_beamApperture; std::string m_sensorLabel; CObs2DScan m_scan; bool m_hdErr; bool m_obsErr; void generateCmd(const char *cmd); bool checkIsConnected(); bool decodeScan(char *buf, CObs2DScan& outObservation); void sendCommand(const char *cmd); void roughPrint( char *msg ); pthread_mutex_t mutex_read; protected: /** Load sensor pose on the robot, or keep the default sensor pose. */ /* void loadConfig_sensorSpecific(const mrpt::utils::CConfigFileBase &configSource, const std::string &iniSection ); */ }; #endif /* CSICK_H_ */
[ "hxzhang1@ualr.edu" ]
hxzhang1@ualr.edu
1ae800acf1efbe4ed47cfd454787e8ab03773ffe
1faf78259839977b53a1d7b9fc954e6a7cf5c887
/include/Transport_system.h
48a5ad55b81aff6b08406ed1f3211d8532661b17
[]
no_license
DeadBread/Tickets
28f18046a3cfd3711a13a612462b32eb0a99e8e2
c247efdd0ac1a2eddecde232b0b241325f1e818d
refs/heads/master
2021-01-10T18:02:46.813616
2016-04-08T16:02:02
2016-04-08T16:02:02
55,857,095
0
0
null
null
null
null
UTF-8
C++
false
false
1,136
h
#ifndef TRANSPORT_SYSTEM_H #define TRANSPORT_SYSTEM_H #include <memory> #include <iostream> #include "Train.h" #include "Plain.h" #include "Bus.h" using namespace std; class Transport_system { public: //Transport_system(); //virtual ~Transport_system(); static Transport_system& get_transport_system() { static Transport_system tmp; return tmp; } void add_plain(Plain &&pl) { all_plains.push_back(pl); } void add_train(Train &&tr) { all_trains.push_back(tr); } void add_bus(Bus &&bs) { all_buses.push_back(bs); } void print_all() const; void print_plains() const; void print_trains() const; void print_buses() const; const Vectr<Train> & get_trains() const { return all_trains; } const Vectr<Plain> & get_plains() const { return all_plains; } const Vectr<Bus> & get_buses() const { return all_buses; } protected: private: Transport_system(); Vectr<Train> all_trains; Vectr<Plain> all_plains; Vectr<Bus> all_buses; }; #endif // TRANSPORT_SYSTEM_H
[ "zhikov_n1@mail.ru" ]
zhikov_n1@mail.ru
f1e2db1971355d10830c5f3be053050855364587
a79d9f2e9626bb428f2f322cafd0fbf800bcdc2f
/src/EC/Item_component.cpp
6b35d684b741b9c35d6005d9ead47ba8d6a953d0
[ "GLWTPL" ]
permissive
marcintaton/Be-hidin
d2bae4ff10ad88a2fad6ec37af93a64d9c972e78
2d3dfce5bd3ec7d613e018a8f1626e77662fc7ea
refs/heads/master
2022-09-30T06:18:21.448676
2018-06-18T08:38:35
2018-06-18T08:38:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
628
cpp
#include "Item_component.h" #include "../Collision.h" #include "../Singletons/Player.h" Item_component::Item_component() { } Item_component::Item_component(Item* _item) { item = _item; } Item_component::~Item_component() { } void Item_component::update() { if (Collision::aabb( parent_entity->get_component<Collider_component>().collider, Player::Get_instance() ->get_component<Collider_component>() .collider)) { Player::Get_instance()->get_component<Inventory_component>().add_item( item); parent_entity->set_inactive(); } }
[ "tatonmarcinpr@gmail.com" ]
tatonmarcinpr@gmail.com
858e1edd5e1ac04de74bfbfd2437a6a6fa0b0e86
d45b17e2cdc712de1a2907b59d69a05ba2dc9533
/Xngine/ResourceModel.cpp
34632ce78e2f09270125fe1c54dc3abdc19b1507
[ "MIT" ]
permissive
FrancPS/Xngine
9e7738799492485327ebaec549e7d75d436a38f2
3eb031eb43a8c7fcfea0638f19347797783633b2
refs/heads/master
2023-01-24T22:02:11.140529
2020-11-29T12:32:45
2020-11-29T12:32:45
313,328,017
0
0
null
null
null
null
UTF-8
C++
false
false
3,135
cpp
#include "Globals.h" #include "Application.h" #include "ResourceModel.h" #include "ResourceMesh.h" #include "ModuleTexture.h" #include "assimp/scene.h" #include "assimp/cimport.h" #include "assimp/postprocess.h" #include "GL/glew.h" void AssimpCallback(const char* message, char* userData) { if (message) LOG("Assimp Message: %s", message); } ResourceModel::ResourceModel() { struct aiLogStream stream; stream.callback = AssimpCallback; aiAttachLogStream(&stream); } ResourceModel::~ResourceModel() { UnLoad(); } void ResourceModel::Load(const char* const file_name) { const aiScene* scene; scene = aiImportFile(file_name, aiProcessPreset_TargetRealtime_MaxQuality); if (scene) { UnLoad(); LoadMaterials(scene, file_name); LoadMeshes(scene); LOG("Scene loaded correctly"); } else { // the file was not a model, but it can be a texture! UnLoadMaterials(); unsigned int texID = App->textures->LoadTexture(file_name, file_name); if (texID) modelMaterials.push_back(texID); else LOG("Error loading %s: %s", file_name, aiGetErrorString()); } } void ResourceModel::LoadMaterials(const aiScene* const scene, const char* const file_name) { aiString file; modelMaterials.reserve(scene->mNumMaterials); for (unsigned i = 0; i < scene->mNumMaterials; ++i) { if (scene->mMaterials[i]->GetTexture(aiTextureType_DIFFUSE, 0, &file) == AI_SUCCESS) { // Populate materials list modelMaterials.push_back(App->textures->LoadTexture(file.data, file_name)); } } LOG("Materials loaded correctly"); } void ResourceModel::LoadMeshes(const aiScene* const scene) { aiString file; modelMeshes.reserve(scene->mNumMeshes); for (unsigned int i = 0; i < scene->mNumMeshes; ++i) { // Populate meshes list modelMeshes.push_back(new ResourceMesh(scene->mMeshes[i])); numMeshes++; } // get total size of all meshes for (unsigned int i = 0; i < modelMeshes.size(); i++) { if (modelMeshes[i]->maxX > maxX) maxX = modelMeshes[i]->maxX; if (modelMeshes[i]->minX < minX) minX = modelMeshes[i]->minX; if (modelMeshes[i]->maxY > maxY) maxY = modelMeshes[i]->maxY; if (modelMeshes[i]->minY < minY) minY = modelMeshes[i]->minY; if (modelMeshes[i]->maxZ > maxZ) maxZ = modelMeshes[i]->maxZ; if (modelMeshes[i]->minZ < minZ) minZ = modelMeshes[i]->minZ; } sizeX = maxX - minX; sizeY = maxY - minY; sizeZ = maxZ - minZ; LOG("Meshes loaded correctly"); } void ResourceModel::Draw() { for (unsigned int i = 0; i < numMeshes; ++i) { modelMeshes[i]->Draw(modelMaterials); } } void ResourceModel::UnLoad() { LOG("Unloading the current module"); // destroy objects from mesh list for (unsigned int i = 0; i < modelMeshes.size(); i++) { delete modelMeshes[i]; } numMeshes = 0; modelMeshes.clear(); // erase modelMaterials UnLoadMaterials(); ResetSizes(); } void ResourceModel::UnLoadMaterials() { for (unsigned int i = 0; i < modelMaterials.size(); i++) { glDeleteTextures(1, &modelMaterials[i]); } modelMaterials.clear(); } void ResourceModel::ResetSizes() { maxX = maxY = maxZ = 0; minX = minY = minZ = 3.40282e+038; // MAXFLOAT* sizeX = sizeY = sizeZ = 0; }
[ "f_xeski94@hotmail.com" ]
f_xeski94@hotmail.com
1f9af01f411e7170e7a94cbd911e0404564730d9
dd80a584130ef1a0333429ba76c1cee0eb40df73
/frameworks/av/media/libstagefright/omx/GraphicBufferSource.cpp
44f0be7a9b640913a7ce2ccd3bdbf65659a2f857
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unicode" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
26,608
cpp
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG_TAG "GraphicBufferSource" //#define LOG_NDEBUG 0 #include <utils/Log.h> #include "GraphicBufferSource.h" #include <OMX_Core.h> #include <media/stagefright/foundation/ADebug.h> #include <media/stagefright/foundation/AMessage.h> #include <media/hardware/MetadataBufferType.h> #include <ui/GraphicBuffer.h> namespace android { static const bool EXTRA_CHECK = true; GraphicBufferSource::GraphicBufferSource(OMXNodeInstance* nodeInstance, uint32_t bufferWidth, uint32_t bufferHeight, uint32_t bufferCount) : mInitCheck(UNKNOWN_ERROR), mNodeInstance(nodeInstance), mExecuting(false), mSuspended(false), mNumFramesAvailable(0), mEndOfStream(false), mEndOfStreamSent(false), mRepeatAfterUs(-1ll), mMaxTimestampGapUs(-1ll), mPrevOriginalTimeUs(-1ll), mPrevModifiedTimeUs(-1ll), mRepeatLastFrameGeneration(0), mRepeatLastFrameTimestamp(-1ll), mLatestSubmittedBufferId(-1), mLatestSubmittedBufferFrameNum(0), mLatestSubmittedBufferUseCount(0), mRepeatBufferDeferred(false) { ALOGV("GraphicBufferSource w=%u h=%u c=%u", bufferWidth, bufferHeight, bufferCount); if (bufferWidth == 0 || bufferHeight == 0) { ALOGE("Invalid dimensions %ux%u", bufferWidth, bufferHeight); mInitCheck = BAD_VALUE; return; } String8 name("GraphicBufferSource"); mBufferQueue = new BufferQueue(); mBufferQueue->setConsumerName(name); mBufferQueue->setDefaultBufferSize(bufferWidth, bufferHeight); mBufferQueue->setConsumerUsageBits(GRALLOC_USAGE_HW_VIDEO_ENCODER | GRALLOC_USAGE_HW_TEXTURE); mInitCheck = mBufferQueue->setMaxAcquiredBufferCount(bufferCount); if (mInitCheck != NO_ERROR) { ALOGE("Unable to set BQ max acquired buffer count to %u: %d", bufferCount, mInitCheck); return; } // Note that we can't create an sp<...>(this) in a ctor that will not keep a // reference once the ctor ends, as that would cause the refcount of 'this' // dropping to 0 at the end of the ctor. Since all we need is a wp<...> // that's what we create. wp<BufferQueue::ConsumerListener> listener = static_cast<BufferQueue::ConsumerListener*>(this); sp<BufferQueue::ProxyConsumerListener> proxy = new BufferQueue::ProxyConsumerListener(listener); mInitCheck = mBufferQueue->consumerConnect(proxy, false); if (mInitCheck != NO_ERROR) { ALOGE("Error connecting to BufferQueue: %s (%d)", strerror(-mInitCheck), mInitCheck); return; } CHECK(mInitCheck == NO_ERROR); } GraphicBufferSource::~GraphicBufferSource() { ALOGV("~GraphicBufferSource"); if (mBufferQueue != NULL) { status_t err = mBufferQueue->consumerDisconnect(); if (err != NO_ERROR) { ALOGW("consumerDisconnect failed: %d", err); } } } void GraphicBufferSource::omxExecuting() { Mutex::Autolock autoLock(mMutex); ALOGV("--> executing; avail=%d, codec vec size=%zd", mNumFramesAvailable, mCodecBuffers.size()); CHECK(!mExecuting); mExecuting = true; // Start by loading up as many buffers as possible. We want to do this, // rather than just submit the first buffer, to avoid a degenerate case: // if all BQ buffers arrive before we start executing, and we only submit // one here, the other BQ buffers will just sit until we get notified // that the codec buffer has been released. We'd then acquire and // submit a single additional buffer, repeatedly, never using more than // one codec buffer simultaneously. (We could instead try to submit // all BQ buffers whenever any codec buffer is freed, but if we get the // initial conditions right that will never be useful.) while (mNumFramesAvailable) { if (!fillCodecBuffer_l()) { ALOGV("stop load with frames available (codecAvail=%d)", isCodecBufferAvailable_l()); break; } } ALOGV("done loading initial frames, avail=%d", mNumFramesAvailable); // If EOS has already been signaled, and there are no more frames to // submit, try to send EOS now as well. if (mEndOfStream && mNumFramesAvailable == 0) { submitEndOfInputStream_l(); } if (mRepeatAfterUs > 0ll && mLooper == NULL) { mReflector = new AHandlerReflector<GraphicBufferSource>(this); mLooper = new ALooper; mLooper->registerHandler(mReflector); mLooper->start(); if (mLatestSubmittedBufferId >= 0) { sp<AMessage> msg = new AMessage(kWhatRepeatLastFrame, mReflector->id()); msg->setInt32("generation", ++mRepeatLastFrameGeneration); msg->post(mRepeatAfterUs); } } } void GraphicBufferSource::omxIdle() { ALOGV("omxIdle"); Mutex::Autolock autoLock(mMutex); if (mExecuting) { // We are only interested in the transition from executing->idle, // not loaded->idle. mExecuting = false; } } void GraphicBufferSource::omxLoaded(){ Mutex::Autolock autoLock(mMutex); if (!mExecuting) { // This can happen if something failed very early. ALOGW("Dropped back down to Loaded without Executing"); } if (mLooper != NULL) { mLooper->unregisterHandler(mReflector->id()); mReflector.clear(); mLooper->stop(); mLooper.clear(); } ALOGV("--> loaded; avail=%d eos=%d eosSent=%d", mNumFramesAvailable, mEndOfStream, mEndOfStreamSent); // Codec is no longer executing. Discard all codec-related state. mCodecBuffers.clear(); // TODO: scan mCodecBuffers to verify that all mGraphicBuffer entries // are null; complain if not mExecuting = false; } void GraphicBufferSource::addCodecBuffer(OMX_BUFFERHEADERTYPE* header) { Mutex::Autolock autoLock(mMutex); if (mExecuting) { // This should never happen -- buffers can only be allocated when // transitioning from "loaded" to "idle". ALOGE("addCodecBuffer: buffer added while executing"); return; } ALOGV("addCodecBuffer h=%p size=%lu p=%p", header, header->nAllocLen, header->pBuffer); CodecBuffer codecBuffer; codecBuffer.mHeader = header; mCodecBuffers.add(codecBuffer); } void GraphicBufferSource::codecBufferEmptied(OMX_BUFFERHEADERTYPE* header) { Mutex::Autolock autoLock(mMutex); if (!mExecuting) { return; } int cbi = findMatchingCodecBuffer_l(header); if (cbi < 0) { // This should never happen. ALOGE("codecBufferEmptied: buffer not recognized (h=%p)", header); return; } ALOGV("codecBufferEmptied h=%p size=%lu filled=%lu p=%p", header, header->nAllocLen, header->nFilledLen, header->pBuffer); CodecBuffer& codecBuffer(mCodecBuffers.editItemAt(cbi)); // header->nFilledLen may not be the original value, so we can't compare // that to zero to see of this was the EOS buffer. Instead we just // see if the GraphicBuffer reference was null, which should only ever // happen for EOS. if (codecBuffer.mGraphicBuffer == NULL) { if (!(mEndOfStream && mEndOfStreamSent)) { // This can happen when broken code sends us the same buffer // twice in a row. ALOGE("ERROR: codecBufferEmptied on non-EOS null buffer " "(buffer emptied twice?)"); } // No GraphicBuffer to deal with, no additional input or output is // expected, so just return. return; } if (EXTRA_CHECK) { // Pull the graphic buffer handle back out of the buffer, and confirm // that it matches expectations. OMX_U8* data = header->pBuffer; buffer_handle_t bufferHandle; memcpy(&bufferHandle, data + 4, sizeof(buffer_handle_t)); if (bufferHandle != codecBuffer.mGraphicBuffer->handle) { // should never happen ALOGE("codecBufferEmptied: buffer's handle is %p, expected %p", bufferHandle, codecBuffer.mGraphicBuffer->handle); CHECK(!"codecBufferEmptied: mismatched buffer"); } } // Find matching entry in our cached copy of the BufferQueue slots. // If we find a match, release that slot. If we don't, the BufferQueue // has dropped that GraphicBuffer, and there's nothing for us to release. int id = codecBuffer.mBuf; if (mBufferSlot[id] != NULL && mBufferSlot[id]->handle == codecBuffer.mGraphicBuffer->handle) { ALOGV("cbi %d matches bq slot %d, handle=%p", cbi, id, mBufferSlot[id]->handle); if (id == mLatestSubmittedBufferId) { CHECK_GT(mLatestSubmittedBufferUseCount--, 0); } else { mBufferQueue->releaseBuffer(id, codecBuffer.mFrameNumber, EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, Fence::NO_FENCE); } } else { ALOGV("codecBufferEmptied: no match for emptied buffer in cbi %d", cbi); } // Mark the codec buffer as available by clearing the GraphicBuffer ref. codecBuffer.mGraphicBuffer = NULL; if (mNumFramesAvailable) { // Fill this codec buffer. CHECK(!mEndOfStreamSent); ALOGV("buffer freed, %d frames avail (eos=%d)", mNumFramesAvailable, mEndOfStream); fillCodecBuffer_l(); } else if (mEndOfStream) { // No frames available, but EOS is pending, so use this buffer to // send that. ALOGV("buffer freed, EOS pending"); submitEndOfInputStream_l(); } else if (mRepeatBufferDeferred) { bool success = repeatLatestSubmittedBuffer_l(); if (success) { ALOGV("deferred repeatLatestSubmittedBuffer_l SUCCESS"); } else { ALOGV("deferred repeatLatestSubmittedBuffer_l FAILURE"); } mRepeatBufferDeferred = false; } return; } void GraphicBufferSource::codecBufferFilled(OMX_BUFFERHEADERTYPE* header) { Mutex::Autolock autoLock(mMutex); if (mMaxTimestampGapUs > 0ll && !(header->nFlags & OMX_BUFFERFLAG_CODECCONFIG)) { ssize_t index = mOriginalTimeUs.indexOfKey(header->nTimeStamp); if (index >= 0) { ALOGV("OUT timestamp: %lld -> %lld", header->nTimeStamp, mOriginalTimeUs[index]); header->nTimeStamp = mOriginalTimeUs[index]; mOriginalTimeUs.removeItemsAt(index); } else { // giving up the effort as encoder doesn't appear to preserve pts ALOGW("giving up limiting timestamp gap (pts = %lld)", header->nTimeStamp); mMaxTimestampGapUs = -1ll; } if (mOriginalTimeUs.size() > BufferQueue::NUM_BUFFER_SLOTS) { // something terribly wrong must have happened, giving up... ALOGE("mOriginalTimeUs has too many entries (%d)", mOriginalTimeUs.size()); mMaxTimestampGapUs = -1ll; } } } void GraphicBufferSource::suspend(bool suspend) { Mutex::Autolock autoLock(mMutex); if (suspend) { mSuspended = true; while (mNumFramesAvailable > 0) { BufferQueue::BufferItem item; status_t err = mBufferQueue->acquireBuffer(&item, 0); if (err == BufferQueue::NO_BUFFER_AVAILABLE) { // shouldn't happen. ALOGW("suspend: frame was not available"); break; } else if (err != OK) { ALOGW("suspend: acquireBuffer returned err=%d", err); break; } --mNumFramesAvailable; mBufferQueue->releaseBuffer(item.mBuf, item.mFrameNumber, EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, item.mFence); } return; } mSuspended = false; if (mExecuting && mNumFramesAvailable == 0 && mRepeatBufferDeferred) { if (repeatLatestSubmittedBuffer_l()) { ALOGV("suspend/deferred repeatLatestSubmittedBuffer_l SUCCESS"); mRepeatBufferDeferred = false; } else { ALOGV("suspend/deferred repeatLatestSubmittedBuffer_l FAILURE"); } } } bool GraphicBufferSource::fillCodecBuffer_l() { CHECK(mExecuting && mNumFramesAvailable > 0); if (mSuspended) { return false; } int cbi = findAvailableCodecBuffer_l(); if (cbi < 0) { // No buffers available, bail. ALOGV("fillCodecBuffer_l: no codec buffers, avail now %d", mNumFramesAvailable); return false; } ALOGV("fillCodecBuffer_l: acquiring buffer, avail=%d", mNumFramesAvailable); BufferQueue::BufferItem item; status_t err = mBufferQueue->acquireBuffer(&item, 0); if (err == BufferQueue::NO_BUFFER_AVAILABLE) { // shouldn't happen ALOGW("fillCodecBuffer_l: frame was not available"); return false; } else if (err != OK) { // now what? fake end-of-stream? ALOGW("fillCodecBuffer_l: acquireBuffer returned err=%d", err); return false; } mNumFramesAvailable--; // Wait for it to become available. err = item.mFence->waitForever("GraphicBufferSource::fillCodecBuffer_l"); if (err != OK) { ALOGW("failed to wait for buffer fence: %d", err); // keep going } // If this is the first time we're seeing this buffer, add it to our // slot table. if (item.mGraphicBuffer != NULL) { ALOGV("fillCodecBuffer_l: setting mBufferSlot %d", item.mBuf); mBufferSlot[item.mBuf] = item.mGraphicBuffer; } err = submitBuffer_l(item, cbi); if (err != OK) { ALOGV("submitBuffer_l failed, releasing bq buf %d", item.mBuf); mBufferQueue->releaseBuffer(item.mBuf, item.mFrameNumber, EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, Fence::NO_FENCE); } else { ALOGV("buffer submitted (bq %d, cbi %d)", item.mBuf, cbi); setLatestSubmittedBuffer_l(item); } return true; } bool GraphicBufferSource::repeatLatestSubmittedBuffer_l() { CHECK(mExecuting && mNumFramesAvailable == 0); if (mLatestSubmittedBufferId < 0 || mSuspended) { return false; } if (mBufferSlot[mLatestSubmittedBufferId] == NULL) { // This can happen if the remote side disconnects, causing // onBuffersReleased() to NULL out our copy of the slots. The // buffer is gone, so we have nothing to show. // // To be on the safe side we try to release the buffer. ALOGD("repeatLatestSubmittedBuffer_l: slot was NULL"); mBufferQueue->releaseBuffer( mLatestSubmittedBufferId, mLatestSubmittedBufferFrameNum, EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, Fence::NO_FENCE); mLatestSubmittedBufferId = -1; mLatestSubmittedBufferFrameNum = 0; return false; } int cbi = findAvailableCodecBuffer_l(); if (cbi < 0) { // No buffers available, bail. ALOGV("repeatLatestSubmittedBuffer_l: no codec buffers."); return false; } BufferQueue::BufferItem item; item.mBuf = mLatestSubmittedBufferId; item.mFrameNumber = mLatestSubmittedBufferFrameNum; item.mTimestamp = mRepeatLastFrameTimestamp; status_t err = submitBuffer_l(item, cbi); if (err != OK) { return false; } ++mLatestSubmittedBufferUseCount; /* repeat last frame up to kRepeatLastFrameCount times. * in case of static scene, a single repeat might not get rid of encoder * ghosting completely, refresh a couple more times to get better quality */ if (--mRepeatLastFrameCount > 0) { mRepeatLastFrameTimestamp = item.mTimestamp + mRepeatAfterUs * 1000; if (mReflector != NULL) { sp<AMessage> msg = new AMessage(kWhatRepeatLastFrame, mReflector->id()); msg->setInt32("generation", ++mRepeatLastFrameGeneration); msg->post(mRepeatAfterUs); } } return true; } void GraphicBufferSource::setLatestSubmittedBuffer_l( const BufferQueue::BufferItem &item) { ALOGV("setLatestSubmittedBuffer_l"); if (mLatestSubmittedBufferId >= 0) { if (mLatestSubmittedBufferUseCount == 0) { mBufferQueue->releaseBuffer( mLatestSubmittedBufferId, mLatestSubmittedBufferFrameNum, EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, Fence::NO_FENCE); } } mLatestSubmittedBufferId = item.mBuf; mLatestSubmittedBufferFrameNum = item.mFrameNumber; mRepeatLastFrameTimestamp = item.mTimestamp + mRepeatAfterUs * 1000; mLatestSubmittedBufferUseCount = 1; mRepeatBufferDeferred = false; mRepeatLastFrameCount = kRepeatLastFrameCount; if (mReflector != NULL) { sp<AMessage> msg = new AMessage(kWhatRepeatLastFrame, mReflector->id()); msg->setInt32("generation", ++mRepeatLastFrameGeneration); msg->post(mRepeatAfterUs); } } status_t GraphicBufferSource::signalEndOfInputStream() { Mutex::Autolock autoLock(mMutex); ALOGV("signalEndOfInputStream: exec=%d avail=%d eos=%d", mExecuting, mNumFramesAvailable, mEndOfStream); if (mEndOfStream) { ALOGE("EOS was already signaled"); return INVALID_OPERATION; } // Set the end-of-stream flag. If no frames are pending from the // BufferQueue, and a codec buffer is available, and we're executing, // we initiate the EOS from here. Otherwise, we'll let // codecBufferEmptied() (or omxExecuting) do it. // // Note: if there are no pending frames and all codec buffers are // available, we *must* submit the EOS from here or we'll just // stall since no future events are expected. mEndOfStream = true; if (mExecuting && mNumFramesAvailable == 0) { submitEndOfInputStream_l(); } return OK; } int64_t GraphicBufferSource::getTimestamp(const BufferQueue::BufferItem &item) { int64_t timeUs = item.mTimestamp / 1000; if (mMaxTimestampGapUs > 0ll) { /* Cap timestamp gap between adjacent frames to specified max * * In the scenario of cast mirroring, encoding could be suspended for * prolonged periods. Limiting the pts gap to workaround the problem * where encoder's rate control logic produces huge frames after a * long period of suspension. */ int64_t originalTimeUs = timeUs; if (mPrevOriginalTimeUs >= 0ll) { if (originalTimeUs < mPrevOriginalTimeUs) { // Drop the frame if it's going backward in time. Bad timestamp // could disrupt encoder's rate control completely. ALOGW("Dropping frame that's going backward in time"); return -1; } int64_t timestampGapUs = originalTimeUs - mPrevOriginalTimeUs; timeUs = (timestampGapUs < mMaxTimestampGapUs ? timestampGapUs : mMaxTimestampGapUs) + mPrevModifiedTimeUs; } mPrevOriginalTimeUs = originalTimeUs; mPrevModifiedTimeUs = timeUs; mOriginalTimeUs.add(timeUs, originalTimeUs); ALOGV("IN timestamp: %lld -> %lld", originalTimeUs, timeUs); } return timeUs; } status_t GraphicBufferSource::submitBuffer_l( const BufferQueue::BufferItem &item, int cbi) { ALOGV("submitBuffer_l cbi=%d", cbi); int64_t timeUs = getTimestamp(item); if (timeUs < 0ll) { return UNKNOWN_ERROR; } CodecBuffer& codecBuffer(mCodecBuffers.editItemAt(cbi)); codecBuffer.mGraphicBuffer = mBufferSlot[item.mBuf]; codecBuffer.mBuf = item.mBuf; codecBuffer.mFrameNumber = item.mFrameNumber; OMX_BUFFERHEADERTYPE* header = codecBuffer.mHeader; CHECK(header->nAllocLen >= 4 + sizeof(buffer_handle_t)); OMX_U8* data = header->pBuffer; const OMX_U32 type = kMetadataBufferTypeGrallocSource; buffer_handle_t handle = codecBuffer.mGraphicBuffer->handle; memcpy(data, &type, 4); memcpy(data + 4, &handle, sizeof(buffer_handle_t)); status_t err = mNodeInstance->emptyDirectBuffer(header, 0, 4 + sizeof(buffer_handle_t), OMX_BUFFERFLAG_ENDOFFRAME, timeUs); if (err != OK) { ALOGW("WARNING: emptyDirectBuffer failed: 0x%x", err); codecBuffer.mGraphicBuffer = NULL; return err; } ALOGV("emptyDirectBuffer succeeded, h=%p p=%p bufhandle=%p", header, header->pBuffer, handle); return OK; } void GraphicBufferSource::submitEndOfInputStream_l() { CHECK(mEndOfStream); if (mEndOfStreamSent) { ALOGV("EOS already sent"); return; } int cbi = findAvailableCodecBuffer_l(); if (cbi < 0) { ALOGV("submitEndOfInputStream_l: no codec buffers available"); return; } // We reject any additional incoming graphic buffers, so there's no need // to stick a placeholder into codecBuffer.mGraphicBuffer to mark it as // in-use. CodecBuffer& codecBuffer(mCodecBuffers.editItemAt(cbi)); OMX_BUFFERHEADERTYPE* header = codecBuffer.mHeader; if (EXTRA_CHECK) { // Guard against implementations that don't check nFilledLen. size_t fillLen = 4 + sizeof(buffer_handle_t); CHECK(header->nAllocLen >= fillLen); OMX_U8* data = header->pBuffer; memset(data, 0xcd, fillLen); } uint64_t timestamp = 0; // does this matter? status_t err = mNodeInstance->emptyDirectBuffer(header, /*offset*/ 0, /*length*/ 0, OMX_BUFFERFLAG_ENDOFFRAME | OMX_BUFFERFLAG_EOS, timestamp); if (err != OK) { ALOGW("emptyDirectBuffer EOS failed: 0x%x", err); } else { ALOGV("submitEndOfInputStream_l: buffer submitted, header=%p cbi=%d", header, cbi); mEndOfStreamSent = true; } } int GraphicBufferSource::findAvailableCodecBuffer_l() { CHECK(mCodecBuffers.size() > 0); for (int i = (int)mCodecBuffers.size() - 1; i>= 0; --i) { if (mCodecBuffers[i].mGraphicBuffer == NULL) { return i; } } return -1; } int GraphicBufferSource::findMatchingCodecBuffer_l( const OMX_BUFFERHEADERTYPE* header) { for (int i = (int)mCodecBuffers.size() - 1; i>= 0; --i) { if (mCodecBuffers[i].mHeader == header) { return i; } } return -1; } // BufferQueue::ConsumerListener callback void GraphicBufferSource::onFrameAvailable() { Mutex::Autolock autoLock(mMutex); ALOGV("onFrameAvailable exec=%d avail=%d", mExecuting, mNumFramesAvailable); if (mEndOfStream || mSuspended) { if (mEndOfStream) { // This should only be possible if a new buffer was queued after // EOS was signaled, i.e. the app is misbehaving. ALOGW("onFrameAvailable: EOS is set, ignoring frame"); } else { ALOGV("onFrameAvailable: suspended, ignoring frame"); } BufferQueue::BufferItem item; status_t err = mBufferQueue->acquireBuffer(&item, 0); if (err == OK) { // If this is the first time we're seeing this buffer, add it to our // slot table. if (item.mGraphicBuffer != NULL) { ALOGV("fillCodecBuffer_l: setting mBufferSlot %d", item.mBuf); mBufferSlot[item.mBuf] = item.mGraphicBuffer; } mBufferQueue->releaseBuffer(item.mBuf, item.mFrameNumber, EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, item.mFence); } return; } mNumFramesAvailable++; mRepeatBufferDeferred = false; ++mRepeatLastFrameGeneration; if (mExecuting) { fillCodecBuffer_l(); } } // BufferQueue::ConsumerListener callback void GraphicBufferSource::onBuffersReleased() { Mutex::Autolock lock(mMutex); uint32_t slotMask; if (mBufferQueue->getReleasedBuffers(&slotMask) != NO_ERROR) { ALOGW("onBuffersReleased: unable to get released buffer set"); slotMask = 0xffffffff; } ALOGV("onBuffersReleased: 0x%08x", slotMask); for (int i = 0; i < BufferQueue::NUM_BUFFER_SLOTS; i++) { if ((slotMask & 0x01) != 0) { mBufferSlot[i] = NULL; } slotMask >>= 1; } } status_t GraphicBufferSource::setRepeatPreviousFrameDelayUs( int64_t repeatAfterUs) { Mutex::Autolock autoLock(mMutex); if (mExecuting || repeatAfterUs <= 0ll) { return INVALID_OPERATION; } mRepeatAfterUs = repeatAfterUs; return OK; } status_t GraphicBufferSource::setMaxTimestampGapUs(int64_t maxGapUs) { Mutex::Autolock autoLock(mMutex); if (mExecuting || maxGapUs <= 0ll) { return INVALID_OPERATION; } mMaxTimestampGapUs = maxGapUs; return OK; } void GraphicBufferSource::onMessageReceived(const sp<AMessage> &msg) { switch (msg->what()) { case kWhatRepeatLastFrame: { Mutex::Autolock autoLock(mMutex); int32_t generation; CHECK(msg->findInt32("generation", &generation)); if (generation != mRepeatLastFrameGeneration) { // stale break; } if (!mExecuting || mNumFramesAvailable > 0) { break; } bool success = repeatLatestSubmittedBuffer_l(); if (success) { ALOGV("repeatLatestSubmittedBuffer_l SUCCESS"); } else { ALOGV("repeatLatestSubmittedBuffer_l FAILURE"); mRepeatBufferDeferred = true; } break; } default: TRESPASS(); } } } // namespace android
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
379e08eeb1421210da657e5cc41c9828747a763f
33e560cfbc2cbd17610ac9a76df203eb8d923399
/leetcode/153insert-interval.cpp
b64a464fc704caef046f6d5319911e7a611024b7
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
gaobaoru/code_day
935b4d63ff0c7a5d8d25a55069d8af5db21ec67f
c00aab4ea56309b4c000f3ef7056e8aa4d9ff7ec
refs/heads/master
2020-04-10T03:28:49.439274
2017-01-21T14:37:09
2017-01-21T14:37:09
62,032,328
0
1
null
2016-11-14T12:54:16
2016-06-27T06:55:35
C++
UTF-8
C++
false
false
1,443
cpp
题目描述 Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according to their start times. Example 1: Given intervals[1,3],[6,9], insert and merge[2,5]in as[1,5],[6,9]. Example 2: Given[1,2],[3,5],[6,7],[8,10],[12,16], insert and merge[4,9]in as[1,2],[3,10],[12,16]. This is because the new interval[4,9]overlaps with[3,5],[6,7],[8,10]. /** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class Solution { public: //时间复杂度O(n),空间复杂度O(1) vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) { vector<Interval>::iterator it = intervals.begin(); while(it != intervals.end()){ if(newInterval.end < it->start){ intervals.insert(it, newInterval); return intervals; }else if(newInterval.start > it->end){ it++; continue; }else{ newInterval.start = min(newInterval.start, it->start); newInterval.end = max(newInterval.end, it->end); it = intervals.erase(it); } } intervals.insert(intervals.end(), newInterval); return intervals; } };
[ "gaobaoru2010@126.com" ]
gaobaoru2010@126.com
1feb2d84deb8047e0a9fa590d0a258b588c837b8
bd2f117637be64d13d7b94093c537d346ca3257f
/Examples/Game/DiceWar/Sources/Server/server_game_player_collection.h
5d77c620aef1d91807b32163a392fd9ff218d02f
[ "Zlib" ]
permissive
animehunter/clanlib-2.3
e6d6a09ff58016809d687c101b64ed4da1467562
7013c39f4cd1f25b0dad3bedfdb7a5cf593b1bb7
refs/heads/master
2016-09-10T12:56:23.015390
2011-12-15T20:58:59
2011-12-15T20:58:59
3,001,221
1
1
null
null
null
null
UTF-8
C++
false
false
711
h
#pragma once class Server; class ServerGame; class ServerGamePlayer; class ServerGamePlayerCollection { public: ServerGamePlayerCollection(Server *server, ServerGame *game); ~ServerGamePlayerCollection(); void add_player(ServerGamePlayer *player); void remove_player(ServerGamePlayer *player); bool contains_player(ServerGamePlayer *player); ServerGamePlayer *get_player(int player_id); std::vector<ServerGamePlayer *> &get_players() { return players; } int get_count() const { return players.size(); } void transfer_players(); void send_event(const CL_NetGameEvent &game_event); private: Server *server; ServerGame *game; std::vector<ServerGamePlayer *> players; int next_visual_id; };
[ "rombust@cc39f7f4-b520-0410-a30f-b56705a9c917" ]
rombust@cc39f7f4-b520-0410-a30f-b56705a9c917
e2a30a1262a1a01b8296fa7c5fad506e89da3e39
cd470ad61c4dbbd37ff004785fd6d75980987fe9
/Codeforces/1213E Two Small Strings/暴力/std.cpp
0f4350f512d992ea4e58989a865cf03b4aea56f4
[]
no_license
AutumnKite/Codes
d67c3770687f3d68f17a06775c79285edc59a96d
31b7fc457bf8858424172bc3580389badab62269
refs/heads/master
2023-02-17T21:33:04.604104
2023-02-17T05:38:57
2023-02-17T05:38:57
202,944,952
3
1
null
null
null
null
UTF-8
C++
false
false
858
cpp
#include <cstdio> #include <cstring> #include <algorithm> int n; char s[5], t[5], c[5]; bool check(char a, char b){ if (a == s[0] && b == s[1]) return 0; if (a == t[0] && b == t[1]) return 0; return 1; } int main(){ scanf("%d%s%s", &n, s, t); c[0] = 'a', c[1] = 'b', c[2] = 'c'; while (1){ if (check(c[0], c[1]) && check(c[1], c[2])){ if (n == 1) return printf("YES\n%s", c), 0; if (check(c[2], c[0])){ puts("YES"); for (register int i = 1; i <= n; ++i) printf("%s", c); return 0; } if (check(c[0], c[0]) && check(c[1], c[1]) && check(c[2], c[2])){ puts("YES"); for (register int i = 1; i <= n; ++i) putchar(c[0]); for (register int i = 1; i <= n; ++i) putchar(c[1]); for (register int i = 1; i <= n; ++i) putchar(c[2]); return 0; } } if (!std :: next_permutation(c, c + 3)) break; } puts("NO"); }
[ "1790397194@qq.com" ]
1790397194@qq.com
09751f8e9e58d8a40a3478d408b88cee5d63630e
0bf1f7b901118b5cbe3d51bbc5885fcb634419c5
/Cpp/SDK/UMG_MobHealthBar_parameters.h
9783d194d299eadb242986463ef38c9738bfa376
[]
no_license
zH4x-SDK/zMCDungeons-SDK
3a90a959e4a72f4007fc749c53b8775b7155f3da
ab9d8f0ab04b215577dd2eb067e65015b5a70521
refs/heads/main
2023-07-15T15:43:17.217894
2021-08-27T13:49:22
2021-08-27T13:49:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,448
h
#pragma once // Name: DBZKakarot, Version: 1.0.3 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Parameters //--------------------------------------------------------------------------- // Function UMG_MobHealthBar.UMG_MobHealthBar_C.UpdateScaling struct UUMG_MobHealthBar_C_UpdateScaling_Params { }; // Function UMG_MobHealthBar.UMG_MobHealthBar_C.setHighlighted struct UUMG_MobHealthBar_C_setHighlighted_Params { }; // Function UMG_MobHealthBar.UMG_MobHealthBar_C.SetWidthScaling struct UUMG_MobHealthBar_C_SetWidthScaling_Params { }; // Function UMG_MobHealthBar.UMG_MobHealthBar_C.UpdateGraphics struct UUMG_MobHealthBar_C_UpdateGraphics_Params { }; // Function UMG_MobHealthBar.UMG_MobHealthBar_C.SetHealthBar struct UUMG_MobHealthBar_C_SetHealthBar_Params { }; // Function UMG_MobHealthBar.UMG_MobHealthBar_C.SetMob struct UUMG_MobHealthBar_C_SetMob_Params { }; // Function UMG_MobHealthBar.UMG_MobHealthBar_C.Tick struct UUMG_MobHealthBar_C_Tick_Params { }; // Function UMG_MobHealthBar.UMG_MobHealthBar_C.PreConstruct struct UUMG_MobHealthBar_C_PreConstruct_Params { }; // Function UMG_MobHealthBar.UMG_MobHealthBar_C.ExecuteUbergraph_UMG_MobHealthBar struct UUMG_MobHealthBar_C_ExecuteUbergraph_UMG_MobHealthBar_Params { }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
3e9358a615d2a5aa49654c998b93134ed91cbcbb
360f38378f4e515be0ff700964e4fadf3374ade5
/cs1400Final/cs1400Final/tom.cpp
cc9543a409c0016bb9d18cc00f24590764feb15f
[]
no_license
jenniferballing/CS1400Final
89b526b26a27c01a77eaa957221133ef6266ee3b
fa8ce7f5250c63f073a87196a52e10850c44ed1b
refs/heads/master
2016-09-10T12:07:53.076600
2013-11-30T04:47:29
2013-11-30T04:47:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,328
cpp
#include "tom.h" #include <cmath> #include <iostream> void tom::Place(int minR,int maxR,int minC,int maxC, SitRep sitrep){ bool done=false; int tr,tc; Dir td; while(!done){ tr=minR+rand()%(maxR-minR); tc=minC+rand()%(maxC-minC); if(sitrep.thing[tr][tc].what==space)done=true; } int rdist=ROWS/2-tr; int cdist=COLS/2-tc; if(abs(rdist)<abs(cdist)){ if(cdist>0)td=rt; else td=lt; }else{ if(rdist>0)td=up; else td=dn; } r=tr; c=tc; dir=td; } // tell someone what you want to do Action tom::Recommendation(SitRep sitrep){ // this code is provided as an example only // use at your own risk Action a; // first, try to attack in front of you int tr=r,tc=c; switch(dir){ case up: tr--; break; case dn: tr++; break; case rt: tc++; break; case lt: tc--; break; case none: break; } if(tr>=0&&tr<ROWS&&tc>=0&&tc<COLS){ if(sitrep.thing[tr][tc].what==unit){ if(sitrep.thing[tr][tc].tla!=tla){ a.action=attack; a.ar=tr; a.ac=tc; return a; } } } // there is not an enemy in front of me // so head to the nearest enemy if(dir==sitrep.nearestEnemy.dirFor){ a.action=fwd; a.maxDist=1; if(rank==knight||rank==crown)a.maxDist=HORSESPEED; return a; } else { a.action=turn; a.dir=sitrep.nearestEnemy.dirFor; return a; } a.action=nothing; return a; }
[ "jenniferballing@gmail.com" ]
jenniferballing@gmail.com
988fba82c03ff63cb837ef88daeda9d94bbd9e2c
a7413d9ce83654f1f34cacb09c20deeb6bd523ea
/toolboxes/operators/cpu/hoMotionCompensation2DTOperator.h
6508ba48d569d42b5285c898789ca5d117128f3a
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
hansenms/gadgetron
1e40b1a6265a96cc6f518d0a28cecb0a1d65d292
10531591411fea4e16a074a574cd449a60d28ef8
refs/heads/master
2022-02-01T23:52:52.993704
2021-12-10T23:31:52
2021-12-10T23:31:52
28,053,346
3
1
NOASSERTION
2021-12-21T23:41:07
2014-12-15T19:54:00
C++
UTF-8
C++
false
false
1,859
h
/** \file hoMotionCompensation2DTOperator.h \brief Implement motion compensation operator for 2DT cases \author Hui Xue */ #pragma once #include "cpuOperatorExport.h" #include "hoNDArray_linalg.h" #include "hoImageRegContainer2DRegistration.h" namespace Gadgetron { template <typename T, typename CoordType> class EXPORTCPUOPERATOR hoMotionCompensation2DTOperator { public: typedef typename realType<T>::Type value_type; typedef hoNDArray<T> ARRAY_TYPE; hoMotionCompensation2DTOperator(); virtual ~hoMotionCompensation2DTOperator(); /// x: [RO E1 CHA N] /// y: [RO E1 CHA N] /// apply forward deformation Mx virtual void mult_M(ARRAY_TYPE* x, ARRAY_TYPE* y, bool accumulate = false); /// appy adjoint deformation M'x virtual void mult_MH(ARRAY_TYPE* x, ARRAY_TYPE* y, bool accumulate = false); /// compute gradient of ||Mx||1 virtual void gradient(ARRAY_TYPE* x, ARRAY_TYPE* g, bool accumulate = false); /// compute cost value of L1 norm ||Mx||1 virtual value_type magnitude(ARRAY_TYPE* x); T bg_value_; Gadgetron::GT_BOUNDARY_CONDITION bc_; hoNDArray<CoordType> dx_; hoNDArray<CoordType> dy_; hoNDArray<CoordType> adj_dx_; hoNDArray<CoordType> adj_dy_; protected: // warp the 2D+T image arrays // im : complex image [RO E1 CHA N] // dx, dy : [RO E1 N] deformation fields // the image domain warpping is performed virtual void warp_image(const hoNDArray<T>& im, const hoNDArray<CoordType>& dx, const hoNDArray<CoordType>& dy, hoNDArray<T>& warpped, T bgValue=0, Gadgetron::GT_BOUNDARY_CONDITION bh=GT_BOUNDARY_CONDITION_FIXEDVALUE); // helper memory ARRAY_TYPE moco_im_; ARRAY_TYPE adj_moco_im_; ARRAY_TYPE grad_im_; hoNDArray<value_type> moco_im_Norm_; hoNDArray<value_type> moco_im_Norm_approx_; }; }
[ "hui.xue@nih.gov" ]
hui.xue@nih.gov
e986708d4a1f7b1834747912c08821f9ac9f4ae0
f84a142a0891022ef44d0f6b6e80b9c7163cc9e4
/.history/src/person_20200716233728.cpp
9ad70eb584eae335ac07a50cfc71b2484b6ea15e
[ "MIT" ]
permissive
zoedsy/LibManage
046b3749cc089355e0d3a9fe0f13b9a042b8ec85
590311fb035d11daa209301f9ce76f53ccae7643
refs/heads/master
2022-11-17T09:44:26.432808
2020-07-17T06:45:50
2020-07-17T06:45:50
279,246,675
1
0
null
null
null
null
GB18030
C++
false
false
17,248
cpp
/* * @Author: DuShiyi * @Date: 2020-07-15 17:56:32 * @LastEditTime: 2020-07-16 23:37:26 * @LastEditors: Please set LastEditors * @Description: about person(admin ,visitor,reader) * @FilePath: \LibManage\src\person.cpp */ #include"../include/person.h" #include"../include/library.h" // logs = new Logs(); //具体功能等待完善 using LibSys::library; // LibSys::library* lib1= LibSys::library::getLibrary(); /* |函 数 名|:apply10 |功能描述|:管理员登陆后显示所有书籍 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:马晓晨 ========================================================================================*/ void Admin::apply10(){ //显示所有内容 LibSys::library* lib1= LibSys::library::getLibrary(); system("cls"); lib1->list(true); system("pause"); //back admin function menu // apply1(); } // Logs* Person::ls = new Logs(); // library* Person::lib = new library(); /*============================================================================== |函 数 名|:apply11 |功能描述|:管理员登陆后的search界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Admin::apply11(){ //search LibSys::library* lib1= LibSys::library::getLibrary(); string s1; char c; system("cls"); cout<<"您希望通过哪种方式来搜索书籍,"<<endl; cout<<"书名请输入‘N’,ISBN请输入‘I’,作者名请输入‘A’,出版社名请输入‘P’:"; cin>>c; cout<<"请输入其关键词:"; cin>>s1; switch(c){ case 'N': if(lib1->search(s1,LibSys::library::field::NAME)){ }else{ cout<<"未找到相应书籍"<<endl; } break; case 'I': if(lib1->search(s1,LibSys::library::field::ISBN)){ }else{ cout<<"未找到相应书籍"<<endl; } break; case 'A': if(lib1->search(s1,LibSys::library::field::AUTHOR)){ }else{ cout<<"未找到相应书籍"<<endl; } break; case 'P': if(lib1->search(s1,LibSys::library::field::PRESS)){ }else{ cout<<"未找到相应书籍"<<endl; } break; } system("pause"); //back admin function menu } /*============================================================================== |函 数 名|:apply12 |功能描述|:管理员登陆后的修改书籍数据界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Admin::apply12(){ //INFORMATION MODIFY LibSys::library* lib1= LibSys::library::getLibrary(); string _isbn; string newname; cout<<"请输入书的ISBN:"; cin>>_isbn; cout<<"请输入书的新名字:"; cin>>newname; lib1->changeBookName(*this,_isbn,newname); // cout<<"successfully change book name!"<<endl; //返回功能主页 system("pause"); // apply1(); } /*============================================================================== |函 数 名|:apply13 |功能描述|:管理员登陆后的插入书籍信息的界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Admin::apply13(){ //information insert LibSys::library* lib1= LibSys::library::getLibrary(); string n;string isbn;string author;string press;int count;string cg; cout<<"请按照示例格式输入所录入书的信息(书名 ISBN 出版社 库存量 上架类型):"<<endl; cin>>n;cin>>isbn;cin>>author;cin>>press;cin>>count;cin>>cg; LibSys::Book b(n,isbn,author,press,count,LibSys::StringToCategory(cg)); lib1->buy(*this,b); // cout<<"successfully insert book"<<endl; system("pause"); // apply1(); } /*============================================================================== |函 数 名|:apply14 |功能描述|:管理员登陆后的书籍信息删除界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Admin::apply14(){ //information delete LibSys::library* lib1= LibSys::library::getLibrary(); string n;string isbn;string author;string press;int count;string cg; cout<<"请按照示例格式输入所删除书的信息(书名 ISBN 出版社 数量 上架类型):"<<endl; cin>>n;cin>>isbn;cin>>author;cin>>press;cin>>count;cin>>cg; LibSys::Book b(n,isbn,author,press,count,LibSys::StringToCategory(cg)); lib1->discard(*this,b); // cout<<"successfully delete book"<<endl; system("pause"); // apply1(); } /*============================================================================== |函 数 名|:apply11 |功能描述|:管理员登陆后的search界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Admin::apply15(){ //look up borrowlog LibSys::library* lib1= LibSys::library::getLibrary(); lib1->listBorrowTrace(); system("pause"); // apply1(); } /* |函 数 名|:apply10 |功能描述|:管理员登陆后显示所有书籍 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:马晓晨 ========================================================================================*/ void Reader::apply20(){ //显示所有内容 LibSys::library* lib1= LibSys::library::getLibrary(); system("cls"); lib1->list(1); system("pause"); //back admin function menu // apply2(); } /*============================================================================== |函 数 名|:apply21 |功能描述|:读者登陆后的search界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Reader::apply21(){ //search LibSys::library* lib1= LibSys::library::getLibrary(); string s1; char c; system("cls"); cout<<"您希望通过哪种方式来搜索书籍,"<<endl; cout<<"书名请输入‘N’,ISBN请输入‘I’,作者名请输入‘A’,出版社名请输入‘P’:"; cin>>c; cout<<"请输入其关键词:"; cin>>s1; switch(c){ case 'N': if(lib1->search(s1,LibSys::library::field::NAME)){ }else{ cout<<"can not find the book"<<endl; } break; case 'I': if(lib1->search(s1,LibSys::library::field::ISBN)){ }else{ cout<<"can not find the book"<<endl; } break; case 'A': if(lib1->search(s1,LibSys::library::field::AUTHOR)){ }else{ cout<<"can not find the book"<<endl; } break; case 'P': if(lib1->search(s1,LibSys::library::field::PRESS)){ }else{ cout<<"can not find the book"<<endl; } break; } system("pause"); //back admin function menu // apply2(); } /*============================================================================== |函 数 名|:apply22 |功能描述|:读者登陆后的借阅界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Reader::apply22(){ //borrow LibSys::library* lib1= LibSys::library::getLibrary(); string isbn; cout<<"please input the isbn of the book:"<<endl; cin>>isbn; lib1->borrow(*this,isbn); system("pause"); } /*============================================================================== |函 数 名|:apply11 |功能描述|:读者登陆后的归还界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Reader::apply23(){ //return LibSys::library* lib1= LibSys::library::getLibrary(); int flag=0; do{ char a; string isbn; cout<<"Do you wannna return all the books?(Y/N):"; cin>>a; if(a=='Y'){ lib1->retAllBook(*this); flag=0; // cout<<"successfully return all the books!"<<endl; }else if(a=='N'){ cout<<"input isbn of the book you wanna return:"; cin>>isbn; lib1->ret(*this,isbn); flag=0; // cout<<"successfully return the book!"<<endl; }else{ cout<<"input error!"<<endl; flag=1; } }while(flag); system("pause"); } /*============================================================================== |函 数 名|:apply25 |功能描述|:读者登陆后的查阅个人借书信息的界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Reader::apply25(){ //look up borrowlog LibSys::library* lib1= LibSys::library::getLibrary(); lib1->personalBorrowTrace(*this); system("pause"); } /*============================================================================== |函 数 名|:apply31 |功能描述|:游客查阅所有书籍信息的界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Visitor::apply31(){ //look up all the information LibSys::library* lib1= LibSys::library::getLibrary(); lib1->list(true); system("pause"); } /*============================================================================== |函 数 名|:apply32 |功能描述|:游客搜索书籍信息的界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Visitor::apply32(){ //search information LibSys::library* lib1= LibSys::library::getLibrary(); string s1; char c; system("cls"); cout<<"您希望通过哪种方式来搜索书籍,"<<endl; cout<<"书名请输入‘N’,ISBN请输入‘I’,作者名请输入‘A’,出版社名请输入‘P’:"; cin>>c; cout<<"请输入其关键词:"; cin>>s1; switch(c){ case 'N': if(lib1->search(s1,LibSys::library::field::NAME)){ }else{ cout<<"can not find the book"<<endl; } break; case 'I': if(lib1->search(s1,LibSys::library::field::ISBN)){ }else{ cout<<"can not find the book"<<endl; } break; case 'A': if(lib1->search(s1,LibSys::library::field::AUTHOR)){ }else{ cout<<"can not find the book"<<endl; } break; case 'P': if(lib1->search(s1,LibSys::library::field::PRESS)){ }else{ cout<<"can not find the book"<<endl; } break; } system("pause"); //back admin function menu } /*============================================================================== |函 数 名|:apply1 |功能描述|:管理员登陆后功能选项界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Admin::apply1() { while(1){ int i; system("cls"); cout<<"----管理员界面----"<<endl; cout<<"0.显示所有书籍" <<endl; cout<<"1.书籍查询"<<endl; cout<<"2.书籍修改"<<endl; cout<<"3.书籍信息增加"<<endl; cout<<"4.书籍信息删除"<<endl; cout<<"5.查看用户借阅记录"<<endl; cout<<"6.返回上一页"<<endl; cout<<"请输入您要使用的功能选项(0-6):"; cin>>i; system("cls"); switch(i){ case 0: //显示所有书籍的接口 apply10(); break; case 1: //录入信息的接口 apply11(); break; case 2: //数据修改接口 apply12(); break; case 3: //数据插入接口 apply13(); break; case 4: //数据删除接口 apply14(); break; case 5: //借阅信息查看接口 apply15(); break; case 6: //last page return; break; default: cout<<"输入错误!"<<endl; } // system("pause"); } } /*============================================================================== |函 数 名|:apply2 |功能描述|:读者登陆后功能界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Reader::apply2() //读者功能 { while(1){ int i; system("cls"); cout<<"-----读者界面-----"<<endl; cout<<"0.显示所有书籍" <<endl; cout<<"1.书籍查询"<<endl; cout<<"2.书籍借阅"<<endl; cout<<"3.书籍归还"<<endl; // cout<<"4.modify personal informatin"<<endl; cout<<"4.查看个人借阅日志"<<endl; cout<<"5.返回上一页"<<endl; cout<<"请输入您要使用的功能选项(0-5):"; cin>>i; system("cls"); switch(i){ case 0: apply20(); break; case 1: apply21(); break; case 2: apply22(); break; case 3: apply23(); break; case 4: apply25(); break; case 5: return; break; default: cout<<"输入错误!"<<endl; } } } /*============================================================================== |函 数 名|:apply3 |功能描述|:游客功能界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Visitor::apply3() { //游客功能 while(1){ system("cls"); int i; cout<<"-----游客界面-----"<<endl; cout<<"1.查询所有馆藏书籍"<<endl; cout<<"2.查询书籍"<<endl; cout<<"3.返回上一页"<<endl; cout<<"请输入您要使用的功能选项(1-3):"<<endl; cin>>i; switch(i){ case 1: apply31(); break; case 2: apply32(); break; case 3: return; //last page default: cout<<"输入错误!"<<endl; } } }
[ "1246906787@qq.com" ]
1246906787@qq.com
76c6718de738397ead6b0222486a428f14a1b25d
e61f5b7a23c3b1ca014e4809e487e95a65fc3e2c
/Source/SBansheeEditor/Source/BsScriptGizmos.cpp
c3a73a3f86956e1ddb2973a7745c3119d1593541
[]
no_license
ketoo/BansheeEngine
83568cb22f2997162905223013f3f6d73ae4227e
1ce5ec1bb46329695dd7cc13c0556b5bf7278e39
refs/heads/master
2021-01-02T08:49:09.416072
2017-08-01T15:46:42
2017-08-01T15:46:42
99,069,699
1
0
null
2017-08-02T03:48:06
2017-08-02T03:48:06
null
UTF-8
C++
false
false
6,423
cpp
//********************************** Banshee Engine (www.banshee3d.com) **************************************************// //**************** Copyright (c) 2016 Marko Pintera (marko.pintera@gmail.com). All rights reserved. **********************// #include "BsScriptGizmos.h" #include "BsScriptMeta.h" #include "BsMonoClass.h" #include "BsScriptSpriteTexture.h" #include "BsGizmoManager.h" #include "BsMonoUtil.h" #include "BsScriptFont.h" #include "BsScriptRendererMeshData.generated.h" namespace bs { void ScriptGizmos::initRuntimeData() { metaData.scriptClass->addInternalCall("Internal_SetColor", &ScriptGizmos::internal_SetColor); metaData.scriptClass->addInternalCall("Internal_GetColor", &ScriptGizmos::internal_GetColor); metaData.scriptClass->addInternalCall("Internal_SetTransform", &ScriptGizmos::internal_SetTransform); metaData.scriptClass->addInternalCall("Internal_GetTransform", &ScriptGizmos::internal_GetTransform); metaData.scriptClass->addInternalCall("Internal_DrawCube", &ScriptGizmos::internal_DrawCube); metaData.scriptClass->addInternalCall("Internal_DrawSphere", &ScriptGizmos::internal_DrawSphere); metaData.scriptClass->addInternalCall("Internal_DrawCone", &ScriptGizmos::internal_DrawCone); metaData.scriptClass->addInternalCall("Internal_DrawDisc", &ScriptGizmos::internal_DrawDisc); metaData.scriptClass->addInternalCall("Internal_DrawWireCube", &ScriptGizmos::internal_DrawWireCube); metaData.scriptClass->addInternalCall("Internal_DrawWireSphere", &ScriptGizmos::internal_DrawWireSphere); metaData.scriptClass->addInternalCall("Internal_DrawWireCapsule", &ScriptGizmos::internal_DrawWireCapsule); metaData.scriptClass->addInternalCall("Internal_DrawWireCone", &ScriptGizmos::internal_DrawWireCone); metaData.scriptClass->addInternalCall("Internal_DrawWireDisc", &ScriptGizmos::internal_DrawWireDisc); metaData.scriptClass->addInternalCall("Internal_DrawWireArc", &ScriptGizmos::internal_DrawWireArc); metaData.scriptClass->addInternalCall("Internal_DrawWireMesh", &ScriptGizmos::internal_DrawWireMesh); metaData.scriptClass->addInternalCall("Internal_DrawLine", &ScriptGizmos::internal_DrawLine); metaData.scriptClass->addInternalCall("Internal_DrawLineList", &ScriptGizmos::internal_DrawLineList); metaData.scriptClass->addInternalCall("Internal_DrawFrustum", &ScriptGizmos::internal_DrawFrustum); metaData.scriptClass->addInternalCall("Internal_DrawIcon", &ScriptGizmos::internal_DrawIcon); metaData.scriptClass->addInternalCall("Internal_DrawText", &ScriptGizmos::internal_DrawText); } void ScriptGizmos::internal_SetColor(Color* color) { GizmoManager::instance().setColor(*color); } void ScriptGizmos::internal_GetColor(Color* color) { *color = GizmoManager::instance().getColor(); } void ScriptGizmos::internal_SetTransform(Matrix4* transform) { GizmoManager::instance().setTransform(*transform); } void ScriptGizmos::internal_GetTransform(Matrix4* transform) { *transform = GizmoManager::instance().getTransform(); } void ScriptGizmos::internal_DrawCube(Vector3* position, Vector3* extents) { GizmoManager::instance().drawCube(*position, *extents); } void ScriptGizmos::internal_DrawSphere(Vector3* position, float radius) { GizmoManager::instance().drawSphere(*position, radius); } void ScriptGizmos::internal_DrawCone(Vector3* base, Vector3* normal, float height, float radius, Vector2* scale) { GizmoManager::instance().drawCone(*base, *normal, height, radius, *scale); } void ScriptGizmos::internal_DrawDisc(Vector3* position, Vector3* normal, float radius) { GizmoManager::instance().drawDisc(*position, *normal, radius); } void ScriptGizmos::internal_DrawWireCube(Vector3* position, Vector3* extents) { GizmoManager::instance().drawWireCube(*position, *extents); } void ScriptGizmos::internal_DrawWireSphere(Vector3* position, float radius) { GizmoManager::instance().drawWireSphere(*position, radius); } void ScriptGizmos::internal_DrawWireCapsule(Vector3* position, float height, float radius) { GizmoManager::instance().drawWireCapsule(*position, height, radius); } void ScriptGizmos::internal_DrawWireCone(Vector3* base, Vector3* normal, float height, float radius, Vector2* scale) { GizmoManager::instance().drawWireCone(*base, *normal, height, radius, *scale); } void ScriptGizmos::internal_DrawLine(Vector3* start, Vector3* end) { GizmoManager::instance().drawLine(*start, *end); } void ScriptGizmos::internal_DrawLineList(MonoArray* linePoints) { ScriptArray lineArray(linePoints); UINT32 numElements = lineArray.size(); Vector<Vector3> points(numElements); for (UINT32 i = 0; i < numElements; i++) points[i] = lineArray.get<Vector3>(i); GizmoManager::instance().drawLineList(points); } void ScriptGizmos::internal_DrawWireDisc(Vector3* position, Vector3* normal, float radius) { GizmoManager::instance().drawWireDisc(*position, *normal, radius); } void ScriptGizmos::internal_DrawWireArc(Vector3* position, Vector3* normal, float radius, float startAngle, float amountAngle) { GizmoManager::instance().drawWireArc(*position, *normal, radius, Degree(startAngle), Degree(amountAngle)); } void ScriptGizmos::internal_DrawWireMesh(ScriptRendererMeshData* meshData) { if (meshData != nullptr) { SPtr<MeshData> nativeMeshData = meshData->getInternal()->getData(); GizmoManager::instance().drawWireMesh(nativeMeshData); } } void ScriptGizmos::internal_DrawFrustum(Vector3* position, float aspect, Degree* FOV, float near, float far) { GizmoManager::instance().drawFrustum(*position, aspect, *FOV, near, far); } void ScriptGizmos::internal_DrawIcon(Vector3* position, MonoObject* image, bool fixedScale) { HSpriteTexture nativeTexture; if (image != nullptr) nativeTexture = ScriptSpriteTexture::toNative(image)->getHandle(); GizmoManager::instance().drawIcon(*position, nativeTexture, fixedScale); } void ScriptGizmos::internal_DrawText(Vector3* position, MonoString* text, ScriptFont* font, int size) { WString nativeText = MonoUtil::monoToWString(text); HFont fontHandle; if (font != nullptr) fontHandle = font->getHandle(); GizmoManager::instance().drawText(*position, nativeText, fontHandle, size); } }
[ "bearishsun@gmail.com" ]
bearishsun@gmail.com
444d586fde259af5249a30d3c8a7a84ab104ca69
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/squid/hunk_4213.cpp
55ac7e050c5fabeb82190ebc99c14390022efca8
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,378
cpp
* X-CACHE-MISS entry should tell us who. */ httpHeaderPutStrf(&rep->header, HDR_X_SQUID_ERROR, "%s %d", name, xerrno); + +#if USE_ERR_LOCALES + /* + * If error page auto-negotiate is enabled in any way, send the Vary. + * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this. + * We have even better reasons though: + * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching + */ + if(!Config.errorDirectory) { + /* We 'negotiated' this ONLY from the Accept-Language. */ + httpHeaderDelById(&rep->header, HDR_VARY); + httpHeaderPutStrf(&rep->header, HDR_VARY, "Accept-Language"); + } + + /* add the Content-Language header according to RFC section 14.12 */ + if(err_language) { + httpHeaderPutStrf(&rep->header, HDR_CONTENT_LANGUAGE, "%s", err_language); + } + else +#endif /* USE_ERROR_LOCALES */ + { + /* default templates are in English */ + /* language is known unless error_directory override used */ + if(!Config.errorDirectory) + httpHeaderPutStrf(&rep->header, HDR_CONTENT_LANGUAGE, "en"); + } + httpBodySet(&rep->body, content); /* do not memBufClean() or delete the content, it was absorbed by httpBody */ }
[ "993273596@qq.com" ]
993273596@qq.com
6b286cce858d36f2fee3e6267ac2fdaa4bc66063
d7909b07bbfcbfa6c066fa8db8fe3a7ecfbf220a
/TumTum_First/Demo/SourceCode/LHSceneCameraFollowDemo.h
9d22aad149820ccfa70b89d64e1dbdc24f017937
[]
no_license
tigerwoods1206/TumTumCopy
bd43a0973eb3478f65aa430b7521b1a69e17d0d2
3d50889ffa5ee0aeb7ff15ed9e08a4be4952bc91
refs/heads/master
2016-09-05T12:04:44.961195
2014-11-11T08:38:04
2014-11-11T08:38:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
576
h
#ifndef __LH_SCENE_CAMERA_FOLLOW_DEMO_H__ #define __LH_SCENE_CAMERA_FOLLOW_DEMO_H__ #include "cocos2d.h" #include "LHSceneDemo.h" class LHSceneCameraFollowDemo : public LHSceneDemo { public: static LHSceneCameraFollowDemo* create(); LHSceneCameraFollowDemo(); virtual ~LHSceneCameraFollowDemo(); virtual bool initWithContentOfFile(const std::string& plistLevelFile); virtual std::string className(); virtual bool onTouchBegan(Touch* touch, Event* event); private: bool didChangeX; }; #endif // __LH_SCENE_CAMERA_FOLLOW_DEMO_H__
[ "ohtaisao@square-enix.com" ]
ohtaisao@square-enix.com
c5baad7e1a3b5102f914421e114c61bc6842c2d2
ea53dfce2ddc7c3eb16381932fe8b2e80018cc0e
/indra/llui/llradiogroup.h
0588900600484c9bd843044191450eb593d951c2
[]
no_license
otwstephanie/hpa2oar
7a1ac9a1502c5a09f946c303ecaf0a9c61f2e409
0660c6a8d66d3ab40a5b034f2ff86ff4b356b15b
refs/heads/master
2021-01-20T22:35:31.868166
2010-12-15T09:52:21
2010-12-15T09:52:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,794
h
/** * @file llradiogroup.h * @brief LLRadioGroup base class * * $LicenseInfo:firstyear=2001&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #ifndef LL_LLRADIOGROUP_H #define LL_LLRADIOGROUP_H #include "lluictrl.h" #include "llcheckboxctrl.h" #include "llctrlselectioninterface.h" /* * An invisible view containing multiple mutually exclusive toggling * buttons (usually radio buttons). Automatically handles the mutex * condition by highlighting only one button at a time. */ class LLRadioGroup : public LLUICtrl, public LLCtrlSelectionInterface { public: struct ItemParams : public LLInitParam::Block<ItemParams, LLCheckBoxCtrl::Params> { Optional<LLSD> value; ItemParams(); }; struct Params : public LLInitParam::Block<Params, LLUICtrl::Params> { Optional<bool> has_border; Multiple<ItemParams, AtLeast<1> > items; Params(); }; protected: LLRadioGroup(const Params&); friend class LLUICtrlFactory; public: /*virtual*/ void initFromParams(const Params&); virtual ~LLRadioGroup(); virtual BOOL postBuild(); virtual BOOL handleMouseDown(S32 x, S32 y, MASK mask); virtual BOOL handleKeyHere(KEY key, MASK mask); void setIndexEnabled(S32 index, BOOL enabled); // return the index value of the selected item S32 getSelectedIndex() const { return mSelectedIndex; } // set the index value programatically BOOL setSelectedIndex(S32 index, BOOL from_event = FALSE); // Accept and retrieve strings of the radio group control names virtual void setValue(const LLSD& value ); virtual LLSD getValue() const; // Update the control as needed. Userdata must be a pointer to the button. void onClickButton(LLUICtrl* clicked_radio); //======================================================================== LLCtrlSelectionInterface* getSelectionInterface() { return (LLCtrlSelectionInterface*)this; }; // LLCtrlSelectionInterface functions /*virtual*/ S32 getItemCount() const { return mRadioButtons.size(); } /*virtual*/ BOOL getCanSelect() const { return TRUE; } /*virtual*/ BOOL selectFirstItem() { return setSelectedIndex(0); } /*virtual*/ BOOL selectNthItem( S32 index ) { return setSelectedIndex(index); } /*virtual*/ BOOL selectItemRange( S32 first, S32 last ) { return setSelectedIndex(first); } /*virtual*/ S32 getFirstSelectedIndex() const { return getSelectedIndex(); } /*virtual*/ BOOL setCurrentByID( const LLUUID& id ); /*virtual*/ LLUUID getCurrentID() const; // LLUUID::null if no items in menu /*virtual*/ BOOL setSelectedByValue(const LLSD& value, BOOL selected); /*virtual*/ LLSD getSelectedValue(); /*virtual*/ BOOL isSelected(const LLSD& value) const; /*virtual*/ BOOL operateOnSelection(EOperation op); /*virtual*/ BOOL operateOnAll(EOperation op); private: const LLFontGL* mFont; S32 mSelectedIndex; typedef std::vector<class LLRadioCtrl*> button_list_t; button_list_t mRadioButtons; BOOL mHasBorder; }; #endif
[ "hazim.gazov@gmail.com" ]
hazim.gazov@gmail.com
915281d52c80e957156a133d370d104799a2c665
4d0a3d58bd66e588a50b834a8b8a65a5dac81170
/Exam/Piscine_cpp/d07/ex02/sources/main.cpp
6513dd584c7d330645ee338fbd20b8f0e27316ba
[]
no_license
fredatgithub/42
0384b35529a42cf09bbe6dc9362b6ad5c5b3e044
7c1352ab9c8dda4a381ce5a11cd3bbbfad078841
refs/heads/master
2023-03-17T09:47:48.850239
2019-12-15T18:13:13
2019-12-15T18:13:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
637
cpp
#include <iostream> #include "Array.hpp" int main(void) { try { Array<std::string> array(5); for (int i = 0; i < array.size(); i++) { array[i] = "t1"; std::cout << array[i] << std::endl; } Array<std::string> sarray(2); std::cout << std::endl; for (int i = 0; i < sarray.size(); i++) { sarray[i] = "t2"; std::cout << sarray[i] << std::endl; } sarray = array; std::cout << std::endl; for (int i = 0; i < sarray.size(); i++) { std::cout << sarray[i] << std::endl; } std::cout << array[6] << std::endl; } catch (std::exception & e) { std::cout << e.what() << std::endl; } return (0); }
[ "julien.balestrieri@gmail.com" ]
julien.balestrieri@gmail.com
bd4ecb48a8f81eafcee88e3b63ccd9a317984854
b9bc1d0da3a33beb813bb9e9ef0ac35c3745bcc4
/AccountTest2.cpp
f24766c302473a5432d9e68eb7f8f6f694d7c066
[]
no_license
nbell990/03052020
40ed6f71c210ba93284675220cfe291acd659f61
6fb7c700c287c7fe403d97ec339125cf469ae247
refs/heads/master
2021-02-19T10:26:02.330358
2020-03-06T01:28:58
2020-03-06T01:28:58
245,303,808
0
0
null
null
null
null
UTF-8
C++
false
false
1,606
cpp
// Fig. 3.5: AccountTest.cpp // Using the Account constructor to initialize the name data // member at the time each Account object is created. #include <iostream> #include "Account2.h" using namespace std; int main() { // create two Account objects Account account1{"Jane Green"}; Account account2{"John Blue"}; // display initial value of name for each Account cout << "account1 name is: " << account1.getName() << endl; cout << "account2 name is: " << account2.getName() << endl; } /************************************************************************** * (C) Copyright 1992-2017 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/
[ "noreply@github.com" ]
nbell990.noreply@github.com
8ba16b70c536b1e4f340995daca952ca65f6ab98
5fb4409abe9e4796c8dc17cc51233c779b9e24bc
/app/src/main/cpp/wechat/zxing/common/binarizer/simple_adaptive_binarizer.cpp
bde11680a18a4d65bf5e5885235e89a2500e468a
[]
no_license
BlackSuns/LearningAndroidOpenCV
6be52f71cd9f3a1d5546da31f71c04064f0c7cac
79dc25e383c740c73cae67f36027abf13ab17922
refs/heads/master
2023-07-10T02:08:10.923992
2021-08-09T02:09:19
2021-08-09T02:09:34
297,529,216
0
0
null
2021-08-09T14:06:05
2020-09-22T03:52:46
C++
UTF-8
C++
false
false
5,405
cpp
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Tencent is pleased to support the open source community by making WeChat QRCode available. // Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. // // Modified from ZXing. Copyright ZXing authors. // Licensed under the Apache License, Version 2.0 (the "License"). #include "../../../precomp.hpp" #include "simple_adaptive_binarizer.hpp" using zxing::SimpleAdaptiveBinarizer; SimpleAdaptiveBinarizer::SimpleAdaptiveBinarizer(Ref<LuminanceSource> source) : GlobalHistogramBinarizer(source) { filtered = false; } SimpleAdaptiveBinarizer::~SimpleAdaptiveBinarizer() {} // Applies simple sharpening to the row data to improve performance of the 1D // readers. Ref<BitArray> SimpleAdaptiveBinarizer::getBlackRow(int y, Ref<BitArray> row, ErrorHandler &err_handler) { // First call binarize image in child class to get matrix0_ and binCache if (!matrix0_) { binarizeImage0(err_handler); if (err_handler.ErrCode()) return Ref<BitArray>(); } // Call parent getBlackMatrix to get current matrix return Binarizer::getBlackRow(y, row, err_handler); } // Does not sharpen the data, as this call is intended to only be used by 2D // readers. Ref<BitMatrix> SimpleAdaptiveBinarizer::getBlackMatrix(ErrorHandler &err_handler) { // First call binarize image in child class to get matrix0_ and binCache if (!matrix0_) { binarizeImage0(err_handler); if (err_handler.ErrCode()) return Ref<BitMatrix>(); } // First call binarize image in child class to get matrix0_ and binCache // Call parent getBlackMatrix to get current matrix return Binarizer::getBlackMatrix(err_handler); } using namespace std; int SimpleAdaptiveBinarizer::binarizeImage0(ErrorHandler &err_handler) { LuminanceSource &source = *getLuminanceSource(); Ref<BitMatrix> matrix(new BitMatrix(width, height, err_handler)); if (err_handler.ErrCode()) return -1; ArrayRef<char> localLuminances = source.getMatrix(); unsigned char *src = (unsigned char *) localLuminances->data(); unsigned char *dst = matrix->getPtr(); qrBinarize(src, dst); matrix0_ = matrix; return 0; } /*A simplified adaptive thresholder. This compares the current pixel value to the mean value of a (large) window surrounding it.*/ int SimpleAdaptiveBinarizer::qrBinarize(const unsigned char *src, unsigned char *dst) { unsigned char *mask = dst; if (width > 0 && height > 0) { unsigned *col_sums; int logwindw; int logwindh; int windw; int windh; int y0offs; int y1offs; unsigned g; int x; int y; /*We keep the window size fairly large to ensure it doesn't fit completely inside the center of a finder pattern of a version 1 QR code at full resolution.*/ for (logwindw = 4; logwindw < 8 && (1 << logwindw) < ((width + 7) >> 3); logwindw++); for (logwindh = 4; logwindh < 8 && (1 << logwindh) < ((height + 7) >> 3); logwindh++); windw = 1 << logwindw; windh = 1 << logwindh; int logwinds = (logwindw + logwindh); col_sums = (unsigned *) malloc(width * sizeof(*col_sums)); /*Initialize sums down each column.*/ for (x = 0; x < width; x++) { g = src[x]; col_sums[x] = (g << (logwindh - 1)) + g; } for (y = 1; y < (windh >> 1); y++) { y1offs = min(y, height - 1) * width; for (x = 0; x < width; x++) { g = src[y1offs + x]; col_sums[x] += g; } } for (y = 0; y < height; y++) { unsigned m; int x0; int x1; /*Initialize the sum over the window.*/ m = (col_sums[0] << (logwindw - 1)) + col_sums[0]; for (x = 1; x < (windw >> 1); x++) { x1 = min(x, width - 1); m += col_sums[x1]; } int offset = y * width; for (x = 0; x < width; x++) { /*Perform the test against the threshold T = (m/n)-D, where n=windw*windh and D=3.*/ g = src[offset + x]; mask[offset + x] = ((g + 3) << (logwinds) < m); /*Update the window sum.*/ if (x + 1 < width) { x0 = max(0, x - (windw >> 1)); x1 = min(x + (windw >> 1), width - 1); m += col_sums[x1] - col_sums[x0]; } } /*Update the column sums.*/ if (y + 1 < height) { y0offs = max(0, y - (windh >> 1)) * width; y1offs = min(y + (windh >> 1), height - 1) * width; for (x = 0; x < width; x++) { col_sums[x] -= src[y0offs + x]; col_sums[x] += src[y1offs + x]; } } } free(col_sums); } return 1; } Ref<Binarizer> SimpleAdaptiveBinarizer::createBinarizer(Ref<LuminanceSource> source) { return Ref<Binarizer>(new SimpleAdaptiveBinarizer(source)); }
[ "onlyloveyd@gmail.com" ]
onlyloveyd@gmail.com
7ef445eab03e60b296417fa903dda17f9f7d6708
a3d5c0f4b5d036659aa4c735f65f2ac6d43454d1
/Preoblem_treasure/dp.cpp
d58f28247366ec190e4a99753d6ab6e2188e24eb
[]
no_license
GoFire2000/CPulsPuls-create-test-problems
4bbf191286ca5cd6b945da249914a96e7da4b7d3
6ccd1fd8e0aa5b47651561cb3155ed6b33118e1a
refs/heads/main
2023-09-04T23:28:55.029152
2021-11-14T09:21:40
2021-11-14T09:21:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
373
cpp
#include <cmath> #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; #define LL long long #define Inf 1e9 const int maxn=1010; void Init(); int main(){ while(true) Init(); return 0; } void Init(){ system("DateMake.exe"); system("Trick.exe"); system("Std.exe"); if(system("fc Std.out Trick.out")) system("pause");; }
[ "xuzikang@bupt.edu.cn" ]
xuzikang@bupt.edu.cn
b7b46f2fb6a11ef25d8cea66cefb4e7bd16f888b
e8f16f6b2fb53bb52088e96ddbc6ceeb39cb00ea
/CLICalendarServer/src/Note.cpp
1805ec7671e16a1c2f3ffa1c0575c7345ec990c4
[]
no_license
MasterElijah97/CLICalendar
0a9b4776ff6a06227ab2c354401abef7a641fa4e
1f452b3b84307b2488ef734a09a453fd4eb62189
refs/heads/master
2023-02-17T19:07:09.070081
2021-01-17T12:03:13
2021-01-17T12:03:13
297,442,990
0
0
null
null
null
null
UTF-8
C++
false
false
2,391
cpp
#include "Note.h" bool operator==(const Note& left, const Note& right) { return (left.label_ == right.label_) && (left.name_ == right.name_) && (left.description_ == right.description_) && (left.version_ == right.version_); } Note::Note() { this->label_ = "Buffer"; this->name_ = "New Task"; this->description_ = "New Task"; this->id_ = -1; this->version_ = 1; } Note::Note(std::string name, std::string description = "New Note", std::string label = "Buffer") { this->label_ = label; this->name_ = name; this->description_ = description; this->id_ = -1; this->version_ = 1; } Note::Note(const Note& right) { this->label_ = right.label_; this->name_ = right.name_; this->description_ = right.description_; this->version_ = right.version_; this->id_ = right.id_; } Note::Note(Note&& right) { this->label_ = right.label_; this->name_ = right.name_; this->description_ = right.description_; this->version_ = right.version_; this->id_ = right.id_; } Note::~Note() { } Note& Note::operator=(const Note& other) { if (this == &other) { return *this; } this->label_ = other.label_; this->name_ = other.name_; this->description_ = other.description_; this->version_ = other.version_; this->id_ = other.id_; return *this; } Note& Note::operator=(Note&& right) { if (this == &right) { return *this; } this->label_ = right.label_; this->name_ = right.name_; this->description_ = right.description_; this->version_ = right.version_; this->id_ = right.id_; return *this; } std::string Note::concatenate() { return label_ +SEPARATOR+ name_ +SEPARATOR+ std::to_string(version_) +SEPARATOR+ std::to_string(id_) +SEPARATOR+ description_; } void Note::deconcatenate(std::string msg) { std::vector<std::string> v = split(msg, SEPARATOR.c_str()[0]); label_ = v[0]; name_ = v[1]; version_ = std::stoi(v[2]); id_ = std::stoi(v[3]); description_ = v[4]; }
[ "morozov97@mail.ru" ]
morozov97@mail.ru
eb5dab6ff494075734c7287419f089c283c73d99
63168b3cc1a8019583b331ebc8c4ec58c241753c
/inference-engine/tests/unit/cpu/mkldnn_memory_desc_test.cpp
66eecf43cf31cf527034021e8f452cbf31ae8a4d
[ "Apache-2.0" ]
permissive
generalova-kate/openvino
2e14552ab9b1196fe35af63b5751a96d0138587a
72fb7d207cb61fd5b9bb630ee8785881cc656b72
refs/heads/master
2023-08-09T20:39:03.377258
2021-09-07T09:43:33
2021-09-07T09:43:33
300,206,718
0
0
Apache-2.0
2020-10-01T08:35:46
2020-10-01T08:35:45
null
UTF-8
C++
false
false
7,264
cpp
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <utility> #include <gtest/gtest.h> #include "mkldnn_memory.h" #include "cpu_memory_desc_utils.h" using namespace MKLDNNPlugin; using namespace InferenceEngine; TEST(MemDescTest, Conversion) { // Check if conversion keep desc structure // dnnl::memory::desc -> MKLDNNMemoryDesc -> BlockedMemoryDesc -> MKLDNNMemoryDesc -> dnnl::memory::desc auto converted_correctly = [] (dnnl::memory::format_tag fmt, dnnl::memory::dims dims) { dnnl::memory::desc orig_tdesc {dims, dnnl::memory::data_type::u8, fmt}; MKLDNNMemoryDesc plg_tdesc {orig_tdesc}; BlockedMemoryDesc blk_tdesc = MemoryDescUtils::convertToBlockedDescriptor(plg_tdesc); MKLDNNMemoryDesc plg_tdesc_after = MemoryDescUtils::convertToMKLDNNMemoryDesc(blk_tdesc); dnnl::memory::desc after_tdesc(plg_tdesc_after); return orig_tdesc == after_tdesc; }; std::pair<dnnl::memory::format_tag, dnnl::memory::dims> payload[] { { dnnl::memory::format_tag::nChw16c, {1, 1, 10, 10} }, // auto blocked { dnnl::memory::format_tag::nhwc, {4, 2, 10, 7 } }, // permuted { dnnl::memory::format_tag::nchw, {4, 2, 10, 7 } }, // plain { dnnl::memory::format_tag::NChw16n16c, {4, 2, 10, 7 } }, // blocked for 2 dims { dnnl::memory::format_tag::BAcd16a16b, {4, 2, 10, 7 } }, // blocked and permuted outer dims { dnnl::memory::format_tag::Acdb16a, {96, 1, 7, 7 } }, // same strides but not default order }; for (const auto &p : payload) ASSERT_TRUE(converted_correctly(p.first, p.second)); } TEST(MemDescTest, CompareWithTensorDescRecomputedStrides) { auto converted_correctly = [] (dnnl::memory::format_tag fmt, dnnl::memory::dims dims) { dnnl::memory::desc orig_tdesc {dims, dnnl::memory::data_type::u8, fmt}; MKLDNNMemoryDesc plg_tdesc {orig_tdesc}; BlockedMemoryDesc blk_tdesc = MemoryDescUtils::convertToBlockedDescriptor(plg_tdesc); BlockedMemoryDesc recomputed_blk_tdesc(blk_tdesc.getPrecision(), blk_tdesc.getShape().getStaticDims(), blk_tdesc.getBlockDims(), blk_tdesc.getOrder()); return blk_tdesc.isCompatible(recomputed_blk_tdesc); }; std::pair<dnnl::memory::format_tag, dnnl::memory::dims> payload[] { { dnnl::memory::format_tag::nChw16c, {1, 1, 10, 10} }, // auto blocked { dnnl::memory::format_tag::nhwc, {4, 2, 10, 7 } }, // permuted { dnnl::memory::format_tag::nchw, {4, 2, 10, 7 } }, // plain { dnnl::memory::format_tag::NChw16n16c, {4, 2, 10, 7 } }, // blocked for 2 dims { dnnl::memory::format_tag::BAcd16a16b, {4, 2, 10, 7 } }, // blocked and permuted outer dims { dnnl::memory::format_tag::Acdb16a, {96, 1, 7, 7 } }, // same strides but not default order }; for (const auto &p : payload) ASSERT_TRUE(converted_correctly(p.first, p.second)); } TEST(MemDescTest, isPlainCheck) { const auto dims = dnnl::memory::dims {3, 2, 5, 7}; const auto type = dnnl::memory::data_type::u8; dnnl::memory::desc plain_tdesc {dims, type, dnnl::memory::format_tag::abcd}; dnnl::memory::desc permt_tdesc {dims, type, dnnl::memory::format_tag::acdb}; dnnl::memory::desc blckd_tdesc {dims, type, dnnl::memory::format_tag::aBcd8b}; ASSERT_TRUE(MKLDNNMemoryDesc(plain_tdesc).hasLayoutType(LayoutType::ncsp)); ASSERT_FALSE(MKLDNNMemoryDesc(permt_tdesc).hasLayoutType(LayoutType::ncsp)); ASSERT_FALSE(MKLDNNMemoryDesc(blckd_tdesc).hasLayoutType(LayoutType::ncsp)); } TEST(MemDescTest, isBlockedCCheck) { const auto dims = dnnl::memory::dims {3, 2, 5, 7}; const auto type = dnnl::memory::data_type::u8; dnnl::memory::desc plain_tdesc {dims, type, dnnl::memory::format_tag::abcd}; dnnl::memory::desc tailc_tdesc {dims, type, dnnl::memory::format_tag::acdb}; dnnl::memory::desc blck8_tdesc {dims, type, dnnl::memory::format_tag::aBcd8b}; dnnl::memory::desc blck8_permCD_tdesc {dims, type, dnnl::memory::format_tag::aBdc16b}; const MKLDNNMemoryDesc plain_mdesc(plain_tdesc); const MKLDNNMemoryDesc tailc_mdesc(tailc_tdesc); ASSERT_FALSE(plain_mdesc.hasLayoutType(LayoutType::nCsp8c) || plain_mdesc.hasLayoutType(LayoutType::nCsp16c)); ASSERT_FALSE(tailc_mdesc.hasLayoutType(LayoutType::nCsp8c) || tailc_mdesc.hasLayoutType(LayoutType::nCsp16c)); ASSERT_TRUE(MKLDNNMemoryDesc(blck8_tdesc).hasLayoutType(LayoutType::nCsp8c)); ASSERT_FALSE(MKLDNNMemoryDesc(blck8_permCD_tdesc).hasLayoutType(LayoutType::nCsp16c)); const auto crop_dims = dnnl::memory::dims {2, 1, 5, 7}; const auto crop_off = dnnl::memory::dims {1, 0, 0, 0}; dnnl::memory::desc blck8_crop_tdesc = blck8_tdesc.submemory_desc(crop_dims, crop_off); dnnl::memory::desc blck8_permCD_crop_tdesc = blck8_permCD_tdesc.submemory_desc(crop_dims, crop_off); ASSERT_TRUE(MKLDNNMemoryDesc(blck8_crop_tdesc).hasLayoutType(LayoutType::nCsp8c)); ASSERT_FALSE(MKLDNNMemoryDesc(blck8_permCD_crop_tdesc).hasLayoutType(LayoutType::nCsp8c)); } TEST(MemDescTest, isTailCCheck) { const auto dims = dnnl::memory::dims {3, 2, 5, 7}; const auto type = dnnl::memory::data_type::u8; dnnl::memory::desc plain_tdesc {dims, type, dnnl::memory::format_tag::abcd}; dnnl::memory::desc tailc_tdesc {dims, type, dnnl::memory::format_tag::acdb}; dnnl::memory::desc permt_tdesc {dims, type, dnnl::memory::format_tag::bcda}; dnnl::memory::desc blck8_tdesc {dims, type, dnnl::memory::format_tag::aBcd8b}; ASSERT_FALSE(MKLDNNMemoryDesc(plain_tdesc).hasLayoutType(LayoutType::nspc)); ASSERT_FALSE(MKLDNNMemoryDesc(permt_tdesc).hasLayoutType(LayoutType::nspc)); ASSERT_TRUE(MKLDNNMemoryDesc(tailc_tdesc).hasLayoutType(LayoutType::nspc)); ASSERT_FALSE(MKLDNNMemoryDesc(blck8_tdesc).hasLayoutType(LayoutType::nspc)); dnnl::memory::desc blck8_permCD_tdesc {dims, type, dnnl::memory::format_tag::aBdc16b}; ASSERT_FALSE(MKLDNNMemoryDesc(blck8_permCD_tdesc).hasLayoutType(LayoutType::nspc)); const auto crop_dims = dnnl::memory::dims {2, 1, 5, 7}; const auto crop_off = dnnl::memory::dims {1, 0, 0, 0}; dnnl::memory::desc tailc_crop_tdesc = blck8_tdesc.submemory_desc(crop_dims, crop_off); ASSERT_FALSE(MKLDNNMemoryDesc(tailc_crop_tdesc).hasLayoutType(LayoutType::nspc)); } TEST(MemDescTest, constructWithPlainFormat) { GTEST_SKIP(); } TEST(MemDescTest, CheckScalar) { GTEST_SKIP(); } TEST(MemDescTest, UpperBound) { GTEST_SKIP(); } TEST(MemDescTest, BlockedConversion) { GTEST_SKIP(); } TEST(MemDescTest, ComaptibleWithFormat) { GTEST_SKIP(); } TEST(isSameMethodTest, CheckTensorWithSameStrides) { auto isSameDataFormat = [] (dnnl::memory::format_tag fmt, dnnl::memory::dims dims) { dnnl::memory::desc oneDnnDesc {dims, dnnl::memory::data_type::u8, fmt}; MKLDNNMemoryDesc pluginDesc {oneDnnDesc}; return pluginDesc.getFormat() == fmt; }; std::pair<dnnl::memory::format_tag, dnnl::memory::dims> testCases[] { { dnnl::memory::format_tag::ntc, {1, 10, 10} }, }; for (const auto &tc : testCases) ASSERT_TRUE(isSameDataFormat(tc.first, tc.second)); }
[ "noreply@github.com" ]
generalova-kate.noreply@github.com
08ec6e2818b8185f07f11b84b1822f1e0f93e302
adb622fb73c702c32c8d1f0a77728fddf180c3a8
/Allegro/Game1_Source/Quest System Advanced/quest_h.h
6f9c07e41057b5807ebdcdb33506faa66454fac4
[]
no_license
jaksamarko/c_cplusplus
5d29439bafcbc3e4db9930175e7240c0a280985e
f37e562f414368e8ff9fd3090725fffa57af623e
refs/heads/master
2020-04-19T20:59:24.650951
2019-01-30T23:49:49
2019-01-30T23:49:49
168,429,449
0
0
null
null
null
null
UTF-8
C++
false
false
2,052
h
class quest_task { public: int start,finish,amount,camount,item,entity; void add(int start, int finish, int amount=0, int item=0, int entity=0) { camount=0;this->start=start;this->finish=finish;this->amount=amount;this->item=item;this->entity=entity; } void destroy() {start=finish=amount=item=entity=-1;camount=0;} }; class quest { char *name,*desc; int id; public: bool completed,undertake; quest *prev,*next; quest_task qt; quest(char *name, char *desc, int id, quest_task qt) { this->name=new char[strlen(name)+1]; strcpy(this->name,name); this->desc=new char[strlen(desc)+1]; strcpy(this->desc,desc); this->id=id; this->qt=qt; completed=undertake=false; } }; class _quests { vector<quest>q,cq; public: vector<int>completed; _quests() {q.clear();cq.clear();} int found(int id); int add(char *name, char *desc, quest_task &qt, int prev=-1) { quest t(name,desc,q.size(),qt); qt.destroy(); if(prev!=-1) {t.prev=&q[id];} q.push_back(t); if(prev!=-1) {q[id].next=&q[q.size()-1];} return q.size()-1; } void getquest(int id) { quest t=q[found(id)]; t.undertake=true; cq.push_back(t); } void check_completed() { quest_task t; for(int i=0;i<cq.size();i++) { if(!cq[i].completed) { t=cq[i].qt; if(amount>0) {completed=(camount==amount);} } } } void draw(); }quests; int _quests::found(int id) { for(int i=0;i<q.size();i++) {if(q[i].id==id) {return i;}} return -1; } void _quests::draw() { for(int i=0;i<cq.size();i++) { al_draw_textf(font,al_map_rgb(0,0,0),0,32+i*32,0,"%s:%s",cq[i].name,cq[i].desc); } }
[ "noreply@github.com" ]
jaksamarko.noreply@github.com
b184e9fcb818b548db391f7b01117bc08b50144b
3985c19fecd6d2b805d5d45217402336d9b7b0fa
/gamewindow.h
40e7431169f32c43954827b011df7aa4ac62382f
[]
no_license
sh0dan/QTetris
5ed39d3d32ff7ea92f0bda4a311ffab596780939
d0fde85aeffc89359fd06ec8bd2ec768733ae68b
refs/heads/master
2020-06-01T11:23:03.186260
2012-05-14T14:11:03
2012-05-14T14:11:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
589
h
#ifndef GAMEWINDOW_H #define GAMEWINDOW_H /* #include <QFrame> #include <QWidget> QT_BEGIN_NAMESPACE class QLCDNumber; class QLabel; class QPushButton; QT_END_NAMESPACE */ #include <QtGui> class GameBoard; class GameWindow : public QWidget { Q_OBJECT public: GameWindow(); private: QLabel *nextBlockLabel; QLabel *playerScoresLabel; QLabel *linesLabel; QLabel *currentLevelLabel; GameBoard *gameBoard; QPushButton *startBtn; QPushButton *pauseBtn; QPushButton *exitBtn; QLabel *createLabel(const QString &text); }; #endif // GAMEWINDOW_H
[ "ruslan.sazonov@postindustria.com" ]
ruslan.sazonov@postindustria.com
6077cd3a58794f87542013047bfcfe70e474e8b5
69a525172319cfb3fe1d5200dd67d8793820531c
/Software/iROB_EA/copia/iROB_EA.ino
a5e1e6b90383738915eaa0a8b508ade21d415a10
[]
no_license
Baphomet2015/iROB-EA
efcd8fd36b33cd3a0cd028447609c5416ea1eb12
d58e078bd40f239fee59d5e8e81c3a032002de24
refs/heads/master
2021-12-08T22:50:17.717175
2021-12-05T19:07:24
2021-12-05T19:07:24
51,265,231
2
0
null
null
null
null
UTF-8
C++
false
false
32,401
ino
//! --------------------------------------------------------- //! //! @mainpage //! //! @brief Proyecto: iROB-EA //! @date Fecha: Enero 2021 //! @author AAL //! //! @remarks Hardware Arduino MEGA 2560\n //! //! @version Versión de SW 1.0 //! @version Versión de IDE Arduino: 1.8.12 //! //! @brief <b>Leitmotiv:</b>\n //! "Toda Bestia necesita un Cerebro...", Dr. Frankenstein, en su laboratorio\n //! "¡Larga y próspera vida!.", Sr. Spock\n //! //! --------------------------------------------------------- //! --------------------------------------------------------- //! //! @brief Funcionalidad: Modulo principal de la Aplicacion //! //! @warning REVISADO --/--/---- //! --------------------------------------------------------- #include <Arduino.h> #include <stdlib.h> #include <WString.h> #include <avr/pgmspace.h> #include <Wire.h> #include <Servo.h> #include <EEPROM.h> #include <LedDisplay.h> #include "iROB_EA.h" #include "UF_SYS.h" #include "MOTOR_FDS5672.h" #include "SENSOR_USS.h" #include "SENSOR_GPS.h" #include "SENSOR_EMC.h" #include "SENSOR_RAZOR.h" #include <Gescom_MEGA2560_V3.h> #include <Gescom_MEGA2560_V3_CMD.h> // --------------------------------------------------------- // // Definicion de Clases y variables GLOBALES // // // . uf_sys Objeto de manejo de funcionalidades basicas // . mDer Objeto de manejo del motor derecho // . mIzq Objeto de manejo del motor izquierdo // . myDisplay Objeto para manejear el display de estado // . sensor_USS Objeto para manejo de los sensores de US // . sensor_EMC Objeto para manejo de la estacion climatica // . sensor_GPS Objeto para manejo del GPS // . sensor_RAZOR Objeto para manejo del RAZOR // . sensor_mlx Objeto para manejar el sensor MLX90614 // . rtc Objeto para manejar el reloj de tiempo real // . gc Objeto que implementa el gestor de comandos // // . GLOBAL_FlgDebug Flag para control del modo DEBUG // . GLOBAL_FlgStatusPC Flag con el estado del PC // . GLOBAL_Timer_Ctrl_PC Timer asociado a los procesos de // encendido/apagado del PC // --------------------------------------------------------- UF_SYS uf_sys = UF_SYS(); // Implementa la funcionalidad relacionada con la UF_SYS MOTOR_FDS5672 mDer = MOTOR_FDS5672( PIN_HW_MTD_DIR , // Implementa el control del motor derecho PIN_HW_MTD_RST , PIN_HW_MTD_PWM ); MOTOR_FDS5672 mIzq = MOTOR_FDS5672( PIN_HW_MTI_DIR , // Implementa el control del motor izquierdo PIN_HW_MTI_RST , PIN_HW_MTI_PWM ); LedDisplay myDisplay = LedDisplay( PIN_HW_HCMS_DATA , // Implementa el control del display PIN_HW_HCMS_RS , PIN_HW_HCMS_CLK , PIN_HW_HCMS_CE , PIN_HW_HCMS_RESET , 4 ); SENSOR_USS sensor_USS = SENSOR_USS( PIN_HW_USR_DER_TRIGGER , // Implementa el control de los sensores de deteccion de objetos PIN_HW_USR_IZQ_TRIGGER , PIN_HW_USR_DER_ECHO , PIN_HW_USR_IZQ_ECHO , PIN_HW_SUPERFICIE ); SENSOR_EMC sensor_EMC = SENSOR_EMC( PIN_HW_SEN_MET_LUZ); // Implementa el control de los sensores de la estacion climatica SENSOR_GPS sensor_GPS; // Implementa el modulo de GPS SENSOR_RAZOR sensor_RAZOR; // Implementa el modulo de sensores AHRS GESCOM3 gc = GESCOM3( IDE_SERIAL_0 , false , IDE_DISPOSITIVO_R00 , IDE_SERIAL_TRX_PC ); // Gestor de comandos byte GLOBAL_FlgDebug; // Flag global que indica si se deben generar trazas por el puerto de Debug o no byte GLOBAL_FlgStatusPC; // Flag para control del proceso de encendido/Apagado byte GLOBAL_FlgModoAvance; // Flag que indica el modo de avance, ver defines IDE_MODO_AVANCE_xx byte GLOBAL_FlgModoAvanceEvento; // Flag que indica eventos detectados cuando la variable GLOBAL_FlgModoAvance = IDE_MODO_AVANCE_CON_PROTECCION unsigned long int GLOBAL_Timer_Ctrl_PC; // Timer asociado a los procesos de encendido/apagado del PC int GLOBAL_Timer_DispD_PC; // Timer asociado a los procesos de encendido/apagado del PC, para mostrar en el display int GLOBAL_Timer_DispF_PC; // Timer asociado a los procesos de encendido/apagado del PC, para mostrar en el display // --------------------------------------------------------- // // void setup() // Funcion para inicializar todos los sistemas del // iROB-EA // // --------------------------------------------------------- void setup(void) { // --------------------------------------------------------- // // ATENCIÓN: // // . Los pines de control de los motores NO se inicializan // aqui porque ya lo hace el constructor de la clase // MOTOR_FDS5672 // // . Los pines de control del display NO se inicializan // aqui porque ya lo hace el constructor de la clase // ledDisplay // // . Los pines de control de los sensores de ultrasonidos // NO se inicializan aqui porque ya lo hace el constructor // de la clase SENSOR_US // // . El pin PIN_HW_OFF_PETICION es la entrada de INT 0, no // es necesario inicializar este pin con pinMode // // --------------------------------------------------------- // --------------------------------------------------------- // // Inicializacion de los pines I/O (MODO) // Los pines que NO se inicializan expresamente aqui es debido // a que se inicializan en los objetos definidos para su // utilizacion, sensor_USS, mDer, MIzq etc // --------------------------------------------------------- pinMode( PIN_HW_MIC_01 ,INPUT); pinMode( PIN_HW_SEN_MET_LUZ ,INPUT); pinMode( PIN_HW_MTDI_INFO ,INPUT); pinMode( PIN_HW_ICC_SENSE_12P,INPUT); pinMode( PIN_HW_ICC_SENSE_5VP,INPUT); pinMode( PIN_HW_INT_OFF_PETICION,INPUT); pinMode( PIN_HW_INT_SQW ,INPUT); pinMode( PIN_HW_POW_CNX_A0,OUTPUT); pinMode( PIN_HW_POW_CNX_A1,OUTPUT); pinMode( PIN_HW_POW_CNX_A2,OUTPUT); pinMode( PIN_HW_DTMF_D0,INPUT); pinMode( PIN_HW_DTMF_D1,INPUT); pinMode( PIN_HW_DTMF_D2,INPUT); pinMode( PIN_HW_DTMF_D3,INPUT); pinMode( PIN_HW_DTMF_DV,INPUT); pinMode( PIN_HW_CNX_DEBUG,INPUT); pinMode( PIN_HW_BAT_N25 ,INPUT); pinMode( PIN_HW_BAT_N50 ,INPUT); pinMode( PIN_HW_BAT_N75 ,INPUT); pinMode( PIN_HW_BAT_N100 ,INPUT); pinMode( PIN_HW_SERVO_HOR,OUTPUT); pinMode( PIN_HW_SERVO_VER,OUTPUT); pinMode( PIN_HW_FAN,OUTPUT); pinMode( PIN_HW_LED_POS ,OUTPUT); pinMode( PIN_HW_LED_DER ,OUTPUT); pinMode( PIN_HW_LED_IZQ ,OUTPUT); pinMode( PIN_HW_LED_FOCO,OUTPUT); pinMode( PIN_HW_MTI_DIR,OUTPUT); pinMode( PIN_HW_MTI_RST,OUTPUT); pinMode( PIN_HW_MTI_PWM,OUTPUT); pinMode( PIN_HW_MTD_DIR,OUTPUT); pinMode( PIN_HW_MTD_RST,OUTPUT); pinMode( PIN_HW_MTD_PWM,OUTPUT); pinMode( PIN_HW_MTDI_SEL_A,OUTPUT); pinMode( PIN_HW_MTDI_SEL_B,OUTPUT); pinMode( PIN_HW_MTDI_SEL_C,OUTPUT); pinMode( PIN_HW_POW_PC_1,OUTPUT); // --------------------------------------------------------- // // !!! Estas variables se INICIALIZAN AQUI !!! // // --------------------------------------------------------- GLOBAL_FlgDebug = false; GLOBAL_FlgStatusPC = IDE_STATUS_PC_INI_ON; GLOBAL_FlgModoAvance = IDE_MODO_AVANCE_CON_PROTECCION; GLOBAL_FlgModoAvanceEvento = IDE_EVENTO_OK; GLOBAL_Timer_Ctrl_PC = 0L; GLOBAL_Timer_DispD_PC = 0; GLOBAL_Timer_DispF_PC = true; // --------------------------------------------------------- // // Inicializacion de variables, objetos Globales y elementos // // // --------------------------------------------------------- analogReference(DEFAULT); // --------------------------------------------------------- // // --------------------------------------------------------- Wire.begin(); mDer.begin(); mIzq.begin(); myDisplay.begin(); myDisplay.setBrightness(15); sensor_USS.begin(); sensor_GPS.begin(); sensor_EMC.begin(); sensor_RAZOR.begin(); gc.begin(); // --------------------------------------------------------- // Interrupciones: // // INT 0: Boton Power OFF // Funcion: INT_power_OFF() // Variable: GLOBAL_FlgPower_OFF // Variable actualizada por esta funcion // // INT 1: Señal generada desde el RTC // Funcion: INT_rtc_SQW() // // --------------------------------------------------------- attachInterrupt(0, INT_power_OFF, RISING); attachInterrupt(1, INT_rtc_SQW , RISING); // --------------------------------------------------------- // // Inicializacion de puertos serie // // . Serial0 Gestor de comandos, se inicializa en gc->begin() // Comunicacion entre Arduino y PC // . Serial1 GPS , se inicializa en sensor_GPS.begin() // . Serial2 RAZOR, se inicializa en sensor_RAZOR.begin() // . Serial3 9600 , puerto de DEBUG, 9600 // // --------------------------------------------------------- Serial3.begin(IDE_SERIAL_TRX_DEBUG); // Puerto de DEBUG, ver comentario de la variable GLOBAL_FlgDebug // --------------------------------------------------------- // IMPORTANTE // !!! NO mover de aqui estas inicializaciones // Para version Funcional, comentar todas las lineas que // puedan aparecer debajo de este comentario y dejar SOLO: // // uf_sys.begin(); // // --------------------------------------------------------- uf_sys.begin(); // --------------------------------------------------------- // Utilidad para escanear el bus I2C // DESCOMENTAR para probar los sensore conectados por I2C // --------------------------------------------------------- // UTIL_Scanner_I2C(); // --------------------------------------------------------- // Atencion: // Cuando se instala un nuevo Arduino MEGA, es conveniente // descomentar esta llamada UNA SOLA VEZ para iniciar la // Variable EEPROM a un valor conocido, despues se DEBE // dejar comentada // --------------------------------------------------------- // uf_sys.set_NUM_RC(1); } // --------------------------------------------------------- // // void loop() // Funcion principal para mantener funcionando iROB-EA // // --------------------------------------------------------- void loop(void) { // --------------------------------------------------------- // Actualizacion de Timers etc de uf_sys // --------------------------------------------------------- uf_sys.timers(); // ------------------------------------------------------- // // BLOQUE GENERAL DE PROGRAMA // // ------------------------------------------------------- // ------------------------------------------------------- // // GESTOR DE COMANDOS // // La funcion exeGesComando ejecuta el gestor de comandos. // Si se ha recibido algo en el puerto serie lo procesa y // envia el resultado obtenido. // TODAS las funciones asociadas a comandos se encuentran // en el fichero iROB-EA_CMD.ino // // Si no se ha recibido nada retorna inmediatamente. // // Esta funcion retorna: // . IDE_BUFF_RX_OK Se ha recibdo algo valido ( un // comando y se ha ejecutado ) // . IDE_BUFF_RX_ER Se ha recibido algo erroneo. // . IDE_BUFF_RX_VACIO NO se ha recibido nada // // Estos defines se encuentran en Gescom_MEGA2560_V3.h // // ------------------------------------------------------- gc.exeGesComando(); // ------------------------------------------------------- // // Proceso de encendido/apagado/Bucle activo // // - Si el proceso de encendido finaliza correctamente: // GLOBAL_FlgStatusPC = IDE_STATUS_PC_OK = procesoActivo() // // - Si el proceso de apagado se solicita actuando sobre // el pulsador: // GLOBAL_FlgStatusPC = IDE_STATUS_PC_INI_OFF // // ------------------------------------------------------- switch( GLOBAL_FlgStatusPC ) { case ( IDE_STATUS_PC_INI_ON ): { // ---------------------------------------- // El PC esta apagado, se acaba de // arrancar el Robot // // Se inicia el proceso de encendido. // La funcion pc_ON() inicia el encendido y // cambia el valor de GLOBAL_FlgStatusPC a // GLOBAL_FlgStatusPC = IDE_STATUS_PC_START // ---------------------------------------- FNG_DisplayMsgPROGMEM(IDE_MSG_DISPLAY_WAIT,0); pc_ON(); break; } case ( IDE_STATUS_PC_START ): { // ---------------------------------------- // El PC esta arrancando // Temporiza esperando respuesta desde el // PC. // // . Si el PC se inicializa correctamente // se recibira un comando desde el PC en // la funcion de comandos cmd_Comando_C_STPC() // con el cnv_Param01 = IDE_PARAM_ACT y esa // funcion cambiara el estado de la // variable // GLOBAL_FlgStatusPC = IDE_STATUS_PC_ON // // . Si se agota el tiempo de espera se pasa // GLOBAL_FlgStatusPC = IDE_STATUS_PC_ON_ERROR // // ---------------------------------------- if ( (unsigned long int)(millis()-GLOBAL_Timer_Ctrl_PC)>=IDE_PC_POWER_ON_TIMEOUT ) { // ------------------------------------------ // Superado el tiempo maximo de espera para // que el PC comunique que se ha encendido, // NO se ha recibido desde el PC el comando // #####1001070000E0001 que indicaria que ha // arrancado correctamente, se indica error y // se cambia GLOBAL_FlgStatusPC // ------------------------------------------ FNG_DisplayMsgPROGMEM(IDE_MSG_DISPLAY_ER_000,0); GLOBAL_FlgStatusPC = IDE_STATUS_PC_ON_ERROR; } else { // ------------------------------------------ // Muestra tiempo de espera restante // ------------------------------------------ displayTimerInicio_PC(); } break; } case ( IDE_STATUS_PC_ON ): { // ---------------------------------------- // Se ha recibido desde el PC la // confirmacion de encendido correcto. // GLOBAL_FlgStatusPC = IDE_STATUS_PC_OK // ---------------------------------------- FNG_DisplayMsgPROGMEM(IDE_MSG_DISPLAY_OK ,(IDE_PAUSA_GENERAL*4)); FNG_DisplayMsgPROGMEM(IDE_MSG_DISPLAY_CLS,0); GLOBAL_FlgStatusPC = IDE_STATUS_PC_OK; break; } case ( IDE_STATUS_PC_OK ): { // ---------------------------------------- // Finalizado correctamente el proceso de // encendido del PC. // Bucle Activo // Aqui se deben incluir todas las cosas // que se deben ejecutar en el modo normal // de funcionamiento. // ---------------------------------------- procesoActivo(); break; } case ( IDE_STATUS_PC_INI_OFF ): { // ---------------------------------------- // Se ha pulsado el boton de // encendido/apagado // Se inicia el proceso de apagado del PC // Independientemente del resultado del // proceso de apagado del PC , se pasara a // GLOBAL_FlgStatusPC = IDE_STATUS_PC_OFF // ---------------------------------------- FNG_DisplayMsgPROGMEM(IDE_MSG_DISPLAY_DOWN,0); pc_OFF(); break; } case ( IDE_STATUS_PC_DOWN ): { // ---------------------------------------- // Proceso de apagado del Robot // // ---------------------------------------- if ( (unsigned long int)(millis()-GLOBAL_Timer_Ctrl_PC)>=IDE_PC_POWER_OFF_TIMEOUT ) { // ------------------------------------------ // Superado el tiempo maximo de espera para // detectar el apagado del PC. // Se indica error y se cambia GLOBAL_FlgStatusPC // para apagar fisicamente el Robot , aunque // el PC no se haya apagado correctamente // ------------------------------------------ FNG_DisplayMsgPROGMEM(IDE_MSG_DISPLAY_ER_001,(IDE_PAUSA_GENERAL*5)); GLOBAL_FlgStatusPC = IDE_STATUS_PC_OFF; } else { // ------------------------------------------ // Mide la corriente consumida por el PC para // detectar cuando se apaga // ------------------------------------------ if ( getIcc5VP()==false ) { // ------------------------------------------ // La corriente medida con el sensor asociado // a la alimentacion del PC determina que se // ha apagado. // Se indica ok y se cambia GLOBAL_FlgStatusPC // para apagar fisicamente el Robot // ------------------------------------------ FNG_DisplayMsgPROGMEM(IDE_MSG_DISPLAY_OK,(IDE_PAUSA_GENERAL*5)); GLOBAL_FlgStatusPC = IDE_STATUS_PC_OFF; } } break; } case ( IDE_STATUS_PC_OFF ): { // ---------------------------------------- // Apagado fisico del Robot -) // ---------------------------------------- uf_sys.power_OFF(); break; } case ( IDE_STATUS_PC_ON_ERROR ): { // ---------------------------------------- // El PC no ha podido encenderse, se debe // dejar la alimentacion conectada para que // desde el exterior , via teclado/Raton se // pueda determinar el fallo // ---------------------------------------- break; } } } // --------------------------------------------------------- // // void pc_ON(void) // Efectua las operaciones necesarias para encender el PC y // cambia el estado de la variable global GLOBAL_FlgStatusPC // al valor: // GLOBAL_FlgStatusPC = IDE_STATUS_PC_START // // --------------------------------------------------------- void pc_ON(void) { unsigned long int t; // --------------------------------------------------------- // 1 - Conecta el rele de alimentacion (5VP) // 2 - Espera x segundos a que el PC se estabilice. // 3 - Activa el pulsador de encendido, durante x seg // 4 - Cambia el estado de GLOBAL_FlgStatusPC = IDE_STATUS_PC_START // 5 - Inicia la variable de Timer que se actualiza con la // interruptor del RTC // 6 - Inicializa los Timers de espera a que el PC comunique // que ha arrancado, enviado el comando #####1001070000E0001 // al Arduino // --------------------------------------------------------- uf_sys.rele(IDE_RELE_5VP,IDE_RELE_ACTIVAR); t = millis(); while( (millis()-t)<IDE_PC_POWER_INICIO ) { // ------------------------------------------ // Bucle de espera para que el HW del PC se // inicie correctamente antes de solicitar su // encendido con el pulsador // ------------------------------------------ } uf_sys.pulsador_PC(IDE_PC_POWER_PULSADOR_ON); GLOBAL_FlgStatusPC = IDE_STATUS_PC_START; GLOBAL_Timer_DispD_PC = int(IDE_PC_POWER_ON_TIMEOUT / 1000); GLOBAL_Timer_DispF_PC = true; GLOBAL_Timer_Ctrl_PC = millis(); } // --------------------------------------------------------- // // void pc_OFF(void) // Efectua las operaciones necesarias para apagar el PC. // 1 - Activa el pulsador de encendido/apagado del PC, SOLO // si se determina que el PC esta encendido // 2 - Cambia el estado de GLOBAL_FlgStatusPC = IDE_STATUS_PC_DOWN // 3 - Inicializa el Timer de espera a que el PC se apague // --------------------------------------------------------- void pc_OFF(void) { if ( getIcc5VP()==true ) { // ---------------------------------------------------- // Hay consumo de corriente, luego el PC esta encendido // se actua sobre el pulsador del PC para apagarlo pero // SOLO se debe actuar sobre este pulsador cuando el // PC esta encendido porque sino lo que se consigue es // lo contrario, encenderlo -) // Esto se hace asi porque existe la posibilidad de que // el PC se pueda apagar directamente por intervencion // del usuario que remotamente esta controlando el Robot // actuando desde alguna de las aplicaciones que ejecuta // ( web, apps etc) // ---------------------------------------------------- uf_sys.pulsador_PC(IDE_PC_POWER_PULSADOR_OFF); } GLOBAL_FlgStatusPC = IDE_STATUS_PC_DOWN; GLOBAL_Timer_Ctrl_PC = millis(); } // --------------------------------------------------------- // // void procesoActivo(void) // // Funcion para manter activas las o peraciones precisas // durante el funcionamiento del Robot // // // --------------------------------------------------------- void procesoActivo(void) { unsigned int sup; int obj; if ( GLOBAL_FlgModoAvance==IDE_MODO_AVANCE_CON_PROTECCION ) { // ------------------------------------------------------- // El modo de proteccion esta activado, esto implica: // // 1 - Deteccion de suelo en modo avance // Paro si existe peligro // // 2 - Deteccion de objetos (ultrasonidos) en modo avance // Paro si existe peligro // // 2 - Deteccion de obstaculos (por sobreconsumo) en modo // avance // Paro si existe peligro // // Al activar este modo, la velocidad esta LIMITADA permanentemente // ver el comando cmd_Comando_CM_CTR(GESCOM_DATA* gd), en // iROB-EA_CMD.ino // // ------------------------------------------------------ sup = sensor_USS.get_Superficie(); if ( sup<IDE_EVENTO_TRIGGER_SUELO ) { bitSet (GLOBAL_FlgModoAvanceEvento, IDE_EVENTO_SUELO); } else { bitClear(GLOBAL_FlgModoAvanceEvento, IDE_EVENTO_SUELO); } obj = sensor_USS.get_DER(); if ( obj<IDE_EVENTO_TRIGGER_OBJETO ) { bitSet (GLOBAL_FlgModoAvanceEvento, IDE_EVENTO_OBJETO_DERECHA); } else { bitClear(GLOBAL_FlgModoAvanceEvento, IDE_EVENTO_OBJETO_DERECHA); } obj = sensor_USS.get_IZQ(); if ( obj<IDE_EVENTO_TRIGGER_OBJETO ) { bitSet (GLOBAL_FlgModoAvanceEvento, IDE_EVENTO_OBJETO_IZQUIERDA); } else { bitClear(GLOBAL_FlgModoAvanceEvento, IDE_EVENTO_OBJETO_IZQUIERDA); } if ( GLOBAL_FlgModoAvanceEvento!=IDE_EVENTO_OK ) { // ------------------------------------------------- // Detectada alguna incidencia, para los motores // ------------------------------------------------- mDer.paro(); mIzq.paro(); } } } // --------------------------------------------------------- // // byte getIcc5VP(void) // Mide la corriente consumida por el PC para determinar si // esta encendido o no. // Retrona: // . true El PC esta encendido // . false El PC esta apagado // // Notas: // . Cuando el PC Stick esta APAGADO, su consumo es inferior // a 100mA ( 68mA medidos con multimetro), situacion de // standby. // // . Cuando el PC Stick esta funcionando, su consumo es de // entorno a 500 ... 800mA // // --------------------------------------------------------- byte getIcc5VP(void) { float iccMedida; byte resultado; iccMedida = uf_sys.get_Corriente(IDE_ICC_5VP); if ( iccMedida<IDE_PC_POWER_ICC_OFF ) { resultado = false; } else { resultado = true; } return(resultado ); } // --------------------------------------------------------- // // void INT_power_OFF(void) // Funcion conectada a la interrupcion 0 para capturar la // pulsacion del pulsador ON/OFF, que se actua para iniciar // y apagar el Robot. // La interrupcion se conecta al iniciar el arduino para poder // capturar la pulsacion del pulsador y poder APAGAR el Robot // cuando el Robot esta apagado el pulsador ENCIENDE el Robot // via Hardware. // Hay que mantener el pulsador actuado durante unos 10 seg // para iniciar el apagado del Robot. // --------------------------------------------------------- void INT_power_OFF(void) { if ( (GLOBAL_FlgStatusPC!=IDE_STATUS_PC_INI_ON) && (GLOBAL_FlgStatusPC!=IDE_STATUS_PC_START) && (GLOBAL_FlgStatusPC!=IDE_STATUS_PC_ON) ) { // ------------------------------------------------------- // solo se permite si NO se esta inicializando el PC Stick // ------------------------------------------------------- GLOBAL_FlgStatusPC = IDE_STATUS_PC_INI_OFF; } } // --------------------------------------------------------- // // void INT_rtc_SQW(void) // Funcion conectada a la interrupcion 1 para capturar la // señal que genera el reloj de tiempo real, modulo // // --------------------------------------------------------- void INT_rtc_SQW(void) { GLOBAL_Timer_DispF_PC = true; } // --------------------------------------------------------- // // void displayTimerInicio_PC(void) // Actualiza y visualiza en el dsipaly el valor de la variable // GLOBAL_Timer_INI_PC // --------------------------------------------------------- void displayTimerInicio_PC(void) { char sBuff[IDE_MAX_DISPLAY_CAR+1]; if ( (GLOBAL_Timer_DispF_PC==true) && (GLOBAL_Timer_DispD_PC>0) ) { GLOBAL_Timer_DispF_PC = false; sprintf(sBuff,"T%3d",GLOBAL_Timer_DispD_PC); FNG_DisplayMsg(sBuff,0); GLOBAL_Timer_DispD_PC--; } } // --------------------------------------------------------- // // byte FNG_DisplayMsgPROGMEM(const char* msg,unsigned int pausa) // // Funcion para mostrar mensajes en el display cuando los // mensajes son CONSTANTES de memoria // // Ver "https://www.arduino.cc/en/Reference/PROGMEM" // // --------------------------------------------------------- byte FNG_DisplayMsgPROGMEM( const char* msgP,unsigned int pausa) { byte resultado; char buff [IDE_MAX_DISPLAY_CAR+1]; char c; byte ind; byte max; resultado = false; max = strlen_P(msgP); ind = 0; if ( max<=IDE_MAX_DISPLAY_CAR) { for ( ;ind<max; ) { c = pgm_read_byte_near(msgP); buff[ind++] = c; buff[ind ] = '\0'; msgP++; } myDisplay.home(); myDisplay.print(buff); resultado = true; if ( pausa>0 ) { FNG_Pausa(pausa); } } return (resultado) ; } // --------------------------------------------------------- // // byte FNG_DisplayMsg(char* msg,unsigned int pausa) // // Funcion para mostrar mensajes en el display cuando los // mensajes son creados dinamicamente durante la ejecucion // // --------------------------------------------------------- byte FNG_DisplayMsg(char* msg,unsigned int pausa) { byte resultado; resultado = false; if ( strlen(msg)<=IDE_MAX_DISPLAY_CAR) { myDisplay.home(); myDisplay.print(msg); resultado = true; if ( pausa>0 ) { FNG_Pausa(pausa); } } return (resultado) ; } // --------------------------------------------------------- // // void FNG_Pausa(unsigned int pausa) // Genera una pausa de los milisegundos indicados // // --------------------------------------------------------- void FNG_Pausa(unsigned int pausa) { unsigned long int tIni; tIni = millis(); while ( 1 ) { if ( (unsigned int)(millis()-tIni)>= pausa ) { break; } } } // --------------------------------------------------------- // // void UTIL_Scanner_I2C (void) // Utilidad para descubrir dispositivos conecatados al bus // I2C // --------------------------------------------------------- void UTIL_Scanner_I2C (void) { byte error; byte address; int nDevices; Serial3.println("Scanning I2C..."); while ( true ) { nDevices = 0; for ( address = 1; address < 127; address++ ) { // Uses the return value of the Write.endTransmisstion to see if // a device did acknowledge to the address. Wire.beginTransmission(address); error = Wire.endTransmission(); if ( error==0 ) { Serial3.print("I2C Device found at address 0x"); if (address<16) { Serial3.print("0"); } Serial3.println(address,HEX); nDevices++; } else if ( error==4 ) { Serial3.print("Unknown error at address 0x"); if (address<16) { Serial3.print("0"); } Serial3.println(address,HEX); } } if (nDevices == 0) { Serial3.println("No I2C devices found\n"); } else { Serial3.println("Done\n"); } delay(3000); } }
[ "antonio.arnaizlago@gmail.com" ]
antonio.arnaizlago@gmail.com
e536899b44c5932ffc9bc3baae5007bea80df57a
10b85163837c1c1976d4de6e179d53cf6e371478
/third_party/common/include/RE/ExtraHealthPerc.h
2af139fff5b0ab928bbaf17a69bfe722913c7f88
[ "ISC", "LicenseRef-scancode-mit-taylor-variant", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
rethesda/alchemy
8e02352240bfb295e1fe7c6682acabe93fc11aa6
fe6897fa8c065eccc49b61c8c82eda223d865d51
refs/heads/master
2023-03-15T19:10:10.132829
2020-05-12T05:02:33
2020-05-12T05:02:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
654
h
#pragma once #include "RE/BSExtraData.h" #include "RE/ExtraDataTypes.h" namespace RE { class ExtraHealthPerc : public BSExtraData { public: inline static const void* RTTI = RTTI_ExtraHealthPerc; enum { kExtraTypeID = ExtraDataType::kHealthPerc }; virtual ~ExtraHealthPerc(); // 00 // override (BSExtraData) virtual ExtraDataType GetType() const override; // 01 - { return kHealthPerc; } virtual bool IsNotEqual(const BSExtraData* a_rhs) const override; // 02 - { return unk10 != a_rhs->unk10; } // members UInt32 unk10; // 10 UInt32 pad14; // 14 }; static_assert(sizeof(ExtraHealthPerc) == 0x18); }
[ "alexej.h@xiphos.de" ]
alexej.h@xiphos.de
a284a0e7243b7f4c66a25132ec6b4209a6c1bd57
6c9146e5b2b973f4ecd43ddcbd79b59c86a7590b
/CppWindowsServices-RemoteConsole/socket-client.cpp
7b779cf11c208ff0ec3cb86aca2a7e02f5266f21
[]
no_license
Gewery/CppWindowsServices-RemoteConsole
822a192e7e381fafa470013141c15ab8c29f3cef
ede295e4f1bb512c620e188761b26e5d0ac0acca
refs/heads/master
2020-12-21T05:20:15.097357
2020-06-01T10:47:57
2020-06-01T10:47:57
236,319,273
0
0
null
null
null
null
UTF-8
C++
false
false
5,132
cpp
#define WIN32_LEAN_AND_MEAN #define _CRT_SECURE_NO_WARNINGS #include <windows.h> #include <winsock2.h> #include <ws2tcpip.h> #include <stdio.h> // Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib #pragma comment (lib, "Ws2_32.lib") #pragma comment (lib, "Mswsock.lib") #pragma comment (lib, "AdvApi32.lib") #define DEFAULT_BUFLEN 512 #define DEFAULT_OUTPUT_PORT "27015" #define DEFAULT_INPUT_PORT "27016" DWORD WINAPI sendingMessages(LPVOID sOutputSocket) { char sendbuf[1024]; //char* sendbuf; int iResult; // Send until the connection closes do { //scanf("%s", sendbuf); fgets(sendbuf, 1024, stdin); //sendbuf = (char*)"dir\n"; // Send a buffer iResult = send((SOCKET)(sOutputSocket), sendbuf, (int)strlen(sendbuf), 0); if (iResult == SOCKET_ERROR) { printf("send failed with error: %d\n", WSAGetLastError()); closesocket((SOCKET)(sOutputSocket)); WSACleanup(); return 1; } //printf("Bytes Sent: %ld\n", iResult); } while (iResult > 0); return 0; } DWORD WINAPI recievingMessages(LPVOID sInputSocket) { char recvbuf[DEFAULT_BUFLEN]; int recvbuflen = DEFAULT_BUFLEN; int iResult; //printf("receiving starting...\n"); // Receive until the peer closes the connection do { iResult = recv((SOCKET)(sInputSocket), recvbuf, recvbuflen, 0); //printf("received something...\n"); if (iResult == 0) printf("Connection closed\n"); else if (iResult < 0) printf("recv failed with error: %d\n", WSAGetLastError()); for (int i = 0; i < iResult; i++) printf("%c", recvbuf[i]); } while (iResult > 0); //printf("receiving finished\n"); return 0; } int establishConnection(SOCKET &ConnectSocket, char* ip, char* port_number) { WSADATA wsaData; struct addrinfo* result = NULL, * ptr = NULL, hints; int iResult; // Initialize Winsock iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { printf("WSAStartup failed with error: %d\n", iResult); return 1; } ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; // Resolve the server address and port iResult = getaddrinfo(ip, port_number, &hints, &result); if (iResult != 0) { printf("getaddrinfo failed with error: %d\n", iResult); WSACleanup(); return 1; } // Attempt to connect to an address until one succeeds for (ptr = result; ptr != NULL; ptr = ptr->ai_next) { // Create a SOCKET for connecting to server ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol); if (ConnectSocket == INVALID_SOCKET) { printf("socket failed with error: %ld\n", WSAGetLastError()); WSACleanup(); return 1; } // Connect to server. iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen); if (iResult == SOCKET_ERROR) { closesocket(ConnectSocket); ConnectSocket = INVALID_SOCKET; continue; } break; } freeaddrinfo(result); if (ConnectSocket == INVALID_SOCKET) { printf("Unable to connect to server!\n"); WSACleanup(); return 1; } } int socket_client(int argc, char* argv[]) { SOCKET sOutputSocket = INVALID_SOCKET; establishConnection(sOutputSocket, argv[1], (char*)DEFAULT_OUTPUT_PORT); SOCKET sInputSocket = INVALID_SOCKET; establishConnection(sInputSocket, argv[1], (char*)DEFAULT_INPUT_PORT); DWORD dwSendingThreadId; HANDLE hSendingThread = CreateThread( NULL, // no security attribute 0, // default stack size sendingMessages, // thread proc (LPVOID)(sOutputSocket), // thread parameter 0, // not suspended &dwSendingThreadId); // returns thread ID if (hSendingThread == NULL) { printf("CreateThread for sending failed, GLE=%d.\n", GetLastError()); return -1; } DWORD dwRecievingThreadId; HANDLE hRecievingThread = CreateThread( NULL, // no security attribute 0, // default stack size recievingMessages, // thread proc (LPVOID)(sInputSocket), // thread parameter 0, // not suspended &dwRecievingThreadId); // returns thread ID if (hRecievingThread == NULL) { printf("CreateThread for recieving failed, GLE=%d.\n", GetLastError()); return -1; } // Wait for threads stops WaitForSingleObject(hRecievingThread, INFINITE); WaitForSingleObject(hSendingThread, INFINITE); CloseHandle(hRecievingThread); CloseHandle(hSendingThread); // cleanup closesocket(sOutputSocket); closesocket(sInputSocket); WSACleanup(); return 0; }
[ "gewery@mail.ru" ]
gewery@mail.ru
b2a8455595e3c5d49d127659ea39a9740904502e
680440f5e59eb2157c1ecb41fd891880ac47c459
/XJOI/CONTEST/xjoi.net/1293/nichijou/nichijou.cpp
60d3ed4b9e85d3435ac7eaa81a6f5449a0f479f5
[]
no_license
Skywt2003/codes
a705dc3a4f5f79d47450179fc597bd92639f3d93
0e09198dc84e3f6907a11b117a068f5e0f55ca68
refs/heads/master
2020-03-29T09:29:54.014364
2019-11-15T12:39:47
2019-11-15T12:39:47
149,760,952
6
0
null
null
null
null
UTF-8
C++
false
false
3,489
cpp
#include<bits/stdc++.h> #define int long long using namespace std; inline int read(){ int ret=0,f=1; char ch=getchar(); while (ch<'0'||ch>'9') {if (ch=='-') f=-1;ch=getchar();} while (ch>='0'&&ch<='9') ret=ret*10+ch-'0',ch=getchar(); return ret*f; } const int maxn=1e6+5,maxe=2e6+5,maxm=1e6+5; int n,m; int tot=0,lnk[maxn],nxt[maxe],to[maxe]; int deep[maxn],f[maxn][22]; void add_edge(int x,int y){ tot++; to[tot]=y; nxt[tot]=lnk[x];lnk[x]=tot; } void build_tree(int x){ for (int i=1;i<22;i++) f[x][i]=f[f[x][i-1]][i-1]; for (int i=lnk[x];i;i=nxt[i]) if (to[i]!=f[x][0]){ f[to[i]][0]=x; deep[to[i]]=deep[x]+1; build_tree(to[i]); } } int get_lca(int x,int y){ if (deep[x]<deep[y]) swap(x,y); for (int i=21;i>=0;i--) if (deep[f[x][i]] >= deep[y]) x=f[x][i]; if (x==y) return x; for (int i=21;i>=0;i--) if (f[x][i] != f[y][i]) x=f[x][i],y=f[y][i]; return f[x][0]; } int get_dist(int x,int y){ int lca=get_lca(x,y); return deep[x]-deep[lca]+deep[y]-deep[lca]; } bool is_subtask3=true; bool is_subtask5=true; struct query{ int x,y,d; }; query q[maxm]; namespace subtask3{ signed main(){ #ifdef DEBUG printf("subtask3::main() | start\n"); #endif puts("1"); return 0; } }; namespace subtask5{ int sum[maxn],ans=-1; void find_answer(int x,int now){ if (ans!=-1) return; if (now==m){ans=x;return;} for (int i=lnk[x];i;i=nxt[i]) if (to[i]!=f[x][0]) find_answer(to[i],now+sum[to[i]]); } signed main(){ #ifdef DEBUG printf("subtask5::main() | start\n"); #endif for (int i=1;i<=m;i++){ int lca=get_lca(q[i].x,q[i].y); sum[lca]++; if (lca!=q[i].x) for (int j=lnk[q[i].x];j;j=nxt[j]) if (to[j]!=f[q[i].x][0]) sum[to[j]]--; if (lca!=q[i].y) for (int j=lnk[q[i].y];j;j=nxt[j]) if (to[j]!=f[q[i].y][0]) sum[to[j]]--; if (lca==q[i].x && lca==q[i].y) for (int j=lnk[q[i].y];j;j=nxt[j]) if (to[j]!=f[q[i].y][0]) sum[to[j]]--; } find_answer(1,sum[1]); if (ans==-1) printf("NO\n"); else printf("%lld\n",ans); return 0; } }; bool now_vis[maxn]; int cnt[maxn]; void make_now_tag(int x,int y){ if (deep[x] < deep[y]) swap(x,y); while (deep[x]>deep[y]) now_vis[x]=true,x=f[x][0]; while (x!=y) now_vis[x]=now_vis[y]=true,x=f[x][0],y=f[y][0]; now_vis[x]=true; } void exDFS(int x,int lft){ now_vis[x]=true; if (lft==0) return; for (int i=lnk[x];i;i=nxt[i]) if (!now_vis[to[i]]) exDFS(to[i],lft-1); } signed main(){ #ifdef DEBUG freopen("data.in","r",stdin); #endif n=read(); m=read(); for (int i=1;i<n;i++){ int x=read(),y=read(); add_edge(x,y); add_edge(y,x); } deep[1]=1; build_tree(1); for (int i=1;i<=m;i++){ q[i].x=read(),q[i].y=read(),q[i].d=read(); if (q[i].d != 2e6) is_subtask3=false; if (is_subtask5){ int dist=get_dist(q[i].x,q[i].y); if (q[i].d != dist) is_subtask5=false; } } if (is_subtask3) return subtask3::main(); if (is_subtask5) return subtask5::main(); #ifdef DEBUG printf("main() | Other subtask\n"); #endif for (int i=1;i<=m;i++){ int dist=get_dist(q[i].x,q[i].y); int ext=(q[i].d-dist)/2; for (int j=1;j<=n;j++) now_vis[j]=false; make_now_tag(q[i].x,q[i].y); int xx=q[i].x,yy=q[i].y; if (deep[xx] < deep[yy]) swap(xx,yy); while (deep[xx] > deep[yy]) exDFS(xx,ext),xx=f[xx][0]; while (xx!=yy) exDFS(xx,ext),exDFS(yy,ext),xx=f[xx][0],yy=f[yy][0]; exDFS(xx,ext); for (int j=1;j<=n;j++) cnt[j]+=now_vis[j]; } for (int i=1;i<=n;i++) if (cnt[i]==m){ printf("%lld\n",i); return 0; } printf("NO\n"); return 0; }
[ "skywt2003@gmail.com" ]
skywt2003@gmail.com
97896ed28071f5ec47fdcc336625498c8f73bfc3
7d7301514d34006d19b2775ae4f967a299299ed6
/leetcode/interview/05.01.insertBits.cpp
2d88373160668ada1ea8fcf96e09854d71d12ff1
[]
no_license
xmlb88/algorithm
ae83ff0e478ea01f37bc686de14f7d009d45731b
cf02d9099569e2638e60029b89fd7b384f3c1a68
refs/heads/master
2023-06-16T00:21:27.922428
2021-07-17T03:46:50
2021-07-17T03:46:50
293,984,271
1
0
null
2020-12-02T09:08:28
2020-09-09T02:44:20
C++
UTF-8
C++
false
false
220
cpp
#include <iostream> using namespace std; int insertBits(int N, int M, int i, int j) { for (int k = i; k <= j; k++) { if (N & (1 << k)) { N -= (1 << k); } } return N | (M << i); }
[ "xmlb@gmail.com" ]
xmlb@gmail.com
5f008f9698fae0baff763c05b0fa03de3d08bc76
df1e1faeb6a66cdf6e2c39d0a61225d8c7c486f8
/include/message.h
28492e7367a11852f2887813f64f5f781964510a
[]
no_license
GBernardo07/DiaryProject
5ce6dc82b64bda4d41f8822e198016a97bfdb5bd
d5dd86526b4f5462e25150152673c7e449d18082
refs/heads/master
2022-11-14T03:12:45.307916
2020-07-02T11:22:23
2020-07-02T11:22:23
272,705,794
0
0
null
null
null
null
UTF-8
C++
false
false
208
h
#ifndef MESSAGE_H #define MESSAGE_h #include <string> #include "timing.h" #include "date.h" struct Message { std::string content; Date date; Time time; bool compare_messages(); }; #endif
[ "gbernardoreis@outlook.com" ]
gbernardoreis@outlook.com