blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
sequencelengths
1
1
author
stringlengths
0
119
ddae6abfa26e9dc67c86027b459688323c0970ec
81e49766487538c8c121fc37ceaa0f113559667c
/src/wallet/test/vote_tests.cpp
d15b8649c7d30e5fc7ea84bc80337d51bd495bea
[ "MIT" ]
permissive
jinhuaio/paicoin
ebd7a3a110d4399c4a5394208e572c73a6870444
09f8029112e7a57548ee5b5202c260f8aee7f2e9
refs/heads/master
2023-01-07T15:34:39.100188
2020-11-06T03:53:43
2020-11-06T03:53:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
45,876
cpp
// // Copyright (c) 2017-2020 Project PAI Foundation // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // #include "wallet/test/wallet_stake_test_fixture.h" #include <boost/test/unit_test.hpp> #include "validation.h" #include "wallet/coincontrol.h" #include "rpc/server.h" BOOST_FIXTURE_TEST_SUITE(vote_tests, WalletStakeTestingSetup) // test the stakebase content verifier BOOST_FIXTURE_TEST_CASE(stakebase_detection, WalletStakeTestingSetup) { const uint256& dummyOutputHash = GetRandHash(); const uint256& prevOutputHash = emptyData.hash; const uint32_t& prevOutputIndex = static_cast<uint32_t>(-1); const CScript& stakeBaseSigScript = consensus.stakeBaseSigScript; // prevout.n BOOST_CHECK_EQUAL(HasStakebaseContents(CTxIn(prevOutputHash, 0, stakeBaseSigScript)), false); BOOST_CHECK_EQUAL(HasStakebaseContents(CTxIn(prevOutputHash, 1, stakeBaseSigScript)), false); BOOST_CHECK_EQUAL(HasStakebaseContents(CTxIn(prevOutputHash, 2, stakeBaseSigScript)), false); // sigScript BOOST_CHECK_EQUAL(HasStakebaseContents(CTxIn(prevOutputHash, prevOutputIndex, CScript())), false); BOOST_CHECK_EQUAL(HasStakebaseContents(CTxIn(prevOutputHash, prevOutputIndex, CScript() << 0x01)), false); BOOST_CHECK_EQUAL(HasStakebaseContents(CTxIn(prevOutputHash, prevOutputIndex, CScript() << 0x01 << 0x02)), false); BOOST_CHECK_EQUAL(HasStakebaseContents(CTxIn(prevOutputHash, prevOutputIndex, CScript() << 0x01)), false); // prevout.hash BOOST_CHECK_EQUAL(HasStakebaseContents(CTxIn(dummyOutputHash, prevOutputIndex, stakeBaseSigScript)), false); // correct BOOST_CHECK(HasStakebaseContents(CTxIn(prevOutputHash, prevOutputIndex, stakeBaseSigScript))); } // test the vote bits BOOST_FIXTURE_TEST_CASE(vote_bits, WalletStakeTestingSetup) { // default values BOOST_CHECK(VoteBits::allRejected.getBits() == 0x0000); BOOST_CHECK(VoteBits::rttAccepted.getBits() == 0x0001); // default construction BOOST_CHECK(VoteBits().getBits() == 0x0000); // construction from uint16_t BOOST_CHECK(VoteBits(0x0000).getBits() == 0x0000); BOOST_CHECK(VoteBits(0x0001).getBits() == 0x0001); BOOST_CHECK(VoteBits(0x1234).getBits() == 0x1234); BOOST_CHECK(VoteBits(0xFFFF).getBits() == 0xFFFF); // construction with signaled bit BOOST_CHECK(VoteBits(VoteBits::Rtt, true).getBits() == 0x0001); BOOST_CHECK(VoteBits(VoteBits::Rtt, false).getBits() == 0x0000); BOOST_CHECK(VoteBits(1, true).getBits() == 0x0002); BOOST_CHECK(VoteBits(1, false).getBits() == 0x0000); BOOST_CHECK(VoteBits(7, true).getBits() == 0x0080); BOOST_CHECK(VoteBits(7, false).getBits() == 0x0000); BOOST_CHECK(VoteBits(15, true).getBits() == 0x8000); BOOST_CHECK(VoteBits(15, false).getBits() == 0x0000); // copy constructor (also testing getting all the bits) VoteBits vb1; BOOST_CHECK(VoteBits(vb1).getBits() == 0x0000); vb1 = VoteBits(0x0001); BOOST_CHECK(VoteBits(vb1).getBits() == 0x0001); vb1 = VoteBits(0x1234); BOOST_CHECK(VoteBits(vb1).getBits() == 0x1234); vb1 = VoteBits(0xFFFF); BOOST_CHECK(VoteBits(vb1).getBits() == 0xFFFF); // move constructor vb1 = VoteBits(0x0000); BOOST_CHECK(VoteBits(std::move(vb1)).getBits() == 0x0000); vb1 = VoteBits(0x0001); BOOST_CHECK(VoteBits(std::move(vb1)).getBits() == 0x0001); vb1 = VoteBits(0x1234); BOOST_CHECK(VoteBits(std::move(vb1)).getBits() == 0x1234); vb1 = VoteBits(0xFFFF); BOOST_CHECK(VoteBits(std::move(vb1)).getBits() == 0xFFFF); // copy assignment vb1 = VoteBits(0x0000); VoteBits vb2 = vb1; BOOST_CHECK(vb2.getBits() == 0x0000); vb1 = VoteBits(0x0001); vb2 = vb1; BOOST_CHECK(vb2.getBits() == 0x0001); vb1 = VoteBits(0x1234); vb2 = vb1; BOOST_CHECK(vb2.getBits() == 0x1234); vb1 = VoteBits(0xFFFF); vb2 = vb1; BOOST_CHECK(vb2.getBits() == 0xFFFF); // move assignment vb1 = VoteBits(0x0000); vb2 = std::move(vb1); BOOST_CHECK(vb2.getBits() == 0x0000); vb1 = VoteBits(0x0001); vb2 = std::move(vb1); BOOST_CHECK(vb2.getBits() == 0x0001); vb1 = VoteBits(0x1234); vb2 = std::move(vb1); BOOST_CHECK(vb2.getBits() == 0x1234); vb1 = VoteBits(0xFFFF); vb2 = std::move(vb1); BOOST_CHECK(vb2.getBits() == 0xFFFF); // equality vb1 = VoteBits(0x0000); BOOST_CHECK(vb1 == VoteBits(0x0000)); vb1 = VoteBits(0x0001); BOOST_CHECK(vb1 == VoteBits(0x0001)); vb1 = VoteBits(0x1234); BOOST_CHECK(vb1 == VoteBits(0x1234)); vb1 = VoteBits(0xFFFF); BOOST_CHECK(vb1 == VoteBits(0xFFFF)); // inequality vb1 = VoteBits(0x0000); BOOST_CHECK(vb1 != VoteBits(0x0001)); BOOST_CHECK(vb1 != VoteBits(0x1234)); BOOST_CHECK(vb1 != VoteBits(0xFFFF)); vb1 = VoteBits(0x0001); BOOST_CHECK(vb1 != VoteBits(0x0000)); BOOST_CHECK(vb1 != VoteBits(0x1234)); BOOST_CHECK(vb1 != VoteBits(0xFFFF)); vb1 = VoteBits(0x1234); BOOST_CHECK(vb1 != VoteBits(0x0000)); BOOST_CHECK(vb1 != VoteBits(0x0001)); BOOST_CHECK(vb1 != VoteBits(0xFFFF)); vb1 = VoteBits(0xFFFF); BOOST_CHECK(vb1 != VoteBits(0x0000)); BOOST_CHECK(vb1 != VoteBits(0x0001)); BOOST_CHECK(vb1 != VoteBits(0x1234)); // set bit vb1 = VoteBits(0x0000); vb1.setBit(VoteBits::Rtt, true); BOOST_CHECK(vb1.getBits() == 0x0001); vb1.setBit(VoteBits::Rtt, false); BOOST_CHECK(vb1.getBits() == 0x0000); vb1.setBit(1, true); BOOST_CHECK(vb1.getBits() == 0x0002); vb1.setBit(1, false); BOOST_CHECK(vb1.getBits() == 0x0000); vb1.setBit(7, true); BOOST_CHECK(vb1.getBits() == 0x0080); vb1.setBit(7, false); BOOST_CHECK(vb1.getBits() == 0x0000); vb1.setBit(15, true); BOOST_CHECK(vb1.getBits() == 0x8000); vb1.setBit(15, false); BOOST_CHECK(vb1.getBits() == 0x0000); // get bit vb1 = VoteBits(0x0001); BOOST_CHECK(vb1.getBit(VoteBits::Rtt)); vb1 = VoteBits(0x0000); BOOST_CHECK(!vb1.getBit(VoteBits::Rtt)); vb1 = VoteBits(0x0002); BOOST_CHECK(vb1.getBit(1)); vb1 = VoteBits(0x0000); BOOST_CHECK(!vb1.getBit(1)); vb1 = VoteBits(0x0080); BOOST_CHECK(vb1.getBit(7)); vb1 = VoteBits(0x0000); BOOST_CHECK(!vb1.getBit(7)); vb1 = VoteBits(0x8000); BOOST_CHECK(vb1.getBit(15)); vb1 = VoteBits(0x0000); BOOST_CHECK(!vb1.getBit(15)); vb1 = VoteBits(0x0003); BOOST_CHECK(vb1.getBit(0)); BOOST_CHECK(vb1.getBit(1)); BOOST_CHECK(!vb1.getBit(2)); vb1 = VoteBits(0xFFFE); BOOST_CHECK(!vb1.getBit(0)); BOOST_CHECK(vb1.getBit(1)); BOOST_CHECK(vb1.getBit(2)); BOOST_CHECK(vb1.getBit(7)); BOOST_CHECK(vb1.getBit(15)); // RTT acceptance verification vb1 = VoteBits(0x0001); BOOST_CHECK(vb1.isRttAccepted()); vb1 = VoteBits(0x4321); BOOST_CHECK(vb1.isRttAccepted()); vb1 = VoteBits(0xCDEF); BOOST_CHECK(vb1.isRttAccepted()); vb1 = VoteBits(0x0000); BOOST_CHECK(!vb1.isRttAccepted()); vb1 = VoteBits(0x1234); BOOST_CHECK(!vb1.isRttAccepted()); vb1 = VoteBits(0xFFFE); BOOST_CHECK(!vb1.isRttAccepted()); // RTT acceptance control vb1 = VoteBits(0x0000); vb1.setRttAccepted(true); BOOST_CHECK(vb1.getBits() == 0x0001); vb1.setRttAccepted(false); BOOST_CHECK(vb1.getBits() == 0x0000); vb1 = VoteBits(0x1234); vb1.setRttAccepted(true); BOOST_CHECK(vb1.getBits() == 0x1235); vb1.setRttAccepted(false); BOOST_CHECK(vb1.getBits() == 0x1234); vb1 = VoteBits(0xFFFE); vb1.setRttAccepted(true); BOOST_CHECK(vb1.getBits() == 0xFFFF); vb1.setRttAccepted(false); BOOST_CHECK(vb1.getBits() == 0xFFFE); vb1 = VoteBits(0xFFFF); vb1.setRttAccepted(true); BOOST_CHECK(vb1.getBits() == 0xFFFF); vb1.setRttAccepted(false); BOOST_CHECK(vb1.getBits() == 0xFFFE); } // test the extended vote bits functions BOOST_FIXTURE_TEST_CASE(extended_vote_bits, WalletStakeTestingSetup) { // string validation BOOST_CHECK(ExtendedVoteBits::containsValidExtendedVoteBits("00")); BOOST_CHECK(ExtendedVoteBits::containsValidExtendedVoteBits("01")); BOOST_CHECK(ExtendedVoteBits::containsValidExtendedVoteBits("0123")); BOOST_CHECK(ExtendedVoteBits::containsValidExtendedVoteBits("1234567890abcdef")); BOOST_CHECK(ExtendedVoteBits::containsValidExtendedVoteBits("1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef")); BOOST_CHECK(ExtendedVoteBits::containsValidExtendedVoteBits(extendedVoteBitsData.validLargeString)); BOOST_CHECK(!ExtendedVoteBits::containsValidExtendedVoteBits("0")); BOOST_CHECK(!ExtendedVoteBits::containsValidExtendedVoteBits("1")); BOOST_CHECK(!ExtendedVoteBits::containsValidExtendedVoteBits("012")); BOOST_CHECK(!ExtendedVoteBits::containsValidExtendedVoteBits("12345")); BOOST_CHECK(!ExtendedVoteBits::containsValidExtendedVoteBits("abc")); BOOST_CHECK(!ExtendedVoteBits::containsValidExtendedVoteBits("lala")); BOOST_CHECK(!ExtendedVoteBits::containsValidExtendedVoteBits("a!")); BOOST_CHECK(!ExtendedVoteBits::containsValidExtendedVoteBits(" ")); BOOST_CHECK(!ExtendedVoteBits::containsValidExtendedVoteBits("a ")); BOOST_CHECK(!ExtendedVoteBits::containsValidExtendedVoteBits(emptyData.string)); BOOST_CHECK(!ExtendedVoteBits::containsValidExtendedVoteBits(extendedVoteBitsData.invalidLargeString)); // vector validation std::vector<unsigned char> vect = {0x00}; BOOST_CHECK(ExtendedVoteBits::containsValidExtendedVoteBits(vect)); vect = {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}; BOOST_CHECK(ExtendedVoteBits::containsValidExtendedVoteBits(vect)); BOOST_CHECK(ExtendedVoteBits::containsValidExtendedVoteBits(extendedVoteBitsData.validLargeVector)); BOOST_CHECK(!ExtendedVoteBits::containsValidExtendedVoteBits(emptyData.vector)); BOOST_CHECK(!ExtendedVoteBits::containsValidExtendedVoteBits(extendedVoteBitsData.invalidLargeVector)); // vote data size VoteData voteData; BOOST_CHECK_EQUAL(ExtendedVoteBits::minSize(), 1U); BOOST_CHECK_EQUAL(ExtendedVoteBits::maxSize(), nMaxStructDatacarrierBytes - GetVoteDataSizeWithEmptyExtendedVoteBits() - 1); BOOST_CHECK_EQUAL(GetVoteDataSizeWithEmptyExtendedVoteBits(), GetSerializeSize(GetScriptForVoteDecl(voteData), SER_NETWORK, PROTOCOL_VERSION)); // default construction BOOST_CHECK(ExtendedVoteBits().getVector() == extendedVoteBitsData.empty.getVector()); // construction from string vect = {0x00}; BOOST_CHECK(ExtendedVoteBits("00").getVector() == vect); vect = {0x01}; BOOST_CHECK(ExtendedVoteBits("01").getVector() == vect); vect = {0x01, 0x23}; BOOST_CHECK(ExtendedVoteBits("0123").getVector() == vect); vect = {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}; BOOST_CHECK(ExtendedVoteBits("0123456789abcdef").getVector() == vect); BOOST_CHECK(ExtendedVoteBits(extendedVoteBitsData.validLargeString).getVector() == extendedVoteBitsData.validLargeVector); BOOST_CHECK(ExtendedVoteBits(emptyData.string).getVector() == extendedVoteBitsData.empty.getVector()); BOOST_CHECK(ExtendedVoteBits("").getVector() == extendedVoteBitsData.empty.getVector()); BOOST_CHECK(ExtendedVoteBits("0").getVector() == extendedVoteBitsData.empty.getVector()); BOOST_CHECK(ExtendedVoteBits("1").getVector() == extendedVoteBitsData.empty.getVector()); BOOST_CHECK(ExtendedVoteBits("123").getVector() == extendedVoteBitsData.empty.getVector()); BOOST_CHECK(ExtendedVoteBits("12345").getVector() == extendedVoteBitsData.empty.getVector()); BOOST_CHECK(ExtendedVoteBits("abc").getVector() == extendedVoteBitsData.empty.getVector()); BOOST_CHECK(ExtendedVoteBits("lala").getVector() == extendedVoteBitsData.empty.getVector()); BOOST_CHECK(ExtendedVoteBits("a!").getVector() == extendedVoteBitsData.empty.getVector()); BOOST_CHECK(ExtendedVoteBits(" ").getVector() == extendedVoteBitsData.empty.getVector()); BOOST_CHECK(ExtendedVoteBits("a ").getVector() == extendedVoteBitsData.empty.getVector()); BOOST_CHECK(ExtendedVoteBits(extendedVoteBitsData.invalidLargeString).getVector() == extendedVoteBitsData.empty.getVector()); // construction from vector (also testing vector access) vect = {0x00}; BOOST_CHECK(ExtendedVoteBits(vect).getVector() == vect); vect = {0x01}; BOOST_CHECK(ExtendedVoteBits(vect).getVector() == vect); vect = {0x01, 0x23}; BOOST_CHECK(ExtendedVoteBits(vect).getVector() == vect); vect = {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}; BOOST_CHECK(ExtendedVoteBits(vect).getVector() == vect); BOOST_CHECK(ExtendedVoteBits(extendedVoteBitsData.validLargeVector).getVector() == extendedVoteBitsData.validLargeVector); vect.clear(); BOOST_CHECK(ExtendedVoteBits(vect).getVector() == extendedVoteBitsData.empty.getVector()); BOOST_CHECK(ExtendedVoteBits(extendedVoteBitsData.invalidLargeVector).getVector() == extendedVoteBitsData.empty.getVector()); // copy constructor vect = {0x00}; BOOST_CHECK(ExtendedVoteBits(ExtendedVoteBits(vect)).getVector() == vect); vect = {0x01, 0x23}; BOOST_CHECK(ExtendedVoteBits(ExtendedVoteBits(vect)).getVector() == vect); vect = {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}; BOOST_CHECK(ExtendedVoteBits(ExtendedVoteBits(vect)).getVector() == vect); BOOST_CHECK(ExtendedVoteBits(ExtendedVoteBits(extendedVoteBitsData.validLargeVector)).getVector() == extendedVoteBitsData.validLargeVector); BOOST_CHECK(ExtendedVoteBits(ExtendedVoteBits()).getVector() == extendedVoteBitsData.empty.getVector()); BOOST_CHECK(ExtendedVoteBits(ExtendedVoteBits(extendedVoteBitsData.invalidLargeVector)).getVector() == extendedVoteBitsData.empty.getVector()); // move constructor vect = {0x00}; ExtendedVoteBits evb1 = ExtendedVoteBits(vect); BOOST_CHECK(ExtendedVoteBits(std::move(evb1)).getVector() == vect); vect = {0x01, 0x23}; evb1 = ExtendedVoteBits(vect); BOOST_CHECK(ExtendedVoteBits(std::move(evb1)).getVector() == vect); vect = {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}; evb1 = ExtendedVoteBits(vect); BOOST_CHECK(ExtendedVoteBits(std::move(evb1)).getVector() == vect); evb1 = ExtendedVoteBits(extendedVoteBitsData.validLargeVector); BOOST_CHECK(ExtendedVoteBits(std::move(evb1)).getVector() == extendedVoteBitsData.validLargeVector); evb1 = ExtendedVoteBits(); BOOST_CHECK(ExtendedVoteBits(std::move(evb1)).getVector() == extendedVoteBitsData.empty.getVector()); evb1 = ExtendedVoteBits(extendedVoteBitsData.invalidLargeVector); BOOST_CHECK(ExtendedVoteBits(std::move(evb1)).getVector() == extendedVoteBitsData.empty.getVector()); // copy assignment vect = {0x00}; evb1 = ExtendedVoteBits(vect); ExtendedVoteBits evb2 = evb1; BOOST_CHECK(evb2.getVector() == vect); vect = {0x01, 0x23}; evb1 = ExtendedVoteBits(vect); evb2 = evb1; BOOST_CHECK(evb2.getVector() == vect); vect = {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}; evb1 = ExtendedVoteBits(vect); evb2 = evb1; BOOST_CHECK(evb2.getVector() == vect); evb1 = ExtendedVoteBits(extendedVoteBitsData.validLargeVector); evb2 = evb1; BOOST_CHECK(evb2.getVector() == extendedVoteBitsData.validLargeVector); evb1 = ExtendedVoteBits(); evb2 = evb1; BOOST_CHECK(evb2.getVector() == extendedVoteBitsData.empty.getVector()); evb1 = ExtendedVoteBits(extendedVoteBitsData.invalidLargeVector); evb2 = evb1; BOOST_CHECK(evb2.getVector() == extendedVoteBitsData.empty.getVector()); // move assignment vect = {0x00}; evb1 = ExtendedVoteBits(vect); evb2 = std::move(evb1); BOOST_CHECK(evb2.getVector() == vect); vect = {0x01, 0x23}; evb1 = ExtendedVoteBits(vect); evb2 = std::move(evb1); BOOST_CHECK(evb2.getVector() == vect); vect = {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}; evb1 = ExtendedVoteBits(vect); evb2 = std::move(evb1); BOOST_CHECK(evb2.getVector() == vect); evb1 = ExtendedVoteBits(extendedVoteBitsData.validLargeVector); evb2 = std::move(evb1); BOOST_CHECK(evb2.getVector() == extendedVoteBitsData.validLargeVector); evb1 = ExtendedVoteBits(); evb2 = std::move(evb1); BOOST_CHECK(evb2.getVector() == extendedVoteBitsData.empty.getVector()); evb1 = ExtendedVoteBits(extendedVoteBitsData.invalidLargeVector); evb2 = std::move(evb1); BOOST_CHECK(evb2.getVector() == extendedVoteBitsData.empty.getVector()); // equality vect = {0x00}; BOOST_CHECK(ExtendedVoteBits(vect) == ExtendedVoteBits("00")); vect = {0x01, 0x23}; BOOST_CHECK(ExtendedVoteBits(vect) == ExtendedVoteBits("0123")); vect = {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}; BOOST_CHECK(ExtendedVoteBits(vect) == ExtendedVoteBits("0123456789abcdef")); BOOST_CHECK(ExtendedVoteBits(extendedVoteBitsData.validLargeVector) == ExtendedVoteBits(extendedVoteBitsData.validLargeString)); BOOST_CHECK(ExtendedVoteBits() == extendedVoteBitsData.empty); BOOST_CHECK(ExtendedVoteBits(extendedVoteBitsData.invalidLargeVector) == ExtendedVoteBits()); // inequality vect = {0x00}; BOOST_CHECK(ExtendedVoteBits(vect) != ExtendedVoteBits("01")); BOOST_CHECK(ExtendedVoteBits(vect) != ExtendedVoteBits("0123")); BOOST_CHECK(ExtendedVoteBits(vect) != ExtendedVoteBits("0123456789abcdef")); BOOST_CHECK(ExtendedVoteBits(vect) != ExtendedVoteBits(extendedVoteBitsData.validLargeString)); vect = {0x01}; BOOST_CHECK(ExtendedVoteBits(vect) != ExtendedVoteBits("00")); BOOST_CHECK(ExtendedVoteBits(vect) != ExtendedVoteBits("0123")); BOOST_CHECK(ExtendedVoteBits(vect) != ExtendedVoteBits("0123456789abcdef")); BOOST_CHECK(ExtendedVoteBits(vect) != ExtendedVoteBits(extendedVoteBitsData.validLargeString)); vect = {0x01, 0x23}; BOOST_CHECK(ExtendedVoteBits(vect) != ExtendedVoteBits("00")); BOOST_CHECK(ExtendedVoteBits(vect) != ExtendedVoteBits("01")); BOOST_CHECK(ExtendedVoteBits(vect) != ExtendedVoteBits("0123456789abcdef")); BOOST_CHECK(ExtendedVoteBits(vect) != ExtendedVoteBits(extendedVoteBitsData.validLargeString)); vect = {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}; BOOST_CHECK(ExtendedVoteBits(vect) != ExtendedVoteBits("00")); BOOST_CHECK(ExtendedVoteBits(vect) != ExtendedVoteBits("01")); BOOST_CHECK(ExtendedVoteBits(vect) != ExtendedVoteBits("0123")); BOOST_CHECK(ExtendedVoteBits(vect) != ExtendedVoteBits(extendedVoteBitsData.validLargeString)); BOOST_CHECK(ExtendedVoteBits(extendedVoteBitsData.validLargeString) != ExtendedVoteBits("00")); BOOST_CHECK(ExtendedVoteBits(extendedVoteBitsData.validLargeString) != ExtendedVoteBits("01")); BOOST_CHECK(ExtendedVoteBits(extendedVoteBitsData.validLargeString) != ExtendedVoteBits("0123")); BOOST_CHECK(ExtendedVoteBits(extendedVoteBitsData.validLargeString) != ExtendedVoteBits("0123456789abcdef")); // validity (also see vector access below) BOOST_CHECK(ExtendedVoteBits().isValid()); BOOST_CHECK(ExtendedVoteBits("00").isValid()); BOOST_CHECK(ExtendedVoteBits("01").isValid()); BOOST_CHECK(ExtendedVoteBits("0123").isValid()); BOOST_CHECK(ExtendedVoteBits("0123456789abcdef").isValid()); BOOST_CHECK(ExtendedVoteBits(extendedVoteBitsData.validLargeString).isValid()); BOOST_CHECK(ExtendedVoteBits(extendedVoteBitsData.invalidLargeString).isValid()); // vector access (mostly already tested in the constructor area above) // const_cast like this is highly discouraged evb1 = ExtendedVoteBits(); const_cast<std::vector<unsigned char>&>(evb1.getVector()).clear(); BOOST_CHECK(!evb1.isValid()); evb1 = ExtendedVoteBits(); const_cast<std::vector<unsigned char>&>(evb1.getVector()) = extendedVoteBitsData.validLargeVector; BOOST_CHECK(evb1.getVector() == extendedVoteBitsData.validLargeVector); evb1 = ExtendedVoteBits(); const_cast<std::vector<unsigned char>&>(evb1.getVector()) = extendedVoteBitsData.invalidLargeVector; BOOST_CHECK(!evb1.isValid()); // hexadecimal string BOOST_CHECK(ExtendedVoteBits().getHex() == "00"); vect = {0x00}; BOOST_CHECK(ExtendedVoteBits(vect).getHex() == "00"); vect = {0x01, 0x23}; BOOST_CHECK(ExtendedVoteBits(vect).getHex() == "0123"); vect = {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}; BOOST_CHECK(ExtendedVoteBits(vect).getHex() == "0123456789abcdef"); BOOST_CHECK(ExtendedVoteBits(extendedVoteBitsData.validLargeVector).getHex() == extendedVoteBitsData.validLargeString); BOOST_CHECK(ExtendedVoteBits(extendedVoteBitsData.invalidLargeVector).getHex() == "00"); } // test the transaction for votes BOOST_FIXTURE_TEST_CASE(vote_transaction, WalletStakeTestingSetup) { std::string voteHashStr; CWalletError we; LOCK2(cs_main, wallet->cs_wallet); // Premature votes and preconditions { // ticket hash std::tie(voteHashStr, we) = wallet->Vote(emptyData.hash, chainActive.Tip()->GetBlockHash(), chainActive.Tip()->nHeight, VoteBits::allRejected, extendedVoteBitsData.empty); BOOST_CHECK_EQUAL(we.code, CWalletError::INVALID_PARAMETER); // stake validation height not reached yet std::tie(voteHashStr, we) = wallet->Vote(chainActive.Tip()->GetBlockHash(), chainActive.Tip()->GetBlockHash(), chainActive.Tip()->nHeight, VoteBits::allRejected, extendedVoteBitsData.empty); BOOST_CHECK_EQUAL(we.code, CWalletError::INVALID_PARAMETER); ExtendChain(consensus.nStakeValidationHeight - chainActive.Height()); // block hash std::tie(voteHashStr, we) = wallet->Vote(chainActive.Tip()->GetBlockHash(), emptyData.hash, chainActive.Tip()->nHeight, VoteBits::allRejected, extendedVoteBitsData.empty); BOOST_CHECK_EQUAL(we.code, CWalletError::INVALID_PARAMETER); std::tie(voteHashStr, we) = wallet->Vote(chainActive.Tip()->GetBlockHash(), chainActive.Tip()->pprev->GetBlockHash(), chainActive.Tip()->nHeight, VoteBits::allRejected, extendedVoteBitsData.empty); BOOST_CHECK_EQUAL(we.code, CWalletError::INVALID_PARAMETER); // block height std::tie(voteHashStr, we) = wallet->Vote(chainActive.Tip()->GetBlockHash(), chainActive.Tip()->GetBlockHash(), chainActive.Tip()->nHeight - 1, VoteBits::allRejected, extendedVoteBitsData.empty); BOOST_CHECK_EQUAL(we.code, CWalletError::INVALID_PARAMETER); std::tie(voteHashStr, we) = wallet->Vote(chainActive.Tip()->GetBlockHash(), chainActive.Tip()->GetBlockHash(), chainActive.Tip()->nHeight + 1, VoteBits::allRejected, extendedVoteBitsData.empty); BOOST_CHECK_EQUAL(we.code, CWalletError::INVALID_PARAMETER); // ticket std::tie(voteHashStr, we) = wallet->Vote(chainActive.Tip()->GetBlockHash(), chainActive.Tip()->GetBlockHash(), chainActive.Tip()->nHeight, VoteBits::allRejected, extendedVoteBitsData.empty); BOOST_CHECK_EQUAL(we.code, CWalletError::INVALID_ADDRESS_OR_KEY); } // Single vote { BOOST_CHECK(chainActive.Tip()->pstakeNode->Winners().size() > 0); const uint256 ticketHash = chainActive.Tip()->pstakeNode->Winners()[0]; BOOST_CHECK(ticketHash != emptyData.hash); std::tie(voteHashStr, we) = wallet->Vote(ticketHash, chainActive.Tip()->GetBlockHash(), chainActive.Tip()->nHeight, VoteBits::rttAccepted, extendedVoteBitsData.empty); BOOST_CHECK_EQUAL(we.code, CWalletError::SUCCESSFUL); BOOST_CHECK(voteHashStr.length() > 0); const uint256& voteHash = uint256S(voteHashStr); BOOST_CHECK(MempoolHasVoteForTicket(ticketHash)); const CWalletTx* ticket = wallet->GetWalletTx(ticketHash); BOOST_CHECK(ticket != nullptr); BOOST_CHECK(ticket->tx != nullptr); const CWalletTx* vote = wallet->GetWalletTx(voteHash); BOOST_CHECK(vote != nullptr); BOOST_CHECK(vote->tx != nullptr); CheckVote(*vote->tx, *ticket->tx); ExtendChain(1); BOOST_CHECK(std::find_if(votesInLastBlock.begin(), votesInLastBlock.end(), [&voteHash](const CTransactionRef tx) { return tx->GetHash() == voteHash; }) != votesInLastBlock.end()); } // Multiple votes { BOOST_CHECK(chainActive.Tip()->pstakeNode->Winners().size() > 0); std::vector<uint256> voteHashes; for (const uint256& ticketHash : chainActive.Tip()->pstakeNode->Winners()) { BOOST_CHECK(ticketHash != emptyData.hash); std::tie(voteHashStr, we) = wallet->Vote(ticketHash, chainActive.Tip()->GetBlockHash(), chainActive.Tip()->nHeight, VoteBits::rttAccepted, extendedVoteBitsData.empty); BOOST_CHECK_EQUAL(we.code, CWalletError::SUCCESSFUL); BOOST_CHECK(voteHashStr.length() > 0); const uint256 voteHash = uint256S(voteHashStr); BOOST_CHECK(MempoolHasVoteForTicket(ticketHash)); const CWalletTx* ticket = wallet->GetWalletTx(ticketHash); BOOST_CHECK(ticket != nullptr); BOOST_CHECK(ticket->tx != nullptr); const CWalletTx* vote = wallet->GetWalletTx(voteHash); BOOST_CHECK(vote != nullptr); BOOST_CHECK(vote->tx != nullptr); CheckVote(*vote->tx, *ticket->tx); voteHashes.push_back(voteHash); } ExtendChain(1); for (const uint256& voteHash : voteHashes) BOOST_CHECK(std::find_if(votesInLastBlock.begin(), votesInLastBlock.end(), [&voteHash](const CTransactionRef tx) { return tx->GetHash() == voteHash; }) != votesInLastBlock.end()); } // Encrypted wallet { wallet->EncryptWallet(passphrase); BOOST_CHECK(wallet->IsLocked()); const uint256 ticketHash = chainActive.Tip()->pstakeNode->Winners()[0]; BOOST_CHECK(ticketHash != emptyData.hash); std::tie(voteHashStr, we) = wallet->Vote(ticketHash, chainActive.Tip()->GetBlockHash(), chainActive.Tip()->nHeight, VoteBits::rttAccepted, extendedVoteBitsData.empty); BOOST_CHECK_EQUAL(we.code, CWalletError::WALLET_UNLOCK_NEEDED); } } // test the transaction for votes with VSP support BOOST_FIXTURE_TEST_CASE(vote_transaction_vsp, WalletStakeTestingSetup) { std::string voteHashStr; CWalletError we; LOCK2(cs_main, wallet->cs_wallet); ExtendChain(consensus.nStakeValidationHeight - chainActive.Height(), true, true); BOOST_CHECK(chainActive.Tip()->pstakeNode->Winners().size() > 0); std::vector<uint256> voteHashes; for (const uint256& ticketHash : chainActive.Tip()->pstakeNode->Winners()) { BOOST_CHECK(ticketHash != emptyData.hash); std::tie(voteHashStr, we) = wallet->Vote(ticketHash, chainActive.Tip()->GetBlockHash(), chainActive.Tip()->nHeight, VoteBits::rttAccepted, extendedVoteBitsData.empty); BOOST_CHECK_EQUAL(we.code, CWalletError::SUCCESSFUL); BOOST_CHECK(voteHashStr.length() > 0); const uint256 voteHash = uint256S(voteHashStr); BOOST_CHECK(MempoolHasVoteForTicket(ticketHash)); const CWalletTx* ticket = wallet->GetWalletTx(ticketHash); BOOST_CHECK(ticket != nullptr); BOOST_CHECK(ticket->tx != nullptr); const CWalletTx* vote = wallet->GetWalletTx(voteHash); BOOST_CHECK(vote != nullptr); BOOST_CHECK(vote->tx != nullptr); CheckVote(*vote->tx, *ticket->tx); voteHashes.push_back(voteHash); } ExtendChain(1); for (const uint256& voteHash : voteHashes) BOOST_CHECK(std::find_if(votesInLastBlock.begin(), votesInLastBlock.end(), [&voteHash](const CTransactionRef tx) { return tx->GetHash() == voteHash; }) != votesInLastBlock.end()); } // test the failing transaction for votes that spend ticket not belonging to the wallet BOOST_FIXTURE_TEST_CASE(foreign_ticket_vote_transaction, WalletStakeTestingSetup) { std::string txHash; CWalletError we; LOCK2(cs_main, wallet->cs_wallet); ExtendChain(consensus.nStakeValidationHeight - 1 - chainActive.Tip()->nHeight, true, false, true); BOOST_CHECK_GT(chainActive.Tip()->pstakeNode->Winners().size(), 0U); for (auto& hash : chainActive.Tip()->pstakeNode->Winners()) { std::tie(txHash, we) = wallet->Vote(hash, chainActive.Tip()->GetBlockHash(), chainActive.Tip()->nHeight, VoteBits::allRejected, extendedVoteBitsData.empty); BOOST_CHECK_EQUAL(we.code, CWalletError::INVALID_ADDRESS_OR_KEY); } } // test the failing transaction for votes that spend ticket not belonging to the wallet and using VSP BOOST_FIXTURE_TEST_CASE(foreign_vsp_ticket_vote_transaction, WalletStakeTestingSetup) { std::string txHash; CWalletError we; LOCK2(cs_main, wallet->cs_wallet); ExtendChain(consensus.nStakeValidationHeight - 1 - chainActive.Tip()->nHeight, true, true, true); BOOST_CHECK_GT(chainActive.Tip()->pstakeNode->Winners().size(), 0U); for (auto& hash : chainActive.Tip()->pstakeNode->Winners()) { std::tie(txHash, we) = wallet->Vote(hash, chainActive.Tip()->GetBlockHash(), chainActive.Tip()->nHeight, VoteBits::allRejected, extendedVoteBitsData.empty); BOOST_CHECK_EQUAL(we.code, CWalletError::INVALID_ADDRESS_OR_KEY); } } // test the automatic voter BOOST_FIXTURE_TEST_CASE(auto_voter, WalletStakeTestingSetup) { LOCK2(cs_main, wallet->cs_wallet); CAutoVoter* av = wallet->GetAutoVoter(); BOOST_CHECK(av != nullptr); BOOST_CHECK(!av->isStarted()); CAutoVoterConfig& cfg = av->GetConfig(); // Premature votes and preconditions av->start(); ExtendChain(1); BOOST_CHECK(votesInLastBlock.size() == 0U); ExtendChain(1); BOOST_CHECK(votesInLastBlock.size() == 0U); av->stop(); ExtendChain(consensus.nStakeValidationHeight - chainActive.Height()); av->start(); // All tickets (in mempool) ExtendChain(1); CheckLatestVotes(true); // All tickets (in blockchain) (from previous extension) ExtendChain(1, false); CheckLatestVotes(); // Encrypted wallet (no passphrase) wallet->EncryptWallet(passphrase); BOOST_CHECK(wallet->IsLocked()); ExtendChain(1, false); // (from previous extension) BOOST_CHECK(ExtendChain(1, false) == false); BOOST_CHECK(votesInLastBlock.size() == 0U); // Encrypted wallet (wrong passphrase) cfg.passphrase = "aWr0ngP4$$word"; BOOST_CHECK(ExtendChain(1, false) == false); BOOST_CHECK(votesInLastBlock.size() == 0U); // Encrypted wallet (good passphrase) cfg.passphrase = passphrase; ExtendChain(1); BOOST_CHECK(votesInLastBlock.size() > 0U); CheckLatestVotes(true); BOOST_CHECK(ExtendChain(1, false)); BOOST_CHECK(votesInLastBlock.size() > 0U); CheckLatestVotes(); av->stop(); } // test the automatic voter with VSP support BOOST_FIXTURE_TEST_CASE(auto_voter_vsp, WalletStakeTestingSetup) { LOCK2(cs_main, wallet->cs_wallet); CAutoVoter* av = wallet->GetAutoVoter(); BOOST_CHECK(av != nullptr); BOOST_CHECK(!av->isStarted()); CAutoVoterConfig& cfg = av->GetConfig(); // Premature votes and preconditions ExtendChain(consensus.nStakeValidationHeight - chainActive.Height(), true, true); av->start(); // All tickets (in mempool) ExtendChain(1, true, true); CheckLatestVotes(true); // All tickets (in blockchain) (from previous extension) ExtendChain(1, false, true); CheckLatestVotes(); // Encrypted wallet (no passphrase) wallet->EncryptWallet(passphrase); BOOST_CHECK(wallet->IsLocked()); ExtendChain(1, false); // (from previous extension) BOOST_CHECK(ExtendChain(1, false, true) == false); BOOST_CHECK(votesInLastBlock.size() == 0U); // Encrypted wallet (wrong passphrase) cfg.passphrase = "aWr0ngP4$$word"; BOOST_CHECK(ExtendChain(1, false, true) == false); BOOST_CHECK(votesInLastBlock.size() == 0U); // Encrypted wallet (good passphrase) cfg.passphrase = passphrase; ExtendChain(1, true, true); BOOST_CHECK(votesInLastBlock.size() > 0U); CheckLatestVotes(true); BOOST_CHECK(ExtendChain(1, false, true)); BOOST_CHECK(votesInLastBlock.size() > 0U); CheckLatestVotes(); av->stop(); } // test the vote generating RPC BOOST_FIXTURE_TEST_CASE(generate_vote_rpc, WalletStakeTestingSetup) { vpwallets.insert(vpwallets.begin(), wallet.get()); RegisterWalletRPCCommands(tableRPC); ExtendChain(consensus.nStakeValidationHeight - 1 - chainActive.Tip()->nHeight); uint256 blockHash = chainActive.Tip()->GetBlockHash(); std::string blockHashStr = blockHash.GetHex(); int blockHeight = chainActive.Tip()->nHeight; std::string blockHeightStr = std::to_string(blockHeight); BOOST_CHECK_EQUAL(chainActive.Tip()->pstakeNode->Winners().size(), consensus.nTicketsPerBlock); uint256 ticketHash = chainActive.Tip()->pstakeNode->Winners()[0]; std::string ticketHashStr = ticketHash.GetHex(); // missing required parameters BOOST_CHECK_THROW(CallRpc(std::string("generatevote")), std::runtime_error); BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + blockHashStr), std::runtime_error); BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + blockHashStr + " " + blockHeightStr), std::runtime_error); BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + blockHashStr + " " + blockHeightStr + " " + ticketHashStr), std::runtime_error); // block hash BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + "0" + " " + blockHeightStr + " " + ticketHashStr + " " + "1"), std::runtime_error); BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + "test" + " " + blockHeightStr + " " + ticketHashStr + " " + "1"), std::runtime_error); BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + "abc!" + " " + blockHeightStr + " " + ticketHashStr + " " + "1"), std::runtime_error); BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + "123" + " " + blockHeightStr + " " + ticketHashStr + " " + "1"), std::runtime_error); // block height BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + blockHashStr + " " + "0" + " " + ticketHashStr + " " + "1"), std::runtime_error); BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + blockHashStr + " " + "test" + " " + ticketHashStr + " " + "1"), std::runtime_error); BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + blockHashStr + " " + "abc!" + " " + ticketHashStr + " " + "1"), std::runtime_error); BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + blockHashStr + " " + "123" + " " + ticketHashStr + " " + "1"), std::runtime_error); // ticket hash BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + blockHashStr + " " + blockHeightStr + " " + "0" + " " + "1"), std::runtime_error); BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + blockHashStr + " " + blockHeightStr + " " + "test" + " " + "1"), std::runtime_error); BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + blockHashStr + " " + blockHeightStr + " " + "abc!" + " " + "1"), std::runtime_error); BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + blockHashStr + " " + blockHeightStr + " " + "123" + " " + "1"), std::runtime_error); // vote bits BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + blockHashStr + " " + blockHeightStr + " " + ticketHashStr + " " + "-1"), std::runtime_error); BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + blockHashStr + " " + blockHeightStr + " " + ticketHashStr + " " + "65536"), std::runtime_error); BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + blockHashStr + " " + blockHeightStr + " " + ticketHashStr + " " + "test"), std::runtime_error); BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + blockHashStr + " " + blockHeightStr + " " + ticketHashStr + " " + "abc!"), std::runtime_error); // vote yes UniValue r; BOOST_CHECK_NO_THROW(r = CallRpc(std::string("generatevote ") + blockHashStr + " " + blockHeightStr + " " + ticketHashStr + " " + "1")); BOOST_CHECK(find_value(r.get_obj(), "hex").isStr()); uint256 voteHash = uint256S(find_value(r.get_obj(), "hex").get_str()); CheckVote(voteHash, ticketHash, VoteData{1, blockHash, static_cast<uint32_t>(blockHeight), VoteBits::rttAccepted, 0, extendedVoteBitsData.empty}); // vote no ticketHash = chainActive.Tip()->pstakeNode->Winners()[1]; ticketHashStr = ticketHash.GetHex(); BOOST_CHECK_NO_THROW(r = CallRpc(std::string("generatevote ") + blockHashStr + " " + blockHeightStr + " " + ticketHashStr + " " + "0")); voteHash = uint256S(find_value(r.get_obj(), "hex").get_str()); CheckVote(voteHash, ticketHash, VoteData{1, blockHash, static_cast<uint32_t>(blockHeight), VoteBits::allRejected, 0, extendedVoteBitsData.empty}); // vote exhaustive ticketHash = chainActive.Tip()->pstakeNode->Winners()[2]; ticketHashStr = ticketHash.GetHex(); BOOST_CHECK_NO_THROW(r = CallRpc(std::string("generatevote ") + blockHashStr + " " + blockHeightStr + " " + ticketHashStr + " " + "65535")); voteHash = uint256S(find_value(r.get_obj(), "hex").get_str()); CheckVote(voteHash, ticketHash, VoteData{1, blockHash, static_cast<uint32_t>(blockHeight), VoteBits(65535U), 0, extendedVoteBitsData.empty}); // extended vote bits ticketHash = chainActive.Tip()->pstakeNode->Winners()[3]; ticketHashStr = ticketHash.GetHex(); BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + blockHashStr + " " + blockHeightStr + " " + ticketHashStr + " " + "1" + " " + "0"), std::runtime_error); BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + blockHashStr + " " + blockHeightStr + " " + ticketHashStr + " " + "1" + " " + "1"), std::runtime_error); BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + blockHashStr + " " + blockHeightStr + " " + ticketHashStr + " " + "1" + " " + "123"), std::runtime_error); BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + blockHashStr + " " + blockHeightStr + " " + ticketHashStr + " " + "1" + " " + "abcde"), std::runtime_error); BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + blockHashStr + " " + blockHeightStr + " " + ticketHashStr + " " + "1" + " " + "test"), std::runtime_error); BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + blockHashStr + " " + blockHeightStr + " " + ticketHashStr + " " + "1" + " " + "abc!"), std::runtime_error); BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + blockHashStr + " " + blockHeightStr + " " + ticketHashStr + " " + "1" + " " + extendedVoteBitsData.invalidLargeString), std::runtime_error); BOOST_CHECK_NO_THROW(r = CallRpc(std::string("generatevote ") + blockHashStr + " " + blockHeightStr + " " + ticketHashStr + " " + "1" + " " + "1234567890abcdef")); voteHash = uint256S(find_value(r.get_obj(), "hex").get_str()); CheckVote(voteHash, ticketHash, VoteData{1, blockHash, static_cast<uint32_t>(blockHeight), VoteBits::rttAccepted, 0, ExtendedVoteBits("1234567890abcdef")}); ticketHash = chainActive.Tip()->pstakeNode->Winners()[4]; ticketHashStr = ticketHash.GetHex(); BOOST_CHECK_NO_THROW(r = CallRpc(std::string("generatevote ") + blockHashStr + " " + blockHeightStr + " " + ticketHashStr + " " + "1" + " " + extendedVoteBitsData.validLargeString)); voteHash = uint256S(find_value(r.get_obj(), "hex").get_str()); CheckVote(voteHash, ticketHash, VoteData{1, blockHash, static_cast<uint32_t>(blockHeight), VoteBits::rttAccepted, 0, ExtendedVoteBits(extendedVoteBitsData.validLargeString)}); // encrypted wallet wallet->EncryptWallet(passphrase); BOOST_CHECK(wallet->IsLocked()); ExtendChain(1); blockHash = chainActive.Tip()->GetBlockHash(); blockHashStr = blockHash.GetHex(); blockHeight = chainActive.Tip()->nHeight; blockHeightStr = std::to_string(blockHeight); BOOST_CHECK_EQUAL(chainActive.Tip()->pstakeNode->Winners().size(), consensus.nTicketsPerBlock); ticketHash = chainActive.Tip()->pstakeNode->Winners()[0]; ticketHashStr = ticketHash.GetHex(); BOOST_CHECK_THROW(CallRpc(std::string("generatevote ") + blockHashStr + " " + blockHeightStr + " " + ticketHashStr + " " + "1" + " " + extendedVoteBitsData.empty.getHex()), std::runtime_error); vpwallets.erase(std::remove(vpwallets.begin(), vpwallets.end(), wallet.get()), vpwallets.end()); } // test the automatic voter RPCs BOOST_FIXTURE_TEST_CASE(auto_voter_rpc, WalletStakeTestingSetup) { vpwallets.insert(vpwallets.begin(), wallet.get()); RegisterWalletRPCCommands(tableRPC); CPubKey ticketPubKey; BOOST_CHECK(wallet->GetKeyFromPool(ticketPubKey)); CTxDestination ticketKeyId = ticketPubKey.GetID(); std::string ticketAddress{EncodeDestination(ticketKeyId)}; CPubKey vspPubKey; BOOST_CHECK(wallet->GetKeyFromPool(vspPubKey)); CTxDestination vspKeyId = vspPubKey.GetID(); std::string vspAddress{EncodeDestination(vspKeyId)}; CAutoVoter* av = wallet->GetAutoVoter(); BOOST_CHECK(av != nullptr); BOOST_CHECK(!av->isStarted()); CAutoVoterConfig& cfg = av->GetConfig(); // Settings (write) BOOST_CHECK_THROW(CallRpc("setautovotervotebits"), std::runtime_error); BOOST_CHECK_THROW(CallRpc("setautovotervotebits abc"), std::runtime_error); BOOST_CHECK_THROW(CallRpc("setautovotervotebits -1"), std::runtime_error); BOOST_CHECK_THROW(CallRpc("setautovotervotebits 65536"), std::runtime_error); BOOST_CHECK_NO_THROW(CallRpc("setautovotervotebits 0")); BOOST_CHECK(cfg.voteBits == VoteBits(0U)); BOOST_CHECK_NO_THROW(CallRpc("setautovotervotebits 1234")); BOOST_CHECK(cfg.voteBits == VoteBits(1234U)); BOOST_CHECK_NO_THROW(CallRpc("setautovotervotebits 65535")); BOOST_CHECK(cfg.voteBits == VoteBits(65535U)); BOOST_CHECK_NO_THROW(CallRpc("setautovotervotebits 1")); BOOST_CHECK(cfg.voteBits == VoteBits(1U)); BOOST_CHECK_THROW(CallRpc("setautovotervotebitsext"), std::runtime_error); BOOST_CHECK_THROW(CallRpc("setautovotervotebitsext "), std::runtime_error); BOOST_CHECK_THROW(CallRpc("setautovotervotebitsext "), std::runtime_error); std::string largeExtendedVoteBits; for (unsigned i = 0; i <= ExtendedVoteBits::maxSize(); ++i) largeExtendedVoteBits += "00"; BOOST_CHECK_THROW(CallRpc("setautovotervotebitsext " + largeExtendedVoteBits), std::runtime_error); BOOST_CHECK(cfg.extendedVoteBits == extendedVoteBitsData.empty); BOOST_CHECK_NO_THROW(CallRpc("setautovotervotebitsext 00")); BOOST_CHECK(cfg.extendedVoteBits == ExtendedVoteBits("00")); BOOST_CHECK_NO_THROW(CallRpc("setautovotervotebitsext 1234")); BOOST_CHECK(cfg.extendedVoteBits == ExtendedVoteBits("1234")); BOOST_CHECK_NO_THROW(CallRpc("setautovotervotebitsext 12345678900abcdef0")); BOOST_CHECK(cfg.extendedVoteBits == ExtendedVoteBits("12345678900abcdef0")); BOOST_CHECK(cfg.voteBits == VoteBits(1U)); BOOST_CHECK(cfg.extendedVoteBits == ExtendedVoteBits("12345678900abcdef0")); BOOST_CHECK_EQUAL(cfg.passphrase, ""); // Settings (read) UniValue r; BOOST_CHECK_NO_THROW(r = CallRpc("autovoterconfig")); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "autovote").get_bool(), false); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "votebits").get_int(), 1); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "votebitsext").get_str(), "12345678900abcdef0"); // Start (with minimal settings) BOOST_CHECK_THROW(CallRpc("startautovoter"), std::runtime_error); BOOST_CHECK_THROW(CallRpc("startautovoter \"\""), std::runtime_error); BOOST_CHECK_NO_THROW(CallRpc("startautovoter 65535")); BOOST_CHECK_EQUAL(cfg.autoVote, true); BOOST_CHECK(cfg.voteBits == VoteBits(65535U)); BOOST_CHECK(cfg.extendedVoteBits == extendedVoteBitsData.empty); BOOST_CHECK_EQUAL(cfg.passphrase, ""); // Start (with full settings) av->stop(); BOOST_CHECK_EQUAL(cfg.autoVote, false); BOOST_CHECK_NO_THROW(CallRpc("startautovoter 1234 123456789abcdef0")); BOOST_CHECK_EQUAL(cfg.autoVote, true); BOOST_CHECK(cfg.voteBits == VoteBits(1234U)); BOOST_CHECK(cfg.extendedVoteBits == ExtendedVoteBits("123456789abcdef0")); BOOST_CHECK_EQUAL(cfg.passphrase, ""); // Stop BOOST_CHECK_NO_THROW(CallRpc("stopautovoter")); BOOST_CHECK_EQUAL(cfg.autoVote, false); // Start with passphrase wallet->EncryptWallet(passphrase); BOOST_CHECK(wallet->IsLocked()); BOOST_CHECK_THROW(CallRpc("startautovoter 1234 123456789abcdef0"), std::runtime_error); BOOST_CHECK_THROW(CallRpc("startautovoter 1234 123456789abcdef0 wrongP4ssword!"), std::runtime_error); BOOST_CHECK_NO_THROW(CallRpc(std::string("startautovoter 1 123456789abcdef0 ") + std::string(passphrase.c_str()))); BOOST_CHECK_EQUAL(cfg.autoVote, true); BOOST_CHECK(cfg.voteBits == VoteBits(1U)); BOOST_CHECK(cfg.extendedVoteBits == ExtendedVoteBits("123456789abcdef0")); BOOST_CHECK_EQUAL(cfg.passphrase, passphrase); av->stop(); BOOST_CHECK_EQUAL(cfg.autoVote, false); BOOST_CHECK_NO_THROW(CallRpc(std::string("startautovoter 1 ") + std::string(passphrase.c_str()))); BOOST_CHECK_EQUAL(cfg.autoVote, true); BOOST_CHECK(cfg.voteBits == VoteBits(1U)); BOOST_CHECK(cfg.extendedVoteBits == extendedVoteBitsData.empty); BOOST_CHECK_EQUAL(cfg.passphrase, passphrase); av->stop(); vpwallets.erase(std::remove(vpwallets.begin(), vpwallets.end(), wallet.get()), vpwallets.end()); } BOOST_AUTO_TEST_SUITE_END()
999ffed004f3fc715a79c7afbbadbaac29091cd6
65a469abb753dc9647fa5488fd65223b3c0c2ec3
/동빈나/chapter13_DFS_BFS/16.cpp
20407638c2e432b9719d480ad7b80b0e34db6741
[]
no_license
namgonkim/DS_Algorithms
735fbd2ebe8c5b62491cf8ec3fd2051051fb442b
18b8e1050ce881c7d9a09d062ccb6edd46e63ba1
refs/heads/master
2022-03-08T18:57:54.418824
2022-02-23T06:43:57
2022-02-23T06:43:57
245,596,477
1
0
null
null
null
null
UTF-8
C++
false
false
2,303
cpp
#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<vector> #include<algorithm> #include<queue> #include<utility> #include<stdio.h> #include<string> #include<stack> /* 제목: 연구소 문제: NxM크기의 연구소에서 바이러스를 피해 안전한 영역 크기의 최대값을 구하는 프로그램 유형: DFS 날짜: 2021-05-17 이름: @namgonkim */ using namespace std; int n, m; // 세로 n 가로 m vector<vector<int>> graph; int dx[4] = { 0,0,-1,1 }; int dy[4] = { -1,1,0,0 }; vector<vector<int>> map; int result = 0; // 최대로 안전한 영역 결과값 // 바이러스 확산에 대한 dfs알고리즘 void dfs(int y, int x) { for (int i = 0; i < 4; i++) { int ny = y + dy[i]; int nx = x + dx[i]; // 상하좌우 탐색해 바이러스 확산 if (nx >= 0 && nx < m && ny >= 0 && ny < n) { if (map[ny][nx] == 0) { map[ny][nx] = 2; // 인접한 방에 대해서도 dfs dfs(ny, nx); } } } } // 벽을 세울 수 있는 모든 경우의 수를 고려하면서, 벽3개를 세우면 DFS를 통해 안전한 영역의 크기를 구하고, 이 과정의 전체 중 가장 영역이 큰 값을 출력한다. void solution(int count) { // 벽을 3개 다 세우면 안전한 영역 찾기 진행 if (count == 3) { // DFS 진행할 임시 그래프 초기화 및 세팅 map.resize(n + 1, vector<int>(m + 1, 0)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { map[i][j] = graph[i][j]; } } // 바이러스에 대한 DFS 진행 for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (map[i][j] == 2) { dfs(i, j); } } } // 해당 그래프에 대한 안전한 영역 int safe = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (map[i][j] == 0) { safe += 1; } } } result = max(result, safe); return; } // 벽 세우기 for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (graph[i][j] == 0) { graph[i][j] = 1; count += 1; solution(count); graph[i][j] = 0; count -= 1; } } } } int main() { cin >> n >> m; graph.resize(n, vector<int>(m, 0)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> graph[i][j]; } } solution(0); cout << result << endl; }
920f5cf21e3b8e3e44bacd048db74483b8abb0e9
9b48ac2884fb28e188bca0644c3ef48482d43825
/vcmap/ch06/ArchiveTest/mfc-person.cpp
b4e3bdbb40980aaee44cbbfd067b4d98e421bf4c
[]
no_license
skyformat99/mybooks
3a4f6cc37cd10624d21693bc22d1d0be93c03509
d0a04f3b1ba271225b6fc23cf8e6d06a88828c09
refs/heads/master
2020-03-19T03:58:35.895559
2018-05-31T05:49:18
2018-05-31T05:49:18
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
845
cpp
#include "stdafx.h" #include "mfc-person.h" IMPLEMENT_SERIAL(CPerson, CObject, 1) CPerson::CPerson() { _name = _T("ÎÞÃûÊÏ"); _age = 0; _gender = true; } CPerson::CPerson(CString name, int age, bool gender) { _name = name; _age = age; _gender = gender; } CString CPerson::getName() { return _name; } CString CPerson::getWords() { return _words; } void CPerson::setWords(CString words) { _words = words; } int CPerson::getAge() { return _age; } bool CPerson::isMale() { return _gender; } void CPerson::say() { say(_words); } void CPerson::say(CString msg) { _tprintf(_T("%s: %s\r\n"), _name, msg); } void CPerson::Serialize(CArchive& ar) { if (ar.IsStoring()) { ar << this->_name << this->_age << this->_gender << this->_words; } else { ar >> this->_name >> this->_age >> this->_gender >> this->_words; } }
e96f64558bc61b93df98dff0793122553428695a
0d346794e50d38d5183f6cab186144afab4ecee2
/QueryApplication/QueryResult.cpp
5c64dea3252b0b5b0d2ff64e748c09f008d34bd3
[]
no_license
dhwgithub/Graduate_Study_Notes
3af98084e9421cdd113b76a595100494839f2065
c8ceed353b5a915606df1bdccc2f6adddfc10ca9
refs/heads/main
2023-07-12T12:42:26.625492
2021-08-25T02:05:50
2021-08-25T02:05:50
312,781,506
0
0
null
null
null
null
GB18030
C++
false
false
354
cpp
#include "QueryResult.h" ostream& print(ostream& os, const QueryResult& qr) { os << qr.sought << " occors " << qr.lines->size() << " " << " times " << endl;//输出关键词和出现次数 for (auto num : *qr.lines) { os << " \t(line " << num + 1 << ")" << *(qr.file->begin() + num) << endl;//输出关键词所在行 } return os; }
423d178c3a91132b0448935d2c6c67d4a02b2e41
fdf75801d87357e459de29f6507e3351ab17a77f
/Helper/main.cpp
44e61ae2d48244d2cb25ab5e277c31830a9000f0
[]
no_license
alate/Helper
deb81f73a19092eea95d6c308226f4b5f0b84a01
349dd6fbbaab070f47659596f2bed95c85216fbc
refs/heads/master
2020-05-17T00:38:59.899775
2015-01-12T06:04:03
2015-01-12T06:04:03
29,077,527
0
0
null
null
null
null
UTF-8
C++
false
false
176
cpp
#include "helperdialog.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); HelperDialog w; w.show(); return a.exec(); }
6487fd03440e1de67eee966edb3efd0d5eae5942
a5f0dcefc642a63b46fbeccbf96cdae4177194d6
/UVA/UVA10935.cpp
57b430dc7a710d266a4dd08983ebe6b55b413c38
[]
no_license
caffeines/CPPS
e7808a55136604c6ecba61642553f82daa99e164
f63b1892fb458b0e7438d18576e99175c21c4c41
refs/heads/master
2021-06-26T00:24:57.403001
2019-04-21T10:43:51
2019-04-21T10:43:51
113,913,848
2
1
null
null
null
null
UTF-8
C++
false
false
1,484
cpp
#include <bits/stdc++.h> using namespace std; #define ll long long #define f first #define s second #define pb push_back #define mp make_pair #define sq(a) (a)*(a) #define pl printf("\n"); #define pf(n) printf("%d",n) #define sf(n) scanf("%d",&n) #define sff(a,b) scanf("%d %d",&a,&b); #define sfff(a,b,c) scanf("%d %d %d",&a,&b,&c); #define INF (numeric_limits<int>::max()) #define kase(i,b) for(int i=1;i<=b;i++) #define asize(arr) (sizeof(arr)/sizeof(arr[0])) #define mem(arr) memset(arr,0,sizeof(arr)); #define KASE(a) printf("Case %d: ",a); #define gcd(x,y) __gcd(abs(x),abs(y)) #define lcm(x,y) ((abs(x)/gcd(x,y))*abs(y)) #define N 10000020 int main() { //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); int n; while(cin>>n && n!=0) { vector <int> dc; list<int> card; for(int i=1;i<=n;i++) card.push_back(i); while(card.size()>1) { int s = card.front(); dc.pb(s); card.pop_front(); s = card.front(); card.pop_front(); card.push_back(s); } if(dc.size()==0) cout<<"Discarded cards:"; else cout<<"Discarded cards: "; for(int i=0;i<dc.size();i++) { if(i+1 < dc.size()) cout<<dc[i]<<", "; else cout<<dc[i]; } cout<<endl<<"Remaining card: "<<card.front()<<endl; } return 0; }
311e9146aec0c7b765e8e5efd0d0423f9c7c05bc
d0fb46aecc3b69983e7f6244331a81dff42d9595
/dyvmsapi/src/model/ReportVoipProblemsResult.cc
dec842c9bbe62d053713f22361af18db1b7880ed
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-cpp-sdk
3d8d051d44ad00753a429817dd03957614c0c66a
e862bd03c844bcb7ccaa90571bceaa2802c7f135
refs/heads/master
2023-08-29T11:54:00.525102
2023-08-29T03:32:48
2023-08-29T03:32:48
115,379,460
104
82
NOASSERTION
2023-09-14T06:13:33
2017-12-26T02:53:27
C++
UTF-8
C++
false
false
1,689
cc
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/dyvmsapi/model/ReportVoipProblemsResult.h> #include <json/json.h> using namespace AlibabaCloud::Dyvmsapi; using namespace AlibabaCloud::Dyvmsapi::Model; ReportVoipProblemsResult::ReportVoipProblemsResult() : ServiceResult() {} ReportVoipProblemsResult::ReportVoipProblemsResult(const std::string &payload) : ServiceResult() { parse(payload); } ReportVoipProblemsResult::~ReportVoipProblemsResult() {} void ReportVoipProblemsResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); if(!value["Code"].isNull()) code_ = value["Code"].asString(); if(!value["Module"].isNull()) module_ = value["Module"].asString(); if(!value["Message"].isNull()) message_ = value["Message"].asString(); } std::string ReportVoipProblemsResult::getMessage()const { return message_; } std::string ReportVoipProblemsResult::getModule()const { return module_; } std::string ReportVoipProblemsResult::getCode()const { return code_; }
0e36ce72e49cd2cedbe51dd73a1f61b9045de001
fcf26223091a6e246f715ef3cac97d7da7d1df8d
/max_prob_class.h
b3995fa2d50eb7642405d3c26bf9af77c7cf500a
[]
no_license
PNapi90/Fuzzy-Bayes-Tracking
a9d8dd669da601540020aad756f4bc9437e02ae9
d15f884e21361f466a4f3dbd75397e8731de8ad3
refs/heads/master
2020-03-23T07:38:53.548590
2018-07-17T12:08:52
2018-07-17T12:08:52
141,283,365
1
0
null
null
null
null
UTF-8
C++
false
false
390
h
#ifndef MAX_PROB_H #define MAX_PROB_H 1 class max_prob_class{ private: double* return_arr; double** l2_peak; double** l2_sum; double** ent_peak; double** ent_sum; double** probs; double** sum_val; public: max_prob_class(); ~max_prob_class(); void store(double*,int,int); double get_prob(int,int); double get_sum(int,int); double* get_all_vals(int,int); }; #endif
3c7440e0d904ae267ae8ac0faca65a77cf28cabe
1f7b3d75141801742a884ba286de16b88602e2fa
/readv_writev/main.cpp
abfa7b62e6cff77c1159f071105beac34c128a8d
[]
no_license
sakishum/My_Linux
4b3720ac5d6c9ce9bff62cee13c70da9061b2ce0
39d8ac934b94858ac8d0730930e3467d4e3ee0a2
refs/heads/master
2021-01-22T04:10:19.097128
2017-02-10T00:26:26
2017-02-10T00:28:21
81,508,713
0
0
null
null
null
null
UTF-8
C++
false
false
2,212
cpp
/** * @file main.cpp * @Synopsis 散布读、写多个非连续的缓冲区。 * @author Saki Shum, [email protected] * @version 0.0.1 * @date 2015-06-02 */ #include <cstdlib> #include <cstdio> #include <iostream> #include <math.h> #include <sys/uio.h> // readv、writev #include <unistd.h> // STDIN_FILENO (0)、STDOUT_FILENO(1)、STDERR_FILENO(2) // 函数功能:读取多个非连续的缓冲区,或从多个非连续的缓冲区写数据到文件; // 返回值:若成功返回已读、写的字节数,若出错返回-1; // 函数原型: // size_t readv(int filedes, const struct iovec *iov, int iovecnt); // size_t writev(int filedes, const struct iovec *iov, int iovecnt); // filedes : 文件描述符 // iov : 指向 iovec 结构数组的一个指针 // iovecnt : 数组元素的个数 // // 说明: // iovec 的指针结构如下: // struct iovec { // void *iov_base; // starting address of buffer // size_t iov_len; // size of buffer // } // writev 以顺序 iov[0], iov[1] 至 iov[iovcnt - 1] 重缓冲区中聚集输出数据。 // writev 返回输出的字节总数。readv 则将读入的数据按照上述同样顺序散布到 // 缓冲区中,readv 总是先填满一个缓冲区,然后再填写下一个。readv 返回读到 // 的总字节数。如果遇到文件结尾,已无数据可读,则返回 0。 int main(void) { double x = 1.3f; std::cout << floor(x) << std::endl; std::cout << ceil(x) << std::endl; struct iovec iov[2]; char *buf1 = (char*)malloc(5); char *buf2 = (char*)malloc(1024); memset(buf1, 0, 5); memset(buf2, 0, 1024); iov[0].iov_base = buf1; iov[0].iov_len = 5; iov[1].iov_base = buf2; iov[1].iov_len = 1024; ssize_t nread = 0; ssize_t nwrite = 0; nread = readv(STDIN_FILENO, iov, 2); if (nread < 0) { perror("readv error."); } else { printf("readv:\n"); printf("buf1 is: %s\t length is: %zu\n", buf1, strlen(buf1)); printf("buf2 is: %s\t length is: %zu\n", buf2, strlen(buf2)); } printf("writev:\n"); nwrite = writev(STDOUT_FILENO, iov, 2); if (nwrite < 0) { perror("writev error."); } free(buf1); free(buf2); printf("readv and writev example from apue.\n"); return EXIT_SUCCESS; }
01e1f3c643f49f5686f19d6e8e6ae3c095cbf1f4
097b2a0f8e5cefbaff31790a359d267bd978e480
/Atcoder/ABC_s1/ABC_072/A-Sandglass_2.cpp
73c0ca4d479ef461d9e40b42886f8d500b2e9c5c
[]
no_license
Noiri/Competitive_Programming
39667ae94d6b167b4d7b9e78a98b8cb53ff1884f
25ec787f7f5a507f9d1713a1e88f198fd495ec01
refs/heads/master
2023-08-16T17:35:15.940860
2021-09-07T20:57:59
2021-09-07T20:57:59
161,947,108
0
0
null
null
null
null
UTF-8
C++
false
false
154
cpp
#include <bits/stdc++.h> using namespace std; int main(){ int x, t; cin >> x >> t; cout << ((x-t)<0?0:(x-t)) << endl; return 0; }
c535ac63d05d848cdee3af24395fda3bc9be1b24
90e02ef236ec48414dcdb5bd08665c865605f984
/src/cisst-saw/sawIntuitiveResearchKit/examples/deprecated/mainQtTeleOperationJSON.cpp
7b3c660621f486fe15693de63748ec3de2ade9d7
[]
no_license
NicholasDascanio/dvrk_moveit
3033ccda21d140a5feda0a7a42585c94784a1f13
4d23fa74f3663551791b958f96203f4196b1d765
refs/heads/master
2021-01-03T00:43:10.683504
2020-03-11T17:54:20
2020-03-11T17:54:20
239,836,095
1
0
null
null
null
null
UTF-8
C++
false
false
15,694
cpp
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* ex: set filetype=cpp softtabstop=4 shiftwidth=4 tabstop=4 cindent expandtab: */ /* Author(s): Zihan Chen, Anton Deguet Created on: 2013-02-07 (C) Copyright 2013-2015 Johns Hopkins University (JHU), All Rights Reserved. --- begin cisst license - do not edit --- This software is provided "as is" under an open source license, with no warranty. The complete license can be found in license.txt and http://www.cisst.org/cisst/license.txt. --- end cisst license --- */ // system #include <iostream> #include <map> // cisst/saw #include <cisstCommon/cmnGetChar.h> #include <cisstCommon/cmnPath.h> #include <cisstCommon/cmnCommandLineOptions.h> #include <cisstOSAbstraction/osaSleep.h> #include <cisstMultiTask/mtsQtApplication.h> #include <sawRobotIO1394/mtsRobotIO1394.h> #include <sawRobotIO1394/mtsRobotIO1394QtWidgetFactory.h> #include <sawControllers/mtsPIDQtWidget.h> #include <sawIntuitiveResearchKit/mtsIntuitiveResearchKitConsole.h> #include <sawIntuitiveResearchKit/mtsIntuitiveResearchKitConsoleQtWidget.h> #include <sawIntuitiveResearchKit/mtsIntuitiveResearchKitArmQtWidget.h> #include <sawIntuitiveResearchKit/mtsIntuitiveResearchKitUDPStreamer.h> #include <sawControllers/mtsTeleOperation.h> #include <sawControllers/mtsTeleOperationQtWidget.h> #include <cisstMultiTask/mtsCollectorFactory.h> #include <cisstMultiTask/mtsCollectorQtFactory.h> #include <cisstMultiTask/mtsCollectorQtWidget.h> #include <QTabWidget> #include <json/json.h> void fileExists(const std::string & description, const std::string & filename) { if (!cmnPath::Exists(filename)) { std::cerr << "File not found for " << description << ": " << filename << std::endl; exit(-1); } else { std::cout << "File found for " << description << ": " << filename << std::endl; } } int main(int argc, char ** argv) { // program deprecated std::cout << "-----------------------------------------------------------" << std::endl << "- This program is deprecated: -" << std::endl << "- use sawIntuitiveResearchKitQtConsoleJSON instead -" << std::endl << "- examples can be found in share/jhu-dVRK/console*.json -" << std::endl << "- Press any key to continue -" << std::endl << "-----------------------------------------------------------" << std::endl << std::endl; cmnGetChar(); // configuration const double periodIO = 0.5 * cmn_ms; const double periodKinematics = 1.0 * cmn_ms; const double periodTeleop = 1.0 * cmn_ms; const double periodUDP = 20.0 * cmn_ms; // log configuration cmnLogger::SetMask(CMN_LOG_ALLOW_ALL); cmnLogger::SetMaskDefaultLog(CMN_LOG_ALLOW_ALL); cmnLogger::SetMaskFunction(CMN_LOG_ALLOW_ALL); cmnLogger::SetMaskClassMatching("mtsIntuitiveResearchKit", CMN_LOG_ALLOW_ALL); cmnLogger::AddChannel(std::cerr, CMN_LOG_ALLOW_ERRORS_AND_WARNINGS); // parse options cmnCommandLineOptions options; int firewirePort = 0; std::string gcmip = "-1"; std::string jsonMainConfigFile; std::string jsonCollectionConfigFile; typedef std::map<std::string, std::string> ConfigFilesType; ConfigFilesType configFiles; std::string masterName, slaveName; options.AddOptionOneValue("j", "json-config", "json configuration file", cmnCommandLineOptions::REQUIRED_OPTION, &jsonMainConfigFile); options.AddOptionOneValue("f", "firewire", "firewire port number(s)", cmnCommandLineOptions::OPTIONAL_OPTION, &firewirePort); options.AddOptionOneValue("g", "gcmip", "global component manager IP address", cmnCommandLineOptions::OPTIONAL_OPTION, &gcmip); options.AddOptionOneValue("c", "collection-config", "json configuration file for data collection", cmnCommandLineOptions::OPTIONAL_OPTION, &jsonCollectionConfigFile); // check that all required options have been provided std::string errorMessage; if (!options.Parse(argc, argv, errorMessage)) { std::cerr << "Error: " << errorMessage << std::endl; options.PrintUsage(std::cerr); return -1; } std::string arguments; options.PrintParsedArguments(arguments); std::cout << "Options provided:" << std::endl << arguments << std::endl; // make sure the json config file exists and can be parsed fileExists("JSON configuration", jsonMainConfigFile); std::ifstream jsonStream; jsonStream.open(jsonMainConfigFile.c_str()); Json::Value jsonConfig; Json::Reader jsonReader; if (!jsonReader.parse(jsonStream, jsonConfig)) { std::cerr << "Error: failed to parse configuration\n" << jsonReader.getFormattedErrorMessages(); return -1; } // start initializing the cisstMultiTask manager std::cout << "FirewirePort: " << firewirePort << std::endl; std::string processname = "dvTeleop"; mtsManagerLocal * componentManager = 0; if (gcmip != "-1") { try { componentManager = mtsManagerLocal::GetInstance(gcmip, processname); } catch(...) { std::cerr << "Failed to get GCM instance." << std::endl; return -1; } } else { componentManager = mtsManagerLocal::GetInstance(); } // create a Qt application and tab to hold all widgets mtsQtApplication * qtAppTask = new mtsQtApplication("QtApplication", argc, argv); qtAppTask->Configure(); componentManager->AddComponent(qtAppTask); // console mtsIntuitiveResearchKitConsole * console = new mtsIntuitiveResearchKitConsole("console"); componentManager->AddComponent(console); mtsIntuitiveResearchKitConsoleQtWidget * consoleGUI = new mtsIntuitiveResearchKitConsoleQtWidget("consoleGUI"); componentManager->AddComponent(consoleGUI); // connect consoleGUI to console componentManager->Connect("console", "Main", "consoleGUI", "Main"); // organize all widgets in a tab widget QTabWidget * tabWidget = new QTabWidget; tabWidget->addTab(consoleGUI, "Main"); // IO is shared accross components mtsRobotIO1394 * io = new mtsRobotIO1394("io", periodIO, firewirePort); // find name of button event used to detect if operator is present std::string operatorPresentComponent = jsonConfig["operator-present"]["component"].asString(); std::string operatorPresentInterface = jsonConfig["operator-present"]["interface"].asString(); //set defaults if (operatorPresentComponent == "") { operatorPresentComponent = "io"; } if (operatorPresentInterface == "") { operatorPresentInterface = "COAG"; } std::cout << "Using \"" << operatorPresentComponent << "::" << operatorPresentInterface << "\" to detect if operator is present" << std::endl; // setup io defined in the json configuration file const Json::Value pairs = jsonConfig["pairs"]; for (unsigned int index = 0; index < pairs.size(); ++index) { // master Json::Value jsonMaster = pairs[index]["master"]; std::string armName = jsonMaster["name"].asString(); std::string ioFile = jsonMaster["io"].asString(); fileExists(armName + " IO", ioFile); io->Configure(ioFile); // slave Json::Value jsonSlave = pairs[index]["slave"]; armName = jsonSlave["name"].asString(); ioFile = jsonSlave["io"].asString(); fileExists(armName + " IO", ioFile); io->Configure(ioFile); } componentManager->AddComponent(io); // connect ioGUIMaster to io mtsRobotIO1394QtWidgetFactory * robotWidgetFactory = new mtsRobotIO1394QtWidgetFactory("robotWidgetFactory"); componentManager->AddComponent(robotWidgetFactory); componentManager->Connect("robotWidgetFactory", "RobotConfiguration", "io", "Configuration"); robotWidgetFactory->Configure(); // add all IO GUI to tab mtsRobotIO1394QtWidgetFactory::WidgetListType::const_iterator iterator; for (iterator = robotWidgetFactory->Widgets().begin(); iterator != robotWidgetFactory->Widgets().end(); ++iterator) { tabWidget->addTab(*iterator, (*iterator)->GetName().c_str()); } tabWidget->addTab(robotWidgetFactory->ButtonsWidget(), "Buttons"); // setup arms defined in the json configuration file for (unsigned int index = 0; index < pairs.size(); ++index) { Json::Value jsonMaster = pairs[index]["master"]; std::string masterName = jsonMaster["name"].asString(); std::string masterPIDFile = jsonMaster["pid"].asString(); std::string masterKinematicFile = jsonMaster["kinematic"].asString(); std::string masterUDPIP = jsonMaster["UDP-IP"].asString(); short masterUDPPort = jsonMaster["UDP-port"].asInt(); fileExists(masterName + " PID", masterPIDFile); fileExists(masterName + " kinematic", masterKinematicFile); mtsIntuitiveResearchKitConsole::Arm * mtm = new mtsIntuitiveResearchKitConsole::Arm(masterName, io->GetName()); mtm->ConfigurePID(masterPIDFile); mtm->ConfigureArm(mtsIntuitiveResearchKitConsole::Arm::ARM_MTM, masterKinematicFile, periodKinematics); console->AddArm(mtm); if (masterUDPIP != "" || masterUDPPort != 0) { if (masterUDPIP != "" && masterUDPPort != 0) { std::cout << "Adding UDPStream component for master " << masterName << " to " << masterUDPIP << ":" << masterUDPPort << std::endl; mtsIntuitiveResearchKitUDPStreamer * streamer = new mtsIntuitiveResearchKitUDPStreamer(masterName + "UDP", periodUDP, masterUDPIP, masterUDPPort); componentManager->AddComponent(streamer); // connect to mtm interface to get cartesian position componentManager->Connect(streamer->GetName(), "Robot", mtm->Name(), "Robot"); // connect to io to get clutch events componentManager->Connect(streamer->GetName(), "Clutch", "io", "CLUTCH"); // connect to io to get coag events componentManager->Connect(streamer->GetName(), "Coag", "io", "COAG"); } else { std::cerr << "Error for master arm " << masterName << ", you can provided UDP-IP w/o UDP-port" << std::endl; exit(-1); } } Json::Value jsonSlave = pairs[index]["slave"]; std::string slaveName = jsonSlave["name"].asString(); std::string slavePIDFile = jsonSlave["pid"].asString(); std::string slaveKinematicFile = jsonSlave["kinematic"].asString(); fileExists(slaveName + " PID", slavePIDFile); fileExists(slaveName + " kinematic", slaveKinematicFile); mtsIntuitiveResearchKitConsole::Arm * psm = new mtsIntuitiveResearchKitConsole::Arm(slaveName, io->GetName()); psm->ConfigurePID(slavePIDFile); psm->ConfigureArm(mtsIntuitiveResearchKitConsole::Arm::ARM_PSM, slaveKinematicFile, periodKinematics); console->AddArm(psm); // PID Master GUI std::string masterPIDName = masterName + " PID"; mtsPIDQtWidget * pidMasterGUI = new mtsPIDQtWidget(masterPIDName, 8); pidMasterGUI->Configure(); componentManager->AddComponent(pidMasterGUI); componentManager->Connect(pidMasterGUI->GetName(), "Controller", mtm->PIDComponentName(), "Controller"); tabWidget->addTab(pidMasterGUI, masterPIDName.c_str()); // PID Slave GUI std::string slavePIDName = slaveName + " PID"; mtsPIDQtWidget * pidSlaveGUI = new mtsPIDQtWidget(slavePIDName, 7); pidSlaveGUI->Configure(); componentManager->AddComponent(pidSlaveGUI); componentManager->Connect(pidSlaveGUI->GetName(), "Controller", psm->PIDComponentName(), "Controller"); tabWidget->addTab(pidSlaveGUI, slavePIDName.c_str()); // Master GUI mtsIntuitiveResearchKitArmQtWidget * masterGUI = new mtsIntuitiveResearchKitArmQtWidget(mtm->Name() + "GUI"); masterGUI->Configure(); componentManager->AddComponent(masterGUI); tabWidget->addTab(masterGUI, mtm->Name().c_str()); // connect masterGUI to master componentManager->Connect(masterGUI->GetName(), "Manipulator", mtm->Name(), "Robot"); // Slave GUI mtsIntuitiveResearchKitArmQtWidget * slaveGUI = new mtsIntuitiveResearchKitArmQtWidget(psm->Name() + "GUI"); slaveGUI->Configure(); componentManager->AddComponent(slaveGUI); tabWidget->addTab(slaveGUI, psm->Name().c_str()); // connect slaveGUI to slave componentManager->Connect(slaveGUI->GetName(), "Manipulator", psm->Name(), "Robot"); // Teleoperation std::string teleName = masterName + "-" + slaveName; mtsTeleOperationQtWidget * teleGUI = new mtsTeleOperationQtWidget(teleName + "GUI"); teleGUI->Configure(); componentManager->AddComponent(teleGUI); tabWidget->addTab(teleGUI, teleName.c_str()); mtsTeleOperation * tele = new mtsTeleOperation(teleName, periodTeleop); // Default orientation between master and slave vctMatRot3 master2slave; master2slave.From(vctAxAnRot3(vct3(0.0, 0.0, 1.0), 180.0 * cmnPI_180)); tele->SetRegistrationRotation(master2slave); componentManager->AddComponent(tele); console->AddTeleOperation(tele->GetName(), mtm->Name(), psm->Name()); } // add foot pedal interfaces console->AddFootpedalInterfaces(); // connect all components from the console console->Connect(); // configure data collection if needed if (options.IsSet("collection-config")) { // make sure the json config file exists fileExists("JSON data collection configuration", jsonCollectionConfigFile); mtsCollectorFactory * collectorFactory = new mtsCollectorFactory("collectors"); collectorFactory->Configure(jsonCollectionConfigFile); componentManager->AddComponent(collectorFactory); collectorFactory->Connect(); mtsCollectorQtWidget * collectorQtWidget = new mtsCollectorQtWidget(); tabWidget->addTab(collectorQtWidget, "Collection"); mtsCollectorQtFactory * collectorQtFactory = new mtsCollectorQtFactory("collectorsQt"); collectorQtFactory->SetFactory("collectors"); componentManager->AddComponent(collectorQtFactory); collectorQtFactory->Connect(); collectorQtFactory->ConnectToWidget(collectorQtWidget); } // show all widgets tabWidget->show(); //-------------- create the components ------------------ io->CreateAndWait(2.0 * cmn_s); // this will also create the pids as they are in same thread io->StartAndWait(2.0 * cmn_s); // start all other components componentManager->CreateAllAndWait(2.0 * cmn_s); componentManager->StartAllAndWait(2.0 * cmn_s); // QtApplication will run in main thread and return control // when exited. componentManager->KillAllAndWait(2.0 * cmn_s); componentManager->Cleanup(); // delete dvgc robot delete io; delete robotWidgetFactory; // stop all logs cmnLogger::Kill(); return 0; }
f0f65a021b28bd3ec950d46c3e193f192f7b67ac
e066903a0ff18033bca598291c67a141ec8626f5
/node_modules/opencv-build/opencv/build/modules/plot/opencv_plot_pch.cpp
b78ee227a2dbfc3487018094a5cdfda2bc9b54b0
[ "BSD-3-Clause" ]
permissive
nikeshkalu/2-Factor-Authentication
fe6b7a9c62844392c820f648c3cc1c42be1f3bb3
d1c56e9c53c9bdc75dbc189d7b58b1de14c1946a
refs/heads/master
2022-12-12T08:53:11.206876
2020-08-22T06:35:50
2020-08-22T06:35:50
247,947,220
0
0
null
2022-12-12T05:46:37
2020-03-17T11:00:12
JavaScript
UTF-8
C++
false
false
120
cpp
#include "C:/Users/5567i5/Desktop/project/node_modules/opencv-build/opencv/opencv_contrib/modules/plot/src/precomp.hpp"
641dde610abf5ff511fa950f01cc01370481b171
591df59d439e1d7cc630a6a5958e7a92c6bdaabc
/manager/resources/components/center_window/src/WindowWidgetPlugin.h
8c62092d56e6806d65f169ccae9de3bf45ecbfb7
[]
no_license
kjhgnkv/DSControl_17_09
b929ef051d7a17705bc963c1bcda96badf860463
03957e8153e3852cbf026ec37bdac340a6b23f24
refs/heads/main
2023-08-02T19:20:05.527221
2021-10-01T14:59:20
2021-10-01T14:59:20
412,485,720
0
0
null
null
null
null
UTF-8
C++
false
false
613
h
#ifndef WindowWidgetPlugin_H #define WindowWidgetPlugin_H #include <QWidget> #include "IWidgetPlugin.h" class WindowWidgetPlugin : public IWidgetPlugin { Q_OBJECT public: WindowWidgetPlugin(); virtual ~WindowWidgetPlugin(); /* Plugin interfaces */ QList<ICenterWindow*> getCenterWindow(); QList<ISettingWindow*> getSettingWindow(); QList<IPluginInfo*> getPluginInfoWindow(); private: QList<ICenterWindow*> m_centerWindowList; QList<ISettingWindow*> m_settingWindowList; QList<IPluginInfo*> m_pluginInfoList; void createWidget(); }; #endif // WindowWidgetPlugin_H
084735ed9c376b8b92d1113dc6419c2a159d864d
a476e690fc05229c7d5eec835d6b350dd8200fe9
/test7.7.cpp
6a4953864de4047694e3741021e28ea9360c2aa1
[]
no_license
baoweike666/oj
45830bff7d70f90aa7d52d464be16a1093c4f2f6
443557815016f2ca93a2cc3daefc830ea34e6e43
refs/heads/master
2020-03-22T01:19:23.723598
2018-08-29T09:41:41
2018-08-29T09:41:41
139,297,793
0
0
null
null
null
null
UTF-8
C++
false
false
980
cpp
#include<iostream> #include<stdio.h> #include<stack> #include<string.h> #include<stdlib.h> #include<queue> #include <iostream> #include <algorithm> using namespace std; //for(int i=0;i<=n;i++) //scanf("%d%d",&m,&n) int c,n; int cost[100]; int value[100]; int dp[100][100]; int main() { while(scanf("%d%d",&c,&n)) { for(int i=1;i<=n;i++) { scanf("%d%d",&cost[i],&value[i]); } // sort(a+1,a+m+1); // for(int i=1;i<=m;i++) // { // printf("%d",a[i]); // } //dp[i][j] 前i个草药,容量j for(int i=0;i<=n;i++) { dp[i][0]=0; } for(int i=0;i<=c;i++) { dp[0][i]=0; } for(int i=1;i<=n;i++) //dp[i][j] 前i个草药,容量j for(int j=1;j<=c;j++) { if(j>=cost[i]) dp[i][j]=max(dp[i-1][j],dp[i-1][j-cost[i]]+value[i]); else dp[i][j]=dp[i-1][j]; } printf("%d",dp[n][c]); } return 0; }
b30688327d9a89dad93cde705d0703532311745d
ecc9ac507ef4b395990a41d8fdaa67a4f0185477
/src/utils/io/instance/postag.h
e544a47d6a0847dd50567036b2b34d27867627b2
[]
no_license
Oneplus/ZuoPar
ba6effb334bdd3423d7b714d79869d039f1af823
afb1a80d90b8ead5312991c7319c3e0905adaa06
refs/heads/master
2021-01-18T17:12:10.428467
2016-04-25T23:50:55
2016-04-25T23:50:55
24,812,348
5
2
null
2015-07-29T03:25:45
2014-10-05T09:21:36
C++
UTF-8
C++
false
false
1,401
h
#ifndef __ZUOPAR_UTILS_IO_INSTANCE_POSTAG_H__ #define __ZUOPAR_UTILS_IO_INSTANCE_POSTAG_H__ #include <iostream> #include "types/postag.h" #include "engine/token_alphabet.h" namespace ZuoPar { namespace IO { namespace eg = ZuoPar::Engine; /** * Read one postag instance from the input stream. * * @param[in] is The input stream. * @param[out] output The output stream. * @param[in] postags_alphabet The alphabet of postags. * @param[in] delimiter The delimiter between form and postag. * @param[in] incremental * @return bool Return true on successfully load, otherwise * false. */ bool read_postag_instance(std::istream& is, Postag& output, eg::TokenAlphabet& postags_alphabet, char delimiter = '/', bool incremental = true); /** * Write one postag with lexical cache instance to the output stream. * * @param[out] os The output stream * @param[in] output The instance. * @param[in] postags_alphabet The alphabet for postags * @param[in] delimiter The delimiter */ void write_postag_instance(std::ostream& os, const Postag& output, const eg::TokenAlphabet& postags_alphabet, char delimiter = '/'); } // end for namespace io } // end for namespace zuopar #endif // end for __ZUOPAR_UTILS_IO_INSTANCE_POSTAG_H__
08f7a9d72948c1001799e2643942b834e958946e
424b57dee7642ceeb84ac55e77e6fc0a125fd4e1
/src/verbatim_frame_buffer.hpp
e78469e048dd4e852a64f213c7fcd0ee68c4a45f
[ "BSD-3-Clause" ]
permissive
fengjixuchui/faemiyah-demoscene_2018-08_40k-intro_cassini
03e67f136798f6d8f0a971147221cf71f79fca89
946843e1a9298d4399052e747557c997dc017271
refs/heads/master
2020-12-14T23:10:18.189169
2019-07-03T16:18:11
2019-07-03T16:18:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,490
hpp
#ifndef VERBATIM_FRAME_BUFFER_HPP #define VERBATIM_FRAME_BUFFER_HPP #include "verbatim_texture_2d.hpp" /// Framebuffer. class FrameBuffer { private: /// Current render target. static FrameBuffer const *g_current_frame_buffer; private: /// Framebuffer id. GLuint m_id; /// Color buffer id. GLuint m_color_buffer; /// Depth buffer id. GLuint m_depth_buffer; /// Attached render target texture. Texture2D m_color_texture; /// Attached render target texture. Texture2D m_depth_texture; /// Width of this framebuffer. unsigned m_width; /// Height of this framebuffer. unsigned m_height; public: /// Constructor. /// /// \param width Framebuffer width. /// \param height Framebuffer height. /// \param color_texture Use color texture (default: yes). /// \param depth_texture Use depth texture (default: no). /// \param bpc Bytes per pixel (default: 2). /// \param filtering Filtering mode (default: BILINEAR). /// \param wrap Wrap mode (default: CLAMP). explicit FrameBuffer(unsigned width, unsigned height, bool color_texture = true, bool depth_texture = false, unsigned bpc = 2, FilteringMode filtering = BILINEAR, WrapMode wrap = CLAMP) : m_id(0), m_depth_buffer(0), m_width(width), m_height(height) { #if defined(USE_LD) if((m_width <= 0) || (m_height <= 0)) { std::ostringstream sstr; sstr << "invalid framebuffer dimensions: " << width << "x" << height; BOOST_THROW_EXCEPTION(std::runtime_error(sstr.str())); } #endif if(color_texture) { m_color_texture.update(width, height, 4, bpc, filtering, wrap); } if(depth_texture) { m_depth_texture.update(width, height, 0, (bpc < 2) ? 2 : bpc, filtering, wrap); } dnload_glGenFramebuffers(1, &m_id); dnload_glBindFramebuffer(GL_FRAMEBUFFER, m_id); if(color_texture) { dnload_glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_color_texture.getId(), 0); } if(depth_texture) { dnload_glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_depth_texture.getId(), 0); } #if 0 // Generate renderbuffer in lieu of texture. else { dnload_glGenRenderbuffers(1, &m_depth_buffer); dnload_glBindRenderbuffer(GL_RENDERBUFFER, m_depth_buffer); dnload_glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, width, height); dnload_glBindRenderbuffer(GL_RENDERBUFFER, 0); dnload_glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_depth_buffer); } #endif #if defined(USE_LD) GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if(status != GL_FRAMEBUFFER_COMPLETE) { std::ostringstream sstr; sstr << "framebuffer " << m_width << "x" << m_height << (color_texture ? "C" : "") << (depth_texture ? "D" : "") << ": error 0x" << std::hex << status << std::endl; BOOST_THROW_EXCEPTION(std::runtime_error(sstr.str())); } #endif // Restore earlier framebuffer. dnload_glBindFramebuffer(GL_FRAMEBUFFER, get_current_frame_buffer_id()); } /// Destructor. ~FrameBuffer() { #if defined(USE_LD) glDeleteFramebuffers(1, &m_id); if(m_color_buffer) { glDeleteRenderbuffers(1, &m_color_buffer); } if(m_depth_buffer) { glDeleteRenderbuffers(1, &m_depth_buffer); } #endif } public: /// Bind this framebuffer to use. void bind() const { if(g_current_frame_buffer != this) { dnload_glBindFramebuffer(GL_FRAMEBUFFER, m_id); dnload_glViewport(0, 0, static_cast<GLsizei>(m_width), static_cast<GLsizei>(m_height)); g_current_frame_buffer = this; } } /// Accessor. /// /// \return Framebuffer id. unsigned getId() const { return m_id; } /// Accessor. /// /// \return Get attached texture. Texture const& getTextureColor() const { return m_color_texture; } /// Accessor. /// /// \return Get attached texture. Texture const& getTextureDepth() const { return m_depth_texture; } /// Accessor. /// /// \return Render target width. unsigned getWidth() const { return m_width; } /// Accessor. /// /// \return Render target height. unsigned getHeight() const { return m_height; } private: /// Get current render target id. /// /// \return ID of currently bound render target or 0. static unsigned get_current_frame_buffer_id() { return g_current_frame_buffer ? g_current_frame_buffer->getId() : 0; } public: /// Bind default framebuffer. /// /// \param screen_width Width of default framebuffer. /// \param screen_height Height of default framebuffer. static void bind_default_frame_buffer(unsigned screen_width, unsigned screen_height) { if(g_current_frame_buffer) { dnload_glBindFramebuffer(GL_FRAMEBUFFER, 0); dnload_glViewport(0, 0, static_cast<GLsizei>(screen_width), static_cast<GLsizei>(screen_height)); g_current_frame_buffer = NULL; } } }; const FrameBuffer *FrameBuffer::g_current_frame_buffer = NULL; #endif
5c7ff3d484b327e5c027a280ca47d102b6a298c6
b749c9f935f2bb2010d881e2aed3631da637af55
/Source/SimpleShooter/BTTask_Shoot.h
bc394acdb00eadb3279bf1980483c0f673cc48f5
[]
no_license
RoyzLevy/SimpleShooter
815a250a4448f369f9635e451a5d6722169b2ba6
e9fe645c8eb5d3c4c81d5df642c258ed115e8d1e
refs/heads/master
2023-01-10T20:26:59.207869
2020-10-24T00:05:35
2020-10-24T00:05:35
306,248,791
0
0
null
null
null
null
UTF-8
C++
false
false
428
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "BehaviorTree/BTTaskNode.h" #include "BTTask_Shoot.generated.h" UCLASS() class SIMPLESHOOTER_API UBTTask_Shoot : public UBTTaskNode { GENERATED_BODY() public: UBTTask_Shoot(); protected: virtual EBTNodeResult::Type ExecuteTask(UBehaviorTreeComponent &OwnerComp, uint8 *NodeMemory) override; };
ed33acf5d8acb240db614b254619b5c1b115ca8f
119ba70d6692743c819bc92a689ab685ff6f619b
/pretest-03.cpp
2e321d9143ed06bee7f50c29c6cb2a2c54124fe1
[]
no_license
alvin2105/pretest-03
4daa09ddebb204a9e4be60ee1ddb46f8f5cf29c1
5335924b6542cfc3213552928e4875b655444ed2
refs/heads/master
2020-04-28T08:00:43.616362
2019-03-12T02:59:59
2019-03-12T02:59:59
175,111,360
0
0
null
null
null
null
UTF-8
C++
false
false
1,032
cpp
/* nama : alvin npm : 140810180013 ddeskripsi : pretest-03 tgl : 12 maret 2019 */ #include<iostream> using namespace std; struct r_mhs{ char npm[14]; char nama[40]; float ipk; }; typedef r_mhs larikMhs[30]; void banyakData (int& n){ cout<<"masukan banyak data : "; cin>>n; } void inputMhs(larikMhs& mhs,int n){ for(int i=0;i<n;i++){ cout<<"npm\t: "; cin>>mhs[i].npm; cout<<"nama\t: "; cin>>mhs[i].nama; cout<<"nama\t: "; cin>>mhs[i].ipk; } cout<<endl; } void cetakMhs(larikMhs& mhs,int n){ for(int i=0;i<n;i++){ cout<<mhs[i].npm<<" "<<mhs[i].nama<<" "<<mhs[i].ipk<<endl; } } void sortNPM(larikMhs& mhs,int n){ int i; r_mhs temp; for(i=1; i<n; i++) { temp = mhs[i]; while(i>0 && mhs[i-1].npm>temp.npm){ mhs[i]= mhs[i-1]; i = i-1; } mhs[i]= temp; } } int main(){ int n; larikMhs mhs; banyakData(n); inputMhs(mhs,n); cetakMhs(mhs, n); sortNPM(mhs, n); }
53bf76bb4537a40b80baa054f1cb376c1b01bcc0
019a9c2de0eeccb4f31eecbeb0e91cc2db5404c2
/CodeForces/520B - Two Buttons.cpp
afdfe5dbb09c07884a6c5b40ef7fc505b147646f
[]
no_license
Prakhar-FF13/Competitive-Programming
4e9bd1944a55b0b89ff21537e0960f058f1693fd
3f0937475d2985da323e5ceb65b20dc458155e74
refs/heads/master
2023-01-09T05:09:27.574518
2023-01-04T11:32:01
2023-01-04T11:32:01
133,995,411
2
1
null
null
null
null
UTF-8
C++
false
false
1,236
cpp
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> pii; typedef pair<ll,ll> pll; typedef vector<int> vi; typedef vector<pii> vii; typedef vector<pll> vll; #define rep(i,a,b) for(int i=a;i<b;i++) #define fsi ios_base::sync_with_stdio(false);cin.tie(0); #define RW() freopen("read.txt","r",stdin);freopen("write.txt","w",stdout); #define MOD 1000000007 #define tt() int t;cin>>t;while(t--) #define pb push_back #define mp make_pair #define ms memset #define all(v) v.begin(),v.end() #define pob pop_back int n,m; int visited[20105]; int dist[20105]; queue<int> numb; int solve(){ if(n == m) return 0; numb.push(n); dist[n] = 0; while ( !numb.empty() ) { int x = numb.front(); numb.pop(); if(visited[x] == 1) continue; visited[x] = 1; if(x - 1 > 0 && visited[x-1] == 0){ numb.push(x-1); dist[x-1] = dist[x] + 1; } if(2*x <= 2*m+5 && visited[x*2] == 0){ numb.push(2*x); dist[2*x] = dist[x] + 1; } } return dist[m]; } int main(){ ms(visited, 0, sizeof(visited)); ms(dist, 0, sizeof(dist)); cin>>n>>m; cout<<solve(); return 0; }
4a69f098e8354e93da4503901ffb7435d67f1d65
c1fca23ff37cd650ac0455082994ffdf721bd949
/ThirdParty/Include/thrust/host_vector.h
3a68d18f6746ba0241553a5df72bf66247a8eecb
[]
no_license
liihuang/ue4-gpgpu-plugin
d9abc7df95c647fea50487581c780f04d31c98d5
a1447dedc6238edb2f3bc9bbd4992222cae08763
refs/heads/master
2023-06-24T14:57:24.202897
2019-04-13T07:28:16
2019-04-13T07:28:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,518
h
/* * Copyright 2008-2013 NVIDIA 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. */ /*! \file host_vector.h * \brief A dynamically-sizable array of elements which reside in the "host" memory space */ #pragma once #include <thrust/detail/config.h> #include <memory> #include <thrust/detail/vector_base.h> #include <vector> namespace thrust { // forward declaration of device_vector template<typename T, typename Alloc> class device_vector; /*! \addtogroup container_classes Container Classes * \addtogroup host_containers Host Containers * \ingroup container_classes * \{ */ /*! A \p host_vector is a container that supports random access to elements, * constant time removal of elements at the end, and linear time insertion * and removal of elements at the beginning or in the middle. The number of * elements in a \p host_vector may vary dynamically; memory management is * automatic. The memory associated with a \p host_vector resides in the memory * space of the host associated with a parallel device. * * \see http://www.sgi.com/tech/stl/Vector.html * \see device_vector */ template<typename T, typename Alloc = std::allocator<T> > class host_vector : public detail::vector_base<T,Alloc> { private: typedef detail::vector_base<T,Alloc> Parent; public: /*! \cond */ typedef typename Parent::size_type size_type; typedef typename Parent::value_type value_type; /*! \endcond */ /*! This constructor creates an empty \p host_vector. */ __host__ host_vector(void) :Parent() {} /*! This constructor creates a \p host_vector with the given * size. * \param n The number of elements to initially craete. */ __host__ explicit host_vector(size_type n) :Parent(n) {} /*! This constructor creates a \p host_vector with copies * of an exemplar element. * \param n The number of elements to initially create. * \param value An element to copy. */ __host__ explicit host_vector(size_type n, const value_type &value) :Parent(n,value) {} /*! Copy constructor copies from an exemplar \p host_vector. * \param v The \p host_vector to copy. */ __host__ host_vector(const host_vector &v) :Parent(v) {} /*! Assign operator copies from an exemplar \p host_vector. * \param v The \p host_vector to copy. */ __host__ host_vector &operator=(const host_vector &v) { Parent::operator=(v); return *this; } /*! Copy constructor copies from an exemplar \p host_vector with different type. * \param v The \p host_vector to copy. */ template<typename OtherT, typename OtherAlloc> __host__ host_vector(const host_vector<OtherT,OtherAlloc> &v) :Parent(v) {} /*! Assign operator copies from an exemplar \p host_vector with different type. * \param v The \p host_vector to copy. */ template<typename OtherT, typename OtherAlloc> __host__ host_vector &operator=(const host_vector<OtherT,OtherAlloc> &v) { Parent::operator=(v); return *this; } /*! Copy constructor copies from an exemplar <tt>std::vector</tt>. * \param v The <tt>std::vector</tt> to copy. */ template<typename OtherT, typename OtherAlloc> __host__ host_vector(const std::vector<OtherT,OtherAlloc> &v) :Parent(v) {} /*! Assign operator copies from an exemplar <tt>std::vector</tt>. * \param v The <tt>std::vector</tt> to copy. */ template<typename OtherT, typename OtherAlloc> __host__ host_vector &operator=(const std::vector<OtherT,OtherAlloc> &v) { Parent::operator=(v); return *this;} /*! Copy constructor copies from an exemplar \p device_vector with possibly different type. * \param v The \p device_vector to copy. */ template<typename OtherT, typename OtherAlloc> __host__ host_vector(const device_vector<OtherT,OtherAlloc> &v); /*! Assign operator copies from an exemplar \p device_vector. * \param v The \p device_vector to copy. */ template<typename OtherT, typename OtherAlloc> __host__ host_vector &operator=(const device_vector<OtherT,OtherAlloc> &v) { Parent::operator=(v); return *this; } /*! This constructor builds a \p host_vector from a range. * \param first The beginning of the range. * \param last The end of the range. */ template<typename InputIterator> __host__ host_vector(InputIterator first, InputIterator last) :Parent(first, last) {} // declare these members for the purpose of Doxygenating them // they actually exist in a derived-from class #if 0 /*! \brief Resizes this vector to the specified number of elements. * \param new_size Number of elements this vector should contain. * \param x Data with which new elements should be populated. * \throw std::length_error If n exceeds max_size(). * * This method will resize this vector to the specified number of * elements. If the number is smaller than this vector's current * size this vector is truncated, otherwise this vector is * extended and new elements are populated with given data. */ void resize(size_type new_size, const value_type &x = value_type()); /*! Returns the number of elements in this vector. */ size_type size(void) const; /*! Returns the size() of the largest possible vector. * \return The largest possible return value of size(). */ size_type max_size(void) const; /*! \brief If n is less than or equal to capacity(), this call has no effect. * Otherwise, this method is a request for allocation of additional memory. If * the request is successful, then capacity() is greater than or equal to * n; otherwise, capacity() is unchanged. In either case, size() is unchanged. * \throw std::length_error If n exceeds max_size(). */ void reserve(size_type n); /*! Returns the number of elements which have been reserved in this * vector. */ size_type capacity(void) const; /*! This method shrinks the capacity of this vector to exactly * fit its elements. */ void shrink_to_fit(void); /*! \brief Subscript access to the data contained in this vector_dev. * \param n The index of the element for which data should be accessed. * \return Read/write reference to data. * * This operator allows for easy, array-style, data access. * Note that data access with this operator is unchecked and * out_of_range lookups are not defined. */ reference operator[](size_type n); /*! \brief Subscript read access to the data contained in this vector_dev. * \param n The index of the element for which data should be accessed. * \return Read reference to data. * * This operator allows for easy, array-style, data access. * Note that data access with this operator is unchecked and * out_of_range lookups are not defined. */ const_reference operator[](size_type n) const; /*! This method returns an iterator pointing to the beginning of * this vector. * \return mStart */ iterator begin(void); /*! This method returns a const_iterator pointing to the beginning * of this vector. * \return mStart */ const_iterator begin(void) const; /*! This method returns a const_iterator pointing to the beginning * of this vector. * \return mStart */ const_iterator cbegin(void) const; /*! This method returns a reverse_iterator pointing to the beginning of * this vector's reversed sequence. * \return A reverse_iterator pointing to the beginning of this * vector's reversed sequence. */ reverse_iterator rbegin(void); /*! This method returns a const_reverse_iterator pointing to the beginning of * this vector's reversed sequence. * \return A const_reverse_iterator pointing to the beginning of this * vector's reversed sequence. */ const_reverse_iterator rbegin(void) const; /*! This method returns a const_reverse_iterator pointing to the beginning of * this vector's reversed sequence. * \return A const_reverse_iterator pointing to the beginning of this * vector's reversed sequence. */ const_reverse_iterator crbegin(void) const; /*! This method returns an iterator pointing to one element past the * last of this vector. * \return begin() + size(). */ iterator end(void); /*! This method returns a const_iterator pointing to one element past the * last of this vector. * \return begin() + size(). */ const_iterator end(void) const; /*! This method returns a const_iterator pointing to one element past the * last of this vector. * \return begin() + size(). */ const_iterator cend(void) const; /*! This method returns a reverse_iterator pointing to one element past the * last of this vector's reversed sequence. * \return rbegin() + size(). */ reverse_iterator rend(void); /*! This method returns a const_reverse_iterator pointing to one element past the * last of this vector's reversed sequence. * \return rbegin() + size(). */ const_reverse_iterator rend(void) const; /*! This method returns a const_reverse_iterator pointing to one element past the * last of this vector's reversed sequence. * \return rbegin() + size(). */ const_reverse_iterator crend(void) const; /*! This method returns a const_reference referring to the first element of this * vector. * \return The first element of this vector. */ const_reference front(void) const; /*! This method returns a reference pointing to the first element of this * vector. * \return The first element of this vector. */ reference front(void); /*! This method returns a const reference pointing to the last element of * this vector. * \return The last element of this vector. */ const_reference back(void) const; /*! This method returns a reference referring to the last element of * this vector_dev. * \return The last element of this vector. */ reference back(void); /*! This method returns a pointer to this vector's first element. * \return A pointer to the first element of this vector. */ pointer data(void); /*! This method returns a const_pointer to this vector's first element. * \return a const_pointer to the first element of this vector. */ const_pointer data(void) const; /*! This method resizes this vector to 0. */ void clear(void); /*! This method returns true iff size() == 0. * \return true if size() == 0; false, otherwise. */ bool empty(void) const; /*! This method appends the given element to the end of this vector. * \param x The element to append. */ void push_back(const value_type &x); /*! This method erases the last element of this vector, invalidating * all iterators and references to it. */ void pop_back(void); /*! This method swaps the contents of this vector_base with another vector. * \param v The vector with which to swap. */ void swap(host_vector &v); /*! This method removes the element at position pos. * \param pos The position of the element of interest. * \return An iterator pointing to the new location of the element that followed the element * at position pos. */ iterator erase(iterator pos); /*! This method removes the range of elements [first,last) from this vector. * \param first The beginning of the range of elements to remove. * \param last The end of the range of elements to remove. * \return An iterator pointing to the new location of the element that followed the last * element in the sequence [first,last). */ iterator erase(iterator first, iterator last); /*! This method inserts a single copy of a given exemplar value at the * specified position in this vector. * \param position The insertion position. * \param x The exemplar element to copy & insert. * \return An iterator pointing to the newly inserted element. */ iterator insert(iterator position, const T &x); /*! This method inserts a copy of an exemplar value to a range at the * specified position in this vector. * \param position The insertion position * \param n The number of insertions to perform. * \param x The value to replicate and insert. */ void insert(iterator position, size_type n, const T &x); /*! This method inserts a copy of an input range at the specified position * in this vector. * \param position The insertion position. * \param first The beginning of the range to copy. * \param last The end of the range to copy. * * \tparam InputIterator is a model of <a href="http://www.sgi.com/tech/stl/InputIterator.html>Input Iterator</a>, * and \p InputIterator's \c value_type is a model of <a href="http://www.sgi.com/tech/stl/Assignable.html">Assignable</a>. */ template<typename InputIterator> void insert(iterator position, InputIterator first, InputIterator last); /*! This version of \p assign replicates a given exemplar * \p n times into this vector. * \param n The number of times to copy \p x. * \param x The exemplar element to replicate. */ void assign(size_type n, const T &x); /*! This version of \p assign makes this vector a copy of a given input range. * \param first The beginning of the range to copy. * \param last The end of the range to copy. * * \tparam InputIterator is a model of <a href="http://www.sgi.com/tech/stl/InputIterator">Input Iterator</a>. */ template<typename InputIterator> void assign(InputIterator first, InputIterator last); /*! This method returns a copy of this vector's allocator. * \return A copy of the alloctor used by this vector. */ allocator_type get_allocator(void) const; #endif // end doxygen-only members }; // end host_vector /*! \} */ } // end thrust #include <thrust/detail/host_vector.inl>
a486790a718f7e987038c321e448783af581be08
2c3bed124be3d5edb1abc646d8f138d7caaae251
/Src/main.cpp
a3755ac97765a463a6903d3e03939230c14a4e5d
[]
no_license
bijanbina/BAudio
291d8f46d1d3e3c62081ce710f1a125a4db3d10b
3e91a0023aa01ed1a5bd6511c73d21886cc1311f
refs/heads/main
2023-05-08T10:49:55.592238
2021-06-01T08:08:18
2021-06-01T08:08:18
371,696,715
3
0
null
null
null
null
UTF-8
C++
false
false
10,266
cpp
// Setup and miniport installation. No resources are used by msvad. // All the GUIDS for all the miniports end up in this object. #define PUT_GUIDS_HERE #include "sonicsaudio.h" #include "common.h" // BUGBUG set this to number of miniports #define MAX_MINIPORTS 2 // Number of maximum miniports. NTSTATUS CreateMiniportWaveCyclic( OUT PUNKNOWN *, IN REFCLSID, IN PUNKNOWN, IN POOL_TYPE); NTSTATUS CreateMiniportTopology( OUT PUNKNOWN *, IN REFCLSID, IN PUNKNOWN, IN POOL_TYPE); extern "C" NTSTATUS AddDevice(IN PDRIVER_OBJECT, IN PDEVICE_OBJECT); NTSTATUS StartDevice(IN PDEVICE_OBJECT, IN PIRP, IN PRESOURCELIST); #pragma code_seg("INIT") /* Installable driver initialization entry point. This entry point is called directly by the I/O system. All audio adapter drivers can use this code without change. Arguments: DriverObject - pointer to the driver object RegistryPath - pointer to a unicode string representing the path, to driver-specific key in the registry. Return Value: STATUS_SUCCESS if successful, STATUS_UNSUCCESSFUL otherwise.*/ extern "C" NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPathName) { PAGED_CODE(); NTSTATUS ntStatus; //DPF(D_TERSE, ("[DriverEntry]")); // Tell the class driver to initialize the driver. ntStatus = PcInitializeAdapterDriver(DriverObject, RegistryPathName, AddDevice); return ntStatus; } #pragma code_seg() #pragma code_seg("PAGE") /* Routine Description: The Plug & Play subsystem is handing us a brand new PDO, for which we (by means of INF registration) have been asked to provide a driver. We need to determine if we need to be in the driver stack for the device. Create a function device object to attach to the stack Initialize that device object Return status success. All audio adapter drivers can use this code without change. Set MAX_MINIPORTS depending on the number of miniports that the driver uses. Arguments: DriverObject - pointer to a driver object PhysicalDeviceObject - pointer to a device object created by the underlying bus driver.*/ extern "C" NTSTATUS AddDevice(IN PDRIVER_OBJECT DriverObject, IN PDEVICE_OBJECT PhysicalDeviceObject) { PAGED_CODE(); NTSTATUS ntStatus; //DPF(D_TERSE, ("[AddDevice]")); // Tell the class driver to add the device. ntStatus = PcAddAdapterDevice(DriverObject, PhysicalDeviceObject, PCPFNSTARTDEVICE(StartDevice), MAX_MINIPORTS, 0); return ntStatus; } /* This function creates and registers a subdevice consisting of a port driver, a minport driver and a set of resources bound together. It will also optionally place a pointer to an interface on the port driver in a specified location before initializing the port driver. This is done so that a common ISR can have access to the port driver during initialization, when the ISR might fire. Arguments: DeviceObject - pointer to the driver object Irp - pointer to the irp object. Name - name of the miniport. Passes to PcRegisterSubDevice PortClassId - port class id. Passed to PcNewPort. MiniportClassId - miniport class id. Passed to PcNewMiniport. MiniportCreate - pointer to a miniport creation function. If NULL, PcNewMiniport is used. UnknownAdapter - pointer to the adapter object. Used for initializing the port. ResourceList - pointer to the resource list. PortInterfaceId - GUID that represents the port interface. OutPortInterface - pointer to store the port interface OutPortUnknown - pointer to store the unknown port interface. */ NTSTATUS InstallSubdevice(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp, IN PWCHAR Name, IN REFGUID PortClassId, IN REFGUID MiniportClassId, IN PFNCREATEINSTANCE MiniportCreate OPTIONAL, IN PUNKNOWN UnknownAdapter OPTIONAL, IN PRESOURCELIST ResourceList, IN REFGUID PortInterfaceId, OUT PUNKNOWN *OutPortInterface OPTIONAL, OUT PUNKNOWN *OutPortUnknown OPTIONAL) { PAGED_CODE(); ASSERT(DeviceObject); ASSERT(Irp); ASSERT(Name); NTSTATUS ntStatus; PPORT port = NULL; PUNKNOWN miniport = NULL; //DPF_ENTER(("[InstallSubDevice %s]", Name)); // Create the port driver object ntStatus = PcNewPort(&port, PortClassId); // Create the miniport object if (NT_SUCCESS(ntStatus)) { if (MiniportCreate) { ntStatus = MiniportCreate( &miniport, MiniportClassId, NULL, NonPagedPool ); } else { ntStatus = PcNewMiniport( (PMINIPORT *) &miniport, MiniportClassId ); } } // Init the port driver and miniport in one go. if (NT_SUCCESS(ntStatus)) { ntStatus = port->Init( DeviceObject, Irp, miniport, UnknownAdapter, ResourceList ); if (NT_SUCCESS(ntStatus)) { // Register the subdevice (port/miniport combination). ntStatus = PcRegisterSubdevice( DeviceObject, Name, port ); } // We don't need the miniport any more. Either the port has it, // or we've failed, and it should be deleted. miniport->Release(); } // Deposit the port interfaces if it's needed. if (NT_SUCCESS(ntStatus)) { if (OutPortUnknown) { ntStatus = port->QueryInterface( IID_IUnknown, (PVOID *)OutPortUnknown ); } if (OutPortInterface) { ntStatus = port->QueryInterface( PortInterfaceId, (PVOID *) OutPortInterface ); } } if (port) { port->Release(); } return ntStatus; } /* This function is called by the operating system when the device is started. It is responsible for starting the miniports. This code is specific to the adapter because it calls out miniports for functions that are specific to the adapter. Arguments: DeviceObject - pointer to the driver object Irp - pointer to the irp ResourceList - pointer to the resource list assigned by PnP manager*/ NTSTATUS StartDevice(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp, IN PRESOURCELIST ResourceList) { UNREFERENCED_PARAMETER(ResourceList); PAGED_CODE(); ASSERT(DeviceObject); ASSERT(Irp); ASSERT(ResourceList); NTSTATUS ntStatus = STATUS_SUCCESS; PUNKNOWN unknownTopology = NULL; PUNKNOWN unknownWave = NULL; PADAPTERCOMMON pAdapterCommon = NULL; PUNKNOWN pUnknownCommon = NULL; //DPF_ENTER(("[StartDevice]")); // create a new adapter common object ntStatus = NewAdapterCommon( &pUnknownCommon, IID_IAdapterCommon, NULL, NonPagedPool ); if (NT_SUCCESS(ntStatus)) { ntStatus = pUnknownCommon->QueryInterface( IID_IAdapterCommon, (PVOID *) &pAdapterCommon ); if (NT_SUCCESS(ntStatus)) { ntStatus = pAdapterCommon->Init(DeviceObject); if (NT_SUCCESS(ntStatus)) { // register with PortCls for power-management services ntStatus = PcRegisterAdapterPowerManagement( PUNKNOWN(pAdapterCommon), DeviceObject ); } } } // install MSVAD topology miniport. if (NT_SUCCESS(ntStatus)) { ntStatus = InstallSubdevice( DeviceObject, Irp, L"Topology", CLSID_PortTopology, CLSID_PortTopology, CreateMiniportTopology, pAdapterCommon, NULL, IID_IPortTopology, NULL, &unknownTopology ); } // install MSVAD wavecyclic miniport. if (NT_SUCCESS(ntStatus)) { ntStatus = InstallSubdevice( DeviceObject, Irp, L"Wave", CLSID_PortWaveCyclic, CLSID_PortWaveCyclic, CreateMiniportWaveCyclic, pAdapterCommon, NULL, IID_IPortWaveCyclic, pAdapterCommon->WavePortDriverDest(), &unknownWave ); } if (unknownTopology && unknownWave) { // register wave <=> topology connections // This will connect bridge pins of wavecyclic and topology // miniports. if ((TopologyPhysicalConnections.ulTopologyOut != (ULONG)-1) && (TopologyPhysicalConnections.ulWaveIn != (ULONG)-1)) { ntStatus = PcRegisterPhysicalConnection( DeviceObject, unknownTopology, TopologyPhysicalConnections.ulTopologyOut, unknownWave, TopologyPhysicalConnections.ulWaveIn ); } if (NT_SUCCESS(ntStatus)) { if ((TopologyPhysicalConnections.ulWaveOut != (ULONG)-1) && (TopologyPhysicalConnections.ulTopologyIn != (ULONG)-1)) { ntStatus = PcRegisterPhysicalConnection( DeviceObject, unknownWave, TopologyPhysicalConnections.ulWaveOut, unknownTopology, TopologyPhysicalConnections.ulTopologyIn ); } } } // Release the adapter common object. It either has other references, // or we need to delete it anyway. if (pAdapterCommon) pAdapterCommon->Release(); if (pUnknownCommon) pUnknownCommon->Release(); if (unknownTopology) unknownTopology->Release(); if (unknownWave) unknownWave->Release(); return ntStatus; } // StartDevice #pragma code_seg()
5dbea3a17acde0804e063bba2659b9e2290f8c54
207161920bab034a6c37da131ae56588e34bcb20
/src/acTemperature.h
4968f07aa7cd909a4eec56e02ff325b68ed84599
[]
no_license
neimar2009/acTemperature
2f31f1955a0f911077241c8d00b884535d40c4e2
fef6d652c36227b348a74de8fffe41d5898592be
refs/heads/master
2021-10-10T15:25:03.724728
2018-09-09T15:01:21
2018-09-09T15:01:21
106,629,333
0
1
null
2018-09-09T15:01:22
2017-10-12T01:31:38
C++
UTF-8
C++
false
false
2,014
h
#ifndef acTemperature_h #define acTemperature_h #include <Arduino.h> // #include "AVRs.h" class acTemperatureClass { private: const double Kv = 273.16; // Kv é iqual a 0 graus Celsios. double averageC = -(Kv); // Começa em zero absoluto. double resolution = 0.0; double nowDegrees = 0.0; double gapDefault = 0.6 / 2; double gap = gapDefault; boolean flagChanged = false; // Será verdade quando a temperatura alterar. // uint8_t pinDry = 0; // Em geral é usado o pino A0. Bulbo seco. uint8_t pinHumid = 0; // Em geral é usado o pino A1. Bulbo úmido. uint8_t pinSensor = 0; // Inicia com o valor de pinDry. // const static uint8_t lastLen = 10; const static uint8_t lastTotal = lastLen * 2; int highLast[lastLen]; int lowLast[lastLen]; // void setDry() { pinSensor = pinDry; }; boolean setHumid() { pinSensor = pinHumid; return pinDry != pinHumid; }; public: // VRefOrigin : DEFAULT, EXTERNAL, INTERNAL, INTERNAL1V1, INTERNAL2V56 ou INTERNAL2V56_EXTCAP. // VperD : Volt por Grau gerado pelo sensor. (Volts per Degrees) acTemperatureClass(uint8_t VRefOrigin, double VperD); ~acTemperatureClass() {}; // pinDry : Pino para o bulbo seco. // pinHumid : Pino para o bulbo úmido. void begin(uint8_t pinDry, uint8_t pinHumid = 0xFF); double Celsius(); double Fahrenheit() { return (Celsius() * (9/5) + 32); }; double Rankine() { return (Celsius() + Kv) * (9/5); }; double Reaumur() { return (Celsius() * (4/5)); }; // Réaumur double Romer() { return (Celsius() * (21/40) + 7.5); }; // Rømer double Newton() { return (Celsius() * (33/100)); }; double Delisle() { return (100 - Celsius()) * (5/6); }; double average(); double humidity(); // Umidade relativa. Só é válido se os dois sensores estiverem ativos. boolean changed() { average(); return flagChanged; }; }; // extern acTemperatureClass acTemperature; #endif //acTemperature_h
c6590a5bef6335d729cf0a84b54fa5f890661936
9b45bcd2996f91cb2593ffee8fda163c35add23b
/MandelBrotGen.h
04ca30e7a45893e653b4ab789cd5741218ceaf5b
[]
no_license
guruRockz/HelloMandelBrot
eb6756093f8ac27747d3f87fd5a7f77d33155255
ea0ee132a5b01fa2179fee1c76e2f6d05c69c557
refs/heads/master
2021-03-12T20:21:33.022668
2012-09-02T07:47:54
2012-09-02T07:47:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,650
h
#ifndef MANDELBROTGEN_H #define MANDELBROTGEN_H #include "SDL.h" #include <math.h> #define MANDEL_SET /* #define REALZn(x,y,a) ((x*x)-(y*y)+a) #define IMAGINARYZn(x,y,b) ((2*x*y)+b) #define ITERATION 400.0 #define MAGNITUDE(x,y) (((x*x) + (y*y))) #define RESOL_X 1600 #define RESOL_Y 1000 #define A_MIN (-2.5) #define A_MAX (1.0) #define B_MIN (-1.0) #define B_MAX (1.0) */ #define MB_THREADS_NUM 4 typedef enum{ IN_MBSET, OUT_MBSET, } Attrib; class MandelBrotGen { private: int xRes, yRes; int xDiv, yDiv; SDL_Surface * drawScreen; bool isInMandelBrotSet; int maxReqIncr; int mostReqIncr; int numBlksThreads; double a_increment; double b_increment; double curr_a_begin, curr_a_end; double curr_b_begin, curr_b_end; MandelBrotGen(); void CalculateThreadBounds(int threadNum, int * xBegin, int * xEnd, int * yBegin, int * yEnd); void SetPixelWithAttrib(int x, int y, Attrib enAttrib, int iter); int CreateMBThreads(); public: MandelBrotGen(int x_Res, int y_Res, SDL_Surface * screen); ~MandelBrotGen(); bool ChkMandelBrotSet(double a, double b, int * reqIncrement); void StartGeneratingMB(); void StartGeneratingMB(int xBegin, int yBegin, int xEnd, int yEnd); int GetXRes(); int GetYRes(); void OnPixel(int x, int y, int iter); void OffPixel(int x, int y, int iter); double GetAIncrement(); double GetBIncrement(); //static void * GenMandelBrotSetBlock(void * arg_Thrd_ID); }; #endif // MANDELBROTGEN_H
053e378fed68338290c15b390161e0b418d1b149
26f6173e21103fce73096db7e3b2e0476107caa7
/Queue data sctructures/QueueDataSctructure/QueueDataSctructure.cpp
0a831dd67a30a02bc2b1d1c2ba9d86ae76904ef8
[ "MIT" ]
permissive
cnc4less/CodeBeautyTutorial
3d0ece49e4456257dc138d78ae8ef59c4b8a443d
6fbedf0df4677199292b987ef63da15db5ad0c2c
refs/heads/master
2023-08-28T03:23:09.346928
2021-11-10T15:32:58
2021-11-10T15:32:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
989
cpp
// QueueDataSctructure : Learning queue data structures // Author : Anthony Guay // Date : 2/6/2021 // Credit : codebeauty youtube tutorial @https://www.youtube.com/watch?v=jaK4pn1jXTo #include <iostream> #include <queue> using namespace std; void printQueue(queue<int> queue) { while (!queue.empty()) { cout << queue.front() << " "; queue.pop(); } cout << endl; } int main() { // Queue data structure is a FIFO/FCFS data structure. Wich mean first in first out or first ocunt first serve. (example a printer) // It's diferente of a stack (last in first out) queue<int> myQueue; myQueue.push(1); myQueue.push(2); myQueue.push(3); cout << "Size is " << myQueue.size() << endl; cout << "First element is " << myQueue.front() << endl; cout << "Last element is " << myQueue.back() << endl; cout << "My queue: " << endl; printQueue(myQueue); cin.get(); }
389dfbf6fba4ac80a0e73a4a783299d9bf67e2dd
dcd6596b601028b51d38d980c261c0afb3fec978
/FlowRate/src/Registry.cpp
5b60e210cbb6a0ce769a04e56d4c5dfab2fdbb88
[]
no_license
UKCoolHandLuke/FlowRate
9774a734d662fc78565af9091bf79d9c4c5c07e6
d2c39209e35c2d981836595afa20532a74d7fa79
refs/heads/master
2021-03-13T10:38:00.602247
2020-03-14T09:45:58
2020-03-14T09:45:58
246,665,653
0
0
null
null
null
null
UTF-8
C++
false
false
1,717
cpp
#include <Registry.h> Registry::Registry() { Key = NULL; } Registry::~Registry() { if (Key != NULL) { //Close the key first Close(); } } bool Registry::Open(HKEY Hive, wstring Path) { LONG lRes = RegOpenKeyExW(HKEY_LOCAL_MACHINE, TEXT(Path.c_str()), 0, KEY_READ | KEY_WOW64_64KEY, &Key); if (lRes != ERROR_SUCCESS) { Key = NULL; return(false); } return(true); } bool Registry::Close() { if (Key != NULL) { RegCloseKey(Key); Key = NULL; return(true); } return(false); } LONG Registry::GetStringValue(const wstring &strValueName, std::wstring &strValue, const wstring &strDefaultValue) { strValue = strDefaultValue; WCHAR szBuffer[512]; DWORD dwBufferSize = sizeof(szBuffer); ULONG nError; if (Key == NULL) return(false); nError = RegQueryValueExW(Key, strValueName.c_str(), 0, NULL, (LPBYTE)szBuffer, &dwBufferSize); if (ERROR_SUCCESS == nError) strValue = szBuffer; return nError; } LONG Registry::GetBoolRegKey(const wstring &strValueName, bool &bValue, bool bDefaultValue) { DWORD nDefValue((bDefaultValue) ? 1 : 0); DWORD nResult(nDefValue); if (Key == NULL) return(false); LONG nError = GetDWORDRegKey(strValueName.c_str(), nResult, nDefValue); if (ERROR_SUCCESS == nError) bValue = (nResult != 0) ? true : false; return nError; } LONG Registry::GetDWORDRegKey(const std::wstring &strValueName, DWORD &nValue, DWORD nDefaultValue) { if (Key == NULL) return(false); nValue = nDefaultValue; DWORD dwBufferSize(sizeof(DWORD)); DWORD nResult(0); LONG nError = ::RegQueryValueExW(Key, strValueName.c_str(), 0, NULL, reinterpret_cast<LPBYTE>(&nResult), &dwBufferSize); if (ERROR_SUCCESS == nError) nValue = nResult; return nError; }
1465e3e0b2a396c321c0ebc11e42ef38b9217673
37b30edf9f643225fdf697b11fd70f3531842d5f
/content/browser/renderer_host/cross_origin_embedder_policy.cc
1b9115cd51d3fc5665e1443076c2b750bd24ad59
[ "BSD-3-Clause" ]
permissive
pauladams8/chromium
448a531f6db6015cd1f48e7d8bfcc4ec5243b775
bc6d983842a7798f4508ae5fb17627d1ecd5f684
refs/heads/main
2023-08-05T11:01:20.812453
2021-09-17T16:13:54
2021-09-17T16:13:54
407,628,666
1
0
BSD-3-Clause
2021-09-17T17:35:31
2021-09-17T17:35:30
null
UTF-8
C++
false
false
1,873
cc
// Copyright 2021 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 "content/browser/renderer_host/cross_origin_embedder_policy.h" #include "services/network/public/cpp/cross_origin_embedder_policy.h" #include "services/network/public/cpp/features.h" #include "services/network/public/mojom/url_response_head.mojom.h" #include "third_party/blink/public/common/origin_trials/trial_token_validator.h" #include "url/gurl.h" namespace content { network::CrossOriginEmbedderPolicy CoepFromMainResponse( const GURL& context_url, const network::mojom::URLResponseHead* context_main_response) { network::CrossOriginEmbedderPolicy coep = context_main_response->parsed_headers->cross_origin_embedder_policy; if (base::FeatureList::IsEnabled( network::features::kCrossOriginEmbedderPolicyCredentialless)) { return coep; } if (base::FeatureList::IsEnabled( network::features:: kCrossOriginEmbedderPolicyCredentiallessOriginTrial) && context_main_response->headers && blink::TrialTokenValidator().RequestEnablesFeature( context_url, context_main_response->headers.get(), "CrossOriginEmbedderPolicyCredentiallessOriginTrial", base::Time::Now())) { return coep; } // At this point COEP:credentialless is not enabled on this context. So it // needs to be cleared. using CoepValue = network::mojom::CrossOriginEmbedderPolicyValue; if (coep.value == CoepValue::kCredentialless) { coep.value = CoepValue::kNone; coep.reporting_endpoint.reset(); } if (coep.report_only_value == CoepValue::kCredentialless) { coep.report_only_value = CoepValue::kNone; coep.report_only_reporting_endpoint.reset(); } return coep; } } // namespace content
3932ce1bb9af536bee098bdcb7775faa0e29b654
573a66e4f4753cc0f145de8d60340b4dd6206607
/JS-CS-Detection-byExample/Dataset (ALERT 5 GB)/899902/osquery-1.4.0/osquery-1.4.0/include/osquery/flags.h
b5a1ff72ed886c94787f83faf38a7e1bcdffac2f
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
mkaouer/Code-Smells-Detection-in-JavaScript
3919ec0d445637a7f7c5f570c724082d42248e1b
7130351703e19347884f95ce6d6ab1fb4f5cfbff
refs/heads/master
2023-03-09T18:04:26.971934
2022-03-23T22:04:28
2022-03-23T22:04:28
73,915,037
8
3
null
2023-02-28T23:00:07
2016-11-16T11:47:44
null
UTF-8
C++
false
false
5,020
h
/* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #pragma once #include <map> #define STRIP_FLAG_HELP 1 #include <gflags/gflags.h> #include <osquery/status.h> #define __GFLAGS_NAMESPACE google namespace osquery { /// Type, Value, Description. typedef std::tuple<std::string, std::string, std::string> FlagDetail; /** * @brief A small tracking wrapper for options, binary flags. * * The osquery-specific gflags-like options define macro `DEFINE_osquery_flag` * uses a Flag instance to track the options data. */ class Flag { public: /* * @brief the instance accessor, but also can register flag data. * * The accessor is mostly needless. The static instance and registration of * flag data requires the accessor wrapper. * * @param name The 'name' or the options switch data. * @param type The lexical type of the flag. * @param value The default value for this flag. * @param desc The description printed to the screen during help. * @param shell_only Only print flag help when using `OSQUERY_TOOL_SHELL`. * * @return A mostly needless flag instance. */ static Flag& get(const std::string& name = "", const std::string& type = "", const std::string& value = "", const std::string& desc = "", bool shell_only = false); /* * @brief Wrapper by the Flag::get. * * @param name The 'name' or the options switch data. * @parma type The lexical type of the flag. * @param value The default value for this flag. * @param desc The description printed to the screen during help. * @param shell_only Restrict this flag to the shell help output. */ void add(const std::string& name, const std::string& type, const std::string& value, const std::string& desc, bool shell_only); private: /// Keep the ctor private, for accessing through `add` wrapper. Flag() {} public: /// The public flags instance, usable when parsing `--help`. std::map<std::string, FlagDetail> flags() { return flags_; } /// The public flags instance, usable when parsing `--help` for the shell. std::map<std::string, FlagDetail> shellFlags() { return shell_flags_; } /* * @brief Access value for a flag name. * * @param name the flag name. * @param value output parameter filled with the flag value on success. * @return status of the flag did exist. */ static Status getDefaultValue(const std::string& name, std::string& value); /* * @brief Check if flag value has been overridden. * * @param name the flag name. * @return is the flag set to its default value. */ static bool isDefault(const std::string& name); /* * @brief Update the flag value by string name, * * @param name the flag name. * @parma value the new value. * @return if the value was updated. */ static Status updateValue(const std::string& name, const std::string& value); /* * @brief Get the value of an osquery flag. * * @param name the flag name. */ std::string getValue(const std::string& name); /* * @brief Print help-style output to stdout for a given flag set. * * @param flags A flag set (usually generated from Flag::flags). */ static void printFlags(const std::map<std::string, FlagDetail> flags); private: /// The private simple map of name to value/desc flag data. std::map<std::string, FlagDetail> flags_; /// The private simple map of name to value/desc shell-only flag data. std::map<std::string, FlagDetail> shell_flags_; }; } /* * @brief Replace gflags' `DEFINE_type` macros to track osquery flags. * * @param type The `_type` symbol portion of the gflags define. * @param name The name symbol passed to gflags' `DEFINE_type`. * @param value The default value, use a C++ literal. * @param desc A string literal used for help display. */ #define DEFINE_osquery_flag(type, name, value, desc) \ DEFINE_##type(name, value, desc); \ namespace flag_##name { \ Flag flag = Flag::get(#name, #type, #value, desc); \ } /* * @brief A duplicate of DEFINE_osquery_flag except the help output will only * show when using OSQUERY_TOOL_SHELL (osqueryi). * * @param type The `_type` symbol portion of the gflags define. * @param name The name symbol passed to gflags' `DEFINE_type`. * @param value The default value, use a C++ literal. * @param desc A string literal used for help display. */ #define DEFINE_shell_flag(type, name, value, desc) \ DEFINE_##type(name, value, desc); \ namespace flag_##name { \ Flag flag = Flag::get(#name, #type, #value, desc, true); \ }
8324eb730212ea583631163ad788fc94e6a63405
8e0cdf324e67daa61f64ca916acac0f809e6a0db
/231A.cpp
021d69e23a0fa3b9641110c0b7075722a709939a
[]
no_license
ayushme53/CodeforcesSolutions
b99c99590a2d1da0a89ede204c7cedee135574b8
2661e5cbff1a735fdfcf341d497eb90fcda56c33
refs/heads/master
2022-12-23T18:29:09.567107
2020-09-30T18:00:28
2020-09-30T18:00:28
257,911,434
0
0
null
null
null
null
UTF-8
C++
false
false
617
cpp
#include <bits/stdc++.h> using namespace std; #define faster ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) #define mp make_pair #define mod 1000000007 #define qmod 998244353 #define endl "\n" #define pb push_back #define ff first #define ss second typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; const int MOD = 1e9 + 7; const int INF = 1e9 + 5; const ll LINF = LLONG_MAX; int main(){ int t; cin>>t; int c2=0; while(t--){ int a,b,c; int c1=0; cin>>a>>b>>c; if(a==1) c1++; if(b==1) c1++; if(c==1) c1++; if(c1>=2) c2++; } cout<<c2<<endl; }
8114ac6532e9fb4388e25add97c8957e52a461b7
d60d03a156d14a1c6a1d93ee112e3e81814ea6f7
/recursion/taylor.cpp
359ae3fb4a21f941f427a2eea0e3ad5c2a6baf42
[]
no_license
sonali-kar/DS
449e5c887e52eb9867fee19376a5911a421be8f2
5cdbd6264a5b2f41a239249331141c0296eaf921
refs/heads/main
2023-08-11T11:15:35.978523
2021-09-27T14:47:33
2021-09-27T14:47:33
365,948,533
0
0
null
null
null
null
UTF-8
C++
false
false
419
cpp
#include<iostream> using namespace std; double taylor(int x,int n) { static double p=1,f=1; double r; if(n==0) return 1; else r= taylor(x,n-1); p=p*x; f=f*n; return r+p/f; } int main() { double n; double r,x; cout<<"Enter the value for n,x "; cin>>x>>n; r=taylor(x,n); cout<<r; return 0; }
0dd722e8dce73867af29a2bb5f5e67f49d88f0fd
775acebaa6559bb12365c930330a62365afb0d98
/source/public/libs/widgetbin/dialogs/AbstractDialogObserver.cpp
65479bbc0a5c4e21244287feac4261416889f2a6
[]
no_license
Al-ain-Developers/indesing_plugin
3d22c32d3d547fa3a4b1fc469498de57643e9ee3
36a09796b390e28afea25456b5d61597b20de850
refs/heads/main
2023-08-14T13:34:47.867890
2021-10-05T07:57:35
2021-10-05T07:57:35
339,970,603
1
1
null
2021-10-05T07:57:36
2021-02-18T07:33:40
C++
UTF-8
C++
false
false
2,370
cpp
//======================================================================================== // // $File: //depot/devtech/16.0.x/plugin/source/public/libs/widgetbin/dialogs/AbstractDialogObserver.cpp $ // // Owner: Michael Burbidge // // $Author: pmbuilder $ // // $DateTime: 2020/11/06 13:08:29 $ // // $Revision: #2 $ // // $Change: 1088580 $ // // Copyright 1997-2010 Adobe Systems Incorporated. All rights reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file in accordance // with the terms of the Adobe license agreement accompanying it. If you have received // this file from a source other than Adobe, then your use, modification, or // distribution of it requires the prior written permission of Adobe. // //======================================================================================== #include "VCWidgetHeaders.h" #include "AbstractDialogObserver.h" // ----- Interface Includes ----- #include "IPanelControlData.h" #include "ISubject.h" // ----- Implementation Includes ----- #ifdef DEBUG #include "DebugClassUtils.h" #endif //======================================================================================== // CLASS AbstractDialogObserver //======================================================================================== AbstractDialogObserver::AbstractDialogObserver(IPMUnknown *boss) : CObserver(boss) { } AbstractDialogObserver::~AbstractDialogObserver() { } void AbstractDialogObserver::AttachToWidget(const WidgetID& widgetId, const PMIID& iidOfDataToObserve, IPanelControlData* panel) { ASSERT(widgetId != kInvalidWidgetID); ASSERT(panel != nil); IControlView * view = panel->FindWidget(widgetId); if (view) { InterfacePtr<ISubject> subject(view, IID_ISUBJECT); if (subject && !subject->IsAttached(this, iidOfDataToObserve)) { subject->AttachObserver(this, iidOfDataToObserve); } } } void AbstractDialogObserver::DetachFromWidget(const WidgetID& widgetId, const PMIID& iidOfDataToUnobserve, IPanelControlData* panel) { ASSERT(widgetId != kInvalidWidgetID); ASSERT(panel != nil); IControlView * view = panel->FindWidget(widgetId); if (view) { InterfacePtr<ISubject> subject(view, IID_ISUBJECT); if (subject && subject->IsAttached(this, iidOfDataToUnobserve)) { subject->DetachObserver(this, iidOfDataToUnobserve); } } }
5bc20a50b1a79f4b5e314f7a1bcbb81bd33f77f5
f7a0bf0b839f8256611ad8fe8d63bf8c44f03a80
/libs/wawo/include/wawo/SmartPtr.hpp
8772ad5115fff7855e19822281ca927437bb1601
[ "MIT" ]
permissive
xldeng1203/wawo
31026027a074e6ec972a6f62f8be212eac728e50
aa871e42cb2bd700974a946bd02cde6edcba72f8
refs/heads/master
2021-01-15T15:58:12.492180
2016-02-21T15:49:32
2016-02-21T15:49:32
52,434,427
0
1
null
2016-02-24T10:34:00
2016-02-24T10:34:00
null
UTF-8
C++
false
false
13,381
hpp
#ifndef _WAWO_SMART_PTR_HPP_ #define _WAWO_SMART_PTR_HPP_ #include <wawo/core.h> #define WAWO_DEBUG_REF_LOGIC #define WAWO_USE_SPIN_LOCK #ifndef NULL #define NULL 0 #endif #ifdef _DEBUG #define _DEBUG_SMART_PTR #endif namespace wawo { template <class T> inline void checked_delete(T* p) { typedef char is_this_a_complete_type[sizeof(T)?1:-1]; (void) sizeof(is_this_a_complete_type); delete p; } struct weak_ptr_lock_faild : public wawo::Exception { weak_ptr_lock_faild(): wawo::Exception(wawo::E_MEMORY_ACCESS_ERROR,"weak_ptr_lock_failed", __FILE__, __FUNCTION__,__LINE__) { } }; struct sp_counter_impl_malloc_failed: public wawo::Exception { sp_counter_impl_malloc_failed(): wawo::Exception(wawo::E_MEMORY_ALLOC_FAILED, "sp_counter_impl_malloc_failed", __FILE__, __FUNCTION__,__LINE__) {} }; } namespace wawo { /* * usage * for non_copy_able object, please extends RefObject_Abstract,,use wawo::RefPoint * for copyable objects, please use wawo::SharedPoint * */ /* * two reason result in below classes * 1, store in stl container is safe * 2, sizeof(wawo::SharedPoint) == 4, compared to sizeof(std::shared_ptr)==8 */ class sp_counter_base { private: sp_counter_base( sp_counter_base const& ); sp_counter_base& operator = (sp_counter_base const&); std::atomic<int32_t> sp_c; std::atomic<int32_t> sp_weak_c; public: sp_counter_base(): sp_c(1),sp_weak_c(1) {} virtual ~sp_counter_base() {} virtual void* get_p() = 0; virtual void dispose() = 0; virtual void destroy() { delete this; } int32_t sp_count() const { return sp_c.load(std::memory_order_acquire); } int32_t weak_count() const { return sp_weak_c.load(std::memory_order_acquire); } void require() { wawo::atomic_increment(&sp_c); } int32_t require_lock(int32_t const& val) { return wawo::atomic_increment_if_not_equal(&sp_c,val); } void release() { if( wawo::atomic_decrement(&sp_c) == 1) { dispose(); weak_release(); } } void weak_require() { wawo::atomic_increment(&sp_weak_c); } void weak_release() { if( wawo::atomic_decrement(&sp_weak_c) == 1 ) { destroy(); } } }; template <class pt> class sp_counter_impl_p: public sp_counter_base { private: typedef sp_counter_impl_p<pt> this_type; pt* _p; sp_counter_impl_p( sp_counter_impl_p const& ); sp_counter_impl_p& operator=(sp_counter_impl_p const&); public: explicit sp_counter_impl_p(pt* p): _p(p) {} virtual void* get_p() {return static_cast<void*>(_p);} virtual void dispose() { wawo::checked_delete<pt>(_p);_p=0;} }; class sp_weak_counter; class sp_counter { friend class sp_weak_counter; private: sp_counter_base* base; public: sp_counter(): base(0) {} template <class pt> explicit sp_counter(pt* p): base(0) { try { base = new sp_counter_impl_p<pt>(p); } catch(...) { wawo::checked_delete(base); throw wawo::sp_counter_impl_malloc_failed(); } } ~sp_counter() { //dcrese sp_counter_impl_p's sp_count if( base != 0) base->release(); } sp_counter(sp_counter const& r): base(r.base) { if( base != 0 ) base->require(); } sp_counter(sp_weak_counter const& weak); inline void* const get_p() const { if( base == 0 ) return 0; return base->get_p(); } //just incre //void incre_sp_count() { base->require(); } //decre , and return previous //int32_t decre_sp_count() { return base->release() ;} sp_counter& operator = (sp_counter const& r) { WAWO_ASSERT( base != r.base ); if( r.base != 0 ) r.base->require(); if( base != 0 ) base->release(); base = r.base; return *this; } void swap( sp_counter& r ) { wawo::swap(base,r.base); } int32_t sp_count() const { return base->sp_count(); } int32_t weak_count() const { return base->weak_count(); } bool operator == ( sp_counter const& r ) const { return base == r.base; } bool operator != ( sp_counter const& r ) const { return base != r.base; } bool operator < ( sp_counter const& r ) const { return base < r.base; } bool operator > ( sp_counter const& r ) const { return base > r.base; } }; class sp_weak_counter { friend class sp_counter; private: sp_counter_base* base; public: sp_weak_counter(): base(0) {} sp_weak_counter( sp_weak_counter const& counter ): base(counter.base) { if( base != 0 ) base->weak_require(); } sp_weak_counter( sp_counter const& counter ): base(counter.base) { if( base != 0 ) base->weak_require(); } ~sp_weak_counter() { if( base != 0 ) base->weak_release(); } sp_weak_counter& operator = ( sp_weak_counter const& counter ) { WAWO_ASSERT( base != counter.base ); if( counter.base != 0 ) { counter.base->weak_require(); } if( base != 0 ) base->weak_release(); base = counter.base; return *this; } sp_weak_counter& operator = (sp_counter const& counter) { WAWO_ASSERT( base != counter.base ); if( counter.base != 0 ) { counter.base->weak_require(); } if( base != 0 ) base->weak_release(); base = counter.base; return *this; } void swap( sp_weak_counter& r ) { wawo::swap(base,r.base); } bool operator == ( sp_weak_counter const& r ) const { return base == r.base; } bool operator != ( sp_weak_counter const& r) const { return base != r.base; } bool operator < ( sp_weak_counter const& r) const { return base < r.base; } bool operator > ( sp_weak_counter const& r) const { return base > r.base; } }; inline sp_counter::sp_counter(sp_weak_counter const& weak): base(weak.base) { if( base != 0 && base->require_lock(0) ) { WAWO_ASSERT( base->get_p() != 0 ); WAWO_ASSERT( base->sp_count() > 0 ); } } //class sp_convert_helper { //public: // template <class T, class Y> // inline static T* pointer_y_to_t(Y* y) { return y; } //}; //struct ap_no_grab_t {}; template <class T> class WeakPoint; //class LoggerManager; template <class T> class SharedPoint { friend class WeakPoint<T>; typedef T* POINT_TYPE; typedef SharedPoint<T> THIS_TYPE ; typedef WeakPoint<T> WEAK_POINT_TYPE; private: sp_counter sp_ct;//sp_counter public: typedef T ELEMENT_TYPE; SharedPoint():sp_ct() { } SharedPoint( T* const& point ): sp_ct(point) { } //dont make this line explicit ,,, compliler will call copy construct for ClassName o = o("xxx") ; SharedPoint( THIS_TYPE const& other ): sp_ct(other.sp_ct) { } //for static , dynamic cast template <class P> explicit SharedPoint( SharedPoint<P> const& r ): sp_ct(r.sp_ct) { } SharedPoint( WEAK_POINT_TYPE const& weak ) : sp_ct(weak.weak_ct) { } ~SharedPoint() { } int32_t SharedCount() const { return sp_ct.sp_count(); } //I don't think we need this actually, // we can use AutoPoint<t> auto_pint( new PointType() ) instead this func THIS_TYPE& operator = ( T* const& p ) { THIS_TYPE(p).swap(*this); return *this; } THIS_TYPE& operator = ( THIS_TYPE const& r ) { THIS_TYPE(r).swap(*this); return *this ; } void swap( THIS_TYPE& other ) { wawo::swap(sp_ct, other.sp_ct); } inline T* operator -> () const { T* pt = static_cast<T*>( sp_ct.get_p() ); WAWO_ASSERT( pt != 0 ); return pt; } inline T* operator -> () { T* pt = static_cast<T*>( sp_ct.get_p() ); WAWO_ASSERT( pt != 0 ); return pt; } inline T& operator * () const { T* pt = static_cast<T*>( sp_ct.get_p() ); WAWO_ASSERT( pt != 0 ); return *pt; } inline T& operator * () { T* pt = static_cast<T*>( sp_ct.get_p() ); WAWO_ASSERT( pt != 0 ); return *pt; } inline T* const Get() const { T* pt = static_cast<T*>( sp_ct.get_p() ); return pt; } inline bool operator ==(THIS_TYPE const& r) const { return sp_ct == r.sp_ct; } inline bool operator !=(THIS_TYPE const& r) const { return sp_ct != r.sp_ct; } inline bool operator < (THIS_TYPE const& r) const { return sp_ct < r.sp_ct; } inline bool operator > (THIS_TYPE const& r) const { return sp_ct > r.sp_ct; } inline bool operator ==(T* const& rp) const { return Get() == rp; } inline bool operator !=(T* const& rp) const { return Get() != rp; } private: template <class Y> friend class SharedPoint; }; template <class T, class U> SharedPoint<T> static_pointer_cast( SharedPoint<U> const& r ) { //typename SharedPoint<T>::ELEMENT_TYPE* p = static_cast< typename SharedPoint<T>::ELEMENT_TYPE* >( r.Get() ); return SharedPoint<T>(r); } //template <class T, class U> //SharedPoint<T> dynamic_pointer_cast( SharedPoint<U> const& r ) //{ //typename SharedPoint<T>::ELEMENT_TYPE* p = dynamic_cast< typename SharedPoint<T>::ELEMENT_TYPE* >( r.Get() ); // return SharedPoint<T>(p); //} //template <class T, class U> //SharedPoint<T> const_pointer_cast( SharedPoint<U> const& r ) //{ // typename SharedPoint<T>::ELEMENT_TYPE* p = const_cast< typename SharedPoint<T>::ELEMENT_TYPE* >( r.Get() ); // return SharedPoint<T>(p); //} template <class T> class WeakPoint { friend class SharedPoint<T>; private: sp_weak_counter weak_ct; public: typedef T ELEMENT_TYPE; typedef T* POINT_TYPE; typedef WeakPoint<T> THIS_TYPE; typedef SharedPoint<T> SHARED_POINT_TYPE; WeakPoint():weak_ct() {} explicit WeakPoint( SHARED_POINT_TYPE const& auto_point ): weak_ct(auto_point.sp_ct) { } ~WeakPoint() { } WeakPoint( THIS_TYPE const& r ): weak_ct(r.weak_ct) { } THIS_TYPE& operator = (THIS_TYPE const& r) { sp_weak_counter(r.weak_ct).swap(weak_ct); return *this; } THIS_TYPE& operator = (SHARED_POINT_TYPE const& r) { sp_weak_counter(r.sp_ct).swap(weak_ct); return *this; } //if lock failed, return a empty wawo::AutoPoint SHARED_POINT_TYPE Lock() const { return SHARED_POINT_TYPE( *this ); } inline bool operator == (THIS_TYPE const& r) const { return weak_ct == r.weak_ct; } inline bool operator != (THIS_TYPE const& r) const { return weak_ct != r.weak_ct; } }; } #define WAWO_SHARED_PTR wawo::SharedPoint #define WAWO_WEAK_PTR wawo::WeakPoint namespace wawo { template <class T> class RefPoint { typedef T* POINT_TYPE; typedef RefPoint<T> THIS_TYPE; private: POINT_TYPE _p; public: typedef T ELEMENT_TYPE; explicit RefPoint():_p(0) {} explicit RefPoint( POINT_TYPE const& p ) :_p(p) { if(_p != 0) _p->Grab(); } ~RefPoint() { if(_p != 0) _p->Drop(); } RefPoint( RefPoint const& r): _p(r._p) { if(_p != 0) _p->Grab(); } RefPoint& operator = (RefPoint const& r) { THIS_TYPE(r).swap(*this); return *this; } RefPoint& operator = (POINT_TYPE const& p) { THIS_TYPE(p).swap(*this); return *this; } void swap(THIS_TYPE& other) { wawo::swap( _p, other._p ); } int32_t RefCount() const { return (_p==0)?0:_p->RefCount(); } POINT_TYPE operator -> () const { WAWO_ASSERT( _p != 0 ); return _p; } T& operator * () { WAWO_ASSERT( _p != 0 ); return *_p; } POINT_TYPE Get() const {return _p;} inline bool operator == (THIS_TYPE const& r) const { return _p == r._p; } inline bool operator != (THIS_TYPE const& r) const { return _p != r._p; } inline bool operator > (THIS_TYPE const& r) const { return _p > r._p; } inline bool operator < (THIS_TYPE const& r) const { return _p < r._p; } inline bool operator == (POINT_TYPE const& p) const { return _p == p; } inline bool operator != (POINT_TYPE const& p) const { return _p != p; } inline bool operator > (POINT_TYPE const& p) const { return _p > p; } inline bool operator < (POINT_TYPE const& p) const { return _p < p; } }; /** * thread security level * you must hold one copy of AUTO_PTR FOR your objects before it is accessed across threads * * Warning: behaviour is undefined is u try to do Grab on ~self Destruct function */ class RefObject_Abstract : public wawo::NonCopyable { private: class ref_counter { friend class RefObject_Abstract; private: ref_counter( ref_counter const& ); ref_counter& operator = ( ref_counter const& ); std::atomic<int32_t> ref_c; protected: ref_counter(): ref_c(0) {} virtual ~ref_counter() {} int32_t ref_count() const {return ref_c;} void require() { wawo::atomic_increment(&ref_c); } int32_t release() { return wawo::atomic_decrement(&ref_c);} }; ref_counter counter; public: RefObject_Abstract() { } virtual ~RefObject_Abstract() { } template <class T> friend class RefPoint; protected: void Grab() { return counter.require(); } void Drop() { if( counter.release() == 1) { delete this; } } int32_t RefCount() const { return counter.ref_count(); } }; /* * Notice, I think we can't impl a const_point_cast for Ref wrapper, or ,it's not a ref wrapper.. */ template <class T, class U> RefPoint<T> static_pointer_cast( RefPoint<U> const& r ) { typename RefPoint<T>::ELEMENT_TYPE* p = static_cast< typename RefPoint<T>::ELEMENT_TYPE* >( r.Get() ); return RefPoint<T>(p); } template <class T, class U> RefPoint<T> dynamic_pointer_cast( RefPoint<U> const& r ) { typename RefPoint<T>::ELEMENT_TYPE* p = dynamic_cast< typename RefPoint<T>::ELEMENT_TYPE* >( r.Get() ); return RefPoint<T>(p); } } #define WAWO_REF_PTR wawo::RefPoint #endif//_WAWO_UTILS_AUTOREFVAR_H_
b9cccf9bf62784d2c4393dcb4eac6ec0c47440fe
c12f0be593a9b1b7507b99e89fa1271bc8089f0c
/tests/validation/reference/BinaryConvolutionLayer.h
8dae374a70268a31d288d0988a04be60bbc9df7e
[ "LicenseRef-scancode-dco-1.1", "MIT" ]
permissive
giorgio-arena/ComputeLibraryBinary
c84c8f86ca0c66179acda275cd0cee321b6c3203
b8bb65f0dc2561907e566908e102aabcb7d41d61
refs/heads/master
2020-05-03T10:45:29.784415
2019-04-29T07:39:22
2019-04-29T07:39:22
178,586,589
0
0
null
null
null
null
UTF-8
C++
false
false
1,783
h
/* * Copyright (c) 2019 ARM Limited. * * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef __ARM_COMPUTE_TEST_BINARY_CONVOLUTION_LAYER_H__ #define __ARM_COMPUTE_TEST_BINARY_CONVOLUTION_LAYER_H__ #include "tests/SimpleTensor.h" namespace arm_compute { namespace test { namespace validation { namespace reference { SimpleTensor<float> binary_convolution(const SimpleTensor<float> &src, const SimpleTensor<float> &weights, const SimpleTensor<float> &bias, const TensorShape &output_shape, const PadStrideInfo &info); } // namespace reference } // namespace validation } // namespace test } // namespace arm_compute #endif /* __ARM_COMPUTE_TEST_BINARY_CONVOLUTION_LAYER_H__ */
855af3bc2c0392a766e2521788a3a2fe73d2eb90
7a3a7295f54454dee81444c844ffe7b57b143f7c
/src/llmq/quorums_commitment.h
6a097f4dc7e072a7d31aade82d3d0fbba6fb71dc
[ "MIT" ]
permissive
Argoneum/argoneum
9f6b7f18f778fca467543035e72e014401f04a56
5c18f9d8551c9dff9e3dcf56e83c66021e291b72
refs/heads/master
2021-06-17T01:33:29.041494
2021-02-28T20:39:30
2021-02-28T20:39:30
155,546,450
7
9
MIT
2020-11-20T18:51:22
2018-10-31T11:30:30
C++
UTF-8
C++
false
false
3,246
h
// Copyright (c) 2018 The Argoneum Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef AGM_QUORUMS_COMMITMENT_H #define AGM_QUORUMS_COMMITMENT_H #include "consensus/params.h" #include "evo/deterministicmns.h" #include "bls/bls.h" namespace llmq { // This message is an aggregation of all received premature commitments and only valid if // enough (>=threshold) premature commitments were aggregated // This is mined on-chain as part of TRANSACTION_QUORUM_COMMITMENT class CFinalCommitment { public: static const uint16_t CURRENT_VERSION = 1; public: uint16_t nVersion{CURRENT_VERSION}; uint8_t llmqType{Consensus::LLMQ_NONE}; uint256 quorumHash; std::vector<bool> signers; std::vector<bool> validMembers; CBLSPublicKey quorumPublicKey; uint256 quorumVvecHash; CBLSSignature quorumSig; // recovered threshold sig of blockHash+validMembers+pubKeyHash+vvecHash CBLSSignature membersSig; // aggregated member sig of blockHash+validMembers+pubKeyHash+vvecHash public: CFinalCommitment() {} CFinalCommitment(const Consensus::LLMQParams& params, const uint256& _quorumHash); int CountSigners() const { return (int)std::count(signers.begin(), signers.end(), true); } int CountValidMembers() const { return (int)std::count(validMembers.begin(), validMembers.end(), true); } bool Verify(const std::vector<CDeterministicMNCPtr>& members, bool checkSigs) const; bool VerifyNull() const; bool VerifySizes(const Consensus::LLMQParams& params) const; void ToJson(UniValue& obj) const; public: ADD_SERIALIZE_METHODS template<typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(nVersion); READWRITE(llmqType); READWRITE(quorumHash); READWRITE(DYNBITSET(signers)); READWRITE(DYNBITSET(validMembers)); READWRITE(quorumPublicKey); READWRITE(quorumVvecHash); READWRITE(quorumSig); READWRITE(membersSig); } public: bool IsNull() const { if (std::count(signers.begin(), signers.end(), true) || std::count(validMembers.begin(), validMembers.end(), true)) { return false; } if (quorumPublicKey.IsValid() || !quorumVvecHash.IsNull() || membersSig.IsValid() || quorumSig.IsValid()) { return false; } return true; } }; class CFinalCommitmentTxPayload { public: static const uint16_t CURRENT_VERSION = 1; public: uint16_t nVersion{CURRENT_VERSION}; uint32_t nHeight{(uint32_t)-1}; CFinalCommitment commitment; public: ADD_SERIALIZE_METHODS template<typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(nVersion); READWRITE(nHeight); READWRITE(commitment); } void ToJson(UniValue& obj) const; }; bool CheckLLMQCommitment(const CTransaction& tx, const CBlockIndex* pindexPrev, CValidationState& state); } #endif //AGM_QUORUMS_COMMITMENT_H
b2a6672c070d0933333a622f58b4c3b2fe7a00a7
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/chromium_org/extensions/common/permissions/permission_message_provider.h
7f682e3e5de37026462d2a4d3d70cf6bdf9ee515
[ "BSD-3-Clause", "MIT" ]
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
2,263
h
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef EXTENSIONS_COMMON_PERMISSIONS_PERMISSION_MESSAGE_PROVIDER_H_ #define EXTENSIONS_COMMON_PERMISSIONS_PERMISSION_MESSAGE_PROVIDER_H_ #include <vector> #include "extensions/common/manifest.h" #include "extensions/common/permissions/permission_message.h" namespace extensions { class PermissionSet; // The PermissionMessageProvider interprets permissions, translating them // into warning messages to show to the user. It also determines whether // a new set of permissions entails showing new warning messages. class PermissionMessageProvider { public: PermissionMessageProvider() {} virtual ~PermissionMessageProvider() {} // Return the global permission message provider. static const PermissionMessageProvider* Get(); // Gets the localized permission messages that represent this set. // The set of permission messages shown varies by extension type. virtual PermissionMessages GetPermissionMessages( const PermissionSet* permissions, Manifest::Type extension_type) const = 0; // Gets the localized permission messages that represent this set (represented // as strings). The set of permission messages shown varies by extension type. virtual std::vector<string16> GetWarningMessages( const PermissionSet* permissions, Manifest::Type extension_type) const = 0; // Gets the localized permission details for messages that represent this set // (represented as strings). The set of permission messages shown varies by // extension type. virtual std::vector<string16> GetWarningMessagesDetails( const PermissionSet* permissions, Manifest::Type extension_type) const = 0; // Returns true if |new_permissions| has a greater privilege level than // |old_permissions|. // Whether certain permissions are considered varies by extension type. virtual bool IsPrivilegeIncrease( const PermissionSet* old_permissions, const PermissionSet* new_permissions, Manifest::Type extension_type) const = 0; }; } // namespace extensions #endif // EXTENSIONS_COMMON_PERMISSIONS_PERMISSION_MESSAGE_PROVIDER_H_
a8e3fa94f5be0504757f6ec41fbe8e938e1a5a2c
504fa56796d605107ac43c8a43a794b338079d75
/hmailserver/source/Server/SMTP/SMTPConfiguration.h
6ca9a976c636720b8c4513f6a4d5e6b3c541eb9d
[]
no_license
bighossbiz/hmailserver
5877796f95d2c19c34744fdbefb06d819c58410d
39506daf6b95e554bd3153206eaaf0bd22affdf1
refs/heads/master
2021-01-21T04:04:09.604030
2014-08-31T13:15:06
2014-08-31T13:15:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,947
h
#pragma once #include "../Common/BO/IncomingRelays.h" namespace HM { class PropertySet; class Routes; class DNSBlackLists; class BlockedAttachments; enum ConnectionSecurity; class SMTPConfiguration { public: SMTPConfiguration(); virtual ~SMTPConfiguration(); bool Load(); void SetMaxSMTPConnections(int newVal); void SetAuthAllowPlainText(bool newVal); void SetAllowMailFromNull(bool newVal); void SetLogSMTPConversations(bool bNewVal); void SetUseORDB(bool NewVal); void SetUseSpamhaus(bool NewVal); void SetNoOfRetries(long lNewVal); void SetMinutesBetweenTry(long lHoursBetween); void SetSMTPRelayer(const String &sRelayer); void SetSMTPRelayerPort(long lPort); long GetSMTPRelayerPort(); void SetSMTPRelayerConnectionSecurity(ConnectionSecurity connection_security); ConnectionSecurity GetSMTPRelayerConnectionSecurity(); void SetSMTPConnectionSecurity(ConnectionSecurity connection_security); ConnectionSecurity GetSMTPConnectionSecurity(); void SetMaxNoOfDeliveryThreads(int lNewValue); String GetWelcomeMessage() const; void SetWelcomeMessage(const String &sMessage); String GetSMTPDeliveryBindToIP() const; void SetSMTPDeliveryBindToIP(const String &sIP); bool GetBlockBareLFs() const; int GetMaxSMTPConnections(); bool GetAuthAllowPlainText(); bool GetAllowMailFromNull(); long GetMinutesBetweenTry(); long GetNoOfRetries(); String GetSMTPRelayer() const; int GetMaxNoOfDeliveryThreads(); bool GetSMTPRelayerRequiresAuthentication(); void SetSMTPRelayerRequiresAuthentication(bool bNewVal); String GetSMTPRelayerUsername() const; void SetSMTPRelayerUsername(const String & Value); String GetSMTPRelayerPassword() const; void SetSMTPRelayerPassword(const String & Value); bool GetAllowIncorrectLineEndings(); void SetAllowIncorrectLineEndings(bool bNewVal); int GetMaxMessageSize(); void SetMaxMessageSize(int iNewVal); int GetMaxSMTPRecipientsInBatch(); void SetMaxSMTPRecipientsInBatch(int iNewVal); int GetRuleLoopLimit(); void SetRuleLoopLimit(int iNewVal); int GetMaxNumberOfMXHosts(); void SetMaxNumberOfMXHosts(int iNewVal); bool XMLStore(XNode *pBackupNode, int Options); bool XMLLoad(XNode *pBackupNode, int iRestoreOptions); bool GetAddDeliveredToHeader(); void SetAddDeliveredToHeader(bool bNewVal); void OnPropertyChanged(shared_ptr<Property> pProperty); shared_ptr<IncomingRelays> GetIncomingRelays() {return incoming_relays_;} shared_ptr<Routes> GetRoutes() {return routes_;} private: shared_ptr<PropertySet> GetSettings_() const; shared_ptr<IncomingRelays> incoming_relays_; shared_ptr<Routes> routes_; }; }
fc13a0aa8e75c060802dec4d3c00864ed08e47c5
096c003ed901129b21e2352ad010232526be239c
/codeEmbarqué/carteMoteur/src/MotorCtrl.cpp
a989aaadaf552f7f668e96a89434b46f4a31b9d5
[]
no_license
RoseTeam/CommandMot
02e4cb62a369437411c43ff9a8fdaede23ddee47
f2270dd00b23ed8f1cac448bf4f2ce2fa4f47be8
refs/heads/master
2021-01-10T15:28:21.684845
2016-03-07T22:53:12
2016-03-07T22:53:12
50,875,833
0
0
null
null
null
null
UTF-8
C++
false
false
8,476
cpp
/********************************************************************************************** * Motor Driver Library - Version 1.0 * by Lucas Soubeyrand and David * This Library is licensed under Copyleft It handles low level (position and speed) control of Continuous Current Motors and Alpha/Delta control of a dual motor mobile platform *********************************************************************************************/ #include "MotorCtrl.h" //#include "SerialParser.h" #include "mbed.h" #define DEUXPI 6.28318530718 #define PI 3.14159265359 MotorCtrl::MotorCtrl(USBSerialCom& _comPC) : ComPC(_comPC), wheelL(Encoder1_A, Encoder1_B, NC, ENCODER_RES), wheelR(Encoder2_A, Encoder2_B, NC, ENCODER_RES), PidAngle(&angle, &pidAngleOutput, &angleCommand.target, KP_POLAR_ANGLE, KI_POLAR_ANGLE, KD_POLAR_ANGLE, -1), PidDistance(&distance, &pidDistanceOutput, &distanceCommand.target ,KP_POLAR_LINEAR, KI_POLAR_LINEAR, KD_POLAR_LINEAR, -1), angle_buf(4), distance_buf(4) { ODO_X = 0; ODO_Y = 0; ODO_Theta = 0; ODO_Theta_Offset = 0.0; ODO_khi = 0.0; ODO_ds = 0.0; tickToDistance = (PI * R_WHEEL/ENCODER_RES) * 54.4 / 100.; tickToAngle = PI * R_WHEEL/(WHEEL_B * ENCODER_RES) * DEUXPI / 5.569498538970947; distanceCommand.SetStepPerMeter(1.0/tickToDistance); angleCommand.SetStepPerMeter(1.0/tickToAngle); isEnabled = 1; commandUUID = 0; // variable de position initialisées mode_deplacement = 1;// sert à définir le mode de déplacement : polaire, linéaire...(ici 1 seul mode : polaire) } void MotorCtrl::ComputeOdometry() { deltaDistance = distance - previousDistance; previousDistance = distance; double trueDeltaDistance = deltaDistance * tickToDistance; static double PREVIOUS_ODO_Theta = 0; //ODO_ds = deltaDistance/ENCODER_RES;// angle rotation en radians!!! ODO_Theta = (tickToAngle * angle) + ODO_Theta_Offset; // mesure la rotation en radian ODO_DELTA_X = trueDeltaDistance * cos(ODO_Theta); //variation de position du robot sur l'axe X de la table ODO_DELTA_Y = trueDeltaDistance * sin(ODO_Theta); ODO_DELTA_Theta = ODO_Theta - PREVIOUS_ODO_Theta; PREVIOUS_ODO_Theta = ODO_Theta; ODO_X = ODO_X + ODO_DELTA_X; ODO_Y = ODO_Y + ODO_DELTA_Y; } void MotorCtrl::setX(float x){ ODO_X = x; } void MotorCtrl::setY(float y){ ODO_Y = y; } void MotorCtrl::setAngle(float Theta){ ODO_Theta_Offset = Theta - (tickToAngle * angle); ODO_Theta = Theta; } void MotorCtrl::setTarget(float distance, float angle, float finalDistanceSpeed, float finalAngleSpeed, int uuid){ commandUUID = uuid; distanceCommand.setTarget(distance,finalDistanceSpeed); angleCommand.setTarget(angle,finalAngleSpeed); } void MotorCtrl::setTargetAngle(float angleAbs, int uuid){ commandUUID = uuid; double angle = angleAbs - ODO_Theta; if (angle > 0.0){ angle = fmod(angle + PI, 2.0 * PI) - PI; } else { angle = fmod(angle - PI, 2.0 * PI) + PI; } angleCommand.setTarget(angle, 0); } void MotorCtrl::setTargetXY(float x, float y, float finalDistanceSpeed, int mode, int uuid){ //mode rotation = 1, distance = 2 , both = 3 commandUUID = uuid; x -= ODO_X; y -= ODO_Y; float dist = 0.0; float angle = 0.0; if (x != 0.0 || y != 0.0){ dist = sqrt(x * x + y * y); angle = atan2(y,x) - ODO_Theta; if (angle > 0.0){ angle = fmod(angle + PI, 2.0 * PI) - PI; } else { angle = fmod(angle - PI, 2.0 * PI) + PI; } } if (mode & 0x2){ distanceCommand.setTarget(dist, finalDistanceSpeed); } if (mode & 0x1){ angleCommand.setTarget(angle,0); } } void MotorCtrl::setTickToAngle(float pTickToAngle){ tickToAngle = pTickToAngle; angleCommand.SetStepPerMeter(1.0/pTickToAngle); } void MotorCtrl::setTickToDistance(float pTickToDistance){ tickToDistance = pTickToDistance; distanceCommand.SetStepPerMeter(1.0/pTickToDistance); } void MotorCtrl::enable(bool is_enabled){ isEnabled = is_enabled; distanceCommand.Reset(distance); // reset speed trajectory generator angleCommand.Reset(angle); } /* void MotorCtrl::SystemCtrl(){ PidDistance.Compute(); PidAngle.Compute(); float setpointAspeed = ComPC.getTtwist()/100.0; float setpointLspeed = ComPC.getVtwist()/100.0; float motorL = pidDistanceOutput + pidAngleOutput; float motorR = pidDistanceOutput - pidAngleOutput; ComPC.sendHeartBeat(motorL); if(isEnabled){ Motors.Motor1(motorL); Motors.Motor2(motorR); } else { Motors.Motor1(0); Motors.Motor2(0); } } */ void MotorCtrl::SystemCtrl(){ float setpointAspeed = ComPC.getTtwist() / 10000.0; float setpointLspeed = ComPC.getVtwist() / 10000.0; //float feedbackAspeed = (ODO_Theta - OLD_ODO_Theta)*TE; //float feedbackLspeed = ODO_ds / ENCODER_RES * TE; float feedbackAspeed = getODO_SPEED_Theta(); float feedbackLspeed = getODO_SPEED_X(); //OLD_ODO_Theta = ODO_Theta; float orien = Compute_PID_Angle(feedbackAspeed, setpointAspeed); float dist = Compute_PID_Linear(feedbackLspeed, setpointLspeed); pidA = orien; pidT = dist; float motorL = dist - orien; float motorR = dist + orien; //motorL = ComPC.getTtwist()/10000.0*600.0; //motorR = ComPC.getTtwist()/10000.0*600.0; if (motorL > 255) {motorL = 255;} else if (motorL < -255) {motorL = -255;} if (motorR > 255) {motorR = 255;} else if (motorR < -255) {motorR = -255;} pidL = motorL; pidR = motorR; if(isEnabled) { Motors.Motor1(motorR); Motors.Motor2(motorL); Debug(orien, dist); } else { Motors.Motor1(0); Motors.Motor2(0); } } float MotorCtrl::Compute_PID_Angle(float feedbackAspeed, float setpointAspeed) { float error = setpointAspeed - feedbackAspeed; static float old_error = 0.0; float error_dif = error - old_error; old_error = error; float P = error * ComPC.getKpPA(); float D = error_dif * ComPC.getKdPA(); float I = 0.0; float res = P + I + D; return res; } float MotorCtrl::Compute_PID_Linear(float feedbackLspeed, float setpointLspeed) { float error = setpointLspeed - feedbackLspeed; static float old_error = 0.0; float error_dif = error - old_error; old_error = error; float P = error * ComPC.getKpPL(); float D = error_dif * ComPC.getKdPL(); float I = 0.0; float res = P + D + I; return res; } void MotorCtrl::Interrupt_Handler_Encoder() { wheelLTick = wheelL.getPulses(); wheelRTick = wheelR.getPulses(); distance_buf.put(wheelLTick + wheelRTick); angle_buf .put(wheelRTick - wheelLTick); } bool MotorCtrl::DataAvailable(){ if (distance_buf.available()){ distance = distance_buf; angle = angle_buf; //ComPC.sendHeartBeat(2); return true; } return false; } void MotorCtrl::ResetCtrl() //Reset all the system control variables according to the Reset be from the comyt { ODO_Theta = 0; ODO_DELTA_X = 0; ODO_DELTA_Y = 0; ODO_DELTA_Theta = 0; ODO_X = 0; ODO_Y = 0; } void MotorCtrl::Compute() { // compute target //distanceCommand.setTarget(0.1,0.0);//ComPC.getVtwist(),0.0); //ComPC.printRobotStatus(); /*distanceCommand.Compute(); angleCommand.Compute(); distanceCommand.blockageDetector(distance); angleCommand.blockageDetector(angle);*/ SystemCtrl(); } double MotorCtrl::getODO_X(){ return ODO_X; } double MotorCtrl::getODO_Y(){ return ODO_Y; } double MotorCtrl::getODO_Theta(){ return ODO_Theta; } double MotorCtrl::getODO_SPEED_X(){ return ODO_DELTA_X * TE; } double MotorCtrl::getODO_SPEED_Y(){ return ODO_DELTA_Y * TE; } double MotorCtrl::getODO_SPEED_Theta() { return ODO_DELTA_Theta * TE; } long MotorCtrl::getWheelL() { return wheelLTick; } long MotorCtrl::getWheelR() { return wheelRTick; } void MotorCtrl::Debug(float orien, float dist){ ComPC.sendFeedback(pidL,pidR,orien,dist); }
cd3746a3fe7911571215010b8ee1576acac22dbd
777a75e6ed0934c193aece9de4421f8d8db01aac
/src/Providers/UNIXProviders/EndpointIdentity/UNIX_EndpointIdentity_SOLARIS.hxx
91811e522dbd4cf95dea6db262acc0adad227670
[ "MIT" ]
permissive
brunolauze/openpegasus-providers-old
20fc13958016e35dc4d87f93d1999db0eae9010a
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
refs/heads/master
2021-01-01T20:05:44.559362
2014-04-30T17:50:06
2014-04-30T17:50:06
19,132,738
1
0
null
null
null
null
UTF-8
C++
false
false
130
hxx
#ifdef PEGASUS_OS_SOLARIS #ifndef __UNIX_ENDPOINTIDENTITY_PRIVATE_H #define __UNIX_ENDPOINTIDENTITY_PRIVATE_H #endif #endif
fe94d7d8db37a20d02bc9dd3662d107dc83813be
5db22247ed9ee65139b87c1ed28108cd4b1ac6e5
/Classes/Native/AssemblyU2DCSharp_MultiPlatformFunction3311920458.h
0143a8c8533ccee76f4b166bf0093ab6272cfc27
[]
no_license
xubillde/JLMC
fbb1a80dc9bbcda785ccf7a85eaf9228f3388aff
408af89925c629a4d0828d66f6ac21e14e78d3ec
refs/heads/master
2023-07-06T00:44:22.164698
2016-11-25T05:01:16
2016-11-25T05:01:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
527
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_Object707969140.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // MultiPlatformFunction struct MultiPlatformFunction_t3311920458 : public Il2CppObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif
622c536fccbc7c696d7d776632888ac6cd18552e
13a32b92b1ba8ffb07e810dcc8ccdf1b8b1671ab
/home--tommy--mypy/mypy/lib/python2.7/site-packages/pystan/stan/lib/stan_math/stan/math/prim/mat/fun/inverse.hpp
18ab75973c50b065e0eb20630956492c20b64c89
[ "Unlicense", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
tommybutler/mlearnpy2
8ec52bcd03208c9771d8d02ede8eaa91a95bda30
9e5d377d0242ac5eb1e82a357e6701095a8ca1ff
refs/heads/master
2022-10-24T23:30:18.705329
2022-10-17T15:41:37
2022-10-17T15:41:37
118,529,175
0
2
Unlicense
2022-10-15T23:32:18
2018-01-22T23:27:10
Python
UTF-8
C++
false
false
570
hpp
#ifndef STAN_MATH_PRIM_MAT_FUN_INVERSE_HPP #define STAN_MATH_PRIM_MAT_FUN_INVERSE_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/mat/err/check_square.hpp> namespace stan { namespace math { /** * Returns the inverse of the specified matrix. * @param m Specified matrix. * @return Inverse of the matrix. */ template <typename T, int R, int C> inline Eigen::Matrix<T, R, C> inverse(const Eigen::Matrix<T, R, C>& m) { check_square("inverse", "m", m); return m.inverse(); } } } #endif
d4d6780e58a227d23fe7e430f1f4c8a13022d111
791214fc524dcaccd49dfe2a08c3b9c4402ec311
/include/pd_sink.h
ac7d28351588debe835c397cb71aacc785851248
[ "MIT" ]
permissive
noahwilliamsson/zy12pdn-oss
efa19d69ff4433835ab335dd67c4921c480c70af
bbf8772fb14eff97a32e478eafc6b9093081e50b
refs/heads/master
2023-02-26T21:09:28.865561
2020-12-05T14:40:48
2020-12-05T14:40:48
333,246,685
7
0
MIT
2021-01-31T17:52:07
2021-01-26T23:35:08
null
UTF-8
C++
false
false
3,331
h
// // USB Power Delivery Sink Using FUSB302B // Copyright (c) 2020 Manuel Bleichenbacher // // Licensed under MIT License // https://opensource.org/licenses/MIT // // USB PD sink handling PD messages and state changes // #ifndef _pd_sink_h_ #define _pd_sink_h_ #include "fusb302.h" namespace usb_pd { /// Power supply type enum class pd_supply_type : uint8_t { /// Fixed supply (Vmin = Vmax) fixed = 0, /// Battery battery = 1, /// Variable supply (non-battery) variable = 2, /// Programmable power supply pps = 3 }; /// Power deliver protocol enum class pd_protocol { /// No USB PD communication (5V only) usb_20, /// USB PD communication usb_pd }; /// Power source capability struct source_capability { /// Supply type (fixed, batttery, variable etc.) pd_supply_type supply_type; /// Position within message (don't touch) uint8_t obj_pos; /// Maximum current (in mA) uint16_t max_current; /// Voltage (in mV) uint16_t voltage; /// Minimum voltage for variable supplies (in mV) uint16_t min_voltage; }; /// Callback event types enum class callback_event { /// Power delivery protocol has changed protocol_changed, /// Source capabilities have changed (immediately request power) source_caps_changed, /// Requested power has been accepted (but not ready yet) power_accepted, /// Requested power has been rejected power_rejected, /// Requested power is now ready power_ready }; struct pd_sink { typedef void (*event_callback)(callback_event event); void init(); void stop(); void set_event_callback(event_callback cb); void poll(); /** * Requests the specified voltage from the source. * * The source will respond with `accepted` and `ps_ready` (if successful) * or `rejected` if unsucessful. Separate events will be triggered for these * messages. * * If the source hasn't advertised the selected message, no request is sent. * * @param voltage the desired voltage (in mV) * @param max_current the desired maximum current (in mA), or 0 for the source's maximum current */ void request_power(int voltage, int max_current = 0); /// Active power delivery protocol pd_protocol protocol() { return protocol_; } /// Number of valid elements in `source_caps` array uint8_t num_source_caps = 0; /// Array of supply capabilities source_capability source_caps[10]; /// Indicates if the source can deliver unconstrained power (e.g. a wall wart) bool is_unconstrained = false; /// Requested voltage (in mV) uint16_t requested_voltage = 0; /// Requested maximum current (in mA) uint16_t requested_max_current = 0; /// Active voltage (in mV) uint16_t active_voltage = 5000; /// Active maximum current (in mA) uint16_t active_max_current = 900; private: void handle_msg(uint16_t header, const uint8_t* payload); void handle_src_cap_msg(uint16_t header, const uint8_t* payload); bool update_protocol(); void notify(callback_event event); fusb302 pd_controller; event_callback event_callback_ = nullptr; pd_protocol protocol_ = pd_protocol::usb_20; bool supports_ext_message = false; }; } // namespace usb_pd #endif
d3acf0fd468751e21229dd39d454b0df4d1f9703
f11f3db409d1df20ac739739ca9c2643bc147c78
/Source/BansheeCore/Source/BsRendererMeshData.cpp
5e65f85c16ef23212d063066d47d1fa5b02fe7f7
[]
no_license
MarcoROG/BansheeEngine
e341c6412f735a072ed04d42859b61ddfb5d25e6
d6d4efa5f3f66b8b70eb8f361223e639679da09a
refs/heads/master
2021-01-01T17:55:37.000197
2017-08-15T20:43:25
2017-08-15T20:43:25
60,541,636
0
0
null
2016-06-06T16:04:40
2016-06-06T16:04:40
null
UTF-8
C++
false
false
16,083
cpp
//********************************** Banshee Engine (www.banshee3d.com) **************************************************// //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************// #include "BsRendererMeshData.h" #include "BsVertexDataDesc.h" #include "BsVector2.h" #include "BsVector3.h" #include "BsVector4.h" #include "BsColor.h" #include "BsPixelUtil.h" #include "BsRendererManager.h" #include "BsRenderer.h" #include "BsMeshUtility.h" namespace bs { RendererMeshData::RendererMeshData(UINT32 numVertices, UINT32 numIndices, VertexLayout layout, IndexType indexType) { SPtr<VertexDataDesc> vertexDesc = vertexLayoutVertexDesc(layout); mMeshData = bs_shared_ptr_new<MeshData>(numVertices, numIndices, vertexDesc, indexType); } RendererMeshData::RendererMeshData(const SPtr<MeshData>& meshData) :mMeshData(meshData) { } void RendererMeshData::getPositions(Vector3* buffer, UINT32 size) { if (!mMeshData->getVertexDesc()->hasElement(VES_POSITION)) return; UINT32 numElements = mMeshData->getNumVertices(); assert(numElements * sizeof(Vector3) == size); mMeshData->getVertexData(VES_POSITION, (UINT8*)buffer, size); } void RendererMeshData::setPositions(Vector3* buffer, UINT32 size) { if (!mMeshData->getVertexDesc()->hasElement(VES_POSITION)) return; UINT32 numElements = mMeshData->getNumVertices(); assert(numElements * sizeof(Vector3) == size); mMeshData->setVertexData(VES_POSITION, (UINT8*)buffer, size); } void RendererMeshData::getNormals(Vector3* buffer, UINT32 size) { if (!mMeshData->getVertexDesc()->hasElement(VES_NORMAL)) return; UINT32 numElements = mMeshData->getNumVertices(); assert(numElements * sizeof(Vector3) == size); UINT8* normalSrc = mMeshData->getElementData(VES_NORMAL); UINT32 stride = mMeshData->getVertexDesc()->getVertexStride(0); MeshUtility::unpackNormals(normalSrc, buffer, numElements, stride); } void RendererMeshData::setNormals(Vector3* buffer, UINT32 size) { if (!mMeshData->getVertexDesc()->hasElement(VES_NORMAL)) return; UINT32 numElements = mMeshData->getNumVertices(); assert(numElements * sizeof(Vector3) == size); UINT8* normalDst = mMeshData->getElementData(VES_NORMAL); UINT32 stride = mMeshData->getVertexDesc()->getVertexStride(0); MeshUtility::packNormals(buffer, normalDst, numElements, sizeof(Vector3), stride); } void RendererMeshData::getTangents(Vector4* buffer, UINT32 size) { if (!mMeshData->getVertexDesc()->hasElement(VES_TANGENT)) return; UINT32 numElements = mMeshData->getNumVertices(); assert(numElements * sizeof(Vector4) == size); UINT8* tangentSrc = mMeshData->getElementData(VES_TANGENT); UINT32 stride = mMeshData->getVertexDesc()->getVertexStride(0); MeshUtility::unpackNormals(tangentSrc, buffer, numElements, stride); } void RendererMeshData::setTangents(Vector4* buffer, UINT32 size) { if (!mMeshData->getVertexDesc()->hasElement(VES_TANGENT)) return; UINT32 numElements = mMeshData->getNumVertices(); assert(numElements * sizeof(Vector4) == size); UINT8* tangentDst = mMeshData->getElementData(VES_TANGENT); UINT32 stride = mMeshData->getVertexDesc()->getVertexStride(0); MeshUtility::packNormals(buffer, tangentDst, numElements, sizeof(Vector4), stride); } void RendererMeshData::getColors(Color* buffer, UINT32 size) { if (!mMeshData->getVertexDesc()->hasElement(VES_COLOR)) return; UINT32 numElements = mMeshData->getNumVertices(); assert(numElements * sizeof(Vector4) == size); UINT8* colorSrc = mMeshData->getElementData(VES_COLOR); UINT32 stride = mMeshData->getVertexDesc()->getVertexStride(0); Color* colorDst = buffer; for (UINT32 i = 0; i < numElements; i++) { PixelUtil::unpackColor(colorDst, PF_RGBA8, (void*)colorSrc); colorSrc += stride; colorDst++; } } void RendererMeshData::setColors(Color* buffer, UINT32 size) { if (!mMeshData->getVertexDesc()->hasElement(VES_COLOR)) return; UINT32 numElements = mMeshData->getNumVertices(); assert(numElements * sizeof(Vector4) == size); UINT8* colorDst = mMeshData->getElementData(VES_COLOR); UINT32 stride = mMeshData->getVertexDesc()->getVertexStride(0); Color* colorSrc = buffer; for (UINT32 i = 0; i < numElements; i++) { PixelUtil::packColor(*colorSrc, PF_RGBA8, (void*)colorDst); colorSrc++; colorDst += stride; } } void RendererMeshData::setColors(UINT32* buffer, UINT32 size) { if (!mMeshData->getVertexDesc()->hasElement(VES_COLOR)) return; UINT32 numElements = mMeshData->getNumVertices(); assert(numElements * sizeof(UINT32) == size); mMeshData->setVertexData(VES_COLOR, (UINT8*)buffer, size); } void RendererMeshData::getUV0(Vector2* buffer, UINT32 size) { if (!mMeshData->getVertexDesc()->hasElement(VES_TEXCOORD, 0)) return; UINT32 numElements = mMeshData->getNumVertices(); assert(numElements * sizeof(Vector2) == size); mMeshData->getVertexData(VES_TEXCOORD, (UINT8*)buffer, size, 0); } void RendererMeshData::setUV0(Vector2* buffer, UINT32 size) { if (!mMeshData->getVertexDesc()->hasElement(VES_TEXCOORD, 0)) return; UINT32 numElements = mMeshData->getNumVertices(); assert(numElements * sizeof(Vector2) == size); mMeshData->setVertexData(VES_TEXCOORD, (UINT8*)buffer, size, 0); } void RendererMeshData::getUV1(Vector2* buffer, UINT32 size) { if (!mMeshData->getVertexDesc()->hasElement(VES_TEXCOORD, 1)) return; UINT32 numElements = mMeshData->getNumVertices(); assert(numElements * sizeof(Vector2) == size); mMeshData->getVertexData(VES_TEXCOORD, (UINT8*)buffer, size, 1); } void RendererMeshData::setUV1(Vector2* buffer, UINT32 size) { if (!mMeshData->getVertexDesc()->hasElement(VES_TEXCOORD, 1)) return; UINT32 numElements = mMeshData->getNumVertices(); assert(numElements * sizeof(Vector2) == size); mMeshData->setVertexData(VES_TEXCOORD, (UINT8*)buffer, size, 1); } void RendererMeshData::getBoneWeights(BoneWeight* buffer, UINT32 size) { SPtr<VertexDataDesc> vertexDesc = mMeshData->getVertexDesc(); if (!vertexDesc->hasElement(VES_BLEND_WEIGHTS) || !vertexDesc->hasElement(VES_BLEND_INDICES)) return; UINT32 numElements = mMeshData->getNumVertices(); assert(numElements * sizeof(BoneWeight) == size); UINT8* weightPtr = mMeshData->getElementData(VES_BLEND_WEIGHTS); UINT8* indexPtr = mMeshData->getElementData(VES_BLEND_INDICES); UINT32 stride = vertexDesc->getVertexStride(0); BoneWeight* weightDst = buffer; for (UINT32 i = 0; i < numElements; i++) { UINT8* indices = indexPtr; float* weights = (float*)weightPtr; weightDst->index0 = indices[0]; weightDst->index1 = indices[1]; weightDst->index2 = indices[2]; weightDst->index3 = indices[3]; weightDst->weight0 = weights[0]; weightDst->weight1 = weights[1]; weightDst->weight2 = weights[2]; weightDst->weight3 = weights[3]; weightDst++; indexPtr += stride; weightPtr += stride; } } void RendererMeshData::setBoneWeights(BoneWeight* buffer, UINT32 size) { SPtr<VertexDataDesc> vertexDesc = mMeshData->getVertexDesc(); if (!vertexDesc->hasElement(VES_BLEND_WEIGHTS) || !vertexDesc->hasElement(VES_BLEND_INDICES)) return; UINT32 numElements = mMeshData->getNumVertices(); assert(numElements * sizeof(BoneWeight) == size); UINT8* weightPtr = mMeshData->getElementData(VES_BLEND_WEIGHTS); UINT8* indexPtr = mMeshData->getElementData(VES_BLEND_INDICES); UINT32 stride = vertexDesc->getVertexStride(0); BoneWeight* weightSrc = buffer; for (UINT32 i = 0; i < numElements; i++) { UINT8* indices = indexPtr; float* weights = (float*)weightPtr; indices[0] = weightSrc->index0; indices[1] = weightSrc->index1; indices[2] = weightSrc->index2; indices[3] = weightSrc->index3; weights[0] = weightSrc->weight0; weights[1] = weightSrc->weight1; weights[2] = weightSrc->weight2; weights[3] = weightSrc->weight3; weightSrc++; indexPtr += stride; weightPtr += stride; } } void RendererMeshData::getIndices(UINT32* buffer, UINT32 size) { UINT32 indexSize = mMeshData->getIndexElementSize(); UINT32 numIndices = mMeshData->getNumIndices(); assert(numIndices * indexSize == size); if (mMeshData->getIndexType() == IT_16BIT) { UINT16* src = mMeshData->getIndices16(); UINT32* dest = buffer; for (UINT32 i = 0; i < numIndices; i++) { *dest = *src; src++; dest++; } } else { memcpy(buffer, mMeshData->getIndices32(), size); } } void RendererMeshData::setIndices(UINT32* buffer, UINT32 size) { UINT32 indexSize = mMeshData->getIndexElementSize(); UINT32 numIndices = mMeshData->getNumIndices(); assert(numIndices * indexSize == size); if (mMeshData->getIndexType() == IT_16BIT) { UINT16* dest = mMeshData->getIndices16(); UINT32* src = buffer; for (UINT32 i = 0; i < numIndices; i++) { *dest = *src; src++; dest++; } } else { memcpy(mMeshData->getIndices32(), buffer, size); } } SPtr<RendererMeshData> RendererMeshData::create(UINT32 numVertices, UINT32 numIndices, VertexLayout layout, IndexType indexType) { return RendererManager::instance().getActive()->_createMeshData(numVertices, numIndices, layout, indexType); } SPtr<RendererMeshData> RendererMeshData::create(const SPtr<MeshData>& meshData) { return RendererManager::instance().getActive()->_createMeshData(meshData); } SPtr<VertexDataDesc> RendererMeshData::vertexLayoutVertexDesc(VertexLayout type) { SPtr<VertexDataDesc> vertexDesc = VertexDataDesc::create(); INT32 intType = (INT32)type; if (intType == 0) type = VertexLayout::Position; if ((intType & (INT32)VertexLayout::Position) != 0) vertexDesc->addVertElem(VET_FLOAT3, VES_POSITION); if ((intType & (INT32)VertexLayout::Normal) != 0) vertexDesc->addVertElem(VET_UBYTE4_NORM, VES_NORMAL); if ((intType & (INT32)VertexLayout::Tangent) != 0) vertexDesc->addVertElem(VET_UBYTE4_NORM, VES_TANGENT); if ((intType & (INT32)VertexLayout::UV0) != 0) vertexDesc->addVertElem(VET_FLOAT2, VES_TEXCOORD, 0); if ((intType & (INT32)VertexLayout::UV1) != 0) vertexDesc->addVertElem(VET_FLOAT2, VES_TEXCOORD, 1); if ((intType & (INT32)VertexLayout::Color) != 0) vertexDesc->addVertElem(VET_COLOR, VES_COLOR); if ((intType & (INT32)VertexLayout::BoneWeights) != 0) { vertexDesc->addVertElem(VET_UBYTE4, VES_BLEND_INDICES); vertexDesc->addVertElem(VET_FLOAT4, VES_BLEND_WEIGHTS); } return vertexDesc; } SPtr<MeshData> RendererMeshData::convert(const SPtr<MeshData>& meshData) { // Note: Only converting between packed normals/tangents for now SPtr<VertexDataDesc> vertexDesc = meshData->getVertexDesc(); UINT32 numVertices = meshData->getNumVertices(); UINT32 numIndices = meshData->getNumIndices(); UINT32 inputStride = vertexDesc->getVertexStride(); INT32 type = 0; const VertexElement* posElem = vertexDesc->getElement(VES_POSITION); if (posElem != nullptr && posElem->getType() == VET_FLOAT3) type = (INT32)VertexLayout::Position; const VertexElement* normalElem = vertexDesc->getElement(VES_NORMAL); bool packNormals = false; if(normalElem != nullptr) { if (normalElem->getType() == VET_FLOAT3) { packNormals = true; type |= (INT32)VertexLayout::Normal; } else if(normalElem->getType() == VET_UBYTE4_NORM) type |= (INT32)VertexLayout::Normal; } const VertexElement* tanElem = vertexDesc->getElement(VES_TANGENT); bool packTangents = false; if (tanElem != nullptr) { if (tanElem->getType() == VET_FLOAT4) { packTangents = true; type |= (INT32)VertexLayout::Tangent; } else if (normalElem->getType() == VET_UBYTE4_NORM) type |= (INT32)VertexLayout::Tangent; } const VertexElement* uv0Elem = vertexDesc->getElement(VES_TEXCOORD, 0); if (uv0Elem != nullptr && uv0Elem->getType() == VET_FLOAT2) type |= (INT32)VertexLayout::UV0; const VertexElement* uv1Elem = vertexDesc->getElement(VES_TEXCOORD, 1); if (uv1Elem != nullptr && uv1Elem->getType() == VET_FLOAT2) type |= (INT32)VertexLayout::UV1; const VertexElement* colorElem = vertexDesc->getElement(VES_COLOR); if (colorElem != nullptr && colorElem->getType() == VET_COLOR) type |= (INT32)VertexLayout::Color; const VertexElement* blendIndicesElem = vertexDesc->getElement(VES_BLEND_INDICES); const VertexElement* blendWeightsElem = vertexDesc->getElement(VES_BLEND_WEIGHTS); if (blendIndicesElem != nullptr && blendIndicesElem->getType() == VET_UBYTE4 && blendWeightsElem != nullptr && blendWeightsElem->getType() == VET_FLOAT4) type |= (INT32)VertexLayout::BoneWeights; SPtr<RendererMeshData> rendererMeshData = create(numVertices, numIndices, (VertexLayout)type, meshData->getIndexType()); SPtr<MeshData> output = rendererMeshData->mMeshData; SPtr<VertexDataDesc> outputVertexDesc = output->getVertexDesc(); UINT32 outputStride = outputVertexDesc->getVertexStride(); if((type & (INT32)VertexLayout::Position) != 0) { UINT8* inData = meshData->getElementData(VES_POSITION); UINT8* outData = output->getElementData(VES_POSITION); for(UINT32 i = 0; i < numVertices; i++) memcpy(outData + i * outputStride, inData + i * inputStride, sizeof(Vector3)); } if ((type & (INT32)VertexLayout::Normal) != 0) { UINT8* inData = meshData->getElementData(VES_NORMAL); UINT8* outData = output->getElementData(VES_NORMAL); if (packNormals) MeshUtility::packNormals((Vector3*)inData, outData, numVertices, inputStride, outputStride); else { for (UINT32 i = 0; i < numVertices; i++) memcpy(outData + i * outputStride, inData + i * inputStride, sizeof(UINT32)); } } if ((type & (INT32)VertexLayout::Tangent) != 0) { UINT8* inData = meshData->getElementData(VES_TANGENT); UINT8* outData = output->getElementData(VES_TANGENT); if (packTangents) MeshUtility::packNormals((Vector4*)inData, outData, numVertices, inputStride, outputStride); else { for (UINT32 i = 0; i < numVertices; i++) memcpy(outData + i * outputStride, inData + i * inputStride, sizeof(UINT32)); } } if ((type & (INT32)VertexLayout::UV0) != 0) { UINT8* inData = meshData->getElementData(VES_TEXCOORD, 0); UINT8* outData = output->getElementData(VES_TEXCOORD, 0); for (UINT32 i = 0; i < numVertices; i++) memcpy(outData + i * outputStride, inData + i * inputStride, sizeof(Vector2)); } if ((type & (INT32)VertexLayout::UV1) != 0) { UINT8* inData = meshData->getElementData(VES_TEXCOORD, 1); UINT8* outData = output->getElementData(VES_TEXCOORD, 1); for (UINT32 i = 0; i < numVertices; i++) memcpy(outData + i * outputStride, inData + i * inputStride, sizeof(Vector2)); } if ((type & (INT32)VertexLayout::Color) != 0) { UINT8* inData = meshData->getElementData(VES_COLOR, 0); UINT8* outData = output->getElementData(VES_COLOR, 0); for (UINT32 i = 0; i < numVertices; i++) memcpy(outData + i * outputStride, inData + i * inputStride, sizeof(UINT32)); } if ((type & (INT32)VertexLayout::BoneWeights) != 0) { { UINT8* inData = meshData->getElementData(VES_BLEND_INDICES, 0); UINT8* outData = output->getElementData(VES_BLEND_INDICES, 0); for (UINT32 i = 0; i < numVertices; i++) memcpy(outData + i * outputStride, inData + i * inputStride, sizeof(UINT32)); } { UINT8* inData = meshData->getElementData(VES_BLEND_WEIGHTS, 0); UINT8* outData = output->getElementData(VES_BLEND_WEIGHTS, 0); for (UINT32 i = 0; i < numVertices; i++) memcpy(outData + i * outputStride, inData + i * inputStride, sizeof(Vector4)); } } if(meshData->getIndexType() == IT_32BIT) { UINT32* dst = output->getIndices32(); memcpy(dst, meshData->getIndices32(), numIndices * sizeof(UINT32)); } else { UINT16* dst = output->getIndices16(); memcpy(dst, meshData->getIndices16(), numIndices * sizeof(UINT16)); } return output; } }
4bbcdf448d338b1dd11eda4817531272aca54e13
b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2
/source/graphics/core/win32/direct3d11/samplerstated3d11.h
e6952ebe3a0a7877d8d8e515bff994d3140ba5dc
[]
no_license
roxygen/maid2
230319e05d6d6e2f345eda4c4d9d430fae574422
455b6b57c4e08f3678948827d074385dbc6c3f58
refs/heads/master
2021-01-23T17:19:44.876818
2010-07-02T02:43:45
2010-07-02T02:43:45
38,671,921
0
0
null
null
null
null
UTF-8
C++
false
false
545
h
#ifndef maid2_graphics_core_win32_direct3d11_samplerstated3d11_h #define maid2_graphics_core_win32_direct3d11_samplerstated3d11_h #include"../../../../config/define.h" #include"../../isamplerstate.h" #include"common.h" namespace Maid { namespace Graphics { class SamplerStateD3D11 : public ISamplerState { public: SamplerStateD3D11( const SAMPLERSTATEPARAM& param, const SPD3D11SAMPLERSTATE& p ) :ISamplerState(param) ,pState(p) { } SPD3D11SAMPLERSTATE pState; }; }} #endif
[ "renji2000@471aaf9e-aa7b-11dd-9b86-41075523de00" ]
renji2000@471aaf9e-aa7b-11dd-9b86-41075523de00
9437fb047f48eccb32e862f48655201ca521f332
d9223496bf9f121e6726129f76ff325609ffb597
/compiler/src/core/Compiler.cpp
44b29422a03129a7ac3a82ad7b4cf0437e4caf3c
[]
no_license
d08ble/acpu
4c42b4c0fff385913ffc99c1a47ce060fc3e856a
fb7b809ada746ecc3d1dbbe1096b120ac8f63256
refs/heads/master
2021-01-23T20:50:44.714637
2014-10-11T19:27:58
2014-10-11T19:27:58
10,024,454
2
0
null
null
null
null
UTF-8
C++
false
false
16,317
cpp
// // Another CPU Language - ACPUL - a{}; // // THIS SOFTWARE IS PROVIDED BY THE FREEBSD PROJECT ``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 FREEBSD PROJECT 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. // // Made by d08ble, thanks for watching. // #include <iostream> #include "Compiler.h" #include "Processor.h" #include "Executor.h" #include "CoreData.h" #include "ErrorNumbers.h" #include "DumpHelper.h" using namespace acpul; extern CoreData *acpulCoreData; int Compiler::compile(ObjectsMap &map, Executor *executor) { _blocks.clear(); // warning for gc? _map = &map; _executor = executor; otree &objects = map.objects(); otree::sibling_iterator i; i = objects.begin(); Object *object = *i; CodeBlock *code = compileObject(object); int mainBlock = code->compile(this); executor->link(*this); return mainBlock; } CodeBlock *Compiler::compileObject(Object *object) { // object->dumpFull(1, 0); _currentObject = object; // special objects or static CodeBlock *code = object->codeBlock(); if (code) return code; // printf("Compile Object: %S (%p) START\n", object->ident(), object); code = compileBlock(object->block()); // printf("Compile Object: %S (%p) END\n", object->ident(), object); return code; } CodeBlock *Compiler::compileBlock(Block &block) { CodeBlock *code = acpulCoreData->newCodeBlock(); for (int i = 0; i < block.expressionsCount(); i++) { Expression *exp = block.expressionAtIndex(i); CodeBlock *code1 = compileExpression(exp); codeBlockAttach(code, code1); } // outtree &otree = code->tree(); // printf("!!!Code Block compiled (%p)\n", &block); // acpulCoreData->dumpTree(otree, otree.begin(), otree.end()); // CoreData::dumpExpressionMultipleNodes(otree, otree.begin()); // printf("\n"); return code; } CodeBlock *Compiler::compileExpression(Expression *exp) { CodeBlock *code = acpulCoreData->newCodeBlock(); stree &tree = *exp->tree(); stree::iterator node = exp->node(); // printf("Compile Expression: "); // _map->dumpExpressionNode(tree, node); // printf("; START\n\n"); Expression *exp1 = _exp; _exp = exp; outtree &otree = code->tree(); outtree::iterator oexp = compileExpressionNode(tree, node, otree, otree.end()); _exp = exp1; // printf("Compile Expression: "); // _map->dumpExpressionNode(tree, node); // printf("; END\n\n"); // printf("CodeBlock: %p\n", code); //// _map->processor()->dumpTree(otree, oexp, otree.end(oexp)); // acpulCoreData->dumpTree(otree, otree.begin(), otree.end()); // _map->dumpExpressionMultipleNodes(otree, otree.begin()); // printf("\n"); return code; } outtree::iterator Compiler::compileExpressionNode(stree &tree, stree::iterator node, outtree &otree, outtree::iterator onode) { // printf("Processing node: \n"); // acpulCoreData->dumpTree(tree, node, tree.end(node)); // printf("\n"); stype type = (*node)->type; stree::sibling_iterator i; i = tree.begin(node); outtree::iterator oexp = outTreeCreateExpression(otree, onode); int a = (*node)->sign; (*oexp)->sign = (*node)->sign; (*oexp)->type = type; // ASSIGN if (type == stype_expression_assign) { Name *name = acpulCoreData->readname(tree, i); i++; //Object *obj = _exp->block()->object(); Object *obj = _exp->objectForName(name); // printf("EXP <name>:=...; name='"); // name->dump(); // printf("' obj=%p\n", obj); if (obj) { CodeBlock *code = compileObject(obj); outtree::iterator iblock = outTreeInsertBlock(otree, oexp, code, false); } else { // Not found. Default - insert 'name' in out expression outtree::iterator iname = outTreeCreateName(otree, oexp, name); } } // COMPOUND if (type == stype_expression_compound) { // logic for fix names 'lo while;lo(r0){};' Name *name = acpulCoreData->readname(tree, i); i++; Object *obj = _exp->objectForName(name); if (obj) { Name *name1 = obj->getExpressionValueAsName(); if (name1) { // ok outTreeCreateName(otree, oexp, name1); } else { // fail outTreeCreateNOPName(otree, oexp); } } else { outtree::iterator iname = outTreeCreateName(otree, oexp, name); } // outtree::iterator oexpc = outTreeCreateExpression(otree, oexp); outtree::iterator iexp = compileExpressionNode(tree, i, otree, oexp); i++; // outtree::iterator oexpc1 = outTreeCreateExpression(otree, oexp); outtree::iterator iexp1 = compileExpressionNode(tree, i, otree, oexp); i++; } outtree::sibling_iterator j = i; j++; bool multiple = j != tree.end(node); // NAME // NUMBER // FUNCTION // EXP_SIMPLE // OPERATOR for (; i != tree.end(node); i++) { stype t = (*i)->type; if (t == stype_name) { Name *name = acpulCoreData->readname(tree, i); // name->dump(); // printf("\n"); Object *obj = _exp->objectForName(name); if (obj) { // _exp->dumpLocals(); // obj->dumpParams(); // _currentObject->dumpParams(); omap *oldParams = obj->setParams(_currentObject->params()); // obj->dumpFull(1, 0); CodeBlock *code = compileObject(obj); obj->unsetParams(oldParams); outtree::iterator iblock = outTreeInsertBlock(otree, oexp, code, multiple); } else { outtree::iterator iname = outTreeCreateName(otree, oexp, name); } } else if (t == stype_number) { outTreeCreateNumber(otree, oexp, (*i)->val()); } else if (t == stype_operator) { outTreeCreateOperator(otree, oexp, (*i)->val()); } else if (t == stype_expression_simple) { outtree::iterator iexp = compileExpressionNode(tree, i, otree, oexp); } else if (t == stype_function) { outtree::iterator ifnexp = compileFunctionNode(tree, i, otree, oexp, multiple); } else { error(L"UNKNOWN OPERAND"); } } return oexp; } outtree::iterator Compiler::compileFunctionNode(stree &tree, stree::iterator node, outtree &otree, outtree::iterator onode, bool multiple) { outtree::iterator out; stree::sibling_iterator i; i = tree.begin(node); Name *name = acpulCoreData->readname(tree, i); Object *obj = _exp->objectForName(name); if (obj) { // HAVE OBJECT -> process compilation of template // _exp->dumpLocals(); omap &oldParams = obj->saveParams(); omap &params = *obj->params(); int j = 0; for (i++; i != tree.end(node); i++, j++) { // Name *varName = acpulCoreData->nameForVarI(j); const wchar_t *varName = acpulCoreData->identForVarI(j); // _exp->save varName stype type = (*i)->type; int count = i.number_of_children(); if (count == 0) { error(L"Internal error. stree node child count can't be 0"); continue; } stree::sibling_iterator cnode = tree.begin(i); stype ctype = (*cnode)->type; if (type == stype_expression_simple && count == 1 && ctype == stype_name) { Name *cname = acpulCoreData->readname(tree, cnode); // cname->dump(); // printf(" -> "); Object *target = _exp->objectForName(cname); // if (target) // target->dumpInfo(); // else // printf("<NULL>\n"); if (target) { params[varName] = target; } else { params[varName] = objectWithStaticName(cname);//objectWithStatic(tree, cnode); } } else { params[varName] = objectWithExpressionNode(tree, i); } } // obj->dumpParams(); CodeBlock *code = compileObject(obj); outTreeInsertBlock(otree, onode, code, multiple); // Restore obj->restoreParams(oldParams); } else { // DON'T HAVE OBJECT -> compile inlines outtree::iterator ofn = outTreeCreateFunction(otree, onode); outtree::iterator ofnname = outTreeCreateName(otree, ofn, name); int j = 0; for (i++; i != tree.end(node); i++, j++) { outtree::iterator ofnarg = compileExpressionNode(tree, i, otree, ofn); } out = ofn; } return out; } Object *Compiler::objectWithStaticName(Name *name) { CodeBlock *code = acpulCoreData->newCodeBlock(); Object *obj = acpulCoreData->newObject(); obj->setCodeBlock(code); outTreeCreateName(code->tree(), code->tree().begin(), name); return obj; } Object *Compiler::objectWithExpressionNode(stree &tree, stree::iterator node) { CodeBlock *code = acpulCoreData->newCodeBlock(); outtree &otree = code->tree(); outtree::iterator oexp = compileExpressionNode(tree, node, otree, otree.end()); Object *obj = acpulCoreData->newObject(); obj->setCodeBlock(code); return obj; } outtree::iterator Compiler::outTreeInsertBlock(outtree &otree, outtree::iterator onode, CodeBlock *code, bool multiple) { outtree::iterator i = onode; if (multiple) i = outTreeCreateExpression(otree, onode); outTreeInsertBlockA(otree, i, code); } outtree::iterator Compiler::outTreeInsertBlockA(outtree &otree, outtree::iterator onode, CodeBlock *code) { outtree::iterator i; outtree &ctree = code->tree(); outtree::iterator from; from = ctree.begin(); ctree.merge(otree.begin(onode), otree.end(onode), ctree.begin(from), ctree.end(from)); i = onode; return i; } outtree::iterator Compiler::outTreeCreateTemporraryName(outtree &otree, outtree::iterator onode) { Name *name = acpulCoreData->tempName(); outtree::iterator oname = outTreeCreateName(otree, onode, name); return oname; } outtree::iterator Compiler::outTreeCreateFunction(outtree &otree, outtree::iterator onode) { acpul::Token *la = acpulCoreData->createToken(); stype type = stype_function; la->val = (wchar_t *)L"FN"; snode *obj = acpulCoreData->newSnode(la, type); outtree::iterator i = otree.append_child(onode, obj); return i; } outtree::iterator Compiler::outTreeCreateCallBlock(outtree &otree, outtree::iterator onode, int n) { outtree::iterator ofn = outTreeCreateFunction(otree, onode); //0 fnname 'block' Name *name = acpulCoreData->newName(); const wchar_t *s = L"block"; name->addIdent(s); outtree::iterator oname = outTreeCreateName(otree, ofn, name); //1 arg0 'r0' Name *name1 = acpulCoreData->newName(); const wchar_t *s1 = L"u0"; name1->addIdent(s1); outtree::iterator op0 = outTreeCreateName(otree, ofn, name1); //2 arg1 block_number // outtree::iterator oexp = outTreeCreateExpression(otree, ofn); wchar_t *sn = new wchar_t[32]; swprintf(sn, 32, L"%i", n); outtree::iterator obn = outTreeCreateNumber(otree, ofn, sn); return ofn; } outtree::iterator Compiler::outTreeCreateExpression(outtree &otree, outtree::iterator onode) { outtree::iterator top; acpul::Token *la = acpulCoreData->createToken(); stype type = stype_expression_simple; // default is simple snode *obj = acpulCoreData->newSnode(la, type); outtree::iterator i; if (onode == otree.end()) { top = otree.begin(); // i = otree.insert(top, obj); i = otree.append_child(top, obj); } else { top = onode; i = otree.append_child(top, obj); } return i; } outtree::iterator Compiler::outTreeCreateName(outtree &otree, outtree::iterator onode, Name *name) { acpul::Token *la = acpulCoreData->createToken(); stype type = stype_name; snode *obj = acpulCoreData->newSnode(la, type); outtree::iterator oname = otree.append_child(onode, obj); const wchar_t *first = NULL; for (int i = 0; i < name->count(); i++) { acpul::Token *la1 = acpulCoreData->createToken(); const wchar_t *s = (*name)[i]; la1->val = (wchar_t *)s; if (!first) { first = s; } snode *obj1 = acpulCoreData->newSnode(la1, stype_ident); otree.append_child(oname, obj1); } la->val = (wchar_t *)first; // TODO FIX 'const'!!! return oname; } outtree::iterator Compiler::outTreeCreateNOPName(outtree &otree, outtree::iterator onode) { acpul::Token *la = acpulCoreData->createToken(); stype type = stype_name; snode *obj = acpulCoreData->newSnode(la, type); outtree::iterator oname = otree.append_child(onode, obj); acpul::Token *la1 = acpulCoreData->createToken(); la1->val = L"NOP"; snode *obj1 = acpulCoreData->newSnode(la1, stype_ident); otree.append_child(oname, obj1); return oname; } /* -- old api outtree::iterator outTreeCreateIdent(outtree &otree, outtree::iterator onode, const wchar_t *ident) { acpul::Token *la = acpulCoreData->createToken(); la->val = ident; // TODO FIX 'const'!!!??? snode *obj = acpulCoreData->newSnode(la, stype_ident); return otree.append_child(onode, obj); }*/ outtree::iterator Compiler::outTreeCreateNumber(outtree &otree, outtree::iterator onode, const wchar_t *s) { acpul::Token *la = acpulCoreData->createToken(); stype type = stype_number; la->val = (wchar_t *)s; snode *obj = acpulCoreData->newSnode(la, type); outtree::iterator i = otree.append_child(onode, obj); return i; } outtree::iterator Compiler::outTreeCreateOperator(outtree &otree, outtree::iterator onode, const wchar_t *s) { acpul::Token *la = acpulCoreData->createToken(); stype type = stype_operator; la->val = (wchar_t *)s; snode *obj = acpulCoreData->newSnode(la, type); outtree::iterator i = otree.append_child(onode, obj); return i; } void Compiler::codeBlockAttach(CodeBlock *code, CodeBlock *code1) { outTreeInsertBlock(code->tree(), code->tree().begin(), code1, false); } int Compiler::registerCodeBlock(CodeBlock *code) { int n = _executor->allocateBlock(); //_blocks.size(); _blocks.push_back(code); code->setBlockId(n); return n; } void Compiler::error(const wchar_t *s, ...) { va_list ap; va_start(ap, s); acpulCoreData->error(EN_COMPILE_ERR, s, ap); va_end(ap); } #if 0 // CALL FUNCTION Name *name; void *arguments; Object *object; if (object) { } else { // default for (arguments;;) { } } #endif
507888e8b07722ac4eb8b698cc960ed02a2af5e7
7869842fd7acebece3f9fee22eb3bacaf85d1f86
/C++/STL/deque-STL.cpp
b03feb2a6083ddf2dba42e6880ebe3d7796c4e68
[]
no_license
thomastan/hackerrank
1f7a99c1f7625ee0bc2f99780c9ab007b5c169b5
a2a9bbc0559bf67c9fe789835ff4b57a4b53e317
refs/heads/master
2023-02-09T09:24:58.970400
2023-01-25T21:19:06
2023-01-25T21:19:06
55,093,662
0
0
null
null
null
null
UTF-8
C++
false
false
1,409
cpp
#include <iostream> #include <deque> #include <algorithm> using namespace std; void printKMax(const int arr[], const int n, const int k) { // fill a deque of size K, and find it's max as an ITERATOR // for insertion of each a[i], i = k...n-1 // if iterator points to element to be removed: // remove the front, add to the back, recalculate max_iterator // else check the new element if it will exceed the iteartor's element // if so, pop the front, add to the back, set the new iterator to back-1 // otherwise: pop the front, add to the back, keep the iterator the same deque<int> d; for (int i = 0; i < k; ++i) d.push_back(arr[i]); auto windowMax = max_element(d.begin(), d.end()); cout << *windowMax; for (int i = k; i < n; ++i) { if (windowMax == d.begin()) { d.pop_front(); d.push_back(arr[i]); windowMax = max_element(d.begin(), d.end()); } else { d.pop_front(); d.push_back(arr[i]); if (d.back() > *windowMax) windowMax = prev(d.end()); } cout << ' ' << *windowMax; } cout << endl; } int main() { int t, n, k; cin >> t; while (t--) { cin >> n >> k; int arr[n]; for (int i = 0; i < n; ++i) cin >> arr[i]; printKMax(arr, n, k); } return 0; }
e5e7427e59ba6d708806ff754d25f23417a40c5c
f0ba9db32f36c5aba864e5978872b2e8ad10aa40
/examples/example_void_t_overview.hpp
b1ce5b055f3d2de68bfc0ca1f91aaae4dff9d817
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
Bareflank/bsl
fb325084b19cd48e03197f4265049f9c8d008c9f
6509cfff948fa34b98585512d7be33a36e2f9522
refs/heads/master
2021-12-25T11:19:43.743888
2021-10-21T14:47:58
2021-10-21T14:47:58
216,364,945
77
5
NOASSERTION
2021-10-21T02:24:26
2019-10-20T13:18:28
C++
UTF-8
C++
false
false
1,649
hpp
/// @copyright /// Copyright (C) 2020 Assured Information Security, Inc. /// /// @copyright /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// @copyright /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// @copyright /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE /// SOFTWARE. #include <bsl/debug.hpp> #include <bsl/is_same.hpp> #include <bsl/void_t.hpp> namespace bsl { /// <!-- description --> /// @brief Provides the example's main function /// inline void example_void_t_overview() noexcept { if constexpr (bsl::is_same<void_t<bool>, void>::value) { bsl::print() << "success\n"; } else { bsl::error() << "failure\n"; } } }
5ee7b40d4b978555fa391577c4daeb2eb9a9e41c
6e22d7679ebeb092232de6052ced81c7d8ab97a6
/hp-socket-3.1.2/Common/Src/GeneralHelper.cpp
b0c4ef0b856fce1eb99c651b339e31b35d583ad5
[ "Apache-2.0" ]
permissive
chengguixing/iArt
e3de63161bd91a18522612d6320453431824061d
c2d60e36f2f2a6a04b2188f20e7264cfc5d05dc4
refs/heads/master
2021-01-02T09:27:11.010862
2014-06-28T12:34:56
2014-06-28T12:34:56
22,207,953
4
5
null
null
null
null
UTF-8
C++
false
false
892
cpp
/* * Copyright: JessMA Open Source ([email protected]) * * Version : 2.3.2 * Author : Bruce Liang * Website : http://www.jessma.org * Project : https://github.com/ldcsaa * Blog : http://www.cnblogs.com/ldcsaa * WeiBo : http://weibo.com/u/1402935851 * QQ Group : 75375912 * * 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 "stdafx.h" #include "GeneralHelper.h"
f1afb36456da38eb877b180b943b9cf8063e5d5b
488be7f987fe5e5dd87e7ec0afcb72be8f656748
/ConsoleApplication5.cpp
36ea57cadf3fd106b40ffd51c8bdb33a438b2988
[]
no_license
MantieReid/ConsoleApplication5
468e336f33e31d3c38384a81f3b3675c2ab23c04
4adc9a9596434ea850e71900b18446ca323939f3
refs/heads/master
2022-09-10T23:02:18.195692
2020-06-03T01:38:02
2020-06-03T01:38:02
268,948,648
0
0
null
null
null
null
UTF-8
C++
false
false
2,677
cpp
// ConsoleApplication5.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include <string> #include <cstdlib> #include <cstring> #include <ctime> #include <time.h> #include <ratio> #include <chrono> #include <Windows.h> #include <Psapi.h> #include <stdio.h> using namespace std; using namespace std::chrono; int main() { #pragma comment(lib,"psapi") // PROCESS_MEMORY_COUNTERS_EX pmc; //int a = GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc)); // SIZE_T virtualMemUsedByMe = pmc.PrivateUsage; int x = 0; int y = 0; int z = 0; steady_clock::time_point t1 = steady_clock::now(); while (x < 90000) { x++; y++; z++; steady_clock::time_point t2 = steady_clock::now(); duration<double> time_span = duration_cast<duration<double>>(t2 - t1); long int* ab; long int* ab2; long int* ab3; long int* ab4; long int* ab5; long int* ab6; //within three minutes, this should use up to 17 gigabytes of ram. //make sure to run this as x64, or else you will get a error. //This might work diffrently on diffrent computers. But within 20 seconds, it should consume 1 gigabyte of ram. for (long int n = 0; n < 10000; n++) { string nToString = to_string(n); ab = new long int[900]; ab2 = new long int[900]; // ab3 = new long int; //ab4 = new long int; //ab5 = new long int; //ab6 = new long int; //string aToString = to_string(a); //string SizeToString = to_string(virtualMemUsedByMe); // cout << "current memory usage is " + SizeToString << endl; cout << "Ab is " + nToString << endl; // cout << "size of ab " + sizeof(ab) << endl; if (time_span.count() >= 23) { cout << " it has been 23 seconds, exiting...." << endl; exit(0); } } } } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
61ae7db6ea87cb74d08c35d1e38f801036d51ade
91077fd89021453432e1208263368f5a8784f38a
/homework1/cpu_matrix.cpp
d2a8bd95ee57004035d05712fd18249786c37ca7
[]
no_license
dfabian5/GPU-Parallel-Processing-Homework
6cf6eb6d79a5f53fce84d49528907bce47809f89
dfaa8e49d70f01b22da75991b254569624017e21
refs/heads/master
2020-12-21T10:40:43.511238
2020-05-05T22:02:22
2020-05-05T22:02:22
236,406,460
1
0
null
null
null
null
UTF-8
C++
false
false
1,546
cpp
//////////////////////////////////////////////////////////////////////////////// // // FILE: cpu_matrix.cpp // DESCRIPTION: calculates matrix multiplication on cpu // AUTHOR: Dan Fabian // DATE: 1/26/2020 #include <iostream> #include <random> #include <chrono> using std::cout; using std::endl; using namespace std::chrono; // create matrices of size SIZExSIZE const int SIZE = 128; typedef high_resolution_clock Clock; void multiply(bool a[][SIZE], bool b[][SIZE], int c[][SIZE]) { for (int row = 0; row < SIZE; ++row) for (int col = 0; col < SIZE; ++col) for (int i = 0; i < SIZE; ++i) c[row][col] += a[row][i] * b[i][col]; } int main() { bool a[SIZE][SIZE], b[SIZE][SIZE]; int c[SIZE][SIZE]; // create rng unsigned int seed = system_clock::now().time_since_epoch().count(); std::default_random_engine generator(seed); std::uniform_int_distribution<int> dist(0, 1); // init matrices for (int i = 0; i < SIZE; ++i) for (int j = 0; j < SIZE; ++j) { a[i][j] = dist(generator); b[i][j] = dist(generator); c[i][j] = 0; } // multiply auto ti = Clock::now(); multiply(a, b, c); auto tf = Clock::now(); // print out answer for (int i = 0; i < SIZE; ++i) { for (int j = 0; j < SIZE; ++j) cout << c[i][j] << ' '; cout << endl; } // print out computation time cout << "Computation took " << duration_cast<nanoseconds>(tf - ti).count() << " nanooseconds" << endl; }
f4d6c0408069f857314964bfb706d586f7fefa8b
bb82a5f977bef455714c16e24e2d8254e2d0faa5
/src/vendor/cget/include/asio/experimental/detail/partial_promise.hpp
de579438893ca17ec6673a77b1fe02e9c5d1e320
[ "Unlicense" ]
permissive
pqrs-org/Karabiner-Elements
4ae307d82f8b67547c161c7d46d2083a0fd07630
d05057d7c769e2ff35638282e888a6d5eca566be
refs/heads/main
2023-09-01T03:11:08.474417
2023-09-01T00:44:19
2023-09-01T00:44:19
63,037,806
8,197
389
Unlicense
2023-09-01T00:11:00
2016-07-11T04:57:55
C++
UTF-8
C++
false
false
101
hpp
../../../../cget/pkg/chriskohlhoff__asio/install/include/asio/experimental/detail/partial_promise.hpp
c6a348fee4df9c52c0546932490c27d1eb24c7bc
b4bff7f61d078e3dddeb760e21174a781ed7f985
/Source/Contrib/Sound/src/Sound/OSGSoundBase.cpp
37101f1fdc25cb08ee35e8e2758384d932c6953a
[]
no_license
Langkamp/OpenSGToolbox
8283edb6074dffba477c2c4d632e954c3c73f4e3
5a4230441e68f001cdf3e08e9f97f9c0f3c71015
refs/heads/master
2021-01-16T18:15:50.951223
2010-05-19T20:24:52
2010-05-19T20:24:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
31,144
cpp
/*---------------------------------------------------------------------------*\ * OpenSG * * * * * * Copyright (C) 2000-2006 by the OpenSG Forum * * * * www.opensg.org * * * * contact: David Kabala ([email protected]) * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * License * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Library General Public License as published * * by the Free Software Foundation, version 2. * * * * 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 * * Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * Changes * * * * * * * * * * * * * \*---------------------------------------------------------------------------*/ /*****************************************************************************\ ***************************************************************************** ** ** ** This file is automatically generated. ** ** ** ** Any changes made to this file WILL be lost when it is ** ** regenerated, which can become necessary at any time. ** ** ** ** Do not change this file, changes should be done in the derived ** ** class Sound! ** ** ***************************************************************************** \*****************************************************************************/ #include <cstdlib> #include <cstdio> #include <boost/assign/list_of.hpp> #include "OSGConfig.h" #include "OSGSoundBase.h" #include "OSGSound.h" #include <boost/bind.hpp> #include "OSGEvent.h" #ifdef WIN32 // turn off 'this' : used in base member initializer list warning #pragma warning(disable:4355) #endif OSG_BEGIN_NAMESPACE /***************************************************************************\ * Description * \***************************************************************************/ /*! \class OSG::Sound A Sound Interface. */ /***************************************************************************\ * Field Documentation * \***************************************************************************/ /*! \var Pnt3f SoundBase::_sfPosition Initial position of this sound. */ /*! \var Vec3f SoundBase::_sfVelocity Initial velocity of this sound. */ /*! \var Real32 SoundBase::_sfVolume Values from 0.0 to 1.0. 0.0 = Silent, 1.0 = Full Volume. */ /*! \var Real32 SoundBase::_sfPan Values from -1.0 to 1.0. -1.0 = Full Left, 0.0 = Full Center, 1.0 = Full Right. */ /*! \var Real32 SoundBase::_sfFrequency Default playback frequency. */ /*! \var Int32 SoundBase::_sfLooping Number of times to loop this sound. 1 = play the sound once, Values less than 0 = Inifinite loop. Values 2 greater than plays the sound that many times. */ /*! \var bool SoundBase::_sfStreaming Whether or not this sound should be streamed. */ /*! \var BoostPath SoundBase::_sfFile The Path to the sound file to load this sound from. */ /*! \var bool SoundBase::_sfEnable3D */ /***************************************************************************\ * FieldType/FieldTrait Instantiation * \***************************************************************************/ #if !defined(OSG_DO_DOC) || defined(OSG_DOC_DEV) DataType FieldTraits<Sound *>::_type("SoundPtr", "AttachmentContainerPtr"); #endif OSG_FIELDTRAITS_GETTYPE(Sound *) OSG_EXPORT_PTR_SFIELD_FULL(PointerSField, Sound *, 0); OSG_EXPORT_PTR_MFIELD_FULL(PointerMField, Sound *, 0); /***************************************************************************\ * Field Description * \***************************************************************************/ void SoundBase::classDescInserter(TypeObject &oType) { FieldDescriptionBase *pDesc = NULL; pDesc = new SFPnt3f::Description( SFPnt3f::getClassType(), "Position", "Initial position of this sound.\n", PositionFieldId, PositionFieldMask, false, (Field::SFDefaultFlags | Field::FStdAccess), static_cast<FieldEditMethodSig>(&Sound::editHandlePosition), static_cast<FieldGetMethodSig >(&Sound::getHandlePosition)); oType.addInitialDesc(pDesc); pDesc = new SFVec3f::Description( SFVec3f::getClassType(), "Velocity", "Initial velocity of this sound.\n", VelocityFieldId, VelocityFieldMask, false, (Field::SFDefaultFlags | Field::FStdAccess), static_cast<FieldEditMethodSig>(&Sound::editHandleVelocity), static_cast<FieldGetMethodSig >(&Sound::getHandleVelocity)); oType.addInitialDesc(pDesc); pDesc = new SFReal32::Description( SFReal32::getClassType(), "Volume", "Values from 0.0 to 1.0. 0.0 = Silent, 1.0 = Full Volume.\n", VolumeFieldId, VolumeFieldMask, false, (Field::SFDefaultFlags | Field::FStdAccess), static_cast<FieldEditMethodSig>(&Sound::editHandleVolume), static_cast<FieldGetMethodSig >(&Sound::getHandleVolume)); oType.addInitialDesc(pDesc); pDesc = new SFReal32::Description( SFReal32::getClassType(), "Pan", "Values from -1.0 to 1.0. -1.0 = Full Left, 0.0 = Full Center, 1.0 = Full Right.\n", PanFieldId, PanFieldMask, false, (Field::SFDefaultFlags | Field::FStdAccess), static_cast<FieldEditMethodSig>(&Sound::editHandlePan), static_cast<FieldGetMethodSig >(&Sound::getHandlePan)); oType.addInitialDesc(pDesc); pDesc = new SFReal32::Description( SFReal32::getClassType(), "Frequency", "Default playback frequency.\n", FrequencyFieldId, FrequencyFieldMask, false, (Field::SFDefaultFlags | Field::FStdAccess), static_cast<FieldEditMethodSig>(&Sound::editHandleFrequency), static_cast<FieldGetMethodSig >(&Sound::getHandleFrequency)); oType.addInitialDesc(pDesc); pDesc = new SFInt32::Description( SFInt32::getClassType(), "Looping", "Number of times to loop this sound. 1 = play the sound once, Values less than 0 = Inifinite loop. Values 2 greater than plays the sound that many times.\n", LoopingFieldId, LoopingFieldMask, false, (Field::SFDefaultFlags | Field::FStdAccess), static_cast<FieldEditMethodSig>(&Sound::editHandleLooping), static_cast<FieldGetMethodSig >(&Sound::getHandleLooping)); oType.addInitialDesc(pDesc); pDesc = new SFBool::Description( SFBool::getClassType(), "Streaming", "Whether or not this sound should be streamed.\n", StreamingFieldId, StreamingFieldMask, false, (Field::SFDefaultFlags | Field::FStdAccess), static_cast<FieldEditMethodSig>(&Sound::editHandleStreaming), static_cast<FieldGetMethodSig >(&Sound::getHandleStreaming)); oType.addInitialDesc(pDesc); pDesc = new SFBoostPath::Description( SFBoostPath::getClassType(), "File", "The Path to the sound file to load this sound from.\n", FileFieldId, FileFieldMask, false, (Field::SFDefaultFlags | Field::FStdAccess), static_cast<FieldEditMethodSig>(&Sound::editHandleFile), static_cast<FieldGetMethodSig >(&Sound::getHandleFile)); oType.addInitialDesc(pDesc); pDesc = new SFBool::Description( SFBool::getClassType(), "Enable3D", "", Enable3DFieldId, Enable3DFieldMask, false, (Field::SFDefaultFlags | Field::FStdAccess), static_cast<FieldEditMethodSig>(&Sound::editHandleEnable3D), static_cast<FieldGetMethodSig >(&Sound::getHandleEnable3D)); oType.addInitialDesc(pDesc); pDesc = new SFEventProducerPtr::Description( SFEventProducerPtr::getClassType(), "EventProducer", "Event Producer", EventProducerFieldId,EventProducerFieldMask, true, (Field::SFDefaultFlags | Field::FStdAccess), static_cast <FieldEditMethodSig>(&Sound::invalidEditField), static_cast <FieldGetMethodSig >(&Sound::invalidGetField)); oType.addInitialDesc(pDesc); } SoundBase::TypeObject SoundBase::_type( SoundBase::getClassname(), Inherited::getClassname(), "NULL", 0, NULL, Sound::initMethod, Sound::exitMethod, reinterpret_cast<InitalInsertDescFunc>(&Sound::classDescInserter), false, 0, "<?xml version=\"1.0\"?>\n" "\n" "<FieldContainer\n" "\tname=\"Sound\"\n" "\tparent=\"AttachmentContainer\"\n" " library=\"ContribSound\"\n" " pointerfieldtypes=\"both\"\n" " structure=\"abstract\"\n" " systemcomponent=\"true\"\n" " parentsystemcomponent=\"true\"\n" " decoratable=\"false\"\n" " useLocalIncludes=\"false\"\n" " isNodeCore=\"false\"\n" " authors=\"David Kabala ([email protected]) \"\n" ">\n" "A Sound Interface.\n" "\t<Field\n" "\t\tname=\"Position\"\n" "\t\ttype=\"Pnt3f\"\n" " category=\"data\"\n" "\t\tcardinality=\"single\"\n" "\t\tvisibility=\"external\"\n" " defaultValue=\"0.0,0.0,0.0\"\n" "\t\taccess=\"public\"\n" "\t>\n" " Initial position of this sound.\n" "\t</Field>\n" "\t<Field\n" "\t\tname=\"Velocity\"\n" "\t\ttype=\"Vec3f\"\n" " category=\"data\"\n" "\t\tcardinality=\"single\"\n" "\t\tvisibility=\"external\"\n" " defaultValue=\"0.0,0.0,0.0\"\n" "\t\taccess=\"public\"\n" "\t>\n" " Initial velocity of this sound.\n" "\t</Field>\n" "\t<Field\n" "\t\tname=\"Volume\"\n" "\t\ttype=\"Real32\"\n" " category=\"data\"\n" "\t\tcardinality=\"single\"\n" "\t\tvisibility=\"external\"\n" " defaultValue=\"1.0\"\n" "\t\taccess=\"public\"\n" "\t>\n" " Values from 0.0 to 1.0. 0.0 = Silent, 1.0 = Full Volume.\n" "\t</Field>\n" "\t<Field\n" "\t\tname=\"Pan\"\n" "\t\ttype=\"Real32\"\n" " category=\"data\"\n" "\t\tcardinality=\"single\"\n" "\t\tvisibility=\"external\"\n" " defaultValue=\"0.0\"\n" "\t\taccess=\"public\"\n" "\t>\n" " Values from -1.0 to 1.0. -1.0 = Full Left, 0.0 = Full Center, 1.0 = Full Right.\n" "\t</Field>\n" "\t<Field\n" "\t\tname=\"Frequency\"\n" "\t\ttype=\"Real32\"\n" " category=\"data\"\n" "\t\tcardinality=\"single\"\n" "\t\tvisibility=\"external\"\n" " defaultValue=\"44100.0\"\n" "\t\taccess=\"public\"\n" "\t>\n" " Default playback frequency.\n" "\t</Field>\n" "\t<Field\n" "\t\tname=\"Looping\"\n" "\t\ttype=\"Int32\"\n" " category=\"data\"\n" "\t\tcardinality=\"single\"\n" "\t\tvisibility=\"external\"\n" " defaultValue=\"1\"\n" "\t\taccess=\"public\"\n" "\t>\n" " Number of times to loop this sound. 1 = play the sound once, Values less than 0 = Inifinite loop. Values 2 greater than plays the sound that many times.\n" "\t</Field>\n" "\t<Field\n" "\t\tname=\"Streaming\"\n" "\t\ttype=\"bool\"\n" " category=\"data\"\n" "\t\tcardinality=\"single\"\n" "\t\tvisibility=\"external\"\n" " defaultValue=\"false\"\n" "\t\taccess=\"public\"\n" "\t>\n" " Whether or not this sound should be streamed.\n" "\t</Field>\n" "\t<Field\n" "\t\tname=\"File\"\n" "\t\ttype=\"BoostPath\"\n" " category=\"data\"\n" "\t\tcardinality=\"single\"\n" "\t\tvisibility=\"external\"\n" "\t\taccess=\"public\"\n" "\t>\n" " The Path to the sound file to load this sound from.\n" "\t</Field>\n" "\t<Field\n" "\t\tname=\"Enable3D\"\n" "\t\ttype=\"bool\"\n" " category=\"data\"\n" "\t\tcardinality=\"single\"\n" "\t\tvisibility=\"external\"\n" "\t\taccess=\"public\"\n" " defaultValue=\"false\"\n" "\t>\n" "\t</Field>\n" "\t<ProducedMethod\n" "\t\tname=\"SoundPlayed\"\n" "\t\ttype=\"SoundEvent\"\n" "\t>\n" "\t</ProducedMethod>\n" "\t<ProducedMethod\n" "\t\tname=\"SoundStopped\"\n" "\t\ttype=\"SoundEvent\"\n" "\t>\n" "\t</ProducedMethod>\n" "\t<ProducedMethod\n" "\t\tname=\"SoundPaused\"\n" "\t\ttype=\"SoundEvent\"\n" "\t>\n" "\t</ProducedMethod>\n" "\t<ProducedMethod\n" "\t\tname=\"SoundUnpaused\"\n" "\t\ttype=\"SoundEvent\"\n" "\t>\n" "\t</ProducedMethod>\n" "\t<ProducedMethod\n" "\t\tname=\"SoundLooped\"\n" "\t\ttype=\"SoundEvent\"\n" "\t>\n" "\t</ProducedMethod>\n" "\t<ProducedMethod\n" "\t\tname=\"SoundEnded\"\n" "\t\ttype=\"SoundEvent\"\n" "\t>\n" "\t</ProducedMethod>\n" "</FieldContainer>\n", "A Sound Interface.\n" ); //! Sound Produced Methods MethodDescription *SoundBase::_methodDesc[] = { new MethodDescription("SoundPlayed", "", SoundPlayedMethodId, SFUnrecEventPtr::getClassType(), FunctorAccessMethod()), new MethodDescription("SoundStopped", "", SoundStoppedMethodId, SFUnrecEventPtr::getClassType(), FunctorAccessMethod()), new MethodDescription("SoundPaused", "", SoundPausedMethodId, SFUnrecEventPtr::getClassType(), FunctorAccessMethod()), new MethodDescription("SoundUnpaused", "", SoundUnpausedMethodId, SFUnrecEventPtr::getClassType(), FunctorAccessMethod()), new MethodDescription("SoundLooped", "", SoundLoopedMethodId, SFUnrecEventPtr::getClassType(), FunctorAccessMethod()), new MethodDescription("SoundEnded", "", SoundEndedMethodId, SFUnrecEventPtr::getClassType(), FunctorAccessMethod()) }; EventProducerType SoundBase::_producerType( "SoundProducerType", "EventProducerType", "", InitEventProducerFunctor(), _methodDesc, sizeof(_methodDesc)); /*------------------------------ get -----------------------------------*/ FieldContainerType &SoundBase::getType(void) { return _type; } const FieldContainerType &SoundBase::getType(void) const { return _type; } const EventProducerType &SoundBase::getProducerType(void) const { return _producerType; } UInt32 SoundBase::getContainerSize(void) const { return sizeof(Sound); } /*------------------------- decorator get ------------------------------*/ SFPnt3f *SoundBase::editSFPosition(void) { editSField(PositionFieldMask); return &_sfPosition; } const SFPnt3f *SoundBase::getSFPosition(void) const { return &_sfPosition; } SFVec3f *SoundBase::editSFVelocity(void) { editSField(VelocityFieldMask); return &_sfVelocity; } const SFVec3f *SoundBase::getSFVelocity(void) const { return &_sfVelocity; } SFReal32 *SoundBase::editSFVolume(void) { editSField(VolumeFieldMask); return &_sfVolume; } const SFReal32 *SoundBase::getSFVolume(void) const { return &_sfVolume; } SFReal32 *SoundBase::editSFPan(void) { editSField(PanFieldMask); return &_sfPan; } const SFReal32 *SoundBase::getSFPan(void) const { return &_sfPan; } SFReal32 *SoundBase::editSFFrequency(void) { editSField(FrequencyFieldMask); return &_sfFrequency; } const SFReal32 *SoundBase::getSFFrequency(void) const { return &_sfFrequency; } SFInt32 *SoundBase::editSFLooping(void) { editSField(LoopingFieldMask); return &_sfLooping; } const SFInt32 *SoundBase::getSFLooping(void) const { return &_sfLooping; } SFBool *SoundBase::editSFStreaming(void) { editSField(StreamingFieldMask); return &_sfStreaming; } const SFBool *SoundBase::getSFStreaming(void) const { return &_sfStreaming; } SFBoostPath *SoundBase::editSFFile(void) { editSField(FileFieldMask); return &_sfFile; } const SFBoostPath *SoundBase::getSFFile(void) const { return &_sfFile; } SFBool *SoundBase::editSFEnable3D(void) { editSField(Enable3DFieldMask); return &_sfEnable3D; } const SFBool *SoundBase::getSFEnable3D(void) const { return &_sfEnable3D; } /*------------------------------ access -----------------------------------*/ UInt32 SoundBase::getBinSize(ConstFieldMaskArg whichField) { UInt32 returnValue = Inherited::getBinSize(whichField); if(FieldBits::NoField != (PositionFieldMask & whichField)) { returnValue += _sfPosition.getBinSize(); } if(FieldBits::NoField != (VelocityFieldMask & whichField)) { returnValue += _sfVelocity.getBinSize(); } if(FieldBits::NoField != (VolumeFieldMask & whichField)) { returnValue += _sfVolume.getBinSize(); } if(FieldBits::NoField != (PanFieldMask & whichField)) { returnValue += _sfPan.getBinSize(); } if(FieldBits::NoField != (FrequencyFieldMask & whichField)) { returnValue += _sfFrequency.getBinSize(); } if(FieldBits::NoField != (LoopingFieldMask & whichField)) { returnValue += _sfLooping.getBinSize(); } if(FieldBits::NoField != (StreamingFieldMask & whichField)) { returnValue += _sfStreaming.getBinSize(); } if(FieldBits::NoField != (FileFieldMask & whichField)) { returnValue += _sfFile.getBinSize(); } if(FieldBits::NoField != (Enable3DFieldMask & whichField)) { returnValue += _sfEnable3D.getBinSize(); } if(FieldBits::NoField != (EventProducerFieldMask & whichField)) { returnValue += _sfEventProducer.getBinSize(); } return returnValue; } void SoundBase::copyToBin(BinaryDataHandler &pMem, ConstFieldMaskArg whichField) { Inherited::copyToBin(pMem, whichField); if(FieldBits::NoField != (PositionFieldMask & whichField)) { _sfPosition.copyToBin(pMem); } if(FieldBits::NoField != (VelocityFieldMask & whichField)) { _sfVelocity.copyToBin(pMem); } if(FieldBits::NoField != (VolumeFieldMask & whichField)) { _sfVolume.copyToBin(pMem); } if(FieldBits::NoField != (PanFieldMask & whichField)) { _sfPan.copyToBin(pMem); } if(FieldBits::NoField != (FrequencyFieldMask & whichField)) { _sfFrequency.copyToBin(pMem); } if(FieldBits::NoField != (LoopingFieldMask & whichField)) { _sfLooping.copyToBin(pMem); } if(FieldBits::NoField != (StreamingFieldMask & whichField)) { _sfStreaming.copyToBin(pMem); } if(FieldBits::NoField != (FileFieldMask & whichField)) { _sfFile.copyToBin(pMem); } if(FieldBits::NoField != (Enable3DFieldMask & whichField)) { _sfEnable3D.copyToBin(pMem); } if(FieldBits::NoField != (EventProducerFieldMask & whichField)) { _sfEventProducer.copyToBin(pMem); } } void SoundBase::copyFromBin(BinaryDataHandler &pMem, ConstFieldMaskArg whichField) { Inherited::copyFromBin(pMem, whichField); if(FieldBits::NoField != (PositionFieldMask & whichField)) { _sfPosition.copyFromBin(pMem); } if(FieldBits::NoField != (VelocityFieldMask & whichField)) { _sfVelocity.copyFromBin(pMem); } if(FieldBits::NoField != (VolumeFieldMask & whichField)) { _sfVolume.copyFromBin(pMem); } if(FieldBits::NoField != (PanFieldMask & whichField)) { _sfPan.copyFromBin(pMem); } if(FieldBits::NoField != (FrequencyFieldMask & whichField)) { _sfFrequency.copyFromBin(pMem); } if(FieldBits::NoField != (LoopingFieldMask & whichField)) { _sfLooping.copyFromBin(pMem); } if(FieldBits::NoField != (StreamingFieldMask & whichField)) { _sfStreaming.copyFromBin(pMem); } if(FieldBits::NoField != (FileFieldMask & whichField)) { _sfFile.copyFromBin(pMem); } if(FieldBits::NoField != (Enable3DFieldMask & whichField)) { _sfEnable3D.copyFromBin(pMem); } if(FieldBits::NoField != (EventProducerFieldMask & whichField)) { _sfEventProducer.copyFromBin(pMem); } } /*------------------------- constructors ----------------------------------*/ SoundBase::SoundBase(void) : _Producer(&getProducerType()), Inherited(), _sfPosition (Pnt3f(0.0,0.0,0.0)), _sfVelocity (Vec3f(0.0,0.0,0.0)), _sfVolume (Real32(1.0)), _sfPan (Real32(0.0)), _sfFrequency (Real32(44100.0)), _sfLooping (Int32(1)), _sfStreaming (bool(false)), _sfFile (), _sfEnable3D (bool(false)) ,_sfEventProducer(&_Producer) { } SoundBase::SoundBase(const SoundBase &source) : _Producer(&source.getProducerType()), Inherited(source), _sfPosition (source._sfPosition ), _sfVelocity (source._sfVelocity ), _sfVolume (source._sfVolume ), _sfPan (source._sfPan ), _sfFrequency (source._sfFrequency ), _sfLooping (source._sfLooping ), _sfStreaming (source._sfStreaming ), _sfFile (source._sfFile ), _sfEnable3D (source._sfEnable3D ) ,_sfEventProducer(&_Producer) { } /*-------------------------- destructors ----------------------------------*/ SoundBase::~SoundBase(void) { } GetFieldHandlePtr SoundBase::getHandlePosition (void) const { SFPnt3f::GetHandlePtr returnValue( new SFPnt3f::GetHandle( &_sfPosition, this->getType().getFieldDesc(PositionFieldId), const_cast<SoundBase *>(this))); return returnValue; } EditFieldHandlePtr SoundBase::editHandlePosition (void) { SFPnt3f::EditHandlePtr returnValue( new SFPnt3f::EditHandle( &_sfPosition, this->getType().getFieldDesc(PositionFieldId), this)); editSField(PositionFieldMask); return returnValue; } GetFieldHandlePtr SoundBase::getHandleVelocity (void) const { SFVec3f::GetHandlePtr returnValue( new SFVec3f::GetHandle( &_sfVelocity, this->getType().getFieldDesc(VelocityFieldId), const_cast<SoundBase *>(this))); return returnValue; } EditFieldHandlePtr SoundBase::editHandleVelocity (void) { SFVec3f::EditHandlePtr returnValue( new SFVec3f::EditHandle( &_sfVelocity, this->getType().getFieldDesc(VelocityFieldId), this)); editSField(VelocityFieldMask); return returnValue; } GetFieldHandlePtr SoundBase::getHandleVolume (void) const { SFReal32::GetHandlePtr returnValue( new SFReal32::GetHandle( &_sfVolume, this->getType().getFieldDesc(VolumeFieldId), const_cast<SoundBase *>(this))); return returnValue; } EditFieldHandlePtr SoundBase::editHandleVolume (void) { SFReal32::EditHandlePtr returnValue( new SFReal32::EditHandle( &_sfVolume, this->getType().getFieldDesc(VolumeFieldId), this)); editSField(VolumeFieldMask); return returnValue; } GetFieldHandlePtr SoundBase::getHandlePan (void) const { SFReal32::GetHandlePtr returnValue( new SFReal32::GetHandle( &_sfPan, this->getType().getFieldDesc(PanFieldId), const_cast<SoundBase *>(this))); return returnValue; } EditFieldHandlePtr SoundBase::editHandlePan (void) { SFReal32::EditHandlePtr returnValue( new SFReal32::EditHandle( &_sfPan, this->getType().getFieldDesc(PanFieldId), this)); editSField(PanFieldMask); return returnValue; } GetFieldHandlePtr SoundBase::getHandleFrequency (void) const { SFReal32::GetHandlePtr returnValue( new SFReal32::GetHandle( &_sfFrequency, this->getType().getFieldDesc(FrequencyFieldId), const_cast<SoundBase *>(this))); return returnValue; } EditFieldHandlePtr SoundBase::editHandleFrequency (void) { SFReal32::EditHandlePtr returnValue( new SFReal32::EditHandle( &_sfFrequency, this->getType().getFieldDesc(FrequencyFieldId), this)); editSField(FrequencyFieldMask); return returnValue; } GetFieldHandlePtr SoundBase::getHandleLooping (void) const { SFInt32::GetHandlePtr returnValue( new SFInt32::GetHandle( &_sfLooping, this->getType().getFieldDesc(LoopingFieldId), const_cast<SoundBase *>(this))); return returnValue; } EditFieldHandlePtr SoundBase::editHandleLooping (void) { SFInt32::EditHandlePtr returnValue( new SFInt32::EditHandle( &_sfLooping, this->getType().getFieldDesc(LoopingFieldId), this)); editSField(LoopingFieldMask); return returnValue; } GetFieldHandlePtr SoundBase::getHandleStreaming (void) const { SFBool::GetHandlePtr returnValue( new SFBool::GetHandle( &_sfStreaming, this->getType().getFieldDesc(StreamingFieldId), const_cast<SoundBase *>(this))); return returnValue; } EditFieldHandlePtr SoundBase::editHandleStreaming (void) { SFBool::EditHandlePtr returnValue( new SFBool::EditHandle( &_sfStreaming, this->getType().getFieldDesc(StreamingFieldId), this)); editSField(StreamingFieldMask); return returnValue; } GetFieldHandlePtr SoundBase::getHandleFile (void) const { SFBoostPath::GetHandlePtr returnValue( new SFBoostPath::GetHandle( &_sfFile, this->getType().getFieldDesc(FileFieldId), const_cast<SoundBase *>(this))); return returnValue; } EditFieldHandlePtr SoundBase::editHandleFile (void) { SFBoostPath::EditHandlePtr returnValue( new SFBoostPath::EditHandle( &_sfFile, this->getType().getFieldDesc(FileFieldId), this)); editSField(FileFieldMask); return returnValue; } GetFieldHandlePtr SoundBase::getHandleEnable3D (void) const { SFBool::GetHandlePtr returnValue( new SFBool::GetHandle( &_sfEnable3D, this->getType().getFieldDesc(Enable3DFieldId), const_cast<SoundBase *>(this))); return returnValue; } EditFieldHandlePtr SoundBase::editHandleEnable3D (void) { SFBool::EditHandlePtr returnValue( new SFBool::EditHandle( &_sfEnable3D, this->getType().getFieldDesc(Enable3DFieldId), this)); editSField(Enable3DFieldMask); return returnValue; } #ifdef OSG_MT_CPTR_ASPECT void SoundBase::execSyncV( FieldContainer &oFrom, ConstFieldMaskArg whichField, AspectOffsetStore &oOffsets, ConstFieldMaskArg syncMode, const UInt32 uiSyncInfo) { Sound *pThis = static_cast<Sound *>(this); pThis->execSync(static_cast<Sound *>(&oFrom), whichField, oOffsets, syncMode, uiSyncInfo); } #endif void SoundBase::resolveLinks(void) { Inherited::resolveLinks(); } OSG_END_NAMESPACE
e9fd55569f0fa3c00bade577ac5a6af8690b9394
f4d7107ee8fc5b795e7006f6af6382b85524449f
/main.cpp
1f06755d1bef5ee71b197279d080f4728f2a4516
[]
no_license
Olympianz/MyChess
5faf7bfa46a013f5c22444d08ef42a6a8477d09e
b8010ad95856782539769a3db7d7dbecc80376b0
refs/heads/master
2016-09-06T15:26:47.081274
2013-06-12T20:31:34
2013-06-12T20:31:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,849
cpp
#include<iostream> #include<string> #include<cstdlib> // in this example pieces aer described as integer values // we will make them constants, so that if at any time we want to change their values we can do so here // but will still need to recompile const int pawn = 100; const int bishop = 305; const int knight = 300; const int rook = 500; const int queen = 900; const int king = 2000; // an alternative would be to use string constants or another data type //now we need a board to put the pieces on and move around on //the board data type should match the pieces data type // the board in regular chess is always 8x8, but for speedy legal move generator //other programs use larger than 8x8 where an 8x8 real board exists in a larger array ie 12x14 // but for simplicity of understanding we will use the simple 8x8 int board[8][8]; // board [rank] [file]; // where rank = 0 - 7 (1 to 8 on a real chess board) and file = 0 - 7 (a - h) const int startup[8][8] = { rook, knight, bishop, queen, king, bishop, knight, rook, pawn, pawn,pawn,pawn,pawn,pawn,pawn, pawn, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -pawn, -pawn, -pawn, -pawn, -pawn, -pawn, -pawn, -pawn, -rook, -knight, -bishop, -queen, -king, -bishop, -knight, -rook}; // the startup constant contains the standard starting position of all chess games (not variants) //each side has 8 pieces and 8 pawns / all pawns are on the colours respective ranks // for black pieces we use -piecetype. (negative) void setup (void) { int i, j; for (i = 0; i < 8; i++){ for (j = 0; j < 8; j++){ board[i][j] = startup[i][j]; //setup starting position } } } //the two for loops run through all the iteratins of the 8x8 array and copy the starting position to the real board. // next we need a function that will display the board some way either graphics or text // in this case we will print to the screen a text version of the boards contents //it is standard in FEN notations and other text of a chess board to express each piece by it's first letter // except the knight which uses 'N' // the black pieces are lower case while the white pieces are upper case // otherwise it is impossible to distinguish black pieces from white pieces void printb (void){ using namespace std; // this must be here in order to begin using strings. int a, b; string piece; for (a = 7; a > -1; a--){ // we must iterate the ranks down from 7 to 0 otherwise the board will be upside down cout << endl; for (b = 0; b < 8; b++){ switch (board[a][b]){ case 0: piece = "-"; break; case pawn: piece = "P"; break; case knight: piece = "N"; break; case bishop: piece = "B"; break; case rook: piece = "R"; break; case queen: piece = "Q"; break; case king: piece = "K"; break; case -pawn: piece = "p"; break; case -knight: piece = "n"; break; case -bishop: piece = "b"; break; case -rook: piece = "r"; break; case -queen: piece = "q"; break; case -king: piece = "k"; break; } cout << " " << piece << " "; } } cout << endl << endl; } // every program in win32 console must have a main int main (void) { using namespace std; //we need to tell the user about the program .. and how to use it cout << "welcome to simplechess 1.0!" << endl << "created by Deepglue555" << endl << endl; cout << "please enter your moves in 4 letter algebraic" << endl << "ie e2e4 in lower case only" << endl; cout << "commands: exit = quit, abort = quit, print = displays the board," << endl << "new = new game" << endl << endl; string passd; // this will be the string that contains info from the user setup(); //we must set up the initial position while (1){ // a while loop that always loops; except when a break; statement occurs getline (cin, passd ); //ask the user to input what he wants the app to do if (passd.substr(0, 4) == "exit" || passd.substr(0, 5) == "abort" || passd.substr(0, 4) == "quit") { //test //for quit or exit statements break; } if (passd.substr(0, 5) == "print") { // display the board printb(); } if (passd.substr(0, 3) == "new") { // ask for a new game setup(); } if (passd.substr(0, 1) >= "a" && passd.substr(0, 1) <= "h" && passd.substr(1, 1) >= "1" && passd.substr(1, 1) <= "8" && passd.substr(2, 1) >= "a" && passd.substr(2, 1) <= "h" && passd.substr(3, 1) >= "1" && passd.substr(3, 1) <= "8") { // this statement makes sure both squares are on the chess board when executing //a move // execute move // then display new board position int a, b, c, d; a = passd[0] - 'a'; b = passd[1] - '1'; c = passd[2] - 'a'; d = passd[3] - '1'; //executes the move if its on the board! board[d][c] = board[b][a]; board[b][a] = 0; printb(); //prints out to the screen the updated position after moving the pieces } } }
[ "Chong@FanChong" ]
Chong@FanChong
874b42a54340c6b5f0e6db568e0096c42cb35beb
d466e547d37eed51027d81bf7e3799cdf6807219
/src/tools/cds-2.2.0/test/stress/map/delodd/map_delodd.cpp
0b9d75174b05f73c8ce435facddffce193fd35f9
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
emilytsui/ParaHash
bd06e5745c887c966c5421c351582c7179dc975a
7285e3525e25ebd8861297d24038e2fdb57a6175
refs/heads/master
2021-01-19T08:39:52.828586
2017-05-12T07:01:14
2017-05-12T07:01:14
87,654,652
0
0
null
null
null
null
UTF-8
C++
false
false
5,069
cpp
/* This file is a part of libcds - Concurrent Data Structures library (C) Copyright Maxim Khizhinsky ([email protected]) 2006-2017 Source code repo: http://github.com/khizmax/libcds/ Download: http://sourceforge.net/projects/libcds/files/ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "map_delodd.h" namespace map { size_t Map_DelOdd::s_nMapSize = 10000; size_t Map_DelOdd::s_nInsThreadCount = 4; size_t Map_DelOdd::s_nDelThreadCount = 4; size_t Map_DelOdd::s_nExtractThreadCount = 4; size_t Map_DelOdd::s_nFindThreadCount = 2; size_t Map_DelOdd::s_nMaxLoadFactor = 8; size_t Map_DelOdd::s_nInsertPassCount = 100; size_t Map_DelOdd::s_nCuckooInitialSize = 1024; size_t Map_DelOdd::s_nCuckooProbesetSize = 16; size_t Map_DelOdd::s_nCuckooProbesetThreshold = 0; size_t Map_DelOdd::s_nFeldmanMap_HeadBits = 10; size_t Map_DelOdd::s_nFeldmanMap_ArrayBits = 4; size_t Map_DelOdd::s_nLoadFactor = 1; std::vector<size_t> Map_DelOdd::m_arrElements; void Map_DelOdd::SetUpTestCase() { cds_test::config const& cfg = get_config( "map_delodd" ); s_nMapSize = cfg.get_size_t( "MapSize", s_nMapSize ); if ( s_nMapSize < 1000 ) s_nMapSize = 1000; s_nInsThreadCount = cfg.get_size_t( "InsThreadCount", s_nInsThreadCount ); if ( s_nInsThreadCount == 0 ) s_nInsThreadCount = 1; s_nDelThreadCount = cfg.get_size_t( "DelThreadCount", s_nDelThreadCount ); s_nExtractThreadCount = cfg.get_size_t( "ExtractThreadCount", s_nExtractThreadCount ); s_nFindThreadCount = cfg.get_size_t( "FindThreadCount", s_nFindThreadCount ); s_nMaxLoadFactor = cfg.get_size_t( "MaxLoadFactor", s_nMaxLoadFactor ); if ( s_nMaxLoadFactor == 0 ) s_nMaxLoadFactor = 1; s_nInsertPassCount = cfg.get_size_t( "PassCount", s_nInsertPassCount ); if ( s_nInsertPassCount == 0 ) s_nInsertPassCount = 100; s_nCuckooInitialSize = cfg.get_size_t( "CuckooInitialSize", s_nCuckooInitialSize ); if ( s_nCuckooInitialSize < 256 ) s_nCuckooInitialSize = 256; s_nCuckooProbesetSize = cfg.get_size_t( "CuckooProbesetSize", s_nCuckooProbesetSize ); if ( s_nCuckooProbesetSize < 8 ) s_nCuckooProbesetSize = 8; s_nCuckooProbesetThreshold = cfg.get_size_t( "CuckooProbesetThreshold", s_nCuckooProbesetThreshold ); s_nFeldmanMap_HeadBits = cfg.get_size_t( "FeldmanMapHeadBits", s_nFeldmanMap_HeadBits ); if ( s_nFeldmanMap_HeadBits == 0 ) s_nFeldmanMap_HeadBits = 2; s_nFeldmanMap_ArrayBits = cfg.get_size_t( "FeldmanMapArrayBits", s_nFeldmanMap_ArrayBits ); if ( s_nFeldmanMap_ArrayBits == 0 ) s_nFeldmanMap_ArrayBits = 2; m_arrElements.resize( s_nMapSize ); for ( size_t i = 0; i < s_nMapSize; ++i ) m_arrElements[i] = i;; shuffle( m_arrElements.begin(), m_arrElements.end()); } void Map_DelOdd::TearDownTestCase() { m_arrElements.clear(); } std::vector<size_t> Map_DelOdd_LF::get_load_factors() { cds_test::config const& cfg = get_config( "map_delodd" ); s_nMaxLoadFactor = cfg.get_size_t( "MaxLoadFactor", s_nMaxLoadFactor ); if ( s_nMaxLoadFactor == 0 ) s_nMaxLoadFactor = 1; std::vector<size_t> lf; for ( size_t n = 1; n <= s_nMaxLoadFactor; n *= 2 ) lf.push_back( n ); return lf; } INSTANTIATE_TEST_CASE_P( a, Map_DelOdd_LF, ::testing::ValuesIn( Map_DelOdd_LF::get_load_factors())); } // namespace map
757700c49fc1d11b7597bd60dc2f218a228efd56
6d370728c3f4b051817e501d60e2b53ddcd20ecc
/Creating_Strings_I.cpp
5a96e71810070f2646b159a761a7fba39013063e
[]
no_license
for-l00p/CSES-1
1fe8983b22a28a5901982089c7792529d32418f6
05ef511b885b671f9a8e6cb704bc50096ab954cf
refs/heads/master
2022-11-23T23:13:50.798146
2020-07-25T14:35:25
2020-07-25T14:35:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
533
cpp
#include <bits/stdc++.h> using namespace std; set<char> s; multiset<char> ms; vector<string> v; string ss; int coun=0; void f(int i){ if(i==1){coun++;ss.push_back(*ms.begin());v.push_back(ss);ss.erase(ss.end()-1);;return;} for(auto j:s){ if(ms.count(j)){ ms.erase(ms.find(j)); ss.push_back(j); f(i-1); ss.erase(ss.end()-1); ms.insert(j); } } } int main(){ char c[9]; scanf("%s",c); int i=0;for(;c[i];i++){s.insert(c[i]);ms.insert(c[i]);} f(i); printf("%d\n",coun); for(auto x:v)cout<<x<<endl; return 0;}
60ab3cafff8344737e04d8ec48159b1746c68c03
33b21217fd205161f8baa5d46014fc2e97c73a64
/GP2 Engine/OverlordProject/CourseObjects/Week 3/SpikeyScene.h
e794f17331edfad45eac09a073ab327cd160f7f0
[]
no_license
ajweeks/RubiksCube
bdb141579fbbf8bd77e0db80fb4949b23c8c770a
2236f10dce0b7745ac7d7bf69f35aa35cc1234d3
refs/heads/master
2020-06-30T18:00:41.254094
2017-06-16T08:43:05
2017-06-16T08:43:05
74,355,982
1
0
null
null
null
null
UTF-8
C++
false
false
619
h
#pragma once #include "Scenegraph/GameScene.h" #include "Helpers\EffectHelper.h" class SpikeyScene: public GameScene { public: SpikeyScene(); virtual ~SpikeyScene(); protected: virtual void Initialize(const GameContext& gameContext); virtual void Update(const GameContext& gameContext); virtual void Draw(const GameContext& gameContext); private: float m_FpsInterval; private: // ------------------------- // Disabling default copy constructor and default // assignment operator. // ------------------------- SpikeyScene( const SpikeyScene &obj); SpikeyScene& operator=( const SpikeyScene& obj); };
15fdcad926ba01c3cece1b97baff215ddeb1f2ef
fc987ace8516d4d5dfcb5444ed7cb905008c6147
/chrome/browser/ui/views/bookmarks/bookmark_bubble_view.h
31015d3e32156a5a81aa289208903b4ea5ce0fdf
[ "BSD-3-Clause" ]
permissive
nfschina/nfs-browser
3c366cedbdbe995739717d9f61e451bcf7b565ce
b6670ba13beb8ab57003f3ba2c755dc368de3967
refs/heads/master
2022-10-28T01:18:08.229807
2020-09-07T11:45:28
2020-09-07T11:45:28
145,939,440
2
4
BSD-3-Clause
2022-10-13T14:59:54
2018-08-24T03:47:46
null
UTF-8
C++
false
false
5,113
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Copyright (c) 2016-2018 CPU and Fundamental Software Research Center, Chinese Academy of Sciences. #ifndef CHROME_BROWSER_UI_VIEWS_BOOKMARKS_BOOKMARK_BUBBLE_VIEW_H_ #define CHROME_BROWSER_UI_VIEWS_BOOKMARKS_BOOKMARK_BUBBLE_VIEW_H_ #include <memory> #include "base/compiler_specific.h" #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/strings/string16.h" #include "chrome/browser/ui/bookmarks/recently_used_folders_combo_model.h" #include "chrome/browser/ui/sync/bubble_sync_promo_delegate.h" #include "chrome/browser/ui/views/location_bar/location_bar_bubble_delegate_view.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/combobox/combobox_listener.h" #include "url/gurl.h" class Profile; namespace bookmarks { class BookmarkBubbleObserver; } namespace views { class LabelButton; class Textfield; } // BookmarkBubbleView is a view intended to be used as the content of an // Bubble. BookmarkBubbleView provides views for unstarring and editing the // bookmark it is created with. Don't create a BookmarkBubbleView directly, // instead use the static Show method. class BookmarkBubbleView : public LocationBarBubbleDelegateView, public views::ButtonListener, public views::ComboboxListener { public: // If |anchor_view| is null, |anchor_rect| is used to anchor the bubble and // |parent_window| is used to ensure the bubble closes if the parent closes. // Returns the newly created bubble's Widget or nullptr in case when the // bubble already exists. static views::Widget* ShowBubble( views::View* anchor_view, const gfx::Rect& anchor_rect, gfx::NativeView parent_window, bookmarks::BookmarkBubbleObserver* observer, std::unique_ptr<BubbleSyncPromoDelegate> delegate, Profile* profile, const GURL& url, bool already_bookmarked); static void Hide(); static BookmarkBubbleView* bookmark_bubble() { return bookmark_bubble_; } ~BookmarkBubbleView() override; // views::WidgetDelegate: void WindowClosing() override; bool AcceleratorPressed(const ui::Accelerator& accelerator) override; protected: // views::BubbleDialogDelegateView method. void Init() override; base::string16 GetWindowTitle() const override; private: friend class BookmarkBubbleViewTest; FRIEND_TEST_ALL_PREFIXES(BookmarkBubbleViewTest, SyncPromoSignedIn); FRIEND_TEST_ALL_PREFIXES(BookmarkBubbleViewTest, SyncPromoNotSignedIn); // views::BubbleDialogDelegateView: const char* GetClassName() const override; View* GetInitiallyFocusedView() override; View* CreateFootnoteView() override; // Creates a BookmarkBubbleView. BookmarkBubbleView(views::View* anchor_view, bookmarks::BookmarkBubbleObserver* observer, std::unique_ptr<BubbleSyncPromoDelegate> delegate, Profile* profile, const GURL& url, bool newly_bookmarked); // Returns the title to display. base::string16 GetTitle(); // Overridden from views::View: void GetAccessibleState(ui::AXViewState* state) override; // Overridden from views::ButtonListener: // Closes the bubble or opens the edit dialog. void ButtonPressed(views::Button* sender, const ui::Event& event) override; // Overridden from views::ComboboxListener: void OnPerformAction(views::Combobox* combobox) override; // Handle the message when the user presses a button. void HandleButtonPressed(views::Button* sender); // Shows the BookmarkEditor. void ShowEditor(); // Sets the title and parent of the node. void ApplyEdits(); // The bookmark bubble, if we're showing one. static BookmarkBubbleView* bookmark_bubble_; // Our observer, to notify when the bubble shows or hides. bookmarks::BookmarkBubbleObserver* observer_; // Delegate, to handle clicks on the sign in link. std::unique_ptr<BubbleSyncPromoDelegate> delegate_; // The profile. Profile* profile_; // The bookmark URL. const GURL url_; // If true, the page was just bookmarked. const bool newly_bookmarked_; RecentlyUsedFoldersComboModel parent_model_; // Button for removing the bookmark. views::LabelButton* remove_button_; // Button to bring up the editor. views::LabelButton* edit_button_; // Button to close the window. views::LabelButton* close_button_; // Textfield showing the title of the bookmark. views::Textfield* title_tf_; // Combobox showing a handful of folders the user can choose from, including // the current parent. views::Combobox* parent_combobox_; // When the destructor is invoked should the bookmark be removed? bool remove_bookmark_; // When the destructor is invoked should edits be applied? bool apply_edits_; DISALLOW_COPY_AND_ASSIGN(BookmarkBubbleView); }; #endif // CHROME_BROWSER_UI_VIEWS_BOOKMARKS_BOOKMARK_BUBBLE_VIEW_H_
499c5c3cad1b66d54268aa7e492aa5eafacfb293
be3b23638c34560829c9e4270fa059039cc75876
/examples/AllThingsTalk_DHT22_SSD1306/AllThingsTalk_DHT22_SSD1306.ino
dd285b31fec86fd9fcc2bf115c77ba2ab6f64946
[ "MIT" ]
permissive
albertskog/telia-iot-workshop-wifi
57c21de36f6a26d7de3d27eb41cbe94f8f387c75
1ef7e1f4c84866bcf7a7f417c156bab67906fe29
refs/heads/master
2020-07-06T19:08:53.869162
2018-06-05T07:08:27
2018-06-05T07:08:27
135,287,815
0
0
null
null
null
null
UTF-8
C++
false
false
3,441
ino
#include <ESP8266WiFi.h> #include <PubSubClient.h> #include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> #include "DHT.h" #include <ATT_IOT.h> #include <ArduinoJson.h> #define DHTPIN D7 // what digital pin we're connected to #define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321 #define http "api.allthingstalk.io" // API endpoint #define mqtt "api.allthingstalk.io" // broker // AllThingsTalk device credentials const char deviceId[] = "XXXXXX"; const char deviceToken[] = "maker:XXXXXXXXXXXXXX"; // Wifi settings const char* ssid = "telia1"; const char* password = "workshop"; void callback(char* topic, byte* payload, unsigned int length); WiFiClient espClient; PubSubClient pubSub(mqtt, 1883, callback, espClient); ATTDevice device(deviceId, deviceToken); Adafruit_SSD1306 display(-1); DHT dht(DHTPIN, DHTTYPE); void setup() { Serial.begin(9600); // by default, we'll generate the high voltage from the 3.3v line internally! (neat!) display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // initialize with the I2C addr 0x3C (for the 128x32) // Clear the buffer. display.clearDisplay(); dht.begin(); setupWiFi(ssid, password); // Connect to AllThingsTalk while(!device.connect(&espClient, http)){ Serial.println("retrying"); } // Create the assets in case they do not exist device.addAsset("temperature", "temperature", "Current temperature", "sensor", "{\"type\": \"number\"}"); device.addAsset("humidity", "humidity", "Current humidity", "sensor", "{\"type\": \"number\"}"); // Subscribe to mqtt while(!device.subscribe(pubSub)){ Serial.println("retrying"); } } void setupWiFi(const char* ssid, const char* password) { delay(10); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); Serial.println("WiFi connected"); } unsigned long prevTime; unsigned int prevVal = 0; int counter = 0; void loop() { unsigned long curTime = millis(); if (curTime > (prevTime + 1000)) // Update and send counter value every 5 seconds { device.send(String(dht.readTemperature()), "temperature"); device.send(String(dht.readHumidity()), "humidity"); display.clearDisplay(); display.setCursor(0,0); display.setTextSize(2); display.setTextColor(WHITE); display.println(String(dht.readTemperature()) + " C"); display.println(String(dht.readHumidity()) + " %"); display.display(); counter++; prevTime = curTime; } device.process(); // Check for incoming messages } void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); // Convert payload to json StaticJsonBuffer<500> jsonBuffer; char json[500]; for (int i = 0; i < length; i++) { json[i] = (char)payload[i]; } json[length] = '\0'; JsonObject& root = jsonBuffer.parseObject(json); // Do something if(root.success()) { const char* value = root["value"]; Serial.println(value); if (strcmp(value,"true") == 0) digitalWrite(LED_BUILTIN, LOW); // Turn the onboard LED on else digitalWrite(LED_BUILTIN, HIGH); // Turn the onboard LED off device.send(value, "toggle"); // Send command back as ACK using JSON } else Serial.println("Parsing JSON failed"); }
ab8211c10fe3b9fcad169082a8a1e022192f43e9
c04e49371d98c136fb484c541a0fb479c96001ff
/code/include/Graphics/Text/Glyph.h
624b5cc313e822d7812700abb51f53cd421a0ce3
[ "MIT" ]
permissive
Arzana/Plutonium
0af59b6ffee010eed7c6c8f6182c87480ef45dc3
5a17c93e5072ac291b96347a4df196e1609fabe2
refs/heads/master
2021-05-09T02:20:42.528906
2020-10-31T20:36:57
2020-10-31T20:36:57
119,201,274
4
0
null
null
null
null
UTF-8
C++
false
false
1,279
h
#pragma once #include "Core/Math/Shapes/Rectangle.h" namespace Pu { /* Defines all information needed for a glyph within a texture altas. */ struct Glyph { public: /* The indentifier for this glyph. */ char32 Key; /* The top left uv coordinate of the glyph. */ Vector2 U; /* The bottom right uv coordinate of the glyph. */ Vector2 V; /* The actual size of the character. */ Vector2 Size; /* The offset from the render position. */ Vector2 Bearing; /* The directional space added to the position after this character is draw. */ uint32 Advance; /* Initializes an empty instance of a glyph. */ Glyph(void) : Key(U'\0'), Advance(0) {} /* Copy constructor. */ Glyph(_In_ const Glyph&) = default; /* Move constructor. */ Glyph(_In_ Glyph&&) = default; /* Copy assignment. */ _Check_return_ Glyph& operator =(_In_ const Glyph&) = default; /* Move assignment. */ _Check_return_ Glyph& operator =(_In_ Glyph&&) = default; /* Checks whether tho glyph are equal. */ _Check_return_ inline bool operator ==(_In_ const Glyph &other) const { return other.Key == Key; } /* Checks whether tho glyph differ. */ _Check_return_ inline bool operator !=(_In_ const Glyph &other) const { return other.Key != Key; } }; }
4391114d1c2ea94c40c1e4be07679f53eb5e2cc7
8635e9e8cde70ce1f55aac7b50d8090add38a163
/Problems/YYHSOJ/Contest1210/C.cpp
ec0e0d8d1f9c7d5cde551db820d62a40b781535b
[]
no_license
99hgz/Algorithms
f0b696f60331ece11e99c93e75eb8a38326ddd96
a24c22bdee5432925f615aef58949402814473cd
refs/heads/master
2023-04-14T15:21:58.434225
2023-04-03T13:01:04
2023-04-03T13:01:04
88,978,471
3
1
null
null
null
null
UTF-8
C++
false
false
1,779
cpp
#include <cstdio> #include <cstring> #include <cstdlib> #include <algorithm> #include <queue> using namespace std; typedef long long ll; struct PATH { int dis, to; }; struct NODE { int s, t; }; vector<PATH> path[1010]; ll dis[55][20005]; int cnt, s, k, a, b, c, n, m, i, mod, t; ll T; void spfa() { memset(dis, 0x7f7f7f7f, sizeof(dis)); queue<NODE> Q1; Q1.push((NODE){s, 0}); dis[s][0] = 0; while (!Q1.empty()) { NODE tmp = Q1.front(); Q1.pop(); int u = tmp.s; for (int i = 0; i < path[u].size(); i++) { int goton = path[u][i].to; int t2 = (tmp.t + path[u][i].dis) % mod; if (dis[goton][t2] > dis[u][tmp.t] + path[u][i].dis) { dis[goton][t2] = dis[u][tmp.t] + path[u][i].dis; Q1.push((NODE){goton, t2}); } } } } void addpath(int a, int b, int c) { PATH tmp; tmp.to = b; tmp.dis = c; path[a].push_back(tmp); if ((a == 1) && (c < mod)) mod = c; } int main() { scanf("%d", &t); while (t--) { for (int i = 1; i <= n; i++) { path[i].clear(); } mod = 0x7f7f7f7f; scanf("%d%d%lld", &n, &m, &T); for (int i = 1; i <= m; i++) { scanf("%d%d%d", &a, &b, &c); a++, b++; addpath(a, b, c); addpath(b, a, c); } if (mod == 0x7f7f7f7f) printf("Impossible\n"); else { mod *= 2; s = 1; spfa(); if (dis[n][T % mod] <= T) printf("Possible\n"); else printf("Impossible\n"); } } system("pause"); return 0; }
f9bb7fdf096f8abaf456fcc39bfc2ca85154d659
cf6ae38d4adf41e3eb219b8ac477aa7ca7c7d18a
/boost/geometry/extensions/iterators/segment_returning_iterator.hpp
b313b6c637834aa7ccef739604783aeb744d5476
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
ryppl/boost-history
a560df2bc79ffc7640f09d258599891dbbb8f6d0
934c80ff671f3afeb72b38d5fdf4396acc2dc58c
HEAD
2016-09-07T08:08:33.930543
2011-07-10T13:15:08
2011-07-10T13:15:08
3,539,914
1
0
null
null
null
null
UTF-8
C++
false
false
3,483
hpp
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2009-2011 Mateusz Loskot, London, UK. // Copyright (c) 2009-2011 Barend Gehrels, Amsterdam, the Netherlands. // Use, modification and distribution is subject to 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 BOOST_GEOMETRY_EXTENSIONS_ITERATORS_SEGMENT_RETURNING_ITERATOR_HPP #define BOOST_GEOMETRY_EXTENSIONS_ITERATORS_SEGMENT_RETURNING_ITERATOR_HPP // TODO: This is very experimental version of input iterator // reading collection of points as segments - proof of concept. // --mloskot // TODO: Move to boost::iterator_adaptor #include <iterator> #include <boost/assert.hpp> #include <boost/iterator.hpp> #include <boost/iterator/iterator_adaptor.hpp> #include <boost/iterator/iterator_categories.hpp> #include <boost/geometry/algorithms/equals.hpp> // Helper geometry #include <boost/geometry/geometries/segment.hpp> namespace boost { namespace geometry { template <typename Base, typename Point> struct segment_returning_iterator { typedef Base base_type; typedef Point point_type; typedef typename model::referring_segment<Point> segment_type; typedef std::input_iterator_tag iterator_category; typedef typename std::iterator_traits<Base>::difference_type difference_type; typedef segment_type value_type; typedef segment_type* pointer; typedef segment_type& reference; explicit segment_returning_iterator(Base const& end) : m_segment(p1 , p2) , m_prev(end) , m_it(end) , m_end(end) { } segment_returning_iterator(Base const& it, Base const& end) : m_segment(p1 , p2) , m_prev(it) , m_it(it) , m_end(end) { if (m_it != m_end) { BOOST_ASSERT(m_prev != m_end); ++m_it; } } reference operator*() { BOOST_ASSERT(m_it != m_end && m_prev != m_end); p1 = *m_prev; p2 = *m_it; return m_segment; } pointer operator->() { return &(operator*()); } segment_returning_iterator& operator++() { ++m_prev; ++m_it; return *this; } segment_returning_iterator operator++(int) { segment_returning_iterator it(*this); ++(*this); return it; } Base const& base() const { return m_it; } private: point_type p1; point_type p2; segment_type m_segment; Base m_prev; Base m_it; Base m_end; }; template <typename Base, typename Point> bool operator==(segment_returning_iterator<Base, Point> const& lhs, segment_returning_iterator<Base, Point> const& rhs) { return (lhs.base() == rhs.base()); } template <typename Base, typename Point> bool operator!=(segment_returning_iterator<Base, Point> const& lhs, segment_returning_iterator<Base, Point> const& rhs) { return (lhs.base() != rhs.base()); } template <typename C> inline segment_returning_iterator < typename C::iterator, typename C::value_type > make_segment_returning_iterator(C& c) { typedef typename C::iterator base_iterator; typedef typename C::value_type point_type; return segment_returning_iterator<base_iterator, point_type>(c.begin(), c.end()); } }} // namespace boost::geometry #endif // BOOST_GEOMETRY_EXTENSIONS_ITERATORS_SEGMENT_RETURNING_ITERATOR_HPP
ca6d62127daf177af87a23c50f6c55f8fc599f03
99c6f753e8fe47f85640899faad4d26d09d79fa4
/A3/Task2/OneTimePad.cpp
ba49ab1dc6215a3e360a83353007a84bef570b26
[]
no_license
israel-sekhwela/COS110_2018
523caafc161b6750baa903c08c9809d1c72b4efd
a979f07131a945d21f5da7acfd63d7e032fa9474
refs/heads/master
2020-03-23T23:37:03.874933
2018-10-16T20:28:31
2018-10-16T20:28:31
142,244,828
0
0
null
null
null
null
UTF-8
C++
false
false
1,305
cpp
#include <cstdlib> #include "OneTimePad.h" OneTimePad :: OneTimePad(long int l){ this->setSeed(l); } void OneTimePad :: setSeed(long int l){ int count; ascii = ""; count = 0; while(count < 95){ ascii = ascii + char(count + 32); count++; } if(l >= 0){ seed = l; } else{ Exception str("Negative number provided"); throw (str); } srand(this->seed); } string OneTimePad :: encode(const string& s){ srand(this->seed); return SubstitutionCipher::encode(s); } string OneTimePad :: decode(const string& s){ srand(this->seed); return (SubstitutionCipher::decode(s)); } char OneTimePad :: encodeChar(char c){ int random; int ascii_diff; int count; ascii_diff = int(c) - 32; random = rand() % 94 + 1; count = 0; while(count < random){ if((ascii_diff + 1) > 94){ ascii_diff = 0; } else{ ascii_diff = ascii_diff + 1; } count++; } return (ascii[ascii_diff]); } char OneTimePad :: decodeChar(char c){ int random; int ascii_diff; int count; ascii_diff = int(c) - 32; random = rand() % 94 + 1; count = 0; while (count < random){ if((ascii_diff - 1)<0){ ascii_diff = 94; } else{ ascii_diff = ascii_diff - 1; } count++; } return (ascii[ascii_diff]); }
81eb7c752e97104fcd9669e9a24d16fd09a746f4
d6b4bdf418ae6ab89b721a79f198de812311c783
/tcss/include/tencentcloud/tcss/v20201101/model/DescribeImageRiskSummaryRequest.h
25c82da02fe3678bf61e961db1b2243735d96ebf
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp-intl-en
d0781d461e84eb81775c2145bacae13084561c15
d403a6b1cf3456322bbdfb462b63e77b1e71f3dc
refs/heads/master
2023-08-21T12:29:54.125071
2023-08-21T01:12:39
2023-08-21T01:12:39
277,769,407
2
0
null
null
null
null
UTF-8
C++
false
false
1,587
h
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TENCENTCLOUD_TCSS_V20201101_MODEL_DESCRIBEIMAGERISKSUMMARYREQUEST_H_ #define TENCENTCLOUD_TCSS_V20201101_MODEL_DESCRIBEIMAGERISKSUMMARYREQUEST_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Tcss { namespace V20201101 { namespace Model { /** * DescribeImageRiskSummary request structure. */ class DescribeImageRiskSummaryRequest : public AbstractModel { public: DescribeImageRiskSummaryRequest(); ~DescribeImageRiskSummaryRequest() = default; std::string ToJsonString() const; private: }; } } } } #endif // !TENCENTCLOUD_TCSS_V20201101_MODEL_DESCRIBEIMAGERISKSUMMARYREQUEST_H_
727b0ece7db6de9a13d62d2862572cb19fb4f9d7
046b675cb8529d1585a688f21563eb0209c94f19
/src/Control2012/libreoffice/com/sun/star/datatransfer/dnd/XDropTargetDragContext.hpp
aa821b742921187894f97f53e3649b4e84035200
[]
no_license
yoshi5534/schorsch-the-robot
a2a4bd35668600451e53bd8d7f879df90dcb9994
77eb8dcabaad5da3908d6b4b78a05985323f9ba4
refs/heads/master
2021-03-12T19:41:35.524173
2013-04-17T20:00:29
2013-04-17T20:00:29
32,867,962
0
0
null
null
null
null
UTF-8
C++
false
false
1,688
hpp
#ifndef INCLUDED_COM_SUN_STAR_DATATRANSFER_DND_XDROPTARGETDRAGCONTEXT_HPP #define INCLUDED_COM_SUN_STAR_DATATRANSFER_DND_XDROPTARGETDRAGCONTEXT_HPP #include "sal/config.h" #include "com/sun/star/datatransfer/dnd/XDropTargetDragContext.hdl" #include "com/sun/star/uno/XInterface.hpp" #include "com/sun/star/uno/RuntimeException.hpp" #include "com/sun/star/uno/Reference.hxx" #include "com/sun/star/uno/Type.hxx" #include "cppu/unotype.hxx" #include "osl/mutex.hxx" #include "sal/types.h" namespace com { namespace sun { namespace star { namespace datatransfer { namespace dnd { inline ::com::sun::star::uno::Type const & cppu_detail_getUnoType(::com::sun::star::datatransfer::dnd::XDropTargetDragContext const *) { static typelib_TypeDescriptionReference * the_type = 0; if ( !the_type ) { typelib_static_mi_interface_type_init( &the_type, "com.sun.star.datatransfer.dnd.XDropTargetDragContext", 0, 0 ); } return * reinterpret_cast< ::com::sun::star::uno::Type * >( &the_type ); } } } } } } inline ::com::sun::star::uno::Type const & SAL_CALL getCppuType(::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::dnd::XDropTargetDragContext > const *) SAL_THROW(()) { return ::cppu::UnoType< ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::dnd::XDropTargetDragContext > >::get(); } ::com::sun::star::uno::Type const & ::com::sun::star::datatransfer::dnd::XDropTargetDragContext::static_type(void *) { return ::getCppuType(static_cast< ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::dnd::XDropTargetDragContext > * >(0)); } #endif // INCLUDED_COM_SUN_STAR_DATATRANSFER_DND_XDROPTARGETDRAGCONTEXT_HPP
[ "schorsch@localhost" ]
schorsch@localhost
e0668e20e5eefef7fc3ec5467b297573d81b44d4
60a15a584b00895e47628c5a485bd1f14cfeebbe
/comps/docs/DBaseDoc/TalbeWiz.cpp
d4128d2474a4ce52c86359eccba1361799b74c99
[]
no_license
fcccode/vt5
ce4c1d8fe819715f2580586c8113cfedf2ab44ac
c88049949ebb999304f0fc7648f3d03f6501c65b
refs/heads/master
2020-09-27T22:56:55.348501
2019-06-17T20:39:46
2019-06-17T20:39:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,377
cpp
// TalbeWiz.cpp : implementation file // #include "stdafx.h" #include "dbasedoc.h" #include "TalbeWiz.h" #include "Wizards.h" ///////////////////////////////////////////////////////////////////////////// // CNewTablePage property page IMPLEMENT_DYNCREATE(CNewTablePage, CPropertyPage) CNewTablePage::CNewTablePage() : CPropertyPage(CNewTablePage::IDD) { //{{AFX_DATA_INIT(CNewTablePage) m_strTableName = _T(""); //}}AFX_DATA_INIT m_strTableName.LoadString( IDS_DEF_TABLE_NAME ); } CNewTablePage::~CNewTablePage() { } void CNewTablePage::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange(pDX); //{{AFX_DATA_MAP(CNewTablePage) DDX_Text(pDX, IDC_TABLE_NAME, m_strTableName); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CNewTablePage, CPropertyPage) //{{AFX_MSG_MAP(CNewTablePage) // NOTE: the ClassWizard will add message map macros here //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CNewTablePage message handlers ///////////////////////////////////////////////////////////////////////////// // CDefineFieldCreationPage dialog IMPLEMENT_DYNCREATE(CDefineFieldCreationPage, CPropertyPage) CDefineFieldCreationPage::CDefineFieldCreationPage() : CPropertyPage(CDefineFieldCreationPage::IDD) { //{{AFX_DATA_INIT(CDefineFieldCreationPage) m_nDefineType = 0; //}}AFX_DATA_INIT } void CDefineFieldCreationPage::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange(pDX); //{{AFX_DATA_MAP(CDefineFieldCreationPage) DDX_Radio(pDX, IDC_DEFINE_FIELD_TYPE, m_nDefineType); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CDefineFieldCreationPage, CPropertyPage) //{{AFX_MSG_MAP(CDefineFieldCreationPage) // NOTE: the ClassWizard will add message map macros here //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDefineFieldCreationPage message handlers ///////////////////////////////////////////////////////////////////////////// // CAdvFieldConstrPage property page IMPLEMENT_DYNCREATE(CAdvFieldConstrPage, CPropertyPage) CAdvFieldConstrPage::CAdvFieldConstrPage() : CPropertyPage(CAdvFieldConstrPage::IDD) { //{{AFX_DATA_INIT(CAdvFieldConstrPage) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } CAdvFieldConstrPage::~CAdvFieldConstrPage() { } void CAdvFieldConstrPage::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAdvFieldConstrPage) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP } BOOL CAdvFieldConstrPage::OnInitDialog() { CPropertyPage::OnInitDialog(); CRect rcGrid; GetClientRect( &rcGrid ); /* CWnd* pWnd = GetDlgItem(IDC_GRID_PLACE); if( pWnd ) { pWnd->GetWindowRect( &rcGrid ); ScreenToClient( &rcGrid ); } */ VERIFY( m_grid.Create( rcGrid, this, 10025, WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_BORDER ) ); CString strTableName( "table" ); CWnd* pParent = GetParent(); if( pParent && pParent->IsKindOf( RUNTIME_CLASS(CWizardSheet)) ) { CNewTablePage* pPage = (CNewTablePage*) ((CWizardSheet*)pParent)->FindPage( RUNTIME_CLASS(CNewTablePage), 0 ); if( pPage ) strTableName = pPage->m_strTableName; } m_grid.Init(); m_grid.Clear(); m_grid.CreateKeyRow( strTableName ); return TRUE; } BEGIN_MESSAGE_MAP(CAdvFieldConstrPage, CPropertyPage) //{{AFX_MSG_MAP(CAdvFieldConstrPage) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CAdvFieldConstrPage message handlers ///////////////////////////////////////////////////////////////////////////// // CSimpleFieldConstrPage property page IMPLEMENT_DYNCREATE(CSimpleFieldConstrPage, CPropertyPage) CSimpleFieldConstrPage::CSimpleFieldConstrPage() : CPropertyPage(CSimpleFieldConstrPage::IDD) { //{{AFX_DATA_INIT(CSimpleFieldConstrPage) m_nImage = 2; m_nNumber = 0; m_nDateTime = 0; m_nString = 2; m_nOLE = 0; //}}AFX_DATA_INIT } CSimpleFieldConstrPage::~CSimpleFieldConstrPage() { } void CSimpleFieldConstrPage::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange(pDX); //{{AFX_DATA_MAP(CSimpleFieldConstrPage) DDX_Text(pDX, IDC_IMAGE, m_nImage); DDV_MinMaxInt(pDX, m_nImage, 0, 100); DDX_Text(pDX, IDC_NUMBER, m_nNumber); DDV_MinMaxInt(pDX, m_nNumber, 0, 100); DDX_Text(pDX, IDC_DATE_TIME, m_nDateTime); DDV_MinMaxInt(pDX, m_nDateTime, 0, 100); DDX_Text(pDX, IDC_STRING, m_nString); DDV_MinMaxInt(pDX, m_nString, 0, 100); DDX_Text(pDX, IDC_OLE, m_nOLE); DDV_MinMaxInt(pDX, m_nOLE, 0, 100); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CSimpleFieldConstrPage, CPropertyPage) //{{AFX_MSG_MAP(CSimpleFieldConstrPage) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CSimpleFieldConstrPage message handlers BOOL CAdvFieldConstrPage::OnSetActive() { PROCESS_SET_ACTIVE_MSG() } BOOL CDefineFieldCreationPage::OnSetActive() { PROCESS_SET_ACTIVE_MSG() } BOOL CNewTablePage::OnSetActive() { PROCESS_SET_ACTIVE_MSG() } BOOL CSimpleFieldConstrPage::OnSetActive() { PROCESS_SET_ACTIVE_MSG() } LRESULT CAdvFieldConstrPage::OnWizardBack() { // TODO: Add your specialized code here and/or call the base class PROCESS_WIZARD_BACK_MSG() } LRESULT CAdvFieldConstrPage::OnWizardNext() { UpdateData( TRUE ); CString strError; if( !m_grid.VerifyStruct( true, strError ) ) { AfxMessageBox( strError, MB_ICONSTOP ); return -1; } PROCESS_WIZARD_NEXT_MSG() } BOOL CAdvFieldConstrPage::OnWizardFinish() { // TODO: Add your specialized code here and/or call the base class PROCESS_WIZARD_FINISH_MSG() } LRESULT CDefineFieldCreationPage::OnWizardBack() { // TODO: Add your specialized code here and/or call the base class PROCESS_WIZARD_BACK_MSG() } LRESULT CDefineFieldCreationPage::OnWizardNext() { // TODO: Add your specialized code here and/or call the base class PROCESS_WIZARD_NEXT_MSG() } BOOL CDefineFieldCreationPage::OnWizardFinish() { // TODO: Add your specialized code here and/or call the base class PROCESS_WIZARD_FINISH_MSG() } LRESULT CNewTablePage::OnWizardBack() { // TODO: Add your specialized code here and/or call the base class PROCESS_WIZARD_BACK_MSG() } LRESULT CNewTablePage::OnWizardNext() { UpdateData( TRUE ); CWnd* pWiz = GetParent(); if( pWiz && pWiz->IsKindOf( RUNTIME_CLASS(CWizardSheet)) ) { TABLEINFO_ARR arrTable; if( ::GetDBFieldInfo( (CWizardSheet*)pWiz, arrTable, 0 ) ) { bool bValidName = false; CString strError; bValidName = IsValidTableName( m_strTableName, arrTable, strError ); for( int i=0;i<arrTable.GetSize();i++ ) delete arrTable[i]; arrTable.RemoveAll(); if( !bValidName ) { AfxMessageBox( strError, MB_ICONSTOP ); GetDlgItem(IDC_TABLE_NAME)->SetFocus(); return -1; } } } PROCESS_WIZARD_NEXT_MSG() } BOOL CNewTablePage::OnWizardFinish() { // TODO: Add your specialized code here and/or call the base class PROCESS_WIZARD_FINISH_MSG() } LRESULT CSimpleFieldConstrPage::OnWizardBack() { // TODO: Add your specialized code here and/or call the base class PROCESS_WIZARD_BACK_MSG() } LRESULT CSimpleFieldConstrPage::OnWizardNext() { if( !UpdateData( TRUE ) ) return -1; if( m_nImage < 1 && m_nNumber < 1 && m_nDateTime < 1 && m_nString < 1 ) { AfxMessageBox( IDS_WARNING_ZERO_FIELD_COUNT, MB_ICONSTOP ); return -1; } PROCESS_WIZARD_NEXT_MSG() } BOOL CSimpleFieldConstrPage::OnWizardFinish() { // TODO: Add your specialized code here and/or call the base class PROCESS_WIZARD_FINISH_MSG() } BOOL CSimpleFieldConstrPage::OnInitDialog() { CPropertyPage::OnInitDialog(); if( GetDlgItem( IDC_SPIN1 ) ) ((CSpinButtonCtrl*)GetDlgItem( IDC_SPIN1 ))->SetRange( 0, 100 ); if( GetDlgItem( IDC_SPIN2 ) ) ((CSpinButtonCtrl*)GetDlgItem( IDC_SPIN2 ))->SetRange( 0, 100 ); if( GetDlgItem( IDC_SPIN3 ) ) ((CSpinButtonCtrl*)GetDlgItem( IDC_SPIN3 ))->SetRange( 0, 100 ); if( GetDlgItem( IDC_SPIN4 ) ) ((CSpinButtonCtrl*)GetDlgItem( IDC_SPIN4 ))->SetRange( 0, 100 ); if( GetDlgItem( IDC_SPIN5 ) ) ((CSpinButtonCtrl*)GetDlgItem( IDC_SPIN5 ))->SetRange( 0, 100 ); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE }
556b3deff07757d51642ecf8f2605e52ca1ef05b
e3a1bfda971a3b4fdd141db44957bdf9e6bee855
/tube.cc
5f2095eaa87c623f185d1a037ba7c22363bb2499
[]
no_license
wuqingjun/steamtrain
85a52ca786a9a683b21db714047dd53d2c4b4301
290239000b67c98d1900bcc916c24e94788507c1
refs/heads/master
2021-01-15T09:29:44.121638
2015-12-08T09:41:02
2015-12-08T09:41:02
46,906,553
3
0
null
null
null
null
UTF-8
C++
false
false
533
cc
#include "color.h" #include "cube.h" #include "pile.h" #include "tube.h" #define GL_GLEXT_PROTOTYPES #ifdef __APPLE__ #include <GLUT/glut.h> #else #include <GL/glut.h> #endif extern float rep; extern float shinyvec[1]; extern unsigned int texture[20]; // // draw the cylinder. for example the stick holding the bubble. // void tube(double l, double w, double h, int degree, Color color) { glPushMatrix(); double d = 1.0; glScaled(l, w, h); glColor3f(color.r, color.g, color.b); glEnd(); glPopMatrix(); }
d96e8116177a15ed0f13c2ad503e73b618fabeac
e3e14afd9c330be84c92a54a465b586520ad1ee4
/acmp/0199.cpp
aa7766db59f869cbe0e7e9b52727e396dcad2422
[]
no_license
zv-proger/ol_programms
ab5a6eeca4fa1c3eb30dc49b4ebd223eb0b8deb5
acf305c1216ab10f507a737d8f4bcf29f0e2024b
refs/heads/master
2022-12-14T22:56:18.294281
2020-09-18T09:54:25
2020-09-18T09:54:25
279,568,502
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,292
cpp
/* Автор кода: Вадим Зинов ([email protected]) Решение задачи 0199 с сайта acmp.ru */ #include<bits/stdc++.h> using namespace std; map<int, string> alpha = { {-1, "I"}, {-4, "IV"}, {-5, "V"}, {-9, "IX"}, {-10, "X"}, {-40, "XL"}, {-49, "IL"}, {-50, "L"}, {-90, "XC"}, {-99, "IC"}, {-100, "C"}, {-400, "CD"}, {-499, "ID"}, {-500, "D"}, {-900, "CM"}, {-999, "IM"}, {-1000, "M"}, }; string to_roman(int x) { string ans; while (x) { for (auto &p: alpha) { if (x + p.first >= 0) { ans += p.second; x += p.first; break; } } } return ans; } map<string, int> from; int gcd(int a, int b) { return b ? gcd(b, a % b): a; } void err() { cout << "ERROR"; exit(0); } int main() { for (int i = 1; i < 1000; i++) { from[to_roman(i)] = i; } string as, bs; if (!getline(cin, as, '/')) err(); if (!getline(cin, bs)) err(); if (!from.count(as)) err(); if (!from.count(bs)) err(); int a = from[as], b = from[bs], c = gcd(a, b); a /= c; b /= c; cout << to_roman(a); if (b > 1) cout << '/' << to_roman(b); }
725ce5f7a0e744692b19eb08cc0ab64e2c2379bc
9fbc3f5a431edf121b6e8c799556838fa0c6b069
/clhero_localization/src/filler.cpp
5679e6555de7a1556bb94fd511d34abf86d2d821
[]
no_license
raulCebolla/clhero_navigation
8777c5fd4f791fceb042d2a1dfa1bc22422c784b
1d1a23683f18a8dd5a934f2a17c863040cc5726d
refs/heads/master
2020-06-25T06:26:47.015947
2019-12-16T15:26:07
2019-12-16T15:26:07
199,230,687
0
1
null
null
null
null
UTF-8
C++
false
false
2,255
cpp
//===================================================================== // Author: Raúl Cebolla Arroyo // File: // Version: // Description: // Changelog: //===================================================================== //--------------------------------------------------------------- // Includes //--------------------------------------------------------------- #include <ros/ros.h> #include <geometry_msgs/PoseWithCovarianceStamped.h> #include <nav_msgs/Odometry.h> #include <string> //--------------------------------------------------------------- // Global variables //--------------------------------------------------------------- ros::Publisher odom_fill_pub; std::string child_frame_id; //--------------------------------------------------------------- // Callbacks //--------------------------------------------------------------- void odom_combined_callback (const geometry_msgs::PoseWithCovarianceStamped::ConstPtr &pose_msg){ nav_msgs::Odometry odom_msg; //Copies the header and the pose odom_msg.header = pose_msg->header; odom_msg.pose = pose_msg->pose; //Sets the child frame id odom_msg.child_frame_id = child_frame_id; //Builds the twist part odom_msg.twist.twist.linear.x = 0; odom_msg.twist.twist.linear.y = 0; odom_msg.twist.twist.linear.z = 0; odom_msg.twist.twist.angular.x = 0; odom_msg.twist.twist.angular.y = 0; odom_msg.twist.twist.angular.z = 0; odom_msg.twist.covariance = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; odom_fill_pub.publish(odom_msg); return; } //--------------------------------------------------------------- // Main Function //--------------------------------------------------------------- int main (int argc, char** argv){ ros::init(argc, argv, "odom_filler"); ros::NodeHandle nh; ros::NodeHandle nh_private ("~"); //Params nh_private.param("base_frame", child_frame_id, std::string("base_footprint")); ros::Subscriber odom_combined_sub = nh.subscribe("/odom_combined", 1000, odom_combined_callback); odom_fill_pub = nh.advertise<nav_msgs::Odometry>("/odom", 1000); while(ros::ok()){ ros::spin(); } return 0; }
162c005f566cb7ab18c6029097528dd74dab986d
6ecf205719a9f0ec50d4dd6892135294c8b9ae01
/unittest/wrtp/CMMFrameManagerTest.cpp
c9742f928630d4a0d390853238d8feee6f4170a1
[]
no_license
zzchu/wme-ref-app
25a8786d29d001e37e2ce91f0ca928bab2187cff
5cbf042d26c6d91f35a352a71e0d2961c12cd3f6
refs/heads/master
2021-01-01T03:39:18.439856
2016-04-21T07:44:56
2016-04-21T07:44:56
56,753,029
0
1
null
null
null
null
UTF-8
C++
false
false
864
cpp
#include "gmock/gmock.h" #include "gtest/gtest.h" #define private public #include "mmframemgr.h" #include "testutil.h" using namespace wrtp; class CMMFrameManagerTest : public ::testing::Test { public: virtual void SetUp() { } virtual void TearDown() { } public: }; TEST_F(CMMFrameManagerTest, Test_GetFragments_and_FreeFragments) { CScopedTracer test_info; CMMFrameManager mgr; FragmentContainer vec; mgr.GetFragments(15, vec, 1400, nullptr); EXPECT_EQ(vec.size(), 15); for (uint32_t i = 0; i < vec.size(); ++i) { EXPECT_TRUE(vec[i]->GetBufferSize() >= 1400); } vec.clear(); EXPECT_EQ(vec.size(), 0); } TEST_F(CMMFrameManagerTest, Test_GetFrame_FreeFrame) { CScopedTracer test_info; CMMFrameManager mgr; CSendFramePtr frame = mgr.GetFrame(nullptr); EXPECT_TRUE(!!frame); }
324a10757801a50417eacf2066fc7ebd0e5cc484
7379c8405ece98bd383f13aea040170e9576a949
/SaveMe/Classes/InfoScreen.cpp
1f2d3b085e0250cdf5763306a311919b6f670218
[ "MIT" ]
permissive
Crasader/SaveMe
77807096cf0222b5682892401c2e7f0a970a96e5
e5fd1af69cbbb2c51e662f7205aa4a371e4bc511
refs/heads/master
2021-06-22T06:40:26.322569
2017-07-06T10:12:35
2017-07-06T10:12:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,201
cpp
#include "InfoScreen.h" #include "MainMenuScene.h" #include "SimpleAudioEngine.h" #include "SonarFrameworks.h" #include "Constants.h" USING_NS_CC; using namespace CocosDenshion; void InfoScreen::initBackButtonListener() { auto listener = EventListenerKeyboard::create(); listener->onKeyPressed = [=](EventKeyboard::KeyCode keyCode, Event* event){}; listener->onKeyReleased = CC_CALLBACK_2(InfoScreen::onKeyPressed, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); } void InfoScreen::onKeyPressed(EventKeyboard::KeyCode keyCode, Event* event) { if(keyCode == EventKeyboard::KeyCode::KEY_BACK) { Director::getInstance()->end(); } } void InfoScreen::GoToMainMenu(Ref *pSender) { SimpleAudioEngine::getInstance()->playEffect(clickSoundPath); auto scene = MainMenu::createScene(); Director::getInstance()->replaceScene(TransitionFade::create(fadeDuration, scene)); } Scene* InfoScreen::createScene() { // 'scene' is an autorelease object auto scene = Scene::create(); // 'layer' is an autorelease object auto layer = InfoScreen::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } // on "init" you need to initialize your instance bool InfoScreen::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } initBackButtonListener(); Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); auto label1 = Label::createWithTTF("Developer", fontPath, 18); label1->setColor(ccc3(255, 0, 0)); label1->enableOutline(Color4B(0, 0, 0, 100), 0.5f); label1->setPosition(Point((visibleSize.width / 2) + origin.x, ((9.0f * visibleSize.height) / 10) + origin.y)); this->addChild(label1, 1); auto label2 = Label::createWithTTF("Parikshit Saraswat", fontPath, 12); label2->setColor(ccc3(255, 0, 0)); label2->enableOutline(Color4B(0, 0, 0, 100), 0.5f); label2->setPosition(Point((visibleSize.width / 2) + origin.x, ((8.0f * visibleSize.height) / 10) + origin.y)); this->addChild(label2, 1); auto label3 = Label::createWithTTF("Attributions", fontPath, 18); label3->setColor(ccc3(255, 0, 0)); label3->enableOutline(Color4B(0, 0, 0, 100), 0.5f); label3->setPosition(Point((visibleSize.width / 2) + origin.x, ((6.0f * visibleSize.height) / 10) + origin.y)); this->addChild(label3, 1); auto label4 = Label::createWithTTF("Butterfly sprite sheet", fontPath, 12); label4->setColor(ccc3(255, 0, 0)); label4->enableOutline(Color4B(0, 0, 0, 100), 0.5f); label4->setPosition(Point((visibleSize.width / 2) + origin.x, ((5.0f * visibleSize.height) / 10) + origin.y)); this->addChild(label4, 1); auto label5 = Label::createWithTTF("2005-2013 Julien Jorge", fontPath, 12); label5->setColor(ccc3(255, 0, 0)); label5->enableOutline(Color4B(0, 0, 0, 100), 0.5f); label5->setPosition(Point((visibleSize.width / 2) + origin.x, ((4.2f * visibleSize.height) / 10) + origin.y)); this->addChild(label5, 1); auto label6 = Label::createWithTTF("<[email protected]>", fontPath, 12); label6->setColor(ccc3(255, 0, 0)); label6->enableOutline(Color4B(0, 0, 0, 100), 0.5f); label6->setPosition(Point((visibleSize.width / 2) + origin.x, ((3.4f * visibleSize.height) / 10) + origin.y)); this->addChild(label6, 1); auto mainMenuItem = MenuItemImage::create(pauseMenuIdlePath, pauseMenuPressedPath, CC_CALLBACK_1(InfoScreen::GoToMainMenu, this)); mainMenuItem->setPosition(Point((visibleSize.width / 2) + origin.x, ((2.0f * visibleSize.height) / 10) + origin.y)); auto menu = Menu::create(mainMenuItem, NULL); menu->setPosition(Point::ZERO); this->addChild(menu); auto bg = cocos2d::LayerColor::create(Color4B(182, 249, 255, 255)); this->addChild(bg, -2); auto sun = Sprite::create(sunPath); sun->setPosition(Point(origin.x + (visibleSize.width * 0.75f), origin.y + (visibleSize.height * 0.9f))); this->addChild(sun, -1); return true; }
d1d20f867681bac2f2692e73949c63078eb9d5a2
3cd606b442ceb7d64e4e1e7d322034a05091c87d
/exercises/ex7/box.h
651eea14c8fd19854f4a3dd9a993742d055ea1df
[]
no_license
Mellechowicz/bill
4dd1b27343e426849d8998e4fce7a6717ed9c773
4598e2bb509ca57b59f90f967f39bf0f731d307e
refs/heads/master
2021-01-11T15:36:44.582258
2019-05-23T17:57:07
2019-05-23T17:57:07
79,896,994
1
1
null
null
null
null
UTF-8
C++
false
false
1,438
h
#ifndef BOX_H #define BOX_H #include "../../headers/billrigidbody.h" #include "../../headers/billvector.h" #include <tuple> class box : public bill::BillRigidBody{ protected: double a,b,c; // długości boków std::vector<bill::vector> colors; bill::vector punkt_tarcia; void rotatevector(bill::vector& v); // rotuje zadany wektor korzystając z obrotu bryły void rotatedcoordinates(bill::vector& i, bill::vector& j, bill::vector& k); // podaje rotowane koordynaty void vertices(std::vector<bill::vector>& vers); // podaje bezwzględne położenia wierzchołków bill::vector Tarcie(); virtual bill::vector Force(); virtual bill::vector Torque(); public: box(bill::BillRBIntegrator algorithm, double _a = .2, double _b = .2, double _c = .2, bill::vector position = bill::vector({0.,0.,0.}),bill::vector velocity = bill::vector({0.,0.,0.}), bill::quaternion rotation = bill::quaternion({0.,0.,1.,0.}),bill::vector angular=bill::vector({0.2,0.2,0.})); virtual ~box(){}; void Draw(); double project(bill::vector n); bill::vector support(bill::vector n); double get_size(const unsigned int i) const; //zwraca wymiar prostopadłościaniu w kierunku: 0:x, 1:y, 2:z bill::vector get_versor(const unsigned int i); // zwraca wersor tworzący wierzchołek: 0:x, 1:y, 2:z void get_vertices(std::vector<bill::vector>& vers); // zwraca std::vector wektorów do wierzchołków }; // end of class box #endif //end of box.h
[ "andrzej@Lancre" ]
andrzej@Lancre
ac9d670cd6a873080e0a2d2eb7f803941655cab9
24ce671e5633255ab8c5a3c7cc17fa5722e52a47
/src/qt/bitcoinunits.cpp
296a110398226c75f6d8d354fe9536bf64386c40
[ "MIT" ]
permissive
corecoin1/CoreCoin
6f3d913165ad7904ae3dee19877c6b5afe745794
959db3d414fee461cbf54d7aad0e5e0636a05e06
refs/heads/master
2021-01-17T08:04:19.279170
2016-07-07T02:27:10
2016-07-07T02:27:10
62,768,152
1
1
null
null
null
null
UTF-8
C++
false
false
4,284
cpp
#include "bitcoinunits.h" #include <QStringList> BitcoinUnits::BitcoinUnits(QObject *parent): QAbstractListModel(parent), unitlist(availableUnits()) { } QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits() { QList<BitcoinUnits::Unit> unitlist; unitlist.append(BTC); unitlist.append(mBTC); unitlist.append(uBTC); return unitlist; } bool BitcoinUnits::valid(int unit) { switch(unit) { case BTC: case mBTC: case uBTC: return true; default: return false; } } QString BitcoinUnits::name(int unit) { switch(unit) { case BTC: return QString("CRC"); case mBTC: return QString("mCRC"); case uBTC: return QString::fromUtf8("μCRC"); default: return QString("???"); } } QString BitcoinUnits::description(int unit) { switch(unit) { case BTC: return QString("CoreCoins"); case mBTC: return QString("Milli-CoreCoins (1 / 1,000)"); case uBTC: return QString("Micro-CoreCoins (1 / 1,000,000)"); default: return QString("???"); } } qint64 BitcoinUnits::factor(int unit) { switch(unit) { case BTC: return 100000000; case mBTC: return 100000; case uBTC: return 100; default: return 100000000; } } int BitcoinUnits::amountDigits(int unit) { switch(unit) { case BTC: return 8; // 21,000,000 (# digits, without commas) case mBTC: return 11; // 21,000,000,000 case uBTC: return 14; // 21,000,000,000,000 default: return 0; } } int BitcoinUnits::decimals(int unit) { switch(unit) { case BTC: return 8; case mBTC: return 5; case uBTC: return 2; default: return 0; } } QString BitcoinUnits::format(int unit, qint64 n, bool fPlus) { // Note: not using straight sprintf here because we do NOT want // localized number formatting. if(!valid(unit)) return QString(); // Refuse to format invalid unit qint64 coin = factor(unit); int num_decimals = decimals(unit); qint64 n_abs = (n > 0 ? n : -n); qint64 quotient = n_abs / coin; qint64 remainder = n_abs % coin; QString quotient_str = QString::number(quotient); QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0'); // Right-trim excess zeros after the decimal point int nTrim = 0; for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i) ++nTrim; remainder_str.chop(nTrim); if (n < 0) quotient_str.insert(0, '-'); else if (fPlus && n > 0) quotient_str.insert(0, '+'); return quotient_str + QString(".") + remainder_str; } QString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign) { return format(unit, amount, plussign) + QString(" ") + name(unit); } bool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out) { if(!valid(unit) || value.isEmpty()) return false; // Refuse to parse invalid unit or empty string int num_decimals = decimals(unit); QStringList parts = value.split("."); if(parts.size() > 2) { return false; // More than one dot } QString whole = parts[0]; QString decimals; if(parts.size() > 1) { decimals = parts[1]; } if(decimals.size() > num_decimals) { return false; // Exceeds max precision } bool ok = false; QString str = whole + decimals.leftJustified(num_decimals, '0'); if(str.size() > 18) { return false; // Longer numbers will exceed 63 bits } qint64 retvalue = str.toLongLong(&ok); if(val_out) { *val_out = retvalue; } return ok; } int BitcoinUnits::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return unitlist.size(); } QVariant BitcoinUnits::data(const QModelIndex &index, int role) const { int row = index.row(); if(row >= 0 && row < unitlist.size()) { Unit unit = unitlist.at(row); switch(role) { case Qt::EditRole: case Qt::DisplayRole: return QVariant(name(unit)); case Qt::ToolTipRole: return QVariant(description(unit)); case UnitRole: return QVariant(static_cast<int>(unit)); } } return QVariant(); }
bee04e07f3718658c4fabfa2dfffefd37ef87e63
d002ed401cba924074e021d22347b84334a02b0f
/export/windows/obj/include/openfl/display/_MovieClip/FrameSymbolInstance.h
f5f21e7ccb18045c83797751d3f1dc8665d2dbd4
[]
no_license
IADenner/LD47
63f6beda87424ba7e0e129848ee190c1eb1da54d
340856f1d77983da0e7f331b467609c45587f5d1
refs/heads/master
2022-12-29T13:01:46.789276
2020-10-05T22:04:42
2020-10-05T22:04:42
301,550,551
1
0
null
null
null
null
UTF-8
C++
false
true
2,570
h
// Generated by Haxe 4.1.2 #ifndef INCLUDED_openfl_display__MovieClip_FrameSymbolInstance #define INCLUDED_openfl_display__MovieClip_FrameSymbolInstance #ifndef HXCPP_H #include <hxcpp.h> #endif HX_DECLARE_CLASS2(openfl,display,DisplayObject) HX_DECLARE_CLASS2(openfl,display,IBitmapDrawable) HX_DECLARE_CLASS3(openfl,display,_MovieClip,FrameSymbolInstance) HX_DECLARE_CLASS2(openfl,events,EventDispatcher) HX_DECLARE_CLASS2(openfl,events,IEventDispatcher) namespace openfl{ namespace display{ namespace _MovieClip{ class HXCPP_CLASS_ATTRIBUTES FrameSymbolInstance_obj : public ::hx::Object { public: typedef ::hx::Object super; typedef FrameSymbolInstance_obj OBJ_; FrameSymbolInstance_obj(); public: enum { _hx_ClassId = 0x7207c88b }; void __construct(int initFrame,int initFrameObjectID,int characterID,int depth, ::openfl::display::DisplayObject displayObject,int clipDepth); inline void *operator new(size_t inSize, bool inContainer=true,const char *inName="openfl.display._MovieClip.FrameSymbolInstance") { return ::hx::Object::operator new(inSize,inContainer,inName); } inline void *operator new(size_t inSize, int extra) { return ::hx::Object::operator new(inSize+extra,true,"openfl.display._MovieClip.FrameSymbolInstance"); } static ::hx::ObjectPtr< FrameSymbolInstance_obj > __new(int initFrame,int initFrameObjectID,int characterID,int depth, ::openfl::display::DisplayObject displayObject,int clipDepth); static ::hx::ObjectPtr< FrameSymbolInstance_obj > __alloc(::hx::Ctx *_hx_ctx,int initFrame,int initFrameObjectID,int characterID,int depth, ::openfl::display::DisplayObject displayObject,int clipDepth); static void * _hx_vtable; static Dynamic __CreateEmpty(); static Dynamic __Create(::hx::DynamicArray inArgs); //~FrameSymbolInstance_obj(); HX_DO_RTTI_ALL; ::hx::Val __Field(const ::String &inString, ::hx::PropertyAccess inCallProp); ::hx::Val __SetField(const ::String &inString,const ::hx::Val &inValue, ::hx::PropertyAccess inCallProp); void __GetFields(Array< ::String> &outFields); static void __register(); void __Mark(HX_MARK_PARAMS); void __Visit(HX_VISIT_PARAMS); bool _hx_isInstanceOf(int inClassId); ::String __ToString() const { return HX_("FrameSymbolInstance",fa,3b,c7,c2); } int characterID; int clipDepth; int depth; ::openfl::display::DisplayObject displayObject; int initFrame; int initFrameObjectID; }; } // end namespace openfl } // end namespace display } // end namespace _MovieClip #endif /* INCLUDED_openfl_display__MovieClip_FrameSymbolInstance */
70a9ff65611d515bf404fef7e86be454b211a2a5
486d72bad6e44007befa7af90e4801c76f0336f1
/src/sdk/client.h
23dce5ad12a904f9db997af21018fc24b74c0f98
[ "BSD-3-Clause" ]
permissive
duzhanyuan/squirrel
1078197852378fdac585ebfb3a0bf83d412baaed
5fb40ea0f8bbcd14dbf42f3b31b8e78f15978f97
refs/heads/master
2021-01-23T04:20:39.160465
2015-12-17T09:44:38
2015-12-17T09:44:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,599
h
// Copyright (c) 2015, squirreldb. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CLIENT_SQUIRREL_CLIENT_H #define CLIENT_SQUIRREL_CLIENT_H #include <sofa/pbrpc/pbrpc.h> #include <thread_pool.h> #include <mutex.h> #include <counter.h> #include "src/proto/server_rpc.pb.h" #include "src/proto/status_code.pb.h" namespace baidu { namespace squirrel { namespace sdk { typedef boost::function<void (const std::string&, const std::string&, StatusCode*)> UserPutCallback; typedef boost::function<void (const std::string&, std::string*, StatusCode*)> UserGetCallback; typedef boost::function<void (const std::string&, StatusCode*)> UserDeleteCallback; typedef server::PutRequest PutRequest; typedef server::PutResponse PutResponse; typedef server::GetRequest GetRequest; typedef server::GetResponse GetResponse; typedef server::DeleteRequest DeleteRequest; typedef server::DeleteResponse DeleteResponse; typedef server::Server_Stub Server_Stub; class Client { public: Client(); ~Client(); void init(); void Put(const std::string& key, const std::string& value, StatusCode* status, UserPutCallback* callback); void Get(const std::string& key, std::string* value, StatusCode* status, UserGetCallback* callback); void Delete(const std::string& key, StatusCode* status, UserDeleteCallback* callback); void Scan(const std::string& key, const std::string& value, StatusCode* status); void GetStat(int* count, int* failed, int* pending, int* thread_pool_pendin, std::string* str); void ResetStat(); private: void PutCallback(sofa::pbrpc::RpcController* cntl, PutRequest* request, PutResponse* response, StatusCode* status, UserPutCallback* callback, CondVar* cond); void GetCallback(sofa::pbrpc::RpcController* cntl, GetRequest* request, GetResponse* response, std::string* value, StatusCode* status, UserGetCallback* callback, CondVar* cond); void DeleteCallback(sofa::pbrpc::RpcController* cntl, DeleteRequest* request, DeleteResponse* response, StatusCode* status, UserDeleteCallback* callback, CondVar* cond); private: int thread_num_; common::Counter count_; common::Counter failed_; common::Counter pending_; ThreadPool* thread_pool_; sofa::pbrpc::RpcClient* rpc_client_; sofa::pbrpc::RpcChannel* rpc_channel_; Server_Stub* stub_; }; } // namespace sdk } // squirrel } // namespace baidu #endif // CLIENT_SQUIRREL_CLIENT_H
09b62e0fb86ecc10f22153bb4a0a53730d8e1169
dbcbd51e50314a081817171de2df8e71dc354e99
/AtCoder/PracticeProblems/AGC017_A_Biscuits/prog.cpp
2ae0becf1c7a6ffe03007c58c34f12371fdeedb1
[]
no_license
Shitakami/AtCoder_SolveProblems
cb3dfedad42486d32d036f896b7b09b1c92bbfa1
a273d001852273581e1749c2c63820946122c1e2
refs/heads/master
2021-01-03T05:19:13.944110
2020-07-05T16:42:09
2020-07-05T16:42:09
239,938,798
0
0
null
null
null
null
UTF-8
C++
false
false
1,226
cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; using ull = unsigned long long; ull C(int size, int count) { ull x = 1; ull y = 1; for(int i = 0; i < count; ++i) { x *= (size - i); y *= (i + 1); if(x % y == 0) { x /= y; y = 1; } } return x / y; } int main() { int n, p; cin >> n >> p; int even = 0; int odd = 0; for(int i = 0; i < n; ++i) { int a; cin >> a; if(a % 2 == 0) even++; else odd++; } ull answer = 0; if(p == 0) { for(int i = 0; i <= even; ++i) answer += C(even, min(i, even - i)); ull evenC = answer; if(evenC != 0) { for(size_t i = 2; i <= odd; i+=2) answer += evenC * C(odd, min(i, odd - i)); } } else { for(size_t i = 1; i <= odd; i+=2) answer += C(odd, min(i, odd - i)); ull oddC = answer; if(oddC != 0) { for(size_t i = 1; i <= even; ++i) answer += C(even, min(i, even - i)) * oddC; } } cout << answer << endl; return 0; }
72d8c6dca5bbdd6b23a93a32b8a3c6327c565f4f
26c7333bdb03120e5d769d090fd34fdf7d2cbf99
/BTree.hpp
70ebcdd3adf8eaef416cc0cfd6a4803e7d4f3e76
[]
no_license
jiangzhongping1999/BTree_Submit
fdf542d20b60ed37cd518fbcb787d3d6dedef190
0fe4d67e376e25fcbcb8bcbdf3e356d896a2f183
refs/heads/master
2020-06-01T23:19:23.943350
2019-06-09T09:47:13
2019-06-09T09:47:13
190,963,508
0
0
null
null
null
null
UTF-8
C++
false
false
35,430
hpp
#include "utility.hpp" #include <functional> #include <cstddef> #include "exception.hpp" #include <cstdio> namespace sjtu { //B+树索引存储地址 constexpr char BPTREE_ADDRESS[128] = "mybptree.sjtu"; template <class Key, class Value, class Compare = std::less<Key> > class BTree { private: // Your private members go here //块头 class Block_Head { public: //存储类型(0普通 1叶子) bool block_type = false; off_t size = 0; off_t pos = 0; off_t parent = 0; off_t last = 0; off_t next = 0; }; //索引数据 struct Normal_Data_Node { off_t child = 0; Key key; }; //B+树大数据块大小 constexpr static off_t BLOCK_SIZE = 4096; //大数据块预留数据块大小 constexpr static off_t INIT_SIZE = sizeof(Block_Head); //Key类型的大小 constexpr static off_t KEY_SIZE = sizeof(Key); //Value类型的大小 constexpr static off_t VALUE_SIZE = sizeof(Value); //大数据块能够存储孩子的个数(M) constexpr static off_t BLOCK_KEY_NUM = (BLOCK_SIZE - INIT_SIZE) / sizeof(Normal_Data_Node) - 1; //小数据块能够存放的记录的个数(L) constexpr static off_t BLOCK_PAIR_NUM = (BLOCK_SIZE - INIT_SIZE) / (KEY_SIZE + VALUE_SIZE) - 1; //私有类 //B+树文件头 class File_Head { public: //存储BLOCK占用的空间 off_t block_cnt = 1; //存储根节点的位置 off_t root_pos = 0; //存储数据块头 off_t data_block_head = 0; //存储数据块尾 off_t data_block_rear = 0; //存储大小 off_t size = 0; }; class Normal_Data { public: Normal_Data_Node val[BLOCK_KEY_NUM]; }; //叶子数据 class Leaf_Data { public: pair<Key, Value> val[BLOCK_PAIR_NUM]; }; //私有变量 //文件头 File_Head tree_data; //文件指针 static FILE* fp; //私有函数 //块内存读取 template <class MEM_TYPE> static void mem_read(MEM_TYPE buff, off_t buff_size, off_t pos) { fseek(fp, long(buff_size * pos), SEEK_SET); fread(buff, buff_size, 1, fp); } //块内存写入 template <class MEM_TYPE> static void mem_write(MEM_TYPE buff, off_t buff_size, off_t pos) { fseek(fp, long(buff_size * pos), SEEK_SET); fwrite(buff, buff_size, 1, fp); fflush(fp); } //写入B+树基本数据 void write_tree_data() { fseek(fp, 0, SEEK_SET); char buff[BLOCK_SIZE] = { 0 }; memcpy(buff, &tree_data, sizeof(tree_data)); mem_write(buff, BLOCK_SIZE, 0); } //获取新内存 off_t memory_allocation() { ++tree_data.block_cnt; write_tree_data(); char buff[BLOCK_SIZE] = { 0 }; mem_write(buff, BLOCK_SIZE, tree_data.block_cnt - 1); return tree_data.block_cnt - 1; } //创建新的索引结点 off_t create_normal_node(off_t parent) { auto node_pos = memory_allocation(); Block_Head temp; Normal_Data normal_data; temp.block_type = false; temp.parent = parent; temp.pos = node_pos; temp.size = 0; write_block(&temp, &normal_data, node_pos); return node_pos; } //创建新的叶子结点 off_t create_leaf_node(off_t parent, off_t last, off_t next) { auto node_pos = memory_allocation(); Block_Head temp; Leaf_Data leaf_data; temp.block_type = true; temp.parent = parent; temp.pos = node_pos; temp.last = last; temp.next = next; temp.size = 0; write_block(&temp, &leaf_data, node_pos); return node_pos; } //索引节点插入新索引 void insert_new_index(Block_Head& parent_info, Normal_Data& parent_data, off_t origin, off_t new_pos, const Key& new_index) { ++parent_info.size; auto p = parent_info.size - 2; while (parent_data.val[p].child != origin) { parent_data.val[p + 1] = parent_data.val[p]; --p; } parent_data.val[p + 1].key = parent_data.val[p].key; parent_data.val[p].key = new_index; parent_data.val[p + 1].child = new_pos; } //读取结点信息 template <class DATA_TYPE> static void read_block(Block_Head* info, DATA_TYPE* data, off_t pos) { char buff[BLOCK_SIZE] = { 0 }; mem_read(buff, BLOCK_SIZE, pos); memcpy(info, buff, sizeof(Block_Head)); memcpy(data, buff + INIT_SIZE, sizeof(DATA_TYPE)); } //写入节点信息 template <class DATA_TYPE> static void write_block(Block_Head* info, DATA_TYPE* data, off_t pos) { char buff[BLOCK_SIZE] = { 0 }; memcpy(buff, info, sizeof(Block_Head)); memcpy(buff + INIT_SIZE, data, sizeof(DATA_TYPE)); mem_write(buff, BLOCK_SIZE, pos); } //创建文件 void check_file() { if (!fp) { //创建新的树 fp = fopen(BPTREE_ADDRESS, "wb+"); write_tree_data(); auto node_head = tree_data.block_cnt, node_rear = tree_data.block_cnt + 1; tree_data.data_block_head = node_head; tree_data.data_block_rear = node_rear; create_leaf_node(0, 0, node_rear); create_leaf_node(0, node_head, 0); return; } char buff[BLOCK_SIZE] = { 0 }; mem_read(buff, BLOCK_SIZE, 0); memcpy(&tree_data, buff, sizeof(tree_data)); } //分裂叶子结点 Key split_leaf_node(off_t pos, Block_Head& origin_info, Leaf_Data& origin_data) { //读入数据 off_t parent_pos; Block_Head parent_info; Normal_Data parent_data; //判断是否为根结点 if (pos == tree_data.root_pos) { //创建根节点 auto root_pos = create_normal_node(0); tree_data.root_pos = root_pos; write_tree_data(); read_block(&parent_info, &parent_data, root_pos); origin_info.parent = root_pos; ++parent_info.size; parent_data.val[0].child = pos; parent_pos = root_pos; } else { read_block(&parent_info, &parent_data, origin_info.parent); parent_pos = parent_info.pos; } if (split_parent(origin_info)) { parent_pos = origin_info.parent; read_block(&parent_info, &parent_data, parent_pos); } //创建一个新的子结点 auto new_pos = create_leaf_node(parent_pos,pos,origin_info.next); //修改后继结点的前驱 auto tmp_pos = origin_info.next; Block_Head tmp_info; Leaf_Data tmp_data; read_block(&tmp_info, &tmp_data, tmp_pos); tmp_info.last = new_pos; write_block(&tmp_info, &tmp_data, tmp_pos); origin_info.next = new_pos; Block_Head new_info; Leaf_Data new_data; read_block(&new_info, &new_data, new_pos); //移动数据的位置 off_t mid_pos = origin_info.size >> 1; for (off_t p = mid_pos, i = 0; p < origin_info.size; ++p, ++i) { new_data.val[i].first = origin_data.val[p].first; new_data.val[i].second = origin_data.val[p].second; ++new_info.size; } origin_info.size = mid_pos; insert_new_index(parent_info, parent_data, pos, new_pos, origin_data.val[mid_pos].first); //写入 write_block(&origin_info, &origin_data, pos); write_block(&new_info, &new_data, new_pos); write_block(&parent_info, &parent_data, parent_pos); return new_data.val[0].first; } //分裂父亲(返回新的父亲) bool split_parent(Block_Head& child_info) { //读入数据 off_t parent_pos, origin_pos = child_info.parent; Block_Head parent_info, origin_info; Normal_Data parent_data, origin_data; read_block(&origin_info, &origin_data, origin_pos); if (origin_info.size < BLOCK_KEY_NUM) return false; //判断是否为根结点 if (origin_pos == tree_data.root_pos) { //创建根节点 auto root_pos = create_normal_node(0); tree_data.root_pos = root_pos; write_tree_data(); read_block(&parent_info, &parent_data, root_pos); origin_info.parent = root_pos; ++parent_info.size; parent_data.val[0].child = origin_pos; parent_pos = root_pos; } else { read_block(&parent_info, &parent_data, origin_info.parent); parent_pos = parent_info.pos; } if (split_parent(origin_info)) { parent_pos = origin_info.parent; read_block(&parent_info, &parent_data, parent_pos); } //创建一个新的子结点 auto new_pos = create_normal_node(parent_pos); Block_Head new_info; Normal_Data new_data; read_block(&new_info, &new_data, new_pos); //移动数据的位置 off_t mid_pos = origin_info.size >> 1; for (off_t p = mid_pos + 1, i = 0; p < origin_info.size; ++p,++i) { if (origin_data.val[p].child == child_info.pos) { child_info.parent = new_pos; } std::swap(new_data.val[i], origin_data.val[p]); ++new_info.size; } origin_info.size = mid_pos + 1; insert_new_index(parent_info, parent_data, origin_pos, new_pos, origin_data.val[mid_pos].key); //写入 write_block(&origin_info, &origin_data, origin_pos); write_block(&new_info, &new_data, new_pos); write_block(&parent_info, &parent_data, parent_pos); return true; } //合并索引 void merge_normal(Block_Head& l_info, Normal_Data& l_data, Block_Head& r_info, Normal_Data& r_data) { for (off_t p = l_info.size, i = 0; i < r_info.size; ++p, ++i) { l_data.val[p] = r_data.val[i]; } l_data.val[l_info.size - 1].key = adjust_normal(r_info.parent, r_info.pos); l_info.size += r_info.size; write_block(&l_info, &l_data, l_info.pos); } //修改LCA的索引(平衡叶子时) void change_index(off_t parent, off_t child, const Key& new_key) { //读取数据 Block_Head parent_info; Normal_Data parent_data; read_block(&parent_info, &parent_data, parent); if (parent_data.val[parent_info.size - 1].child == child) { change_index(parent_info.parent, parent, new_key); return; } off_t cur_pos = parent_info.size - 2; while (true) { if (parent_data.val[cur_pos].child == child) { parent_data.val[cur_pos].key = new_key; break; } --cur_pos; } write_block(&parent_info, &parent_data, parent); } //平衡索引 void balance_normal(Block_Head& info, Normal_Data& normal_data) { if (info.size >= BLOCK_KEY_NUM / 2) { write_block(&info, &normal_data, info.pos); return; } //判断是否是根 if (info.pos == tree_data.root_pos && info.size <= 1) { tree_data.root_pos = normal_data.val[0].child; write_tree_data(); return; } else if (info.pos == tree_data.root_pos) { write_block(&info, &normal_data, info.pos); return; } //获取兄弟 Block_Head parent_info, brother_info; Normal_Data parent_data, brother_data; read_block(&parent_info, &parent_data, info.parent); off_t value_pos; for (value_pos = 0; parent_data.val[value_pos].child != info.pos; ++value_pos); if (value_pos > 0) { read_block(&brother_info, &brother_data, parent_data.val[value_pos - 1].child); brother_info.parent = info.parent; if (brother_info.size > BLOCK_KEY_NUM / 2) { off_t p = info.size; while (p > 0) { normal_data.val[p] = normal_data.val[p - 1]; --p; } normal_data.val[0].child = brother_data.val[brother_info.size - 1].child; normal_data.val[0].key = parent_data.val[value_pos - 1].key; parent_data.val[value_pos - 1].key = brother_data.val[brother_info.size - 2].key; --brother_info.size; ++info.size; write_block(&brother_info, &brother_data, brother_info.pos); write_block(&info, &normal_data, info.pos); write_block(&parent_info, &parent_data, parent_info.pos); return; } else { merge_normal(brother_info, brother_data, info, normal_data); return; } } if (value_pos < parent_info.size - 1) { read_block(&brother_info, &brother_data, parent_data.val[value_pos + 1].child); brother_info.parent = info.parent; if (brother_info.size > BLOCK_KEY_NUM / 2) { normal_data.val[info.size].child = brother_data.val[0].child; normal_data.val[info.size - 1].key = parent_data.val[value_pos].key; parent_data.val[value_pos].key = brother_data.val[0].key; for (off_t p = 1; p < brother_info.size; ++p) { brother_data.val[p - 1] = brother_data.val[p]; } --brother_info.size; ++info.size; write_block(&brother_info, &brother_data, brother_info.pos); write_block(&info, &normal_data, info.pos); write_block(&parent_info, &parent_data, parent_info.pos); return; } else { merge_normal(info, normal_data, brother_info, brother_data); return; } } } //调整索引(返回关键字) Key adjust_normal(off_t pos, off_t removed_child) { Block_Head info; Normal_Data normal_data; read_block(&info, &normal_data, pos); off_t cur_pos; for (cur_pos = 0; normal_data.val[cur_pos].child != removed_child; ++cur_pos); Key ans = normal_data.val[cur_pos - 1].key; normal_data.val[cur_pos - 1].key = normal_data.val[cur_pos].key; while(cur_pos < info.size - 1) { normal_data.val[cur_pos] = normal_data.val[cur_pos + 1]; ++cur_pos; } --info.size; balance_normal(info, normal_data); return ans; } //合并叶子 void merge_leaf(Block_Head& l_info, Leaf_Data& l_data, Block_Head& r_info, Leaf_Data& r_data) { for (off_t p = l_info.size, i = 0; i < r_info.size; ++p, ++i) { l_data.val[p].first = r_data.val[i].first; l_data.val[p].second = r_data.val[i].second; } l_info.size += r_info.size; adjust_normal(r_info.parent, r_info.pos); //修改链表 l_info.next = r_info.next; Block_Head temp_info; Leaf_Data temp_data; read_block(&temp_info, &temp_data, r_info.next); temp_info.last = l_info.pos; write_block(&temp_info, &temp_data, temp_info.pos); write_block(&l_info, &l_data, l_info.pos); } //平衡叶子 void balance_leaf(Block_Head& leaf_info, Leaf_Data& leaf_data) { if (leaf_info.size >= BLOCK_PAIR_NUM / 2) { write_block(&leaf_info, &leaf_data, leaf_info.pos); return; } else if (leaf_info.pos == tree_data.root_pos) { if (leaf_info.size == 0) { Block_Head temp_info; Leaf_Data temp_data; read_block(&temp_info, &temp_data, tree_data.data_block_head); temp_info.next = tree_data.data_block_rear; write_block(&temp_info, &temp_data, tree_data.data_block_head); read_block(&temp_info, &temp_data, tree_data.data_block_rear); temp_info.last = tree_data.data_block_head; write_block(&temp_info, &temp_data, tree_data.data_block_rear); return; } write_block(&leaf_info, &leaf_data, leaf_info.pos); return; } //查找兄弟结点 Block_Head brother_info, parent_info; Leaf_Data brother_data; Normal_Data parent_data; read_block(&parent_info, &parent_data, leaf_info.parent); off_t node_pos = 0; while (node_pos < parent_info.size) { if (parent_data.val[node_pos].child == leaf_info.pos) break; ++node_pos; } //左兄弟 if (node_pos > 0) { read_block(&brother_info, &brother_data, leaf_info.last); brother_info.parent = leaf_info.parent; if (brother_info.size > BLOCK_PAIR_NUM / 2) { for (off_t p = leaf_info.size; p > 0; --p) { leaf_data.val[p].first = leaf_data.val[p - 1].first; leaf_data.val[p].second = leaf_data.val[p - 1].second; } leaf_data.val[0].first = brother_data.val[brother_info.size - 1].first; leaf_data.val[0].second = brother_data.val[brother_info.size - 1].second; --brother_info.size; ++leaf_info.size; change_index(brother_info.parent, brother_info.pos, leaf_data.val[0].first); write_block(&brother_info, &brother_data, brother_info.pos); write_block(&leaf_info, &leaf_data, leaf_info.pos); return; } else { merge_leaf(brother_info, brother_data, leaf_info, leaf_data); //write_block(&brother_info, &brother_data, brother_info._pos); return; } } //右兄弟 if (node_pos < parent_info.size - 1) { read_block(&brother_info, &brother_data, leaf_info.next); brother_info.parent = leaf_info.parent; if (brother_info.size > BLOCK_PAIR_NUM / 2) { leaf_data.val[leaf_info.size].first = brother_data.val[0].first; leaf_data.val[leaf_info.size].second = brother_data.val[0].second; for (off_t p = 1; p < brother_info.size; ++p) { brother_data.val[p - 1].first = brother_data.val[p].first; brother_data.val[p - 1].second = brother_data.val[p].second; } ++leaf_info.size; --brother_info.size; change_index(leaf_info.parent, leaf_info.pos, brother_data.val[0].first); write_block(&leaf_info, &leaf_data, leaf_info.pos); write_block(&brother_info, &brother_data, brother_info.pos); return; } else { merge_leaf(leaf_info, leaf_data, brother_info, brother_data); return; } } } public: typedef pair<const Key, Value> value_type; class const_iterator; class iterator { friend class sjtu::BTree<Key, Value, Compare>::const_iterator; friend iterator sjtu::BTree<Key, Value, Compare>::begin(); friend iterator sjtu::BTree<Key, Value, Compare>::end(); friend iterator sjtu::BTree<Key, Value, Compare>::find(const Key&); friend pair<iterator, OperationResult> sjtu::BTree<Key, Value, Compare>::insert(const Key&, const Value&); private: // Your private members go here //指向当前bpt BTree* cur_bptree = nullptr; //存储当前块的基本信息 Block_Head block_info; //存储当前指向的元素位置 off_t cur_pos = 0; public: bool modify(const Value& value) { Block_Head info; Leaf_Data leaf_data; read_block(&info, &leaf_data, block_info.pos); leaf_data.val[cur_pos].second = value; write_block(&info, &leaf_data, block_info.pos); return true; } iterator() { // TODO Default Constructor } iterator(const iterator& other) { // TODO Copy Constructor cur_bptree = other.cur_bptree; block_info = other.block_info; cur_pos = other.cur_pos; } // Return a new iterator which points to the n-next elements iterator operator++(int) { // Todo iterator++ auto tmp = *this; ++cur_pos; if (cur_pos >= block_info.size) { char buff[BLOCK_SIZE] = { 0 }; mem_read(buff, BLOCK_SIZE, block_info.next); memcpy(&block_info, buff, sizeof(block_info)); cur_pos = 0; } return tmp; } iterator& operator++() { // Todo ++iterator ++cur_pos; if (cur_pos >= block_info.size) { char buff[BLOCK_SIZE] = { 0 }; mem_read(buff, BLOCK_SIZE, block_info.next); memcpy(&block_info, buff, sizeof(block_info)); cur_pos = 0; } return *this; } iterator operator--(int) { // Todo iterator-- auto temp = *this; if (cur_pos == 0) { char buff[BLOCK_SIZE] = { 0 }; mem_read(buff, BLOCK_SIZE, block_info.last); memcpy(&block_info, buff, sizeof(block_info)); cur_pos = block_info.size - 1; } else --cur_pos; return temp; } iterator& operator--() { // Todo --iterator if (cur_pos == 0) { char buff[BLOCK_SIZE] = { 0 }; mem_read(buff, BLOCK_SIZE, block_info.last); memcpy(&block_info, buff, sizeof(block_info)); cur_pos = block_info.size - 1; } else --cur_pos; return *this; } // Overloaded of operator '==' and '!=' // Check whether the iterators are same value_type operator*() const { // Todo operator*, return the <K,V> of iterator if (cur_pos >= block_info.size) throw invalid_iterator(); char buff[BLOCK_SIZE] = { 0 }; mem_read(buff, BLOCK_SIZE, block_info.pos); Leaf_Data leaf_data; memcpy(&leaf_data, buff + INIT_SIZE, sizeof(leaf_data)); value_type result(leaf_data.val[cur_pos].first,leaf_data.val[cur_pos].second); return result; } bool operator==(const iterator& rhs) const { // Todo operator == return cur_bptree == rhs.cur_bptree && block_info.pos == rhs.block_info.pos && cur_pos == rhs.cur_pos; } bool operator==(const const_iterator& rhs) const { // Todo operator == return block_info.pos == rhs.block_info.pos && cur_pos == rhs.cur_pos; } bool operator!=(const iterator& rhs) const { // Todo operator != return cur_bptree != rhs.cur_bptree || block_info.pos != rhs.block_info.pos || cur_pos != rhs.cur_pos; } bool operator!=(const const_iterator& rhs) const { // Todo operator != return block_info.pos != rhs.block_info.pos || cur_pos != rhs.cur_pos; } }; class const_iterator { // it should has similar member method as iterator. // and it should be able to construct from an iterator. friend class sjtu::BTree<Key, Value, Compare>::iterator; friend const_iterator sjtu::BTree<Key, Value, Compare>::cbegin() const; friend const_iterator sjtu::BTree<Key, Value, Compare>::cend() const; friend const_iterator sjtu::BTree<Key, Value, Compare>::find(const Key&) const; private: // Your private members go here //存储当前块的基本信息 Block_Head block_info; //存储当前指向的元素位置 off_t cur_pos = 0; public: const_iterator() { // TODO } const_iterator(const const_iterator& other) { // TODO block_info = other.block_info; cur_pos = other.cur_pos; } const_iterator(const iterator& other) { // TODO block_info = other.block_info; cur_pos = other.cur_pos; } // And other methods in iterator, please fill by yourself. // Return a new iterator which points to the n-next elements const_iterator operator++(int) { // Todo iterator++ auto tmp = *this; ++cur_pos; if (cur_pos >= block_info.size) { char buff[BLOCK_SIZE] = { 0 }; mem_read(buff, BLOCK_SIZE, block_info.next); memcpy(&block_info, buff, sizeof(block_info)); cur_pos = 0; } return tmp; } const_iterator& operator++() { // Todo ++iterator ++cur_pos; if (cur_pos >= block_info.size) { char buff[BLOCK_SIZE] = { 0 }; mem_read(buff, BLOCK_SIZE, block_info.next); memcpy(&block_info, buff, sizeof(block_info)); cur_pos = 0; } return *this; } const_iterator operator--(int) { // Todo iterator-- auto tmp = *this; if (cur_pos == 0) { char buff[BLOCK_SIZE] = { 0 }; mem_read(buff, BLOCK_SIZE, block_info.last); memcpy(&block_info, buff, sizeof(block_info)); cur_pos = block_info.size - 1; } else --cur_pos; return tmp; } const_iterator& operator--() { // Todo --iterator if (cur_pos == 0) { char buff[BLOCK_SIZE] = { 0 }; mem_read(buff, BLOCK_SIZE, block_info.last); memcpy(&block_info, buff, sizeof(block_info)); cur_pos = block_info.size - 1; } else --cur_pos; return *this; } // Overloaded of operator '==' and '!=' // Check whether the iterators are same value_type operator*() const { // Todo operator*, return the <K,V> of iterator if (cur_pos >= block_info.size) throw invalid_iterator(); char buff[BLOCK_SIZE] = { 0 }; mem_read(buff, BLOCK_SIZE, block_info.pos); Leaf_Data leaf_data; memcpy(&leaf_data, buff + INIT_SIZE, sizeof(leaf_data)); value_type result(leaf_data.val[cur_pos].first, leaf_data.val[cur_pos].second); return result; } bool operator==(const iterator& rhs) const { // Todo operator == return block_info.pos == rhs.block_info.pos && cur_pos == rhs.cur_pos; } bool operator==(const const_iterator& rhs) const { // Todo operator == return block_info.pos == rhs.block_info.pos && cur_pos == rhs.cur_pos; } bool operator!=(const iterator& rhs) const { // Todo operator != return block_info.pos != rhs.block_info.pos || cur_pos != rhs.cur_pos; } bool operator!=(const const_iterator& rhs) const { // Todo operator != return block_info.pos != rhs.block_info.pos || cur_pos != rhs.cur_pos; } }; // Default Constructor and Copy Constructor BTree() { // Todo Default fp = fopen(BPTREE_ADDRESS, "rb+"); if (!fp) { //创建新的树 fp = fopen(BPTREE_ADDRESS, "wb+"); write_tree_data(); auto node_head = tree_data.block_cnt, node_rear = tree_data.block_cnt + 1; tree_data.data_block_head = node_head; tree_data.data_block_rear = node_rear; create_leaf_node(0, 0, node_rear); create_leaf_node(0, node_head, 0); return; } char buff[BLOCK_SIZE] = { 0 }; mem_read(buff, BLOCK_SIZE, 0); memcpy(&tree_data, buff, sizeof(tree_data)); } BTree(const BTree& other) { // Todo Copy fp = fopen(BPTREE_ADDRESS, "rb+"); tree_data.block_cnt = other.tree_data.block_cnt; tree_data.data_block_head = other.tree_data.data_block_head; tree_data.data_block_rear = other.tree_data.data_block_rear; tree_data.root_pos = other.tree_data.root_pos; tree_data.size = other.tree_data.size; } BTree& operator=(const BTree& other) { // Todo Assignment fp = fopen(BPTREE_ADDRESS, "rb+"); tree_data.block_cnt = other.tree_data.block_cnt; tree_data.data_block_head = other.tree_data.data_block_head; tree_data.data_block_rear = other.tree_data.data_block_rear; tree_data.root_pos = other.tree_data.root_pos; tree_data.size = other.tree_data.size; return *this; } ~BTree() { // Todo Destructor fclose(fp); } // Insert: Insert certain Key-Value into the database // Return a pair, the first of the pair is the iterator point to the new // element, the second of the pair is Success if it is successfully inserted pair<iterator, OperationResult> insert(const Key& key, const Value& value) { // TODO insert function check_file(); if (empty()) { auto root_pos = create_leaf_node(0, tree_data.data_block_head, tree_data.data_block_rear); Block_Head temp_info; Leaf_Data temp_data; read_block(&temp_info, &temp_data, tree_data.data_block_head); temp_info.next = root_pos; write_block(&temp_info, &temp_data, tree_data.data_block_head); read_block(&temp_info, &temp_data, tree_data.data_block_rear); temp_info.last = root_pos; write_block(&temp_info, &temp_data, tree_data.data_block_rear); read_block(&temp_info, &temp_data, root_pos); ++temp_info.size; temp_data.val[0].first = key; temp_data.val[0].second = value; write_block(&temp_info, &temp_data, root_pos); ++tree_data.size; tree_data.root_pos = root_pos; write_tree_data(); pair<iterator, OperationResult> result(begin(), Success); return result; } //查找正确的节点位置 char buff[BLOCK_SIZE] = { 0 }; off_t cur_pos = tree_data.root_pos, cur_parent = 0; while (true) { mem_read(buff, BLOCK_SIZE, cur_pos); Block_Head temp; memcpy(&temp, buff, sizeof(temp)); //判断父亲是否更新 if (cur_parent != temp.parent) { temp.parent = cur_parent; memcpy(buff, &temp, sizeof(temp)); mem_write(buff, BLOCK_SIZE, cur_pos); } if (temp.block_type) { break; } Normal_Data normal_data; memcpy(&normal_data, buff + INIT_SIZE, sizeof(normal_data)); off_t child_pos = temp.size - 1; while (child_pos > 0) { if (normal_data.val[child_pos - 1].key <= key) break; --child_pos; } cur_parent = cur_pos; cur_pos = normal_data.val[child_pos].child; cur_pos = cur_pos; } Block_Head info; memcpy(&info, buff, sizeof(info)); Leaf_Data leaf_data; memcpy(&leaf_data, buff + INIT_SIZE, sizeof(leaf_data)); for (off_t value_pos = 0;; ++value_pos) { if (value_pos < info.size && (!(leaf_data.val[value_pos].first < key || leaf_data.val[value_pos].first > key))) { return pair<iterator, OperationResult>(end(), Fail); } if (value_pos >= info.size || leaf_data.val[value_pos].first > key) { //在此结点之前插入 if (info.size >= BLOCK_PAIR_NUM) { auto cur_key = split_leaf_node(cur_pos, info, leaf_data); if (key > cur_key) { cur_pos = info.next; value_pos -= info.size; read_block(&info, &leaf_data, cur_pos); } } for (off_t p = info.size - 1; p >= value_pos; --p) { leaf_data.val[p + 1].first = leaf_data.val[p].first; leaf_data.val[p + 1].second = leaf_data.val[p].second; if (p == value_pos) break; } leaf_data.val[value_pos].first = key; leaf_data.val[value_pos].second = value; ++info.size; write_block(&info, &leaf_data, cur_pos); iterator ans; ans.block_info = info; ans.cur_bptree = this; ans.cur_pos = value_pos; //修改树的基本参数 ++tree_data.size; write_tree_data(); pair<iterator, OperationResult> re(ans, Success); return re; } } return pair<iterator, OperationResult>(end(), Fail); } // Erase: Erase the Key-Value // Return Success if it is successfully erased // Return Fail if the key doesn't exist in the database OperationResult erase(const Key& key) { return Fail; } iterator begin() { check_file(); iterator result; char buff[BLOCK_SIZE] = { 0 }; mem_read(buff, BLOCK_SIZE, tree_data.data_block_head); Block_Head block_head; memcpy(&block_head, buff, sizeof(block_head)); result.block_info = block_head; result.cur_bptree = this; result.cur_pos = 0; ++result; return result; } const_iterator cbegin() const { const_iterator result; char buff[BLOCK_SIZE] = { 0 }; mem_read(buff, BLOCK_SIZE, tree_data.data_block_head); Block_Head block_head; memcpy(&block_head, buff, sizeof(block_head)); result.block_info = block_head; result.cur_pos = 0; ++result; return result; } // Return a iterator to the end(the next element after the last) iterator end() { check_file(); iterator result; char buff[BLOCK_SIZE] = { 0 }; mem_read(buff, BLOCK_SIZE, tree_data.data_block_rear); Block_Head block_head; memcpy(&block_head, buff, sizeof(block_head)); result.block_info = block_head; result.cur_bptree = this; result.cur_pos = 0; return result; } const_iterator cend() const { const_iterator result; char buff[BLOCK_SIZE] = { 0 }; mem_read(buff, BLOCK_SIZE, tree_data.data_block_rear); Block_Head block_head; memcpy(&block_head, buff, sizeof(block_head)); result.block_info = block_head; result.cur_pos = 0; return result; } // Check whether this BTree is empty bool empty() const { if (!fp) return true; return tree_data.size == 0; } // Return the number of <K,V> pairs off_t size() const { if (!fp) return 0; return tree_data.size; } // Clear the BTree void clear() { if (!fp) return; remove(BPTREE_ADDRESS); File_Head new_file_head; tree_data = new_file_head; fp = nullptr; } // Return the value refer to the Key(key) Value at(const Key& key) { if (empty()) { throw container_is_empty(); } //查找正确的节点位置 char buff[BLOCK_SIZE] = { 0 }; off_t cur_pos = tree_data.root_pos, cur_parent = 0; while (true) { mem_read(buff, BLOCK_SIZE, cur_pos); Block_Head temp; memcpy(&temp, buff, sizeof(temp)); //判断父亲是否更新 if (cur_parent != temp.parent) { temp.parent = cur_parent; memcpy(buff, &temp, sizeof(temp)); mem_write(buff, BLOCK_SIZE, cur_pos); } if (temp.block_type) break; Normal_Data normal_data; memcpy(&normal_data, buff + INIT_SIZE, sizeof(normal_data)); off_t child_pos = temp.size - 1; for (; child_pos > 0; --child_pos) { if (normal_data.val[child_pos - 1].key <= key) { break; } } cur_pos = normal_data.val[child_pos].child; } Block_Head info; memcpy(&info, buff, sizeof(info)); Leaf_Data leaf_data; memcpy(&leaf_data, buff + INIT_SIZE, sizeof(leaf_data)); for (off_t value_pos = 0;; ++value_pos) { if (value_pos < info.size && (!(leaf_data.val[value_pos].first<key || leaf_data.val[value_pos].first>key))) { return leaf_data.val[value_pos].second; } if (value_pos >= info.size || leaf_data.val[value_pos].first > key) { throw index_out_of_bound(); } } } /** * Returns the number of elements with key * that compares equivalent to the specified argument, * The default method of check the equivalence is !(a < b || b > a) */ off_t count(const Key& key) const { return find(key) == cend() ? 0 : 1; } /** * Finds an element with key equivalent to key. * key value of the element to search for. * Iterator to an element with key equivalent to key. * If no such element is found, past-the-end (see end()) iterator is * returned. */ iterator find(const Key& key) { if (empty()) { return end(); } //查找正确的节点位置 char buff[BLOCK_SIZE] = { 0 }; off_t cur_pos = tree_data.root_pos, cur_parent = 0; while (true) { mem_read(buff, BLOCK_SIZE, cur_pos); Block_Head temp; memcpy(&temp, buff, sizeof(temp)); //判断父亲是否更新 if (cur_parent != temp.parent) { temp.parent = cur_parent; memcpy(buff, &temp, sizeof(temp)); mem_write(buff, BLOCK_SIZE, cur_pos); } if (temp.block_type) { break; } Normal_Data normal_data; memcpy(&normal_data, buff + INIT_SIZE, sizeof(normal_data)); off_t child_pos = temp.size - 1; for (; child_pos > 0; --child_pos) { if (!(normal_data.val[child_pos - 1].key > key)) { break; } } cur_pos = normal_data.val[child_pos].child; } Block_Head info; memcpy(&info, buff, sizeof(info)); sizeof(Normal_Data); Leaf_Data leaf_data; memcpy(&leaf_data, buff + INIT_SIZE, sizeof(leaf_data)); for (off_t value_pos = 0;; ++value_pos) { if (value_pos < info.size && (!(leaf_data.val[value_pos].first<key || leaf_data.val[value_pos].first>key))) { iterator result; result.cur_bptree = this; result.block_info = info; result.cur_pos = value_pos; return result; } if (value_pos >= info.size || leaf_data.val[value_pos].first > key) { return end(); } } return end(); } const_iterator find(const Key& key) const { if (empty()) { return cend(); } //查找正确的节点位置 char buff[BLOCK_SIZE] = { 0 }; off_t cur_pos = tree_data.root_pos, cur_parent = 0; while (true) { mem_read(buff, BLOCK_SIZE, cur_pos); Block_Head temp; memcpy(&temp, buff, sizeof(temp)); //判断父亲是否更新 if (cur_parent != temp.parent) { temp.parent = cur_parent; memcpy(buff, &temp, sizeof(temp)); mem_write(buff, BLOCK_SIZE, cur_pos); } if (temp.block_type) { break; } Normal_Data normal_data; memcpy(&normal_data, buff + INIT_SIZE, sizeof(normal_data)); off_t child_pos = temp.size - 1; for (; child_pos > 0; --child_pos) { if (!(normal_data.val[child_pos - 1].key > key)) { break; } } cur_pos = normal_data.val[child_pos].child; } Block_Head info; memcpy(&info, buff, sizeof(info)); Leaf_Data leaf_data; memcpy(&leaf_data, buff + INIT_SIZE, sizeof(leaf_data)); for (off_t value_pos = 0;; ++value_pos) { if (value_pos < info.size && (!(leaf_data.val[value_pos].first<key || leaf_data.val[value_pos].first>key))) { const_iterator result; result.block_info = info; result.cur_pos = value_pos; return result; } if (value_pos >= info.size || leaf_data.val[value_pos].first > key) { return cend(); } } return cend(); } }; template <typename Key, typename Value, typename Compare> FILE* BTree<Key, Value, Compare>::fp = nullptr; } // namespace sjtu
f821062ef758b0e264b6ded72d3fc6d173e2d426
314609125e587610353ad0fe67f58bdf45b0c6e1
/Game/Tiles/BridgeTile.h
71c91f29aab854da8194b316f875754ba837b03c
[]
no_license
Epidilius/ZeldaStyleAdventureGame
1e1b71cf2914c1ca5ea1ff803bf10d172e74b562
bd2bbc89f5acf07c8c89f6301aef326fdeead238
refs/heads/master
2021-01-10T17:15:54.039969
2015-09-27T22:31:38
2015-09-27T22:31:38
43,267,623
0
0
null
null
null
null
UTF-8
C++
false
false
1,044
h
// // BridgeTile.h // GameDev2D // // Student: Joel Cright & Rachel Joannis // Cretion Date: Fall 2014 // Course Number: GAM1540 // Professor: Bradley Flood // Purpose: To create bridges // Copyright (c) 2014 Algonquin College. All rights reserved. // #ifndef __GameDev2D__BridgeTile__ #define __GameDev2D__BridgeTile__ #include "Tile.h" namespace GameDev2D { //Constants const unsigned short BRIDGE_VARIANT_COUNT = 2; //Forward Declarations class SubSection; //Bridge Tile class class BridgeTile : public Tile { public: BridgeTile(SubSection* subSection, uvec2 coordinates, unsigned int variant); ~BridgeTile(); //Returns the type of tile TileType GetTileType(); //Returns the number of tile variants unsigned int GetVariantCount(); //Gets the atlas key for the tile variant void GetAtlasKeyForVariant(unsigned int variant, string& atlasKey); }; } #endif /* defined(__GameDev2D__BridgeTile__) */
d66abe262399f213323e4765a86a1d11958e76fe
83220a9e4c64babd163da3e8d345de3b597a8707
/18open/alex/family_bronze.cpp
c96ef099c21304312ac31c0456e0a8a3fabc2c2e
[]
no_license
hzhou/usaco
bd9dfa8be88206ad9f152edce81ea63b0f119ba7
928777159d8243fc0f6e0bdb26ec0b094a0ec30f
refs/heads/master
2021-12-23T05:27:38.817952
2021-12-12T16:23:44
2021-12-12T16:23:44
177,450,503
1
13
null
null
null
null
UTF-8
C++
false
false
2,467
cpp
//ALEX, DIDNT FINISH #include <cstdio> #include <fstream> #include <iostream> #include <algorithm> #include <string> using namespace std; int main () { ifstream fin ("family.in"); ofstream fout ("family.out"); int n; string bessie, elsie; fin >> n >> bessie >> elsie; cout << "bessie: "<<bessie <<"\n"; const char* s_A = bessie.c_str(); printf("%c\n", bessie[1]); /* string mothers[n]; string daughters[n]; for (int i = 0; i < n; i++) { fout >> mothers[i] >> daughters[i]; } int b, e; for (int i = 0; i < n; i++) { if (daugters[i] == besie) { b = i; } if (daugthers[i] == elsie) { e = i } } if (mothers[b] == mothers[e]) { //they are siblings } //check if mother of besie/elsie is tempcow //mothers[b] is bessies mother, mothers[e] is elsies mom string tempcow = besie; for (int i = 0; i < 1000; i++) { for (int x = 0; x < n; x++) { if (daughters[x] == tempcow) { if (mothers[x] == mothers[e]) { //Greatt aunt or something } if (mothers[x] == elsie) { //Elsie is the great*(i-2)grandma of bessie } } } } tempcow = elsie; for (int i = 0; i < 1000; i++) { for (int x = 0; x < n; x++) { if (daughters[x] == tempcow) { if (mothers[x] == mothers[b]) { //Greatt aunt or something } if (mothers[x] == besie) { //Elsie is the great*(i-2)grandma of bessie } } } } */ }
a63b3bcfe04d4aa28d3068cbfea8c58291806fe8
e7a6eb8dd69843e7a4e4196d25d572e5ac8e4cee
/source/SaveController.cpp
c8d31422d31b58d046569072350ce5cf893b5f5a
[ "MIT" ]
permissive
Git-Teo/Lidl-Soundboard
fe7e6f7be2743bcf0ee6816c34bb123ceb324ccd
2de2792899beb827a6c2d95f8481ec732d022416
refs/heads/master
2021-05-18T18:05:07.078865
2019-07-30T12:36:45
2019-07-30T12:36:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
42,381
cpp
#include "SaveController.h" namespace LIDL { namespace Controller { SaveController* SaveController::self = nullptr; SaveController::SaveController() { connect(this,&SaveController::lidlJsonDetected, LIDL::Controller::SettingsController::GetInstance(),&LIDL::Controller::SettingsController::addFileToRecent); } SaveController *SaveController::GetInstance() { if (self == nullptr) self = new SaveController(); return self; } void SaveController::Save() { // if file doesn't exist we throw the save as prompt if (this->_saveName.isEmpty()) { this->SaveAs(); return; } else { this->SaveAs(this->_saveName); } } void SaveController::SetStopKeyName(QString name) { this->_stopKeyName = name; } void SaveController::SetStopVirtualKey(unsigned int vk) { this->_stopVirtualKey = vk; } void SaveController::OpenSaveFile(QString fileName) { switch(this->CheckAndPromptIfNeedsSaving()) { case 0: this->Save(); break; // yes case 1: break; // no case 2: return; break; // cancel or x button case -1: break; // file up to date } // if filename is empty we ask for a filename if ((fileName).isEmpty()) fileName = QFileDialog::getOpenFileName(nullptr,QObject::tr("Open file"), LIDL::Controller::SettingsController::GetInstance()->GetDefaultSoundboardFolder() , QObject::tr("LIDL JSON file(*.lidljson)")); // if it is still empty at this point we return if ((fileName).isEmpty()) return; QFile file(fileName); QJsonObject json; if (file.open(QIODevice::ReadOnly | QIODevice::Text) ) { QString jsonAsString = file.readAll(); //QJsonParseError error; QJsonDocument cdOMEGALUL = QJsonDocument::fromJson(jsonAsString.toUtf8()); if (cdOMEGALUL.isNull()) { file.close(); QString errorMsg( "\"" + fileName + "\" isn't a valid .lidljson file."); return; } json = cdOMEGALUL.object(); file.close(); } // searching for version to know how to read if (!(json.contains("Settings"))) { QMessageBox::warning(nullptr,QObject::tr("Error"), QObject::tr("File \"%1\" is not a valid lidljson file.").arg(fileName)); return; } // if it is valid we clear soundboard as we are going to open it emit Clear(); QString version; if (json.contains("Version")) version = json.value("Version").toString(); else version = "1.x.x"; qDebug() << "gneee" << version; QRegExp regexp("^(\\d+)\\.(\\d+).+"); //execute the regex, i think regexp.indexIn(version); if (regexp.capturedTexts().size() < 3){ // show error about invalid string version in json return; } //save 1.9.x introduced profiles bool saveFormat190 = false; if ( regexp.cap(1).toInt() > 1){ saveFormat190 = true; } else if (regexp.cap(1).toInt() == 1 && regexp.cap(2).toInt() >= 9){ saveFormat190 = true; } // we clear the soundboard and the profile // here forsenD QString mainOutputDevice, vacOutputDevice; QString pttName; QString stopName; int stopVirtualKey =-1; this->_saveName = fileName; // this shit is the same for > 1.9 and < // parsing the settings QJsonObject settings = json.value("Settings").toObject(); if (settings.contains("Main Output Device")) mainOutputDevice = settings.value("Main Output Device").toString(); if (settings.contains("VAC Output Device")) vacOutputDevice = settings.value("VAC Output Device").toString(); if (settings.contains("Stop Sound Key")) { QJsonObject settingsStop = settings.value("Stop Sound Key").toObject(); if (settingsStop.contains("Key Name")) stopName = settingsStop.value("Key Name").toString(); if (settingsStop.contains("VirtualKey")) stopVirtualKey = settingsStop.value("VirtualKey").toInt(); } if (settings.contains("Show Flags")) { LIDL::SHOW_SETTINGS flags = static_cast<LIDL::SHOW_SETTINGS>(settings.value("Show Flags").toInt()); if (flags & LIDL::SHOW_SETTINGS::SHOW_SFX){ LIDL::Controller::SettingsController::GetInstance()->addShowFlag(LIDL::SHOW_SETTINGS::SHOW_SFX); //this->_actions.at(16)->setIcon(QIcon(":/icon/resources/checkmark.png")); } if (flags & LIDL::SHOW_SETTINGS::WRAP_SONG_LIST){ LIDL::Controller::SettingsController::GetInstance()->addShowFlag(LIDL::SHOW_SETTINGS::WRAP_SONG_LIST); //this->_actions.at(17)->setIcon(QIcon(":/icon/resources/checkmark.png")); } } if (saveFormat190) { //parse the "new" json syntax //parsing the profiles if (json.contains("Profiles")){ QJsonArray profiles = json.value("Profiles").toArray(); foreach (const QJsonValue & value, profiles) { QVector <std::shared_ptr<SoundWrapper>> wrappers; QJsonObject profile = value.toObject(); QString profileName; QSet<QString> exes; int pttScanCode=-1, pttVirtualKey =-1; QKeySequence pttKeySequence; if (profile.contains("Profile Name")){ profileName = profile.value("Profile Name").toString(); } if (profile.contains("Executables")){ QJsonArray execs = profile.value("Executables").toArray(); foreach(const QJsonValue & value, execs ) { exes.insert(value.toString()); } } if (profile.contains("Push To Talk Key")){ QJsonObject ptt = profile.value("Push To Talk Key").toObject(); qDebug() << QString::fromStdString(QJsonDocument(ptt).toJson().toStdString()); pttScanCode = ptt.value("ScanCode").toInt(); pttVirtualKey = ptt.value("VirtualKey").toInt(); pttKeySequence = QKeySequence(ptt.value("Key Name").toString()); } // sounds if (profile.contains("Sounds")){ QJsonArray wrappersArray = profile.value("Sounds").toArray(); for (auto i:wrappersArray) { QJsonObject item = i.toObject(); LIDL::Playback playbackmode; QString shortcutString; int shortcutVirtualKey; QVector<LIDL::SoundFile*> fileArray; // Playback // don't mind me just avoiding the may be unitialized warnings ppHop playbackmode = LIDL::Playback::Singleton; if (item.contains("Playback Mode")) { playbackmode = static_cast<LIDL::Playback>(item.value("Playback Mode").toInt()); //accounting for the removval of singleton if (playbackmode == LIDL::Playback::Singleton) playbackmode = LIDL::Playback::Sequential; } // Shortcut info // don't mind me just avoiding the may be unitialized warnings ppHop shortcutVirtualKey = -1; if (item.contains("Shortcut")) { QJsonObject shortcut = item.value("Shortcut").toObject(); if (shortcut.contains("Key")) shortcutString = shortcut.value("Key").toString(); if (shortcut.contains("VirtualKey")) shortcutVirtualKey = shortcut.value("VirtualKey").toInt(); } // Sound collection if (item.contains("Sound Collection")) { if (item.value("Sound Collection").isObject()) { qDebug() << "this is an object forsenE, so new file format forsenE"; QJsonObject soundCollection = item.value("Sound Collection").toObject(); // Have to use traditional iterators because auto doesn't allow to use key DansGame for (QJsonObject::iterator it = soundCollection.begin(); it!= soundCollection.end(); it++) { QJsonObject settings; QString fileName; // if (ok170) // if ver > 1.7.0 we need to go down the arborescence (forsen2) // { QJsonObject subObject = it.value().toObject(); fileName = subObject.keys().at(0); settings = subObject.value(fileName).toObject(); //} // else // < 1.7.0 // { // fileName = it.key(); // settings = it.value().toObject(); // } float mainVolume = 1.0; float vacVolume = 1.0; if (settings.contains("Main Volume")) mainVolume = static_cast<float>(settings.value("Main Volume").toInt()/100.0); if (settings.contains("VAC Volume")) vacVolume = static_cast<float>(settings.value("VAC Volume").toInt()/100.0); // SFX LIDL::SFX sfx; if (settings.contains("SFX Flags")) sfx.flags = static_cast<LIDL::SFX_TYPE>(settings.value("SFX Flags").toInt()); if (settings.contains("SFX")) { QJsonObject sfx_obj = settings.value("SFX").toObject(); if (sfx_obj.contains("Distortion")) { QJsonObject distObj = sfx_obj.value("Distortion").toObject(); for (QJsonObject::iterator l = distObj.begin(); l!= distObj.end();l++) { if (l.key() == "Cutoff") sfx.distortion.fPreLowpassCutoff = static_cast<float>(l.value().toInt()); if (l.key() =="EQBandwidth") sfx.distortion.fPostEQBandwidth = static_cast<float>(l.value().toInt()); if (l.key() =="EQCenterFrequency") sfx.distortion.fPostEQCenterFrequency = static_cast<float>(l.value().toInt()); if (l.key() =="Edge") sfx.distortion.fEdge = static_cast<float>(l.value().toInt()); if (l.key() =="Gain") sfx.distortion.fGain= static_cast<float>(l.value().toInt()); } } if (sfx_obj.contains("Chorus")) { QJsonObject chorusObj = sfx_obj.value("Chorus").toObject(); for (QJsonObject::iterator l = chorusObj.begin(); l!= chorusObj.end();l++) { if (l.key() == "Delay") sfx.chorus.fDelay = static_cast<float>(l.value().toInt()); if (l.key() == "Depth") sfx.chorus.fDepth = static_cast<float>(l.value().toInt()); if (l.key() == "Feedback") sfx.chorus.fFeedback = static_cast<float>(l.value().toInt()); if (l.key() == "Frequency") sfx.chorus.fFrequency = static_cast<float>(l.value().toInt()); if (l.key() == "WetDryMix" || l.key() == "Wet Dry Mix") sfx.chorus.fWetDryMix = static_cast<float>(l.value().toInt()); if (l.key() == "Phase") sfx.chorus.lPhase = static_cast<int>(l.value().toInt()); if (l.key() == "Waveform") sfx.chorus.lWaveform = static_cast<int>(l.value().toInt()); } } if (sfx_obj.contains("Echo")) { QJsonObject obj = sfx_obj.value("Echo").toObject(); for (QJsonObject::iterator l = obj.begin(); l!= obj.end();l++) { if (l.key() =="Feedback" ) sfx.echo.fFeedback = static_cast<float>(l.value().toInt()); if (l.key() =="Left Delay" ) sfx.echo.fLeftDelay = static_cast<float>(l.value().toInt()); if (l.key() =="Right Delay" ) sfx.echo.fRightDelay = static_cast<float>(l.value().toInt()); if (l.key() =="Wet Dry Mix" ) sfx.echo.fWetDryMix = static_cast<float>(l.value().toInt()); if (l.key() =="Swap" ) sfx.echo.lPanDelay = static_cast<bool>(l.value().toInt()); } } if (sfx_obj.contains("Flanger")) { QJsonObject obj = sfx_obj.value("Flanger").toObject(); for (QJsonObject::iterator l = obj.begin(); l!= obj.end();l++) { if (l.key() =="Delay") sfx.flanger.fDelay = static_cast<float>(l.value().toInt()); if (l.key() =="Depth") sfx.flanger.fDepth = static_cast<float>(l.value().toInt()); if (l.key() =="Feedback" ) sfx.flanger.fFeedback = static_cast<float>(l.value().toInt()); if (l.key() =="Frequency" ) sfx.flanger.fFrequency = static_cast<float>(l.value().toInt()); if (l.key() =="Phase" ) sfx.flanger.lPhase = static_cast<float>(l.value().toInt()); if (l.key() =="Waveform" ) sfx.flanger.lWaveform = static_cast<bool>(l.value().toInt()); } } if (sfx_obj.contains("Compressor")) { QJsonObject obj = sfx_obj.value("Compressor").toObject(); for (QJsonObject::iterator l = obj.begin(); l!= obj.end();l++) { if (l.key() =="Attack") sfx.compressor.fAttack = static_cast<float>(l.value().toInt()); if (l.key() =="Gain") sfx.compressor.fGain = static_cast<float>(l.value().toInt()); if (l.key() =="Predelay") sfx.compressor.fPredelay = static_cast<float>(l.value().toInt()); if (l.key() =="Ratio") sfx.compressor.fRatio = static_cast<float>(l.value().toInt()); if (l.key() =="Release") sfx.compressor.fRelease = static_cast<float>(l.value().toInt()); if (l.key() =="Threshold") sfx.compressor.fThreshold = static_cast<float>(l.value().toInt()); } } if (sfx_obj.contains("Gargle")) { QJsonObject obj = sfx_obj.value("Gargle").toObject(); for (QJsonObject::iterator l = obj.begin(); l!= obj.end();l++) { if (l.key() =="Rate") sfx.gargle.dwRateHz = static_cast<float>(l.value().toInt()); if (l.key() =="Waveform") sfx.gargle.dwWaveShape = static_cast<bool>(l.value().toBool()); } } } qDebug() << "[SaveController::OpenSaveFile] Profile:" << profileName; qDebug() << "[SaveController::OpenSaveFile] File:" << fileName; fileArray.append(new LIDL::SoundFile(fileName, mainVolume, vacVolume,sfx)); } } //Else If this is an array than we are on the old save system without the volumes else if (item.value("Sound Collection").isArray()) { //qDebug() << "Old file detected forsenBee"; QJsonArray soundArray = item.value("Sound Collection").toArray(); // We iterate over the sound files and add them to the array // (default volume is 100%). for (auto j: soundArray) { fileArray.append(new LIDL::SoundFile(j.toString(),LIDL::Controller::SettingsController::GetInstance()->GetDefaultMainVolume(),LIDL::Controller::SettingsController::GetInstance()->GetDefaultVacVolume()) ); } } // else if sound collection is array( rly fucking old format) } /*************************************************** CREATING THE WRAPPERS ****************************************************/ wrappers.append( std::make_shared<SoundWrapper>(fileArray, playbackmode, QKeySequence(shortcutString), shortcutVirtualKey, 0, 0, nullptr)); } // end for auto wrapper // Once the wrappers are created we need to create the profile i guess PepeS } // end if profile contains sounds // Now we can add the profile i guess PepeS Profile::Builder temp; temp.setName(profileName); for ( QString i: exes) { temp.addExe(i); } temp.setSounds(wrappers) .setPttScanCode(pttScanCode) .setPttVirtualKey(pttVirtualKey) .setPttKeySequence(pttKeySequence); LIDL::Controller::ProfileController::GetInstance()->AddProfile(temp.Build()); } // end for each profile } // end if contain profiles } // end if 1.9.0 else { this->ParseOldSave(json); } // once parse, we set the device on the soundboard // and we swap to default profile, it should re-add the sound with the correct device // in any case we revert to default profile forsenT LIDL::Controller::ProfileController::GetInstance()->AutomaticConfigurationChange("Default"); // we set the sounds output i guess emit SetDevices(mainOutputDevice,vacOutputDevice); // setting the stop emit SetStopShortcut(QKeySequence(stopName), stopVirtualKey); this->_snapshot = GenerateSaveFile(); emit lidlJsonDetected(QFileInfo(fileName) ); } void SaveController::ParseOldSave(QJsonObject json) { // Declare the temp variables we are going to use to construct our objects QString mainOutputDevice, vacOutputDevice; QString pttName; int pttScanCode=-1, pttVirtualKey =-1; QString stopName; int stopVirtualKey =-1; QVector<std::shared_ptr<SoundWrapper>> wrappers; // check for version for retrocompability with version <170 QString version; if (json.contains("Version")) version = json.value("Version").toString(); else version = "1.x.x"; // do i really need the test tho? Because... we added ver number in 1.7.0 releases. // better safe than sorry i guess eShrug // if the version key is present we could be using either 1.7.0 or > (or < if a smartass tries to break the system) bool ok170 = true; if (version != "1.x.x") { QString target = "1.7.0"; int size = (version.size() < target.size() ? version.size() : target.size()); for (int z = 0; z < size; z++ ) { if (version[z] == ".") continue; if (version[z].digitValue() < target[z].digitValue()) { ok170 = false; break; } } } else ok170 = false; // QVector<SoundWrapper*> sounds; // if it has a setting block we read it if (json.contains("Settings")) { QJsonObject settings = json.value("Settings").toObject(); if (settings.contains("Push To Talk Key")) { QJsonObject settingsPTT = settings.value("Push To Talk Key").toObject(); if (settingsPTT.contains("Key Name")) pttName = settingsPTT.value("Key Name").toString(); if (settingsPTT.contains("ScanCode")) pttScanCode = settingsPTT.value("ScanCode").toInt(); if (settingsPTT.contains("VirtualKey")) pttVirtualKey = settingsPTT.value("VirtualKey").toInt(); } }// end if it contains settings // The wrapper stuff if (json.contains("SoundWrappers")) { //progressWidget->move(0,this->resultView->size().height() - progressWidget->height() + 20); QJsonArray wrappersArray = json.value("SoundWrappers").toArray(); // we iterate over wrappers for (auto i:wrappersArray) { QJsonObject item = i.toObject(); LIDL::Playback playbackmode; QString shortcutString; int shortcutVirtualKey; QVector<LIDL::SoundFile*> fileArray; // Playback // don't mind me just avoiding the may be unitialized warnings ppHop playbackmode = LIDL::Playback::Singleton; if (item.contains("Playback Mode")) { playbackmode = static_cast<LIDL::Playback>(item.value("Playback Mode").toInt()); if (playbackmode == LIDL::Playback::Singleton) playbackmode = LIDL::Playback::Sequential; } // Shortcut info // don't mind me just avoiding the may be unitialized warnings ppHop shortcutVirtualKey = -1; if (item.contains("Shortcut")) { QJsonObject shortcut = item.value("Shortcut").toObject(); if (shortcut.contains("Key")) shortcutString = shortcut.value("Key").toString(); if (shortcut.contains("VirtualKey")) shortcutVirtualKey = shortcut.value("VirtualKey").toInt(); } // Sound collection if (item.contains("Sound Collection")) { if (item.value("Sound Collection").isObject()) { //qDebug() << "this is an object forsenE, so new file format forsenE"; QJsonObject soundCollection = item.value("Sound Collection").toObject(); // Have to use traditional iterators because auto doesn't allow to use key DansGame for (QJsonObject::iterator it = soundCollection.begin(); it!= soundCollection.end(); ++it) { QJsonObject settings; QString fileName; if (ok170) // if ver > 1.7.0 we need to go down the arborescence (forsen2) { QJsonObject subObject = it.value().toObject(); fileName = subObject.keys().at(0); settings = subObject.value(fileName).toObject(); } else // < 1.7.0 { fileName = it.key(); settings = it.value().toObject(); } float mainVolume = 1.0; float vacVolume = 1.0; if (settings.contains("Main Volume")) mainVolume = static_cast<float>(settings.value("Main Volume").toInt()/100.0); if (settings.contains("VAC Volume")) vacVolume = static_cast<float>(settings.value("VAC Volume").toInt()/100.0); // SFX LIDL::SFX sfx; if (settings.contains("SFX Flags")) sfx.flags = static_cast<LIDL::SFX_TYPE>(settings.value("SFX Flags").toInt()); if (settings.contains("SFX")) { QJsonObject sfx_obj = settings.value("SFX").toObject(); if (sfx_obj.contains("Distortion")) { QJsonObject distObj = sfx_obj.value("Distortion").toObject(); for (QJsonObject::iterator l = distObj.begin(); l!= distObj.end();++l) { if (l.key() == "Cutoff") sfx.distortion.fPreLowpassCutoff = static_cast<float>(l.value().toInt()); if (l.key() =="EQBandwidth") sfx.distortion.fPostEQBandwidth = static_cast<float>(l.value().toInt()); if (l.key() =="EQCenterFrequency") sfx.distortion.fPostEQCenterFrequency = static_cast<float>(l.value().toInt()); if (l.key() =="Edge") sfx.distortion.fEdge = static_cast<float>(l.value().toInt()); if (l.key() =="Gain") sfx.distortion.fGain= static_cast<float>(l.value().toInt()); } } if (sfx_obj.contains("Chorus")) { QJsonObject chorusObj = sfx_obj.value("Chorus").toObject(); for (QJsonObject::iterator l = chorusObj.begin(); l!= chorusObj.end();++l) { if (l.key() == "Delay") sfx.chorus.fDelay = static_cast<float>(l.value().toInt()); if (l.key() == "Depth") sfx.chorus.fDepth = static_cast<float>(l.value().toInt()); if (l.key() == "Feedback") sfx.chorus.fFeedback = static_cast<float>(l.value().toInt()); if (l.key() == "Frequency") sfx.chorus.fFrequency = static_cast<float>(l.value().toInt()); if (l.key() == "WetDryMix" || l.key() == "Wet Dry Mix") sfx.chorus.fWetDryMix = static_cast<float>(l.value().toInt()); if (l.key() == "Phase") sfx.chorus.lPhase = static_cast<int>(l.value().toInt()); if (l.key() == "Waveform") sfx.chorus.lWaveform = static_cast<int>(l.value().toInt()); } } if (sfx_obj.contains("Echo")) { QJsonObject obj = sfx_obj.value("Echo").toObject(); for (QJsonObject::iterator l = obj.begin(); l!= obj.end();l++) { if (l.key() =="Feedback" ) sfx.echo.fFeedback = static_cast<float>(l.value().toInt()); if (l.key() =="Left Delay" ) sfx.echo.fLeftDelay = static_cast<float>(l.value().toInt()); if (l.key() =="Right Delay" ) sfx.echo.fRightDelay = static_cast<float>(l.value().toInt()); if (l.key() =="Wet Dry Mix" ) sfx.echo.fWetDryMix = static_cast<float>(l.value().toInt()); if (l.key() =="Swap" ) sfx.echo.lPanDelay = static_cast<bool>(l.value().toInt()); } } if (sfx_obj.contains("Flanger")) { QJsonObject obj = sfx_obj.value("Flanger").toObject(); for (QJsonObject::iterator l = obj.begin(); l!= obj.end();l++) { if (l.key() =="Delay") sfx.flanger.fDelay = static_cast<float>(l.value().toInt()); if (l.key() =="Depth") sfx.flanger.fDepth = static_cast<float>(l.value().toInt()); if (l.key() =="Feedback" ) sfx.flanger.fFeedback = static_cast<float>(l.value().toInt()); if (l.key() =="Frequency" ) sfx.flanger.fFrequency = static_cast<float>(l.value().toInt()); if (l.key() =="Phase" ) sfx.flanger.lPhase = static_cast<float>(l.value().toInt()); if (l.key() =="Waveform" ) sfx.flanger.lWaveform = static_cast<bool>(l.value().toInt()); } } if (sfx_obj.contains("Compressor")) { QJsonObject obj = sfx_obj.value("Compressor").toObject(); for (QJsonObject::iterator l = obj.begin(); l!= obj.end();l++) { if (l.key() =="Attack") sfx.compressor.fAttack = static_cast<float>(l.value().toInt()); if (l.key() =="Gain") sfx.compressor.fGain = static_cast<float>(l.value().toInt()); if (l.key() =="Predelay") sfx.compressor.fPredelay = static_cast<float>(l.value().toInt()); if (l.key() =="Ratio") sfx.compressor.fRatio = static_cast<float>(l.value().toInt()); if (l.key() =="Release") sfx.compressor.fRelease = static_cast<float>(l.value().toInt()); if (l.key() =="Threshold") sfx.compressor.fThreshold = static_cast<float>(l.value().toInt()); } } if (sfx_obj.contains("Gargle")) { QJsonObject obj = sfx_obj.value("Gargle").toObject(); for (QJsonObject::iterator l = obj.begin(); l!= obj.end();l++) { if (l.key() =="Rate") sfx.gargle.dwRateHz = static_cast<float>(l.value().toInt()); if (l.key() =="Waveform") sfx.gargle.dwWaveShape = static_cast<bool>(l.value().toBool()); } } } fileArray.append(new LIDL::SoundFile(fileName, mainVolume, vacVolume,sfx)); } } //Else If this is an array than we are on the old save system without the volumes else if (item.value("Sound Collection").isArray() ) { //qDebug() << "Old file detected forsenBee"; QJsonArray soundArray = item.value("Sound Collection").toArray(); // We iterate over the sound files and add them to the array // (default volume is 100%). for (auto j: soundArray) { fileArray.append(new LIDL::SoundFile(j.toString(),LIDL::Controller::SettingsController::GetInstance()->GetDefaultMainVolume(),LIDL::Controller::SettingsController::GetInstance()->GetDefaultVacVolume()) ); } } } /*************************************************** CREATING THE WRAPPERS ****************************************************/ wrappers.append( std::make_shared<SoundWrapper>(fileArray, playbackmode, QKeySequence(shortcutString), shortcutVirtualKey, 0, 0, nullptr)); } // end for auto wrapper Profile::Builder temp; temp.setSounds(wrappers) .setPttScanCode(pttScanCode) .setPttVirtualKey(pttVirtualKey) .setPttKeySequence(QKeySequence(pttName)); LIDL::Controller::ProfileController::GetInstance()->AddProfile(temp.Build()); } // end if json contains wrapper } bool SaveController::NeedsSaving() { return (this->GenerateSaveFile() == _snapshot); } QString SaveController::GetSaveName() const { return this->_saveName; } int SaveController::CheckAndPromptIfNeedsSaving() { QJsonObject newSnapshot = this->GenerateSaveFile(); // if NOTHING HERE we return if ( _snapshot == newSnapshot) return -1; QMessageBox::StandardButton reply; reply = QMessageBox::question(nullptr,tr("LIDL Soundboard: Changes Detected"), tr("Do you wish to save changes?"), QMessageBox::Yes|QMessageBox::No| QMessageBox::Cancel); switch (reply){ case QMessageBox::Yes: this->Save(); return 0; break; case QMessageBox::No : return 1; break; case QMessageBox::Cancel: return 2; break; default: return 2; break; } } void SaveController::SaveState() { this->_snapshot = this->GenerateSaveFile(); } void SaveController::SaveAs(QString fileName) { // if filename is empty we show the prompt if (fileName.isEmpty()) { fileName = QFileDialog::getSaveFileName(nullptr, QObject::tr("Save Soundboard As.."), LIDL::Controller::SettingsController::GetInstance()->GetDefaultSoundboardFolder() , QObject::tr("LIDL JSON file(*.lidljson)")); } // fileName.append(".lidljson"); QJsonObject save = GenerateSaveFile(); QJsonDocument *doc = new QJsonDocument(save); QString jsonString = doc->toJson(QJsonDocument::Indented); QFile file(fileName); if (!file.open(QIODevice::WriteOnly)) { QMessageBox::information(nullptr, QObject::tr("Unable to open file"), file.errorString()); return; } else { this->_saveName = fileName; QTextStream out(&file); out.setCodec("UTF-8"); out << jsonString.toUtf8(); // lidljson detected is used to add the file in the recent file thing // emit lidlJsonDetected(QFileInfo(file)); file.close(); // Saving Soundboard state in the SettingsController object // emit SaveSoundboardState(); // this->SetStatusTextEditText("Succesfully saved file: " + fileName); } // not sure about this. delete doc; this->_snapshot = save; emit lidlJsonDetected(QFileInfo(fileName) ); } QJsonObject SaveController::GenerateSaveFile() const { QJsonObject obj; // inserting version // defined in qmake (.pro) file obj.insert("Version", VER_STRING); QJsonObject settings; settings.insert("Main Output Device", this->_mainOutputDevice); settings.insert("VAC Output Device", this->_vacOutputDevice); settings.insert("Show Flags", static_cast<int>(LIDL::Controller::SettingsController::GetInstance()->getShowFlags())); QJsonObject stopSoundKey; stopSoundKey.insert("Key Name",this->_stopKeyName); stopSoundKey.insert("VirtualKey" ,static_cast<int>(this->_stopVirtualKey)); settings.insert("Stop Sound Key",stopSoundKey); obj.insert("Settings", settings); QJsonArray profiles; for (auto &i: LIDL::Controller::ProfileController::GetInstance()->GetProfiles()) { profiles.append(i->GetProfileAsObject()); } obj.insert("Profiles",profiles); return obj; // qDebug() << QJsonDocument(obj).toJson(); } void SaveController::SetMainOutputDevice(QString device) { this->_mainOutputDevice = device; } void SaveController::SetVacOutputDevice(QString device) { this->_vacOutputDevice = device; } QString SaveController::GetMainOutputDevice() const { return this->_mainOutputDevice; } QString SaveController::GetVacOutputDevice() const { return this->_vacOutputDevice; } } // end namespace controller } // end namespace LIDL
e450d4c08262cb124fdc18358c67660965af0c27
dc182283f6eed3b5aaa45c7da61bdc07b41ee161
/chrome/browser/ui/startup/startup_browser_creator_welcome_back_browsertest.cc
ee5d5e0d807fd5e25a2ddd7d9dea4db93d206390
[ "BSD-3-Clause" ]
permissive
KHJcode/chromium
c2bf1c71363e81aaa9e14de582cd139e46877e0a
61f837c7b6768f2e74501dd614624f44e396f363
refs/heads/master
2023-06-19T07:25:15.090544
2021-07-08T12:38:31
2021-07-08T12:38:31
299,554,207
1
0
BSD-3-Clause
2020-09-29T08:33:13
2020-09-29T08:33:12
null
UTF-8
C++
false
false
5,056
cc
// Copyright 2021 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 <memory> #include <string> #include <utility> #include <vector> #include "base/command_line.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_keep_alive_types.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/profiles/scoped_profile_keep_alive.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/startup/startup_browser_creator.h" #include "chrome/browser/ui/startup/startup_tab_provider.h" #include "chrome/test/base/in_process_browser_test.h" #include "components/keep_alive_registry/keep_alive_types.h" #include "components/keep_alive_registry/scoped_keep_alive.h" #include "components/policy/core/browser/browser_policy_connector.h" #include "components/policy/core/common/mock_configuration_policy_provider.h" #include "components/policy/core/common/policy_types.h" #include "components/policy/policy_constants.h" #include "content/public/test/browser_test.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "url/gurl.h" namespace { typedef absl::optional<policy::PolicyLevel> PolicyVariant; } class StartupBrowserCreatorWelcomeBackTest : public InProcessBrowserTest { protected: StartupBrowserCreatorWelcomeBackTest() = default; void SetUpInProcessBrowserTestFixture() override { ON_CALL(provider_, IsInitializationComplete(testing::_)) .WillByDefault(testing::Return(true)); ON_CALL(provider_, IsFirstPolicyLoadComplete(testing::_)) .WillByDefault(testing::Return(true)); policy::BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_); } void SetUpOnMainThread() override { profile_ = browser()->profile(); // Keep the browser process and Profile running when all browsers are // closed. scoped_keep_alive_ = std::make_unique<ScopedKeepAlive>( KeepAliveOrigin::BROWSER, KeepAliveRestartOption::DISABLED); scoped_profile_keep_alive_ = std::make_unique<ScopedProfileKeepAlive>( profile_, ProfileKeepAliveOrigin::kBrowserWindow); // Close the browser opened by InProcessBrowserTest. CloseBrowserSynchronously(browser()); ASSERT_EQ(0U, BrowserList::GetInstance()->size()); } void StartBrowser(PolicyVariant variant) { browser_creator_.set_welcome_back_page(true); if (variant) { policy::PolicyMap values; values.Set(policy::key::kRestoreOnStartup, variant.value(), policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_CLOUD, base::Value(4), nullptr); base::Value url_list(base::Value::Type::LIST); url_list.Append("http://managed.site.com/"); values.Set(policy::key::kRestoreOnStartupURLs, variant.value(), policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_CLOUD, std::move(url_list), nullptr); provider_.UpdateChromePolicy(values); } ASSERT_TRUE(browser_creator_.Start( base::CommandLine(base::CommandLine::NO_PROGRAM), base::FilePath(), profile_, g_browser_process->profile_manager()->GetLastOpenedProfiles())); ASSERT_EQ(1U, BrowserList::GetInstance()->size()); } void ExpectUrlInBrowserAtPosition(const GURL& url, int tab_index) { Browser* browser = BrowserList::GetInstance()->get(0); TabStripModel* tab_strip = browser->tab_strip_model(); EXPECT_EQ(url, tab_strip->GetWebContentsAt(tab_index)->GetURL()); } void TearDownOnMainThread() override { scoped_profile_keep_alive_.reset(); scoped_keep_alive_.reset(); } private: Profile* profile_ = nullptr; std::unique_ptr<ScopedKeepAlive> scoped_keep_alive_; std::unique_ptr<ScopedProfileKeepAlive> scoped_profile_keep_alive_; StartupBrowserCreator browser_creator_; testing::NiceMock<policy::MockConfigurationPolicyProvider> provider_; }; IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorWelcomeBackTest, WelcomeBackStandardNoPolicy) { ASSERT_NO_FATAL_FAILURE(StartBrowser(PolicyVariant())); ExpectUrlInBrowserAtPosition(StartupTabProviderImpl::GetWelcomePageUrl(false), 0); } IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorWelcomeBackTest, WelcomeBackStandardMandatoryPolicy) { ASSERT_NO_FATAL_FAILURE( StartBrowser(PolicyVariant(policy::POLICY_LEVEL_MANDATORY))); ExpectUrlInBrowserAtPosition(GURL("http://managed.site.com/"), 0); } IN_PROC_BROWSER_TEST_F(StartupBrowserCreatorWelcomeBackTest, WelcomeBackStandardRecommendedPolicy) { ASSERT_NO_FATAL_FAILURE( StartBrowser(PolicyVariant(policy::POLICY_LEVEL_RECOMMENDED))); ExpectUrlInBrowserAtPosition(GURL("http://managed.site.com/"), 0); }
4b41305daffc76daab2e0f684eb5d4b5e1c7d2cf
683537fa4613aa5a404520cd5cc9dab2d85c9ef7
/tp4_ESIR/third-party/visp-3.1.0-build/include/visp3/core/vpNetwork.h
2c866d33efe5d83f3f7a1976b4bd42f82e6000b0
[]
no_license
SuperRonan/IMM
caac5a2e7fd87af81ecac63119640ade61914d2a
0b88dd11213c0bf99bc371a5b50412c8eccffcfb
refs/heads/master
2020-11-23T20:49:37.482881
2019-12-19T09:59:57
2019-12-19T09:59:57
227,814,002
0
0
null
null
null
null
UTF-8
C++
false
false
16,362
h
/**************************************************************************** * * This file is part of the ViSP software. * Copyright (C) 2005 - 2017 by Inria. All rights reserved. * * This software is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * See the file LICENSE.txt at the root directory of this source * distribution for additional information about the GNU GPL. * * For using ViSP with software that can not be combined with the GNU * GPL, please contact Inria about acquiring a ViSP Professional * Edition License. * * See http://visp.inria.fr for more information. * * This software was developed at: * Inria Rennes - Bretagne Atlantique * Campus Universitaire de Beaulieu * 35042 Rennes Cedex * France * * If you have questions regarding the use of this file, please contact * Inria at [email protected] * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * Description: * TCP Network * * Authors: * Aurelien Yol * *****************************************************************************/ #ifndef vpNetwork_H #define vpNetwork_H #include <visp3/core/vpConfig.h> #include <visp3/core/vpRequest.h> #include <iostream> #include <stdio.h> #include <string.h> #include <vector> #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX #include <arpa/inet.h> #include <netdb.h> #include <netinet/in.h> #include <sys/socket.h> #include <unistd.h> #else #include <io.h> //# include<winsock.h> #include <winsock2.h> //# pragma comment(lib, "ws2_32.lib") // Done by CMake in main CMakeLists.txt #endif #if defined(__APPLE__) && defined(__MACH__) // Apple OSX and iOS (Darwin) #include <TargetConditionals.h> // To detect OSX or IOS using TARGET_OS_IPHONE or TARGET_OS_IOS macro #endif /*! \class vpNetwork \ingroup group_core_network \brief This class represents a Transmission Control Protocol (TCP) network. TCP provides reliable, ordered delivery of a stream of bytes from a program on one computer to another program on another computer. \warning This class shouldn't be used directly. You better use vpClient and vpServer to simulate your network. Some exemples are provided in these classes. \sa vpServer \sa vpNetwork */ class VISP_EXPORT vpNetwork { protected: #ifndef DOXYGEN_SHOULD_SKIP_THIS struct vpReceptor { #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX int socketFileDescriptorReceptor; socklen_t receptorAddressSize; #else SOCKET socketFileDescriptorReceptor; int receptorAddressSize; #endif struct sockaddr_in receptorAddress; std::string receptorIP; vpReceptor() : socketFileDescriptorReceptor(0), receptorAddressSize(), receptorAddress(), receptorIP() {} }; struct vpEmitter { struct sockaddr_in emitterAddress; #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX int socketFileDescriptorEmitter; #else SOCKET socketFileDescriptorEmitter; #endif vpEmitter() : emitterAddress(), socketFileDescriptorEmitter(0) { emitterAddress.sin_family = AF_INET; emitterAddress.sin_addr.s_addr = INADDR_ANY; emitterAddress.sin_port = 0; socketFileDescriptorEmitter = 0; } }; #endif //######## PARAMETERS ######## //# # //############################ vpEmitter emitter; std::vector<vpReceptor> receptor_list; fd_set readFileDescriptor; #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX int socketMax; #else SOCKET socketMax; #endif // Message Handling std::vector<vpRequest *> request_list; unsigned int max_size_message; std::string separator; std::string beginning; std::string end; std::string param_sep; std::string currentMessageReceived; struct timeval tv; long tv_sec; long tv_usec; bool verboseMode; private: std::vector<int> _handleRequests(); int _handleFirstRequest(); void _receiveRequest(); void _receiveRequestFrom(const unsigned int &receptorEmitting); int _receiveRequestOnce(); int _receiveRequestOnceFrom(const unsigned int &receptorEmitting); public: vpNetwork(); virtual ~vpNetwork(); void addDecodingRequest(vpRequest *); int getReceptorIndex(const char *name); /*! Get the Id of the request at the index ind. \param ind : Index of the request. \return Id of the request. */ std::string getRequestIdFromIndex(const int &ind) { if (ind >= (int)request_list.size() || ind < 0) return ""; return request_list[(unsigned)ind]->getId(); } /*! Get the maximum size that the emitter can receive (in request mode). \sa vpNetwork::setMaxSizeReceivedMessage() \return Acutal max size value. */ unsigned int getMaxSizeReceivedMessage() { return max_size_message; } void print(const char *id = ""); template <typename T> int receive(T *object, const unsigned int &sizeOfObject = sizeof(T)); template <typename T> int receiveFrom(T *object, const unsigned int &receptorEmitting, const unsigned int &sizeOfObject = sizeof(T)); std::vector<int> receiveRequest(); std::vector<int> receiveRequestFrom(const unsigned int &receptorEmitting); int receiveRequestOnce(); int receiveRequestOnceFrom(const unsigned int &receptorEmitting); std::vector<int> receiveAndDecodeRequest(); std::vector<int> receiveAndDecodeRequestFrom(const unsigned int &receptorEmitting); int receiveAndDecodeRequestOnce(); int receiveAndDecodeRequestOnceFrom(const unsigned int &receptorEmitting); void removeDecodingRequest(const char *); template <typename T> int send(T *object, const int unsigned &sizeOfObject = sizeof(T)); template <typename T> int sendTo(T *object, const unsigned int &dest, const unsigned int &sizeOfObject = sizeof(T)); int sendRequest(vpRequest &req); int sendRequestTo(vpRequest &req, const unsigned int &dest); int sendAndEncodeRequest(vpRequest &req); int sendAndEncodeRequestTo(vpRequest &req, const unsigned int &dest); /*! Change the maximum size that the emitter can receive (in request mode). \sa vpNetwork::getMaxSizeReceivedMessage() \param s : new maximum size value. */ void setMaxSizeReceivedMessage(const unsigned int &s) { max_size_message = s; } /*! Change the time the emitter spend to check if he receives a message from a receptor. Initially this value is set to 10usec. \sa vpNetwork::setTimeoutUSec() \param sec : new value in second. */ void setTimeoutSec(const long &sec) { tv_sec = sec; } /*! Change the time the emitter spend to check if he receives a message from a receptor. Initially this value is set to 10usec. \sa vpNetwork::setTimeoutSec() \param usec : new value in micro second. */ void setTimeoutUSec(const long &usec) { tv_usec = usec; } /*! Set the verbose mode. \param mode : Change the verbose mode. True to turn on, False to turn off. */ void setVerbose(const bool &mode) { verboseMode = mode; } }; //######## Definition of Template Functions ######## //# # //################################################## /*! Receives a object. The size of the received object is suppose to be the size of the type of the object. Note that a received message can correspond to a deconnection signal. \warning Using this function means that you know what kind of object you are suppose to receive, and when you are suppose to receive. If the emitter has several receptors. It might be a problem, and in that case you better use the "request" option. \sa vpNetwork::receiveRequest() \sa vpNetwork::receiveRequestOnce() \sa vpNetwork::receiveAndDecodeRequest() \sa vpNetwork::receiveAndDecodeRequestOnce() \param object : Received object. \param sizeOfObject : Size of the received object. \return the number of bytes received, or -1 if an error occured. */ template <typename T> int vpNetwork::receive(T *object, const unsigned int &sizeOfObject) { if (receptor_list.size() == 0) { if (verboseMode) vpTRACE("No receptor"); return -1; } tv.tv_sec = tv_sec; #if TARGET_OS_IPHONE tv.tv_usec = (int)tv_usec; #else tv.tv_usec = tv_usec; #endif FD_ZERO(&readFileDescriptor); for (unsigned int i = 0; i < receptor_list.size(); i++) { FD_SET((unsigned int)receptor_list[i].socketFileDescriptorReceptor, &readFileDescriptor); if (i == 0) socketMax = receptor_list[i].socketFileDescriptorReceptor; if (socketMax < receptor_list[i].socketFileDescriptorReceptor) socketMax = receptor_list[i].socketFileDescriptorReceptor; } int value = select((int)socketMax + 1, &readFileDescriptor, NULL, NULL, &tv); int numbytes = 0; if (value == -1) { if (verboseMode) vpERROR_TRACE("Select error"); return -1; } else if (value == 0) { // Timeout return 0; } else { for (unsigned int i = 0; i < receptor_list.size(); i++) { if (FD_ISSET((unsigned int)receptor_list[i].socketFileDescriptorReceptor, &readFileDescriptor)) { #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX numbytes = recv(receptor_list[i].socketFileDescriptorReceptor, (char *)(void *)object, sizeOfObject, 0); #else numbytes = recv((unsigned int)receptor_list[i].socketFileDescriptorReceptor, (char *)(void *)object, (int)sizeOfObject, 0); #endif if (numbytes <= 0) { std::cout << "Disconnected : " << inet_ntoa(receptor_list[i].receptorAddress.sin_addr) << std::endl; receptor_list.erase(receptor_list.begin() + (int)i); return numbytes; } break; } } } return numbytes; } /*! Receives a object from a receptor, by specifying its size or not. Note that a received message can correspond to a deconnection signal. \warning Using this function means that you know what kind of object you are suppose to receive, and when you are suppose to receive. If the emitter has several receptors. It might be a problem, and in that case you better use the "request" mode. \sa vpNetwork::getReceptorIndex() \sa vpNetwork::receiveRequestFrom() \sa vpNetwork::receiveRequestOnceFrom() \sa vpNetwork::receiveAndDecodeRequestFrom() \sa vpNetwork::receiveAndDecodeRequestOnceFrom() \param object : Received object. \param receptorEmitting : Index of the receptor emitting the message. \param sizeOfObject : Size of the received object. \return the number of bytes received, or -1 if an error occured. */ template <typename T> int vpNetwork::receiveFrom(T *object, const unsigned int &receptorEmitting, const unsigned int &sizeOfObject) { if (receptor_list.size() == 0 || receptorEmitting > (unsigned int)receptor_list.size() - 1) { if (verboseMode) vpTRACE("No receptor at the specified index"); return -1; } tv.tv_sec = tv_sec; #if TARGET_OS_IPHONE tv.tv_usec = (int)tv_usec; #else tv.tv_usec = tv_usec; #endif FD_ZERO(&readFileDescriptor); socketMax = receptor_list[receptorEmitting].socketFileDescriptorReceptor; FD_SET((unsigned int)receptor_list[receptorEmitting].socketFileDescriptorReceptor, &readFileDescriptor); int value = select((int)socketMax + 1, &readFileDescriptor, NULL, NULL, &tv); int numbytes = 0; if (value == -1) { if (verboseMode) vpERROR_TRACE("Select error"); return -1; } else if (value == 0) { // timeout return 0; } else { if (FD_ISSET((unsigned int)receptor_list[receptorEmitting].socketFileDescriptorReceptor, &readFileDescriptor)) { #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX numbytes = recv(receptor_list[receptorEmitting].socketFileDescriptorReceptor, (char *)(void *)object, sizeOfObject, 0); #else numbytes = recv((unsigned int)receptor_list[receptorEmitting].socketFileDescriptorReceptor, (char *)(void *)object, (int)sizeOfObject, 0); #endif if (numbytes <= 0) { std::cout << "Disconnected : " << inet_ntoa(receptor_list[receptorEmitting].receptorAddress.sin_addr) << std::endl; receptor_list.erase(receptor_list.begin() + (int)receptorEmitting); return numbytes; } } } return numbytes; } /*! Send an object. The size of the received object is suppose to be the size of its type. Note that sending object containing pointers, virtual methods, etc, won't probably work. \warning Using this function means that, in the other side of the network, it knows what kind of object it is suppose to receive, and when it is suppose to receive. If the emitter has several receptors. It might be a problem, and in that case you better use the "request" option. \sa vpNetwork::sendTo() \sa vpNetwork::sendRequest() \sa vpNetwork::sendRequestTo() \sa vpNetwork::sendAndEncodeRequest() \sa vpNetwork::sendAndEncodeRequestTo() \param object : Received object. \param sizeOfObject : Size of the object \return The number of bytes sent, or -1 if an error happened. */ template <typename T> int vpNetwork::send(T *object, const unsigned int &sizeOfObject) { if (receptor_list.size() == 0) { if (verboseMode) vpTRACE("No receptor !"); return 0; } int flags = 0; //#if ! defined(APPLE) && ! defined(SOLARIS) && ! defined(_WIN32) #if defined(__linux__) flags = MSG_NOSIGNAL; // Only for Linux #endif #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX return sendto(receptor_list[0].socketFileDescriptorReceptor, (const char *)(void *)object, sizeOfObject, flags, (sockaddr *)&receptor_list[0].receptorAddress, receptor_list[0].receptorAddressSize); #else return sendto(receptor_list[0].socketFileDescriptorReceptor, (const char *)(void *)object, (int)sizeOfObject, flags, (sockaddr *)&receptor_list[0].receptorAddress, receptor_list[0].receptorAddressSize); #endif } /*! Send an object. The size has to be specified. \warning Using this function means that, in the other side of the network, it knows what kind of object it is suppose to receive, and when it is suppose to receive. If the emitter has several receptors. It might be a problem, and in that case you better use the "request" option. \sa vpNetwork::getReceptorIndex() \sa vpNetwork::send() \sa vpNetwork::sendRequest() \sa vpNetwork::sendRequestTo() \sa vpNetwork::sendAndEncodeRequest() \sa vpNetwork::sendAndEncodeRequestTo() \param object : Object to send. \param dest : Index of the receptor that you are sending the object. \param sizeOfObject : Size of the object. \return The number of bytes sent, or -1 if an error happened. */ template <typename T> int vpNetwork::sendTo(T *object, const unsigned int &dest, const unsigned int &sizeOfObject) { if (receptor_list.size() == 0 || dest > (unsigned int)receptor_list.size() - 1) { if (verboseMode) vpTRACE("No receptor at the specified index."); return 0; } int flags = 0; //#if ! defined(APPLE) && ! defined(SOLARIS) && ! defined(_WIN32) #if defined(__linux__) flags = MSG_NOSIGNAL; // Only for Linux #endif #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))) // UNIX return sendto(receptor_list[dest].socketFileDescriptorReceptor, (const char *)(void *)object, sizeOfObject, flags, (sockaddr *)&receptor_list[dest].receptorAddress, receptor_list[dest].receptorAddressSize); #else return sendto(receptor_list[dest].socketFileDescriptorReceptor, (const char *)(void *)object, (int)sizeOfObject, flags, (sockaddr *)&receptor_list[dest].receptorAddress, receptor_list[dest].receptorAddressSize); #endif } #endif
6eeafd598fa9504bb4f4261d8c555a1768f70de3
54fed540dd338575aa1e4210b8bb1d4853235e64
/contracts/examples/store/store.cpp
0e8800ee9f142067c43136d4b25e786ed2c6e077
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
my-graphene/core
84d3c30efd3b0f2e8fc7332831a6af93e0403482
3959619043c06bd3f54a3e6897fab755801db464
refs/heads/master
2020-05-23T14:43:12.963494
2019-05-22T12:55:22
2019-05-22T12:55:22
186,809,764
0
1
MIT
2019-05-22T12:56:14
2019-05-15T11:08:15
WebAssembly
UTF-8
C++
false
false
481
cpp
#include <graphenelib/graphene.hpp> #include <graphenelib/contract.hpp> #include <graphenelib/dispatcher.hpp> #include <graphenelib/print.hpp> #include <graphenelib/types.h> using namespace graphene; class store : public contract { public: store(uint64_t id) : contract(id) { } /// @abi action void set() { i=3; } /// @abi action void show() { print("i=", i, "\n"); } uint32_t i; }; GRAPHENE_ABI(store, (set)(show))
f8ab80498f724af067f4329f3a7e6fed016938b2
81fea7e421f7a8dce11870ca64d4aed1d1c75e04
/c++03/bitwise.cpp
cf3365d10cdcd4788a485c64d72eebbdfff2824b
[]
no_license
petergottschling/dmc2
d88b258717faf75f2bc808233d1b6237cbe92712
cbb1df755cbfe244efa0f87ac064382d87a1f4d2
refs/heads/master
2020-03-26T14:34:26.143182
2018-08-16T14:00:58
2018-08-16T14:00:58
144,994,456
27
3
null
null
null
null
UTF-8
C++
false
false
388
cpp
#include <iostream> int main () { const int concave = 1, monotone = 2, continuous = 4; int f_is = concave | continuous; std::cout << "f is " << f_is << std::endl; std::cout << "Is f concave? (0 means no, 1 means yes) " << (f_is & concave) << std::endl; f_is = f_is | monotone; f_is = f_is ^ concave; std::cout << "f is now " << f_is << std::endl; return 0 ; }
092e3d6993652eeeae5cfb85986c75dd1eeb6d36
19194c2f2c07ab3537f994acfbf6b34ea9b55ae7
/android-31/android/speech/tts/TextToSpeech_EngineInfo.def.hpp
ea34a380ead758ac657b720f3d4eb8f600c0c387
[ "GPL-3.0-only" ]
permissive
YJBeetle/QtAndroidAPI
e372609e9db0f96602da31b8417c9f5972315cae
ace3f0ea2678967393b5eb8e4edba7fa2ca6a50c
refs/heads/Qt6
2023-08-05T03:14:11.842336
2023-07-24T08:35:31
2023-07-24T08:35:31
249,539,770
19
4
Apache-2.0
2022-03-14T12:15:32
2020-03-23T20:42:54
C++
UTF-8
C++
false
false
607
hpp
#pragma once #include "../../../JObject.hpp" class JString; namespace android::speech::tts { class TextToSpeech_EngineInfo : public JObject { public: // Fields jint icon(); JString label(); JString name(); // QJniObject forward template<typename ...Ts> explicit TextToSpeech_EngineInfo(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} TextToSpeech_EngineInfo(QJniObject obj) : JObject(obj) {} // Constructors TextToSpeech_EngineInfo(); // Methods JString toString() const; }; } // namespace android::speech::tts
419b26cab7336b70f781633af5b3ec099a3c60fb
215931e243fdf5a977972b603ec853a254c46d65
/tb_supply.hpp
da2265430123728d71bf14131c982333755ebbcd
[]
no_license
TacBF/tb_rhs_front_line.takistan
15aee727415ca6803b2b40dfe40e2b7fea400b48
23fcf7bebe73cdbfcf6240a2d835d335bfb7d9ac
refs/heads/master
2021-01-19T20:31:28.604088
2017-04-17T14:40:14
2017-04-17T14:40:14
88,517,306
0
0
null
null
null
null
UTF-8
C++
false
false
2,577
hpp
class TacBF { class Supply { // Generates cargo IDs (More effecient broadcasting for these items + their ammo) staticWeapons[] = {"RHS_M2StaticMG_WD", "RHS_M2StaticMG_MiniTripod_WD", "RHS_M252_D", "RHS_AGS30_TriPod_MSV", "rhs_Kornet_9M133_2_msv", "RHS_TOW_TriPod_D", "RHS_MK19_TriPod_D", "rhs_Igla_AA_pod_msv", "rhsgref_ins_DSHKM", "rhsgref_ins_DSHKM_Mini_TriPod", "rhs_KORD_high_MSV", "rhs_KORD_MSV", "rhs_2b14_82mm_msv", "rhs_SPG9M_MSV", "rhs_Metis_9k115_2_msv"}; class CargoCollections { class statics_west { transportClear = 1; cargo[] = { {"RHS_M2StaticMG_WD", 2, 4}, {"RHS_M2StaticMG_MiniTripod_WD", 2, 4}, {"RHS_MK19_TriPod_D", 1, 0}, {"RHS_M252_D", -0, 12}, {"TB_Box_West_Mines_F", 8, 0}, {"RHS_TOW_TriPod_D", 1, 15} }; }; class statics_east { transportClear = 1; cargo[] = { {"rhs_KORD_MSV", 2, 4}, {"rhs_KORD_high_MSV", 2, 4}, {"RHS_AGS30_TriPod_MSV", 1, 0}, {"rhs_2b14_82mm_msv", -0, 12}, {"rhs_Metis_9k115_2_msv", 1, 15}, {"RHS_ZU23_MSV", -0, 8}, {"TB_Box_East_Mines_F", 8, 0}, {"rhs_Igla_AA_pod_msv", -0, 6} }; }; class rds_westFO { transportClear = 1; cargo[] = { {"RHS_M2StaticMG_WD", 2, 4}, {"RHS_M2StaticMG_MiniTripod_WD", 2, 0}, {"RHS_M252_D", 1, 1}, {"RHS_TOW_TriPod_D", 1, 2}, {"TB_Box_West_Mines_F", 1, 0}, {"ICE_emptySandbagsCrate_supply", 4,0} }; }; class rds_eastFO { transportClear = 1; cargo[] = { {"rhs_KORD_MSV", 2, 4}, {"rhs_KORD_high_MSV", 2, 0}, {"rhs_2b14_82mm_msv", 1, 1}, {"rhs_Kornet_9M133_2_msv", 1, 2}, {"TB_Box_East_Mines_F", 1, 0}, {"ICE_emptySandbagsCrate_supply", 4,0} }; }; }; class Containers { class ICE_ForwardOutpost_container_WestMG { crateCollection = "rds_westFO"; mass = 1750; }; class ICE_ForwardOutpost_container_EastMG { crateCollection = "rds_eastFO"; mass = 1750; }; }; }; };
d94fd6646ad997bf6aed938d70fa3d867f2f0d51
9e438d6219ef9943aab8a65ec5262a911c5fb74e
/css/grammar.c++
b8f01c4dde194577e35ba5030cfe93d5a83ccbb0
[ "MIT" ]
permissive
zengqh/skui-1
1f7a476ea493b7dbd0203c6e1caf3ec3f37a5abc
1ce452cbee3230ffc20fa477b57a5fde3ea113b9
refs/heads/master
2020-04-14T11:10:25.712744
2018-12-31T12:54:42
2018-12-31T12:54:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,391
/** * The MIT License (MIT) * * Copyright © 2018 Ruben Van Boxem * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. **/ #include "css/grammar.h++" namespace skui::css::grammar { //BOOST_SPIRIT_DEFINE(rule_set) //BOOST_SPIRIT_DEFINE(selector) //BOOST_SPIRIT_DEFINE(declaration_block) //BOOST_SPIRIT_DEFINE(declaration) //BOOST_SPIRIT_DEFINE(value) }
e29b75600eeea5252a69217c3c9c6d26eb447d08
76300ff711cae22c52ce801eea7bec1a340cd5d1
/include/ExecutedCommand.h
33a1e2b8566f167a3a34262505e655e977c7e239
[ "MIT" ]
permissive
benhe119/osquery_history_extension
d23ef21e744362e6d97231ebaa964c0618de105c
8fcf927e319db53fbda59de4cd66c56d48012b20
refs/heads/master
2020-12-04T11:09:29.931916
2020-01-03T11:14:25
2020-01-03T11:14:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
810
h
#pragma once #include <iostream> #include <string> #include <chrono> #include <boost/filesystem.hpp> namespace bfs = boost::filesystem; class ExecutedCommand { public: ExecutedCommand(const std::string& command, const bfs::path& path, const std::time_t& time); std::string getCommand(); bfs::path getPath(); std::time_t getTime(); static bool parseEvent(std::string&, std::string&, bfs::path&, std::time_t&); private: static bool isTime(const std::string& time); static unsigned int findSpace(const std::string&); static unsigned int findSpace(const std::string&, const unsigned int&); std::string command_; bfs::path path_; std::time_t time_; };
69c5238b9e8f6e756c1409ca3b80f0d10c4f4a7d
0ecf2d067e8fe6cdec12b79bfd68fe79ec222ffd
/ash/app_menu/notification_item_view.cc
d4efe9aef5440f2132f4afee7e00d2e09c8284c4
[ "BSD-3-Clause" ]
permissive
yachtcaptain23/browser-android-tabs
e5144cee9141890590d6d6faeb1bdc5d58a6cbf1
a016aade8f8333c822d00d62738a922671a52b85
refs/heads/master
2021-04-28T17:07:06.955483
2018-09-26T06:22:11
2018-09-26T06:22:11
122,005,560
0
0
NOASSERTION
2019-05-17T19:37:59
2018-02-19T01:00:10
null
UTF-8
C++
false
false
5,969
cc
// Copyright 2018 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/app_menu/notification_item_view.h" #include "ash/public/cpp/app_menu_constants.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/image/image.h" #include "ui/gfx/text_elider.h" #include "ui/message_center/views/proportional_image_view.h" #include "ui/views/background.h" #include "ui/views/border.h" #include "ui/views/controls/label.h" #include "ui/views/controls/menu/menu_config.h" #include "ui/views/layout/box_layout.h" namespace ash { namespace { // Line height of all text in NotificationItemView in dips. constexpr int kNotificationItemTextLineHeight = 16; // Padding of |proportional_icon_view_|. constexpr int kIconVerticalPadding = 4; constexpr int kIconHorizontalPadding = 12; // The size of the icon in NotificationItemView in dips. constexpr gfx::Size kProportionalIconViewSize(24, 24); // Text color of NotificationItemView's |message_|. constexpr SkColor kNotificationMessageTextColor = SkColorSetARGB(179, 0x5F, 0x63, 0x68); // Text color of NotificationItemView's |title_|. constexpr SkColor kNotificationTitleTextColor = SkColorSetARGB(230, 0x21, 0x23, 0x24); } // namespace NotificationItemView::NotificationItemView( NotificationItemView::Delegate* delegate, message_center::SlideOutController::Delegate* slide_out_controller_delegate, const base::string16& title, const base::string16& message, const gfx::Image& icon, const std::string& notification_id) : delegate_(delegate), slide_out_controller_( std::make_unique<message_center::SlideOutController>( this, slide_out_controller_delegate)), title_(title), message_(message), notification_id_(notification_id) { DCHECK(delegate_); DCHECK(slide_out_controller_delegate); // Paint to a new layer so |slide_out_controller_| can control the opacity. SetPaintToLayer(); layer()->SetFillsBoundsOpaquely(true); SetBorder(views::CreateEmptyBorder( gfx::Insets(kNotificationVerticalPadding, kNotificationHorizontalPadding, kNotificationVerticalPadding, kIconHorizontalPadding))); SetBackground(views::CreateSolidBackground(SK_ColorWHITE)); text_container_ = new views::View(); text_container_->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical)); AddChildView(text_container_); title_label_ = new views::Label(title_); title_label_->SetEnabledColor(kNotificationTitleTextColor); title_label_->SetLineHeight(kNotificationItemTextLineHeight); title_label_->SetHorizontalAlignment(gfx::ALIGN_LEFT); text_container_->AddChildView(title_label_); message_label_ = new views::Label(message_); message_label_->SetEnabledColor(kNotificationMessageTextColor); message_label_->SetLineHeight(kNotificationItemTextLineHeight); message_label_->SetHorizontalAlignment(gfx::ALIGN_LEFT); text_container_->AddChildView(message_label_); proportional_icon_view_ = new message_center::ProportionalImageView(kProportionalIconViewSize); AddChildView(proportional_icon_view_); proportional_icon_view_->SetImage(icon.AsImageSkia(), kProportionalIconViewSize); } NotificationItemView::~NotificationItemView() = default; void NotificationItemView::UpdateContents(const base::string16& title, const base::string16& message, const gfx::Image& icon) { if (title_ != title) { title_ = title; title_label_->SetText(title_); } if (message_ != message) { message_ = message; message_label_->SetText(message_); } proportional_icon_view_->SetImage(icon.AsImageSkia(), kProportionalIconViewSize); } gfx::Size NotificationItemView::CalculatePreferredSize() const { return gfx::Size(views::MenuConfig::instance().touchable_menu_width, kNotificationItemViewHeight); } void NotificationItemView::Layout() { gfx::Insets insets = GetInsets(); // Enforce |text_container_| width, if necessary the labels will elide as a // result of |text_container_| being too small to hold the full width of its // children labels. const gfx::Size text_container_size( views::MenuConfig::instance().touchable_menu_width - kNotificationHorizontalPadding - kIconHorizontalPadding * 2 - kProportionalIconViewSize.width(), title_label_->GetPreferredSize().height() + message_label_->GetPreferredSize().height()); text_container_->SetBounds(insets.left(), insets.top(), text_container_size.width(), text_container_size.height()); proportional_icon_view_->SetBounds( width() - insets.right() - kProportionalIconViewSize.width(), insets.top() + kIconVerticalPadding, kProportionalIconViewSize.width(), kProportionalIconViewSize.height()); } bool NotificationItemView::OnMousePressed(const ui::MouseEvent& event) { return true; } bool NotificationItemView::OnMouseDragged(const ui::MouseEvent& event) { return true; } void NotificationItemView::OnMouseReleased(const ui::MouseEvent& event) { gfx::Point location(event.location()); views::View::ConvertPointToScreen(this, &location); if (!event.IsOnlyLeftMouseButton() || !GetBoundsInScreen().Contains(location)) { return; } delegate_->ActivateNotificationAndClose(notification_id_); } void NotificationItemView::OnGestureEvent(ui::GestureEvent* event) { // Drag gestures are handled by |slide_out_controller_|. switch (event->type()) { case ui::ET_GESTURE_TAP: event->SetHandled(); delegate_->ActivateNotificationAndClose(notification_id_); return; default: return; } } } // namespace ash
7e5ed687c86bff103e627f51d17858d9f32dee0f
2bf70fea41c01477d93fa4f6cb64809a74e643e0
/CSE-2422/27.4.21/main.cpp
28b9e12c42f537c87fadff72075a930a212d896d
[]
no_license
Shafiahuma/UVA
3f6fc1517f1e0c09b4e8fcb8f383e8a3e6975a8e
94b179366fc33a6aac3f7465be3a3fa569816144
refs/heads/main
2023-04-26T00:32:54.148880
2021-05-24T07:03:00
2021-05-24T07:03:00
370,254,559
0
0
null
null
null
null
UTF-8
C++
false
false
1,699
cpp
/*Fractional Knapsack using Greedy Method*/ #include<stdio.h> void knapsack(int n,float profit[],float weight[],float M){ float x[20],tp=0; int i,j; printf("\nEntered Items are :\n "); printf(" Value\t\t\tProfit:"); printf("\n---------------------------\n"); for(i=0;i<n;i++){ printf("%f\t\t\t%f\n",profit[i],weight[i]); } for(i=0;i<n;i++) x[i]=0.0; for(i=0;i<n;i++){ if(weight[i]>M) break; else { x[i]=1.0; tp+=profit[i]; M-=weight[i]; } } if(i<n){ x[i]=M/weight[i]; } tp+=x[i]*profit[i]; printf("\n\nProfit Vector is : "); for(i=0;i<n;i++) printf("%f\t",x[i]); printf("\n"); printf("\nTotal Profit : %f",tp); } int main(){ float weight[20],profit[20],ratio[20],capacity,temp; int n,i,j; printf("\nEnter no of items : "); scanf("%d",&n); printf("\nEnter Capacity : "); scanf("%f",&capacity); printf("\nEnter Weight and Profit : "); for(i=0;i<n;i++){ printf("\nEnter Weight and Profit for item%d : ",i); scanf("%f %f",&weight[i],&profit[i]); } for(i=0;i<n;i++) ratio[i]=profit[i]/weight[i]; for(i=0;i<n;i++) for(j=i+1;j<n;j++){ if(ratio[i]<ratio[j]){ temp=ratio[j]; ratio[j]=ratio[i]; ratio[i]=temp; temp=weight[j]; weight[j]=weight[i]; weight[i]=temp; temp=profit[j]; profit[j]=profit[i]; profit[i]=temp; } } knapsack(n,profit,weight,capacity); return(0); }
49cd13e88df1778f3f7dc732c78d96b1cc7db253
06e3cbf6440cc2aea46100c3a5e8f5b26869c80d
/data_check/EnergyLoss.h
bfe9790eb21e7dcf7a2698f3e427a50e0ebf520f
[]
no_license
LasDes/RPC_Geant4
c3615a852ee9776900345453128f4c8586280a6b
9e17791f2f9423b8d9296e3d74d845688aae8977
refs/heads/master
2021-06-13T03:33:51.281032
2017-02-10T07:44:42
2017-02-10T07:44:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,038
h
//Written by Rohith Saradhy #include <iostream> #include <fstream> #include <string> #include <math.h> using namespace std; #ifndef ENERGYLOSS_H #define ENERGYLOSS_H double density(double b,double C,double x0,double x1,double a ,double k, double d,bool conductor) { double x = log(b/pow((1-pow(b,2)),0.5))/log(10); if(x>=x1) { return 2*(log(10))*x - C; } else if(x<x1 && x>=x0) { return 2*(log(10))*x - C + a*pow((x1-x),k); } else if(x<x0 && conductor==false) { return 0; } else { return d*pow(10,2*(x-x0)); } } // function for shell correction double shell(double b,double I) { double n= b/pow((1-pow(b,2)),0.5) ; if(n>0.13) { return (0.422377*pow(n,-2) +0.0304043*pow(n,-4)-0.00038106*pow(n,-6))*pow(10,-6)*pow(I,2)+(3.858019*pow(n,-2)-0.1667989*pow(n,-4)+0.00157955*pow(n,-6))*pow(10,-9)*pow(I,3); } else{ return 0; } } double EnergyLoss(double p[10],double d[], bool conductor) { double b=p[4]; p[6] = density(p[4],d[0],d[1],d[2],d[3],d[4],d[5],conductor); //density(double b,double C,double x0,double x1,double a ,double k, double d,bool conductor) p[7] =shell(b,p[5]); return ((0.307*p[0]*(pow(p[1],2))*p[2])/(p[3]*(pow(b,2))))*(log((1021997.82*(pow(b,2)))/(p[5]*(1-(pow(b,2)))))-(pow(b,2)) -p[6]/2 -p[7]/p[2]); } double EnergyLossArCO2(double p[],double percentCO2) { double dAr[6]={11.948,1.7635,4.4855,0.1971,2.9618,0.0}; double dC[6]={3.155,0.048,2.5387,0.2076,2.9532,0.14}; double dO[6]={10.7004,1.7541,4.3213,0.1178,3.2913,0.0}; double loss_energy, ar,c,o,co2; // for Argon p[0]=0.00166; p[2]=18; p[3]=39.947; p[5]=188; ar = EnergyLoss(p,dAr,false); // for Carbon p[0]=1.7; p[2]=6; p[3]=12.01115; p[5]=78; c = EnergyLoss(p,dC,false); // for Oxygen p[0]=0.00133; p[2]=8; p[3]=15.9994; p[5]=95; o = EnergyLoss(p,dO,false); co2 = 0.001977*((12.01115/(44.01*1.7))*c + (2*15.9994/(44.01*0.00133))*o); loss_energy =(1-(percentCO2/100))*ar +(percentCO2/100)*co2; return loss_energy; } #endif
[ "rohithsaradhy" ]
rohithsaradhy
b1452f8614bd5be63cd4630c964f412ea632532b
67281c684a1722151cfdbbba2f09c215b2bb7b19
/greedy/candyshop.cpp
17904ca8fc30efaeced7b003226a47d40f33b0df
[]
no_license
ritikdhasmana/DS-Algo
e20d388de977e3f8a24fe0e1e7612275041c7e3d
c86e63cc5b868b391888d4b4995a39a00cf21aad
refs/heads/main
2023-06-29T03:31:36.117050
2021-08-06T05:27:26
2021-08-06T05:27:26
393,258,107
2
0
null
null
null
null
UTF-8
C++
false
false
1,688
cpp
/*In a candy store, there are N different types of candies available and the prices of all the N different types of candies are provided to you. You are now provided with an attractive offer. You can buy a single candy from the store and get at most K other candies ( all are different types ) for free. Now you have to answer two questions. Firstly, you have to find what is the minimum amount of money you have to spend to buy all the N different candies. Secondly, you have to find what is the maximum amount of money you have to spend to buy all the N different candies. In both the cases you must utilize the offer i.e. you buy one candy and get K other candies for free.*/ #include<bits/stdc++.h> using namespace std; class Solution { public: vector<int> candyStore(int candies[], int N, int K) { // Write Your Code here int num=ceil((double)N/(K+1)); vector<int> v; // cout<<num<<endl; int ans=0; sort(candies,candies +N); for(int i=0;i<num;i++) { ans+=candies[i]; } v.push_back(ans); ans=0; for(int i=N-1;i>=N-num;i--)ans+=candies[i]; v.push_back(ans); return v; } }; // { Driver Code Starts. int main() { int t; cin >> t; while (t--) { int N, K; cin >> N >> K; int candies[N]; for (int i = 0; i < N; i++) { cin >> candies[i]; } Solution ob; vector<int> cost = ob.candyStore(candies, N, K); cout << cost[0] << " " << cost[1] << endl; } return 0; } // } Driver Code Ends
134140c345f9faa09aef2b551b3f4338e30d66b8
c0616d556e33ef70e310030cc63d99bc2c00c65e
/高晨雨-Plan_A/Uva548.cpp
d87b185cf6f1972848111dea40f567e436e1c4e8
[]
no_license
CSWithJoy/Week-03-04-Coding-Training
7aad7749ab4a1a5214729ff3aaffd20863fccc98
b75bebcc1f3cf2017ee8b175cd1ce82963b1766d
refs/heads/master
2021-01-01T05:16:33.580710
2016-05-10T05:29:39
2016-05-10T05:29:39
56,973,674
0
7
null
2016-05-10T05:29:39
2016-04-24T13:43:22
C++
UTF-8
C++
false
false
1,210
cpp
//二叉树的重建 #include<iostream> #include<stdio.h> #include<algorithm> using namespace std; #define MAX 10005 int in_order[MAX],post_order[MAX],lch[MAX],rch[MAX]; int n; char s[MAX]; int build(int L1,int R1,int L2,int R2) { if(L1>R1) return 0; int root=post_order[R2];//后序遍历中的最后一个为根节点 int p=L1; while(in_order[p]!=root) p++; int cnt=p-L1; lch[root]=build(L1,p-1,L2,L2+cnt-1);//中序遍历的根节点左边是左子树部分 rch[root]=build(p+1,R1,L2+cnt,R2-1);//中序遍历的根节点右边为右子树部分 return root; } int init(char *s,int *v) { int top=0; for(int i=0;s[i];i++) { while(s[i]==' ') i++; v[top]=0; while(s[i]&&isdigit(s[i])) { v[top]=v[top]*10+s[i]-'0'; i++; } top++; if(!s[i]) break; } return top; } int best,best_sum; void DFS(int u,int sum) { sum+=u; if(!lch[u]&&!rch[u]) { if((sum<best_sum)||(sum==best_sum&&u<best)) { best=u; best_sum=sum; } } if(lch[u]) DFS(lch[u],sum); if(rch[u]) DFS(rch[u],sum); } int main() { while(gets(s)) { init(s,in_order); gets(s); n=init(s,post_order); build(0,n-1,0,n-1); best_sum=100000000; DFS(post_order[n-1],0); cout<<best<<endl; } return 0; }
753690aa3f093fb4e67903e9d7de097dc068876b
b22588340d7925b614a735bbbde1b351ad657ffc
/athena/Trigger/TrigTools/TrigInDetTrackFitter/TrigInDetTrackFitter/TrigL2HighPtTrackFitter.h
9ed6b5525c1fbcdba3690b26bc1b17398705de6a
[]
no_license
rushioda/PIXELVALID_athena
90befe12042c1249cbb3655dde1428bb9b9a42ce
22df23187ef85e9c3120122c8375ea0e7d8ea440
refs/heads/master
2020-12-14T22:01:15.365949
2020-01-19T03:59:35
2020-01-19T03:59:35
234,836,993
1
0
null
null
null
null
UTF-8
C++
false
false
1,322
h
/* Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ #ifndef __TRIG_L2_HIGH_PT_TRACK_FITTER_H__ #define __TRIG_L2_HIGH_PT_TRACK_FITTER_H__ #include "AthenaBaseComps/AthAlgTool.h" #include "GaudiKernel/MsgStream.h" #include "GaudiKernel/ToolHandle.h" #include "TrkDistributedKalmanFilter/TrkBaseNode.h" #include "TrkDistributedKalmanFilter/TrkTrackState.h" #include "TrigInDetTrackFitter/ITrigL2FastExtrapolationTool.h" #include "TrigInDetTrackFitter/ITrigL2TrackFittingTool.h" #include "TrkToolInterfaces/IRIO_OnTrackCreator.h" #include <vector> namespace Trk { class IRIO_OnTrackCreator; } class TrigL2HighPtTrackFitter : virtual public ITrigL2TrackFittingTool, public AthAlgTool { public: // standard AlgTool methods TrigL2HighPtTrackFitter(const std::string&,const std::string&,const IInterface*); virtual ~TrigL2HighPtTrackFitter(){}; // standard Athena methods StatusCode initialize(); StatusCode finalize(); Trk::TrkTrackState* fit(Trk::TrkTrackState*, std::vector<Trk::TrkBaseNode*>&, bool runSmoother=true); private: void m_recalibrateFilteringNode(Trk::TrkBaseNode*, Trk::TrkTrackState*); bool m_recalibrate; ToolHandle<ITrigL2FastExtrapolationTool> m_fastExtrapolator; ToolHandle<Trk::IRIO_OnTrackCreator> m_ROTcreator; }; #endif
d0850262991566ed0d0d0a570bea822d9848d435
8438f7731580fa5dfe6643e9cdfaa55a9e0a2c6a
/protara/PRatio/peakPicker.cpp
e66270a6e18a61c07aa940d2bd30091f2ea310b2
[]
no_license
guo-xuan/ProRata
84b5d016f9bb1a2b7d4c66010f5b58bf4c96719a
94d743a6c44f2abe48dc75b77750e6bb6f7eb1c0
refs/heads/master
2020-06-27T05:07:48.083670
2017-07-13T20:59:37
2017-07-13T20:59:37
97,048,530
0
0
null
null
null
null
UTF-8
C++
false
false
12,870
cpp
#include "../../protara/PRatio/peakPicker.h" PeakPicker::PeakPicker() { iRightValley = 0; iLeftValley = 0; dPeakHeightPPC = 0; bPeakValidity = false; iChroLength = 0; fLeftMS2Time = 0; fRightMS2Time = 0; iNumberofScansShifted = 0; } PeakPicker::~PeakPicker() { // destructor } bool PeakPicker::process( const vector< float > & vfMS2TimeInput, const vector< float > & vfRetentionTimeInput, vector< double > & vdTreatmentChroInput, vector< double > & vdReferenceChroInput ) { iChroLength = vfRetentionTimeInput.size(); if ( iChroLength <= ProRataConfig::getPeakPickerWindowSize() ) { cout << "ERROR! The input chromatograms have too few MS1 scans!" << endl; return false; } if( vdTreatmentChroInput.size() != iChroLength || vdReferenceChroInput.size() != iChroLength ) { cout << "ERROR! the input chromatograms are in different length!" << endl; return false; } if ( ( ProRataConfig::getPeakPickerWindowSize() % 2) == 0 ) { cout << "ERROR! The window size for Sav-Gol smoothing has to be odd! " << endl; return false; } if ( ProRataConfig::getPeakPickerWindowSize() < 3 ) { cout << "ERROR! The window size for Sav-Gol smoothing is too small! " << endl; return false; } vfRetentionTime = vfRetentionTimeInput; // set the earliest MS2 time and the last MS2 scan time // used for initialize left valley and right valley fLeftMS2Time = *( min_element( vfMS2TimeInput.begin(), vfMS2TimeInput.end() ) ); fRightMS2Time = *( max_element( vfMS2TimeInput.begin(), vfMS2TimeInput.end() ) ); // the fLeftMS2Time and fRightMS2Time have to be within the RT range if( fLeftMS2Time < vfRetentionTime.front() ) fLeftMS2Time = vfRetentionTime.front(); if( fRightMS2Time > vfRetentionTime.back() ) fRightMS2Time = vfRetentionTime.back(); if( (ProRataConfig::getLeftPeakShift() < 0.001) && (ProRataConfig::getRightPeakShift() < 0.001) ) { iNumberofScansShifted = 0; // compute the final vdCovarianceChro computeCovarianceChro( iNumberofScansShifted, vdTreatmentChroInput, vdReferenceChroInput ); // compute the final peak findPeak(); return true; } /* * detect peak shift */ int i; // the calcuated peak height in PPC for all tested peak shift // vector< double > vdPeakHeight; // vector< int > viScanShift; map< int, double > mScanShift2Height; // scans that shifts left is negative and scans that shifts right is positive for( i = 0; i < vfRetentionTime.size() - 3; i++ ) { if( (vfRetentionTime[i] - vfRetentionTime[0]) >= ProRataConfig::getLeftPeakShift() - 0.001) break; } int iScanShiftLeft = -i; for( i = (vfRetentionTime.size() - 1); i > 2; i-- ) { if( (vfRetentionTime.back() - vfRetentionTime[i]) >= ProRataConfig::getRightPeakShift() - 0.001) break; } int iScanShiftRight = vfRetentionTime.size() - i - 1; double dMaxPeakHeight = -100; for( i = iScanShiftLeft; i < ( iScanShiftRight + 1 ); ++i ) { // viScanShift.push_back( i ); computeCovarianceChro( i, vdTreatmentChroInput, vdReferenceChroInput ); findPeak(); mScanShift2Height[i] = dPeakHeightPPC; if( dPeakHeightPPC > dMaxPeakHeight ) dMaxPeakHeight = dPeakHeightPPC; // vdPeakHeight.push_back( dPeakHeightPPC ); } if( mScanShift2Height[ 0 ] > dMaxPeakHeight*0.9 ) { iNumberofScansShifted = 0; } else { iNumberofScansShifted = 0; bool bIsMaxFound = false; if( abs( iScanShiftLeft ) > iScanShiftRight ) { for( i = 0; i > ( iScanShiftLeft - 1 ); --i ) { if( mScanShift2Height[i] > dMaxPeakHeight*0.95 ) { iNumberofScansShifted = i; bIsMaxFound = true; break; } } if( !bIsMaxFound ) { for( i = 0; i < iScanShiftRight + 1 ; ++i ) { if( mScanShift2Height[i] > dMaxPeakHeight*0.95 ) { iNumberofScansShifted = i; break; } } } } else { for( i = 0; i < iScanShiftRight + 1 ; ++i ) { if( mScanShift2Height[i] > dMaxPeakHeight*0.95 ) { iNumberofScansShifted = i; bIsMaxFound = true; break; } } if( !bIsMaxFound ) { for( i = 0; i > ( iScanShiftLeft - 1 ); --i ) { if( mScanShift2Height[i] > dMaxPeakHeight*0.95 ) { iNumberofScansShifted = i; break; } } } } } // compute the final vdCovarianceChro computeCovarianceChro( iNumberofScansShifted, vdTreatmentChroInput, vdReferenceChroInput ); // compute the final peak findPeak(); // actually change the input vdReferenceChroInput shiftChro( iNumberofScansShifted, vdReferenceChroInput ); // cout << "bPeakValidity = " << boolalpha << bPeakValidity << endl; return true; } void PeakPicker::computeCovarianceChro( int iScanShiftReference, vector< double > vdTreatmentChroInput, vector< double > vdReferenceChroInput ) { vdCovarianceChro.clear(); vdCovarianceChro.resize( iChroLength, 0.0 ); // ensure all input chromatograms have the right length if( vdTreatmentChroInput.size() != iChroLength || vdReferenceChroInput.size() != iChroLength ) return; // shift vdReferenceChro for the iScanShiftReference number of scans shiftChro( iScanShiftReference, vdReferenceChroInput ); // compute noise level for treatment chro double dNoiseTreatmentChro = (*( min_element(vdTreatmentChroInput.begin(), vdTreatmentChroInput.end() ) )); dNoiseTreatmentChro = dNoiseTreatmentChro - 1; if( dNoiseTreatmentChro < 0 ) dNoiseTreatmentChro = 0; // compute noise level for reference chro double dNoiseReferenceChro = (*( min_element(vdReferenceChroInput.begin(), vdReferenceChroInput.end() ) )); dNoiseReferenceChro = dNoiseReferenceChro - 1; if( dNoiseReferenceChro < 0 ) dNoiseReferenceChro = 0; vector<double>::iterator itr; // substract the noise for treatment chro for( itr = vdTreatmentChroInput.begin(); itr != vdTreatmentChroInput.end(); itr++ ) *(itr) = *(itr) - dNoiseTreatmentChro; // substract the noise for reference chro for( itr = vdReferenceChroInput.begin(); itr != vdReferenceChroInput.end(); itr++ ) *(itr) = *(itr) - dNoiseReferenceChro; // Construct covariance chromatogram transform( vdTreatmentChroInput.begin(), vdTreatmentChroInput.end(), vdReferenceChroInput.begin(), vdCovarianceChro.begin(), multiplies<double>() ); Smoother smootherCovariance( ProRataConfig::getPeakPickerWindowSize(), ProRataConfig::getPeakPickerFOrder() ); smootherCovariance.smoothen( vdCovarianceChro ); } void PeakPicker::shiftChro( int iScanShift, vector< double > & vdChro ) { // no shift if( iScanShift == 0 ) return; // check input validity if( abs( iScanShift ) > vdChro.size() - 3 || vdChro.size() < 3 ) return; double dTempIntensity = 0; // shift left if( iScanShift < 0 ) { dTempIntensity = vdChro.back(); vdChro.erase( vdChro.begin(), vdChro.begin() + abs( iScanShift ) ); vdChro.insert( vdChro.end(), abs( iScanShift ), dTempIntensity ); } // shift right if( iScanShift > 0 ) { dTempIntensity = vdChro.front(); vdChro.erase( ( vdChro.end() - iScanShift ) , vdChro.end() ); vdChro.insert( vdChro.begin(), iScanShift, dTempIntensity ); } } void PeakPicker::findPeak() { int iOffset = ( ProRataConfig::getPeakPickerWindowSize() - 1) / 2; // initialize iRightValley; for( iRightValley = ( iChroLength - 2 ) ; iRightValley > ProRataConfig::getPeakPickerWindowSize(); --iRightValley ) { if ( vfRetentionTime[ iRightValley ] < fRightMS2Time ) break; } ++iRightValley; // initialize iLeftValley for( iLeftValley = 1 ; iLeftValley < (iChroLength - ProRataConfig::getPeakPickerWindowSize() - 1); ++iLeftValley ) { if ( vfRetentionTime[ iLeftValley ] > fLeftMS2Time ) break; } --iLeftValley; // compute iLeftValley and iRightValley iRightValley = findNextRightValley( iRightValley ); iLeftValley = findNextLeftValley( iLeftValley ); double dCovarianceCutOff = median( vdCovarianceChro ); vector<double>::iterator itrBegin = vdCovarianceChro.begin(); double dHalfPeakIntensity = ( *(max_element( itrBegin + iLeftValley, itrBegin + iRightValley + 1 ) ) - dCovarianceCutOff ) * 0.5 ; double dLeftValleyIntensity = vdCovarianceChro.at( iLeftValley ) - dCovarianceCutOff; double dRightValleyIntensity = vdCovarianceChro.at( iRightValley ) - dCovarianceCutOff; bool bMoveLeftValley = ( (dLeftValleyIntensity > dHalfPeakIntensity) && iLeftValley > iOffset ); bool bMoveRightValley = ( (dRightValleyIntensity > dHalfPeakIntensity) && iRightValley < (iChroLength - iOffset - 1) ); bool bMoveLeftOrRight = ( vdCovarianceChro.at(iLeftValley) > vdCovarianceChro.at(iRightValley) ); while ( bMoveLeftValley || bMoveRightValley ) { if ( bMoveLeftValley && ( bMoveLeftOrRight || !bMoveRightValley ) ) iLeftValley = findNextLeftValley( iLeftValley ); if ( (!bMoveLeftValley || !bMoveLeftOrRight ) && bMoveRightValley ) iRightValley = findNextRightValley( iRightValley ); dHalfPeakIntensity = ( *(max_element(itrBegin + iLeftValley, itrBegin + iRightValley +1 ) ) - dCovarianceCutOff ) * 0.5 ; dLeftValleyIntensity = vdCovarianceChro.at( iLeftValley ) - dCovarianceCutOff; dRightValleyIntensity = vdCovarianceChro.at( iRightValley ) - dCovarianceCutOff; bMoveLeftValley = ( (dLeftValleyIntensity > dHalfPeakIntensity) && iLeftValley > iOffset ) ; bMoveRightValley = ( (dRightValleyIntensity > dHalfPeakIntensity) && iRightValley < (iChroLength - iOffset - 1) ) ; bMoveLeftOrRight = ( vdCovarianceChro.at(iLeftValley) > vdCovarianceChro.at(iRightValley) ); } // compute bPeakValidity bool bIsPeakBelowNoise = ( *( max_element( itrBegin + iLeftValley, itrBegin + iRightValley + 1 ) ) ) < dCovarianceCutOff; float fPeakWidth = vfRetentionTime[ iRightValley ] - vfRetentionTime[ iLeftValley ]; // float fChroDuration = vfRetentionTime.back() - vfRetentionTime.front() ; // minimal peak width = 0.1 min // maximal peak width = 8 min bool bIsPeakTooSmall = fPeakWidth < ( 0.1 ); bool bIsPeakTooBroad = fPeakWidth > ( 8 ); if ( bIsPeakBelowNoise || bIsPeakTooSmall || bIsPeakTooBroad ) bPeakValidity = false; else bPeakValidity = true; // compute dPeakHeightPPC dPeakHeightPPC = ( *( max_element( itrBegin + iLeftValley, itrBegin + iRightValley + 1) ) ) - ( ( vdCovarianceChro.at(iLeftValley) + vdCovarianceChro.at(iRightValley) )/2 ); } double PeakPicker::median( vector<double> vdData ) { if( vdData.size() < 1 ) return 0; sort( vdData.begin(), vdData.end() ); return *( vdData.begin() + (vdData.size() / 2 ) ); } int PeakPicker::findNextLeftValley( int iCurrentLeftValley ) { double dCurrentMinimumIntensity; double dCurrentValleyIntensity; int iOffset = ( ProRataConfig::getPeakPickerWindowSize() - 1) / 2; bool bIsTrueValley = false; int iValleyMinusOffset; int iValleyPlusOffset; vector<double>::iterator itrBegin; itrBegin = vdCovarianceChro.begin(); while ( (iCurrentLeftValley > iOffset ) && ( !bIsTrueValley ) ) { iCurrentLeftValley--; dCurrentValleyIntensity = *( itrBegin + iCurrentLeftValley ); iValleyMinusOffset = max( 0, iCurrentLeftValley - iOffset ); iValleyPlusOffset = min( iChroLength -1,iCurrentLeftValley + iOffset ); // Add one, because // min_element finds the smallest element in the range [first, last). // Note the last element is not included. dCurrentMinimumIntensity = *( min_element(itrBegin + iValleyMinusOffset, itrBegin + iValleyPlusOffset + 1 ) ); if ( dCurrentMinimumIntensity >= dCurrentValleyIntensity ) bIsTrueValley = true; } return iCurrentLeftValley; } int PeakPicker::findNextRightValley( int iCurrentRightValley ) { double dCurrentMinimumIntensity; double dCurrentValleyIntensity; int iOffset = ( ProRataConfig::getPeakPickerWindowSize() - 1) / 2; bool bIsTrueValley = false; int iValleyMinusOffset; int iValleyPlusOffset; vector<double>::iterator itrBegin; itrBegin = vdCovarianceChro.begin(); while ( (iCurrentRightValley < ( iChroLength - iOffset - 1 )) && (!bIsTrueValley) ) { iCurrentRightValley++; dCurrentValleyIntensity = *( itrBegin + iCurrentRightValley ); iValleyMinusOffset = max( 0, iCurrentRightValley - iOffset ); iValleyPlusOffset = min( iChroLength - 1, iCurrentRightValley + iOffset ) ; dCurrentMinimumIntensity = *( min_element(itrBegin + iValleyMinusOffset, itrBegin + iValleyPlusOffset + 1 ) ); if ( dCurrentMinimumIntensity >= dCurrentValleyIntensity ) bIsTrueValley = true; } return iCurrentRightValley; }
debb4c968a272fbe2fb3d7e7ba81c57914e26ce3
bf78b4d9842faeeeb1d715161d71f137a718b7f1
/core/include/engine/Solver_LBFGS_Atlas.hpp
0f2f85fe115be6c21c1b5fa017b48e7af29baa3f
[ "MIT" ]
permissive
FermiQ/spirit
d7eecc9e3db4cb206a7d9d852f92ec7206caf336
14ed7782bd23f4828bf23ab8136ae31a21037bb3
refs/heads/master
2023-06-28T02:43:46.331959
2021-01-11T18:06:06
2021-01-11T18:06:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,694
hpp
#pragma once #ifndef SOLVER_LBFGS_ATLAS_HPP #define SOLVER_LBFGS_ATLAS_HPP #include <utility/Constants.hpp> // #include <utility/Exception.hpp> #include <engine/Backend_par.hpp> #include <algorithm> using namespace Utility; template <> inline void Method_Solver<Solver::LBFGS_Atlas>::Initialize () { this->n_lbfgs_memory = 3; // how many updates the solver tracks to estimate the hessian this->atlas_updates = std::vector<field<vector2field>>( this->noi, field<vector2field>( this->n_lbfgs_memory, vector2field(this->nos, { 0,0 } ) )); this->grad_atlas_updates = std::vector<field<vector2field>>( this->noi, field<vector2field>( this->n_lbfgs_memory, vector2field(this->nos, { 0,0 } ) )); this->rho = scalarfield( this->n_lbfgs_memory, 0 ); this->alpha = scalarfield( this->n_lbfgs_memory, 0 ); this->forces = std::vector<vectorfield>( this->noi, vectorfield( this->nos, { 0,0,0 } ) ); this->forces_virtual = std::vector<vectorfield>( this->noi, vectorfield( this->nos, { 0,0,0 } ) ); this->atlas_coords3 = std::vector<scalarfield>( this->noi, scalarfield(this->nos, 1) ); this->atlas_directions = std::vector<vector2field>( this->noi, vector2field( this->nos, { 0,0 } ) ); this->atlas_residuals = std::vector<vector2field>( this->noi, vector2field( this->nos, { 0,0 } ) ); this->atlas_residuals_last = std::vector<vector2field>( this->noi, vector2field( this->nos, { 0,0 } ) ); this->atlas_q_vec = std::vector<vector2field>( this->noi, vector2field( this->nos, { 0,0 } ) ); this->maxmove = 0.05; this->local_iter = 0; for (int img=0; img<this->noi; img++) { // Choose atlas3 coordinates for(int i=0; i<this->nos; i++) { this->atlas_coords3[img][i] = (*this->configurations[img])[i][2] > 0 ? 1.0 : -1.0; // Solver_Kernels::ncg_spins_to_atlas( *this->configurations[i], this->atlas_coords[i], this->atlas_coords3[i] ); } } } /* Stereographic coordinate system implemented according to an idea of F. Rybakov TODO: reference painless conjugate gradients See also Jorge Nocedal and Stephen J. Wright 'Numerical Optimization' Second Edition, 2006 (p. 121) */ template <> inline void Method_Solver<Solver::LBFGS_Atlas>::Iteration() { int noi = configurations.size(); int nos = (*configurations[0]).size(); // Current force this->Calculate_Force( this->configurations, this->forces ); for( int img=0; img<this->noi; img++ ) { auto& image = *this->configurations[img]; auto& grad_ref = this->atlas_residuals[img]; auto fv = this->forces_virtual[img].data(); auto f = this->forces[img].data(); auto s = image.data(); Backend::par::apply( this->nos, [f,fv,s] SPIRIT_LAMBDA (int idx) { fv[idx] = s[idx].cross(f[idx]); } ); Solver_Kernels::atlas_calc_gradients(grad_ref, image, this->forces[img], this->atlas_coords3[img]); } // Calculate search direction Solver_Kernels::lbfgs_get_searchdir(this->local_iter, this->rho, this->alpha, this->atlas_q_vec, this->atlas_directions, this->atlas_updates, this->grad_atlas_updates, this->atlas_residuals, this->atlas_residuals_last, this->n_lbfgs_memory, maxmove); scalar a_norm_rms = 0; // Scale by averaging for(int img=0; img<noi; img++) { a_norm_rms = std::max(a_norm_rms, scalar( sqrt( Backend::par::reduce(this->atlas_directions[img], [] SPIRIT_LAMBDA (const Vector2 & v){ return v.squaredNorm(); }) / nos ))); } scalar scaling = (a_norm_rms > maxmove) ? maxmove/a_norm_rms : 1.0; for(int img=0; img<noi; img++) { auto d = atlas_directions[img].data(); Backend::par::apply(nos, [scaling, d] SPIRIT_LAMBDA (int idx){ d[idx] *= scaling; }); } // Rotate spins Solver_Kernels::atlas_rotate( this->configurations, this->atlas_coords3, this->atlas_directions ); if(Solver_Kernels::ncg_atlas_check_coordinates(this->configurations, this->atlas_coords3, -0.6)) { Solver_Kernels::lbfgs_atlas_transform_direction(this->configurations, this->atlas_coords3, this->atlas_updates, this->grad_atlas_updates, this->atlas_directions, this->atlas_residuals_last, this->rho); } } template <> inline std::string Method_Solver<Solver::LBFGS_Atlas>::SolverName() { return "LBFGS_Atlas"; } template <> inline std::string Method_Solver<Solver::LBFGS_Atlas>::SolverFullName() { return "Limited memory Broyden-Fletcher-Goldfarb-Shanno using stereographic atlas"; } #endif
32cecb39d31ff8d10cb14e4644b1569a91297d07
63a6335819200bd4eef3fea8ec3cf0e7d77d7d82
/EmptyGeneralTesting/source/Variable.h
c44e9cc130242eb53aec8750517847e5cb7959cf
[]
no_license
CupsAndBottles/CS3201-MiniSPA
289448b46e60bb00a36c9c31d455e0dfd42f04bb
37749775ff5007fc15e472d5a840bfb518301a4e
refs/heads/master
2021-05-08T21:58:18.387040
2015-11-12T04:08:44
2015-11-12T04:08:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
592
h
#pragma once #include <string> #include <vector> #include <algorithm> #include <iostream> using namespace std; class Variable { public: Variable(); ~Variable(); int getindex(); string getVarName(); vector<int> getModifiedBy(); vector<int> getUsedBy(); vector<int> getProcNames(); void insertIntoModify(int modify); void insertIntoUses(int use); void insertIntoProc(int procName); void setVarName(string varName); void sortVectors(vector<int> list); private: int index; string varName; vector<int> procNamesList; vector<int> usedByList; vector<int> modifiedByList; };
39dd3052a53f14160d32bddcb25971dba76d2df2
3b9b4049a8e7d38b49e07bb752780b2f1d792851
/src/third_party/WebKit/Source/core/css/FontFaceSetLoadEvent.h
da7407242133e4d68f8a047eedabb45ede1d83b7
[ "BSD-3-Clause", "Apache-2.0", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "MIT" ]
permissive
webosce/chromium53
f8e745e91363586aee9620c609aacf15b3261540
9171447efcf0bb393d41d1dc877c7c13c46d8e38
refs/heads/webosce
2020-03-26T23:08:14.416858
2018-08-23T08:35:17
2018-09-20T14:25:18
145,513,343
0
2
Apache-2.0
2019-08-21T22:44:55
2018-08-21T05:52:31
null
UTF-8
C++
false
false
2,872
h
/* * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef FontFaceSetLoadEvent_h #define FontFaceSetLoadEvent_h #include "core/css/FontFace.h" #include "core/css/FontFaceSetLoadEventInit.h" #include "core/dom/DOMError.h" #include "core/events/Event.h" #include "wtf/PassRefPtr.h" #include "wtf/RefPtr.h" namespace blink { class FontFaceSetLoadEvent final : public Event { DEFINE_WRAPPERTYPEINFO(); public: static FontFaceSetLoadEvent* create() { return new FontFaceSetLoadEvent(); } static FontFaceSetLoadEvent* create(const AtomicString& type, const FontFaceSetLoadEventInit& initializer) { return new FontFaceSetLoadEvent(type, initializer); } static FontFaceSetLoadEvent* createForFontFaces(const AtomicString& type, const FontFaceArray& fontfaces = FontFaceArray()) { return new FontFaceSetLoadEvent(type, fontfaces); } ~FontFaceSetLoadEvent() override; FontFaceArray fontfaces() const { return m_fontfaces; } const AtomicString& interfaceName() const override; DECLARE_VIRTUAL_TRACE(); private: FontFaceSetLoadEvent(); FontFaceSetLoadEvent(const AtomicString&, const FontFaceArray&); FontFaceSetLoadEvent(const AtomicString&, const FontFaceSetLoadEventInit&); FontFaceArray m_fontfaces; }; } // namespace blink #endif // FontFaceSetLoadEvent_h
2367ac3aa008eee21925a76ed700941d35f6ee7d
0e19b378b2e043ddc50ef1497779a01221fc6b78
/Classes/models/paths/square/SquarePath.h
f764f2f92270ac639296ebfb5af915cb8ca8ff55
[]
no_license
DadTraining/YearEnd2018_Group3_the.hopeful.letter
a0c9e9ee7d4c01f02cce370df56b79e439ede414
8187d6916299a728ce62938bc591768a25ad1517
refs/heads/master
2020-04-18T06:04:24.175103
2019-03-08T06:47:36
2019-03-08T06:47:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,264
h
#pragma once #include "models/paths/core/CorePath.h" #include "cocos2d.h" class SquarePath : public CorePath { private: cocos2d::Vec2 mTouchLocation; cocos2d::Vec2 mPoint1; cocos2d::Vec2 mPoint2; cocos2d::Vec2 mPoint3; cocos2d::Vec2 mPoint4; int mLength; int mDirection; /*Change variables here to fit your needs*/ int mSquareWidthSize; // corresponding to your picture's width and height int mSquareHeightSize; // corresponding to your picture's width and height /**************************************/ bool OnTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event) override; void OnTouchEnded(cocos2d::Touch *touch, cocos2d::Event *event) override; public: SquarePath(cocos2d::Scene* scene, const int& squareWidthSize, const std::string& pathNamePath, const std::string& balloonNamePath, const float& pathPositionY, const float& ballooonMovingSpeed); /** *change the balloon direction when it's moving clockwise * */ void ClockwiseDirection(); /** *change the balloon direction when it's moving counter clockwise * */ void CounterClockwiseDirection(); /** *move the balloon * */ void moveBalloon(int speed); /** * Update every single frame */ void Update() override; };
c05c6820c26d9e526214ca8bb32a80ef83f9d4ef
1686fa830ebabd71e455372dd5335b5e60c027d4
/Tutorial 39_Particle Systems/Engine/systemclass.cpp
c87399e96ddbeeabd3652a4d72bb8be98adc2b7f
[]
no_license
matt77hias/RasterTek
ec7892d8871641cf434d3ec1c2c6dbb688952136
f65a3eb7bfe4c2419dbece9fce8adebd92c580f9
refs/heads/master
2023-07-23T04:02:42.010575
2023-07-10T07:05:12
2023-07-10T07:05:12
93,774,234
125
36
null
2023-07-10T07:35:04
2017-06-08T17:18:25
C++
UTF-8
C++
false
false
7,192
cpp
//////////////////////////////////////////////////////////////////////////////// // Filename: systemclass.cpp //////////////////////////////////////////////////////////////////////////////// #include "systemclass.h" SystemClass::SystemClass() { m_Input = 0; m_Graphics = 0; m_Timer = 0; } SystemClass::SystemClass(const SystemClass& other) { } SystemClass::~SystemClass() { } bool SystemClass::Initialize() { int screenWidth, screenHeight; bool result; // Initialize the width and height of the screen to zero before sending the variables into the function. screenWidth = 0; screenHeight = 0; // Initialize the windows api. InitializeWindows(screenWidth, screenHeight); // Create the input object. This object will be used to handle reading the keyboard input from the user. m_Input = new InputClass; if(!m_Input) { return false; } // Initialize the input object. m_Input->Initialize(); // Create the graphics object. This object will handle rendering all the graphics for this application. m_Graphics = new GraphicsClass; if(!m_Graphics) { return false; } // Initialize the graphics object. result = m_Graphics->Initialize(screenWidth, screenHeight, m_hwnd); if(!result) { return false; } // Create the timer object. m_Timer = new TimerClass; if(!m_Timer) { return false; } // Initialize the timer object. result = m_Timer->Initialize(); if(!result) { MessageBox(m_hwnd, L"Could not initialize the Timer object.", L"Error", MB_OK); return false; } return true; } void SystemClass::Shutdown() { // Release the timer object. if(m_Timer) { delete m_Timer; m_Timer = 0; } // Release the graphics object. if(m_Graphics) { m_Graphics->Shutdown(); delete m_Graphics; m_Graphics = 0; } // Release the input object. if(m_Input) { delete m_Input; m_Input = 0; } // Shutdown the window. ShutdownWindows(); return; } void SystemClass::Run() { MSG msg; bool done, result; // Initialize the message structure. ZeroMemory(&msg, sizeof(MSG)); // Loop until there is a quit message from the window or the user. done = false; while(!done) { // Handle the windows messages. if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } // If windows signals to end the application then exit out. if(msg.message == WM_QUIT) { done = true; } else { // Otherwise do the frame processing. result = Frame(); if(!result) { done = true; } } } return; } bool SystemClass::Frame() { bool result; // Update the system stats. m_Timer->Frame(); // Check if the user pressed escape and wants to exit the application. if(m_Input->IsKeyDown(VK_ESCAPE)) { return false; } // Do the frame processing for the graphics object. result = m_Graphics->Frame(m_Timer->GetTime()); if(!result) { return false; } return true; } LRESULT CALLBACK SystemClass::MessageHandler(HWND hwnd, UINT umsg, WPARAM wparam, LPARAM lparam) { switch(umsg) { // Check if a key has been pressed on the keyboard. case WM_KEYDOWN: { // If a key is pressed send it to the input object so it can record that state. m_Input->KeyDown((unsigned int)wparam); return 0; } // Check if a key has been released on the keyboard. case WM_KEYUP: { // If a key is released then send it to the input object so it can unset the state for that key. m_Input->KeyUp((unsigned int)wparam); return 0; } // Any other messages send to the default message handler as our application won't make use of them. default: { return DefWindowProc(hwnd, umsg, wparam, lparam); } } } void SystemClass::InitializeWindows(int& screenWidth, int& screenHeight) { WNDCLASSEX wc; DEVMODE dmScreenSettings; int posX, posY; // Get an external pointer to this object. ApplicationHandle = this; // Get the instance of this application. m_hinstance = GetModuleHandle(NULL); // Give the application a name. m_applicationName = L"Engine"; // Setup the windows class with default settings. wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = m_hinstance; wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); wc.hIconSm = wc.hIcon; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wc.lpszMenuName = NULL; wc.lpszClassName = m_applicationName; wc.cbSize = sizeof(WNDCLASSEX); // Register the window class. RegisterClassEx(&wc); // Determine the resolution of the clients desktop screen. screenWidth = GetSystemMetrics(SM_CXSCREEN); screenHeight = GetSystemMetrics(SM_CYSCREEN); // Setup the screen settings depending on whether it is running in full screen or in windowed mode. if(FULL_SCREEN) { // If full screen set the screen to maximum size of the users desktop and 32bit. memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); dmScreenSettings.dmSize = sizeof(dmScreenSettings); dmScreenSettings.dmPelsWidth = (unsigned long)screenWidth; dmScreenSettings.dmPelsHeight = (unsigned long)screenHeight; dmScreenSettings.dmBitsPerPel = 32; dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; // Change the display settings to full screen. ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN); // Set the position of the window to the top left corner. posX = posY = 0; } else { // If windowed then set it to 800x600 resolution. screenWidth = 800; screenHeight = 600; // Place the window in the middle of the screen. posX = (GetSystemMetrics(SM_CXSCREEN) - screenWidth) / 2; posY = (GetSystemMetrics(SM_CYSCREEN) - screenHeight) / 2; } // Create the window with the screen settings and get the handle to it. m_hwnd = CreateWindowEx(WS_EX_APPWINDOW, m_applicationName, m_applicationName, WS_POPUP, posX, posY, screenWidth, screenHeight, NULL, NULL, m_hinstance, NULL); // Bring the window up on the screen and set it as main focus. ShowWindow(m_hwnd, SW_SHOW); SetForegroundWindow(m_hwnd); SetFocus(m_hwnd); // Hide the mouse cursor. ShowCursor(false); return; } void SystemClass::ShutdownWindows() { // Show the mouse cursor. ShowCursor(true); // Fix the display settings if leaving full screen mode. if(FULL_SCREEN) { ChangeDisplaySettings(NULL, 0); } // Remove the window. DestroyWindow(m_hwnd); m_hwnd = NULL; // Remove the application instance. UnregisterClass(m_applicationName, m_hinstance); m_hinstance = NULL; // Release the pointer to this class. ApplicationHandle = NULL; return; } LRESULT CALLBACK WndProc(HWND hwnd, UINT umessage, WPARAM wparam, LPARAM lparam) { switch(umessage) { // Check if the window is being destroyed. case WM_DESTROY: { PostQuitMessage(0); return 0; } // Check if the window is being closed. case WM_CLOSE: { PostQuitMessage(0); return 0; } // All other messages pass to the message handler in the system class. default: { return ApplicationHandle->MessageHandler(hwnd, umessage, wparam, lparam); } } }
0e4c1524371c41fe411594a74553caf520e28290
6c9215424549ed2f5d8d34ca12cdaa191a1de2c3
/LoginFrame.cpp
40dcc4c4e27f4dd4f1115c32bcbd12b64655a516
[]
no_license
JakeKalstad/HushClient
e5d4caf97053a94000fcc1ec68b288280d780558
d02bb23fabe4ff667af13b2aca3e78d0d2c3e3f1
refs/heads/master
2020-05-19T13:14:07.548221
2012-07-23T03:47:06
2012-07-23T03:47:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
448
cpp
#include "LoginFrame.h" #include "SendCmd.cpp" LoginFrame::LoginFrame(User& user, const wxString& title, const wxPoint& pos, const wxSize& size) : wxDialog(NULL, -1, title, pos, size), user(user) { Result = Fail; } bool LoginFrame::Prompt() { while(Result != Success) { ShowModal(); // send server request sendCommand(new Message()); // set result if(Result == Cancel) { Close(); return false; } } return true; }
a2e880259e8888517b833a397401a3cd750c36ae
3af68b32aaa9b7522a1718b0fc50ef0cf4a704a9
/cpp/A/D/B/D/B/AADBDB.h
4c362c13592081c261ed037da5b8381dc270fceb
[]
no_license
devsisters/2021-NDC-ICECREAM
7cd09fa2794cbab1ab4702362a37f6ab62638d9b
ac6548f443a75b86d9e9151ff9c1b17c792b2afd
refs/heads/master
2023-03-19T06:29:03.216461
2021-03-10T02:53:14
2021-03-10T02:53:14
341,872,233
0
0
null
null
null
null
UTF-8
C++
false
false
67
h
#ifndef AADBDB_H namespace AADBDB { std::string run(); } #endif
d68e99ca1b30c8dee880632377ed8fc951defbf1
b0815bbf979b5a1b4be70f61d592b2b86b371ac8
/src/sdk-reference/cpp/1/realtime/unsubscribe/snippets/unsubscribe.cpp
fab1db109432ef97a4b0ee9cdba57a14036b43d2
[]
no_license
stafyniaksacha/documentation-V2
59bfa6bb6511921422f9d6b2209f6e6f03c42066
e43b933f6a9fe936f9f036d24ee064f3f110b330
refs/heads/master
2020-04-17T07:49:52.437235
2019-01-16T13:19:44
2019-01-16T13:19:44
166,386,202
0
0
null
2019-01-18T10:16:13
2019-01-18T10:16:12
null
UTF-8
C++
false
false
409
cpp
kuzzleio::NotificationListener listener = [](const kuzzleio::notification_result *notification){}; try { std::string room_id = kuzzle->realtime->subscribe( "nyc-open-data", "yellow-taxi", "{}", &listener); kuzzle->realtime->unsubscribe(room_id); std::cout << "Successfully unsubscribed" << std::endl; } catch (kuzzleio::KuzzleException &e) { std::cerr << e.what() << std::endl; }